@shirudo/ddd-kit 0.9.8 → 0.11.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,1516 @@
1
+ import { R as Result } from './result-jCwPSjFa.js';
2
+ import { a as DeepEqualExceptOptions } from './deep-equal-except-C8yoSk4L.js';
3
+
4
+ type Id<Tag extends string> = string & {
5
+ readonly __brand: Tag;
6
+ };
7
+ interface IdGenerator {
8
+ next: <T extends string>() => Id<T>;
9
+ }
10
+
11
+ /**
12
+ * Functional definition of an Entity via its capability.
13
+ * An object is identifiable if it has an id.
14
+ */
15
+ type Identifiable<TId> = {
16
+ readonly id: TId;
17
+ };
18
+ /**
19
+ * Interface for Entities.
20
+ * Extends Identifiable and adds equality comparison behavior.
21
+ *
22
+ * @template TId - The type of the entity identifier
23
+ */
24
+ interface IEntity<TId> extends Identifiable<TId> {
25
+ /**
26
+ * Checks if this entity is equal to another.
27
+ * Two entities are equal if they have the same ID.
28
+ *
29
+ * @param other - The other entity to compare
30
+ * @returns true if IDs are equal
31
+ */
32
+ equals(other: Identifiable<TId>): boolean;
33
+ }
34
+ /**
35
+ * Abstract base class for Entities.
36
+ * Provides identity equality and common behavior.
37
+ *
38
+ * @template TId - The type of the entity identifier
39
+ */
40
+ declare abstract class Entity<TId> implements IEntity<TId> {
41
+ readonly id: TId;
42
+ constructor(id: TId);
43
+ /**
44
+ * Optional validation hook that can be overridden by subclasses.
45
+ * Should throw an error if validation fails.
46
+ */
47
+ protected validate(): void;
48
+ /**
49
+ * Serializes the entity to a plain object.
50
+ * Default implementation returns the entity as is (since it's an object with properties).
51
+ * Subclasses can override this to control JSON serialization.
52
+ */
53
+ toJSON(): unknown;
54
+ /**
55
+ * Checks if this entity is equal to another.
56
+ * Two entities are equal if they have the same ID.
57
+ *
58
+ * @param other - The other entity to compare
59
+ * @returns true if IDs are equal
60
+ */
61
+ equals(other: Identifiable<TId>): boolean;
62
+ }
63
+ /**
64
+ * Checks if two entities have the same ID.
65
+ * Works with any object that has an 'id' property.
66
+ *
67
+ * @param a - First entity
68
+ * @param b - Second entity
69
+ * @returns true if both entities have the same ID, false otherwise
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * const item1: OrderItem = { id: itemId1, productId: "prod-1", quantity: 2 };
74
+ * const item2: OrderItem = { id: itemId2, productId: "prod-2", quantity: 1 };
75
+ *
76
+ * sameEntity(item1, item2); // false
77
+ * sameEntity(item1, item1); // true
78
+ * ```
79
+ */
80
+ declare function sameEntity<TId>(a: Identifiable<TId>, b: Identifiable<TId>): boolean;
81
+ /**
82
+ * Finds an entity by ID in a collection.
83
+ * Returns undefined if not found.
84
+ *
85
+ * @param entities - Array of entities to search
86
+ * @param id - The ID to search for
87
+ * @returns The entity if found, undefined otherwise
88
+ *
89
+ * @example
90
+ * ```typescript
91
+ * const items: OrderItem[] = [
92
+ * { id: itemId1, productId: "prod-1", quantity: 2 },
93
+ * { id: itemId2, productId: "prod-2", quantity: 1 }
94
+ * ];
95
+ *
96
+ * const item = findEntityById(items, itemId1);
97
+ * // item is { id: itemId1, productId: "prod-1", quantity: 2 }
98
+ * ```
99
+ */
100
+ declare function findEntityById<TId, T extends Identifiable<TId>>(entities: T[], id: TId): T | undefined;
101
+ /**
102
+ * Checks if an entity with the given ID exists in the collection.
103
+ *
104
+ * @param entities - Array of entities to search
105
+ * @param id - The ID to check for
106
+ * @returns true if an entity with the ID exists, false otherwise
107
+ *
108
+ * @example
109
+ * ```typescript
110
+ * const items: OrderItem[] = [
111
+ * { id: itemId1, productId: "prod-1", quantity: 2 }
112
+ * ];
113
+ *
114
+ * hasEntityId(items, itemId1); // true
115
+ * hasEntityId(items, itemId2); // false
116
+ * ```
117
+ */
118
+ declare function hasEntityId<TId, T extends Identifiable<TId>>(entities: T[], id: TId): boolean;
119
+ /**
120
+ * Removes an entity with the given ID from the collection.
121
+ * Returns a new array without the entity.
122
+ *
123
+ * @param entities - Array of entities
124
+ * @param id - The ID of the entity to remove
125
+ * @returns A new array without the entity with the given ID
126
+ *
127
+ * @example
128
+ * ```typescript
129
+ * const items: OrderItem[] = [
130
+ * { id: itemId1, productId: "prod-1", quantity: 2 },
131
+ * { id: itemId2, productId: "prod-2", quantity: 1 }
132
+ * ];
133
+ *
134
+ * const updated = removeEntityById(items, itemId1);
135
+ * // updated is [{ id: itemId2, productId: "prod-2", quantity: 1 }]
136
+ * ```
137
+ */
138
+ declare function removeEntityById<TId, T extends Identifiable<TId>>(entities: T[], id: TId): T[];
139
+ /**
140
+ * Updates an entity with the given ID in the collection.
141
+ * Returns a new array with the updated entity.
142
+ * If the entity is not found, returns the original array unchanged.
143
+ *
144
+ * @param entities - Array of entities
145
+ * @param id - The ID of the entity to update
146
+ * @param updater - Function that takes the entity and returns the updated entity
147
+ * @returns A new array with the updated entity
148
+ *
149
+ * @example
150
+ * ```typescript
151
+ * const items: OrderItem[] = [
152
+ * { id: itemId1, productId: "prod-1", quantity: 2 }
153
+ * ];
154
+ *
155
+ * const updated = updateEntityById(items, itemId1, (item) => ({
156
+ * ...item,
157
+ * quantity: item.quantity + 1
158
+ * }));
159
+ * // updated is [{ id: itemId1, productId: "prod-1", quantity: 3 }]
160
+ * ```
161
+ */
162
+ declare function updateEntityById<TId, T extends Identifiable<TId>>(entities: T[], id: TId, updater: (entity: T) => T): T[];
163
+ /**
164
+ * Replaces an entity with the given ID in the collection.
165
+ * Returns a new array with the replaced entity.
166
+ * If the entity is not found, returns the original array unchanged.
167
+ *
168
+ * @param entities - Array of entities
169
+ * @param id - The ID of the entity to replace
170
+ * @param replacement - The replacement entity
171
+ * @returns A new array with the replaced entity
172
+ *
173
+ * @example
174
+ * ```typescript
175
+ * const items: OrderItem[] = [
176
+ * { id: itemId1, productId: "prod-1", quantity: 2 }
177
+ * ];
178
+ *
179
+ * const updated = replaceEntityById(items, itemId1, {
180
+ * id: itemId1,
181
+ * productId: "prod-1",
182
+ * quantity: 5
183
+ * });
184
+ * ```
185
+ */
186
+ declare function replaceEntityById<TId, T extends Identifiable<TId>>(entities: T[], id: TId, replacement: T): T[];
187
+ /**
188
+ * Extracts all IDs from a collection of entities.
189
+ *
190
+ * @param entities - Array of entities
191
+ * @returns Array of entity IDs
192
+ *
193
+ * @example
194
+ * ```typescript
195
+ * const items: OrderItem[] = [
196
+ * { id: itemId1, productId: "prod-1", quantity: 2 },
197
+ * { id: itemId2, productId: "prod-2", quantity: 1 }
198
+ * ];
199
+ *
200
+ * const ids = entityIds(items);
201
+ * // ids is [itemId1, itemId2]
202
+ * ```
203
+ */
204
+ declare function entityIds<TId, T extends Identifiable<TId>>(entities: T[]): TId[];
205
+
206
+ /**
207
+ * Marker interface for Aggregate Roots.
208
+ *
209
+ * In Domain-Driven Design, an Aggregate Root is an Entity (the parent Entity of the aggregate).
210
+ * It represents the aggregate externally and is the only object that external code
211
+ * is allowed to hold references to. All access to child entities within the aggregate
212
+ * must go through the Aggregate Root.
213
+ *
214
+ * An Aggregate consists of:
215
+ * - One Aggregate Root (Entity with id + version)
216
+ * - Optional child entities (Entities with id, but no own version)
217
+ * - Optional value objects
218
+ *
219
+ * The Aggregate Root has identity (id) and version for optimistic concurrency control.
220
+ * Child entities exist only within the aggregate boundary and are versioned through
221
+ * the Aggregate Root.
222
+ *
223
+ * @template TId - The type of the aggregate root identifier
224
+ *
225
+ * @example
226
+ * ```typescript
227
+ * class Order extends AggregateRoot<OrderState, OrderId> implements IAggregateRoot<OrderId> {
228
+ * // Order is an Aggregate Root (an Entity)
229
+ * // OrderState contains child entities (e.g., OrderItem) and value objects
230
+ * }
231
+ * ```
232
+ */
233
+ interface IAggregateRoot<TId extends Id<string>> extends Identifiable<TId> {
234
+ /**
235
+ * Unique identifier of the aggregate root entity.
236
+ */
237
+ readonly id: TId;
238
+ /**
239
+ * Version number for optimistic concurrency control.
240
+ * Incremented on each state change to detect concurrent modifications.
241
+ * This version applies to the entire aggregate, including all child entities.
242
+ */
243
+ readonly version: Version;
244
+ }
245
+ /**
246
+ * Configuration options for AggregateRoot behavior.
247
+ */
248
+ interface AggregateConfig {
249
+ /**
250
+ * Whether to automatically bump the version when state changes.
251
+ * Defaults to false. Set to true for automatic versioning.
252
+ */
253
+ autoVersionBump?: boolean;
254
+ }
255
+ /**
256
+ * Base class for creating Aggregate Roots (Entities) without Event Sourcing.
257
+ *
258
+ * This class creates an Entity that serves as the Aggregate Root. The Aggregate Root
259
+ * is the parent Entity of the aggregate and represents it externally. It has identity
260
+ * (id) and version for optimistic concurrency control.
261
+ *
262
+ * The aggregate state (`TState`) contains:
263
+ * - Child entities (Entities with id, but no own version)
264
+ * - Value objects (immutable objects)
265
+ *
266
+ * All changes to child entities are versioned through the Aggregate Root. The version
267
+ * applies to the entire aggregate, including all child entities.
268
+ *
269
+ * Provides core functionality:
270
+ * - ID and Version management (for Optimistic Concurrency Control)
271
+ * - State management (containing child entities and value objects)
272
+ * - Snapshot support for performance optimization
273
+ *
274
+ * Implements `IAggregateRoot<TId>` to mark this as an Aggregate Root Entity.
275
+ *
276
+ * Use this class when you don't need Event Sourcing but still want
277
+ * aggregate patterns with versioning and state management.
278
+ *
279
+ * @template TState - The type of the aggregate state (contains child entities and value objects)
280
+ * @template TId - The type of the aggregate root identifier
281
+ *
282
+ * @example
283
+ * ```typescript
284
+ * // Order is an Aggregate Root (an Entity)
285
+ * class Order extends AggregateRoot<OrderState, OrderId> {
286
+ * constructor(id: OrderId, initialState: OrderState) {
287
+ * super(id, initialState);
288
+ * }
289
+ *
290
+ * confirm(): void {
291
+ * this._state = { ...this._state, status: "confirmed" };
292
+ * this.bumpVersion(); // Versions the entire aggregate
293
+ * }
294
+ * }
295
+ * ```
296
+ */
297
+ declare abstract class AggregateRoot<TState, TId extends Id<string>> implements IAggregateRoot<TId> {
298
+ readonly id: TId;
299
+ version: Version;
300
+ private readonly _config;
301
+ private readonly _autoVersionBump;
302
+ private _domainEvents;
303
+ get state(): TState;
304
+ /**
305
+ * Returns a read-only list of domain events recorded by this aggregate.
306
+ * These events are side-effects of state changes.
307
+ */
308
+ get domainEvents(): ReadonlyArray<unknown>;
309
+ /**
310
+ * Clears the list of recorded domain events.
311
+ * Call this after dispatching the events.
312
+ */
313
+ clearDomainEvents(): void;
314
+ /**
315
+ * The state is 'protected' so that only the subclass can change it.
316
+ * Subclasses can mutate this directly or use helper methods.
317
+ */
318
+ protected _state: TState;
319
+ protected constructor(id: TId, initialState: TState, config?: AggregateConfig);
320
+ /**
321
+ * Optional validation hook to ensure state invariants.
322
+ * Called during construction, setState, and snapshot restoration.
323
+ * Override this method to implement validation logic.
324
+ *
325
+ * @param state - The state to validate
326
+ * @throws Error if validation fails
327
+ */
328
+ protected validateState(_state: TState): void;
329
+ /**
330
+ * Adds a domain event to the aggregate's list of changes.
331
+ * Use this to record side-effects that should be published.
332
+ *
333
+ * @param event - The domain event to add
334
+ */
335
+ protected addDomainEvent(event: unknown): void;
336
+ /**
337
+ * Manually bumps the aggregate version.
338
+ * Call this after state changes for Optimistic Concurrency Control.
339
+ *
340
+ * If `autoVersionBump` is enabled, this is called automatically
341
+ * when using `setState()`.
342
+ */
343
+ protected bumpVersion(): void;
344
+ /**
345
+ * Sets the state and optionally bumps the version automatically.
346
+ * This is a convenience method for state mutations.
347
+ * Automatically validates the newState using `validateState()`.
348
+ *
349
+ * @param newState - The new state
350
+ * @param bumpVersion - Whether to bump the version (defaults to autoVersionBump config)
351
+ */
352
+ protected setState(newState: TState, bumpVersion?: boolean): void;
353
+ /**
354
+ * Creates a snapshot of the current aggregate state.
355
+ * Useful for performance optimization, backup/restore, and audit trails.
356
+ *
357
+ * @returns A snapshot containing the current state and version
358
+ *
359
+ * @example
360
+ * ```typescript
361
+ * const snapshot = aggregate.createSnapshot();
362
+ * await snapshotRepository.save(aggregate.id, snapshot);
363
+ * ```
364
+ */
365
+ createSnapshot(): AggregateSnapshot<TState>;
366
+ /**
367
+ * Restores the aggregate from a snapshot.
368
+ * This is useful for loading aggregates from snapshots instead of
369
+ * rebuilding them from scratch.
370
+ * Validates the restored state.
371
+ *
372
+ * @param snapshot - The snapshot to restore from
373
+ *
374
+ * @example
375
+ * ```typescript
376
+ * const snapshot = await snapshotRepository.getLatest(aggregateId);
377
+ * aggregate.restoreFromSnapshot(snapshot);
378
+ * ```
379
+ */
380
+ restoreFromSnapshot(snapshot: AggregateSnapshot<TState>): void;
381
+ }
382
+
383
+ /**
384
+ * Interface for Event-Sourced Aggregate Roots.
385
+ * Defines the contract for aggregates that manage state changes via event sourcing.
386
+ *
387
+ * @template TId - The type of the aggregate root identifier
388
+ * @template TEvent - The union type of all domain events
389
+ */
390
+ interface IAggregateEventSourced<TId extends Id<string>, TEvent extends DomainEvent<string, unknown>> extends IAggregateRoot<TId> {
391
+ /**
392
+ * Returns a read-only list of new, not-yet-persisted events.
393
+ */
394
+ readonly pendingEvents: ReadonlyArray<TEvent>;
395
+ /**
396
+ * Reconstitutes the aggregate from an event history.
397
+ *
398
+ * @param history - An ordered list of past events
399
+ */
400
+ loadFromHistory(history: TEvent[]): Result<void, string>;
401
+ /**
402
+ * Clears the list of pending events.
403
+ */
404
+ clearPendingEvents(): void;
405
+ /**
406
+ * Checks if the aggregate has any pending events.
407
+ */
408
+ hasPendingEvents(): boolean;
409
+ /**
410
+ * Returns the number of pending events.
411
+ */
412
+ getEventCount(): number;
413
+ /**
414
+ * Returns the latest pending event, if any.
415
+ */
416
+ getLatestEvent(): TEvent | undefined;
417
+ }
418
+ type Handler<TState, TEvent> = (state: TState, event: TEvent) => TState;
419
+ /**
420
+ * Extended configuration options for AggregateEventSourced behavior.
421
+ */
422
+ interface AggregateEventSourcedConfig extends AggregateConfig {
423
+ /**
424
+ * Whether to automatically bump the version when applying new events.
425
+ * Defaults to true. Set to false to manually control versioning.
426
+ */
427
+ autoVersionBump?: boolean;
428
+ }
429
+ /**
430
+ * Base class for Event-Sourced Aggregate Roots (Entities).
431
+ *
432
+ * Extends `AggregateRoot` to create an Aggregate Root Entity with Event Sourcing capabilities.
433
+ * The Aggregate Root is the parent Entity of the aggregate and represents it externally.
434
+ *
435
+ * The aggregate state (`TState`) contains:
436
+ * - Child entities (Entities with id, but no own version)
437
+ * - Value objects (immutable objects)
438
+ *
439
+ * All changes to child entities are versioned through the Aggregate Root. The version
440
+ * applies to the entire aggregate, including all child entities.
441
+ *
442
+ * Extends `AggregateRoot` with Event Sourcing capabilities:
443
+ * - Event tracking (pendingEvents)
444
+ * - Event handlers for state transitions
445
+ * - Event validation
446
+ * - History replay
447
+ *
448
+ * Use this class when you want Event Sourcing with full event tracking
449
+ * and replay capabilities.
450
+ *
451
+ * @template TState - The type of the aggregate state (contains child entities and value objects)
452
+ * @template TEvent - The union type of all domain events
453
+ * @template TId - The type of the aggregate root identifier
454
+ *
455
+ * @example
456
+ * ```typescript
457
+ * // Order is an Aggregate Root (an Entity) with Event Sourcing
458
+ * class Order extends AggregateEventSourced<OrderState, OrderEvent, OrderId> {
459
+ * confirm(): void {
460
+ * this.apply(createDomainEvent("OrderConfirmed", {}));
461
+ * }
462
+ *
463
+ * protected readonly handlers = {
464
+ * OrderConfirmed: (state: OrderState): OrderState => ({
465
+ * ...state,
466
+ * status: "confirmed",
467
+ * }),
468
+ * };
469
+ * }
470
+ * ```
471
+ */
472
+ declare abstract class AggregateEventSourced<TState, TEvent extends DomainEvent<string, unknown>, TId extends Id<string>> extends AggregateRoot<TState, TId> implements IAggregateEventSourced<TId, TEvent> {
473
+ private readonly _eventConfig;
474
+ private readonly _eventAutoVersionBump;
475
+ protected constructor(id: TId, initialState: TState, config?: AggregateEventSourcedConfig);
476
+ /**
477
+ * Returns a read-only list of new, not-yet-persisted events.
478
+ */
479
+ get pendingEvents(): ReadonlyArray<TEvent>;
480
+ /**
481
+ * Clears the list of pending events.
482
+ * Typically called after the events have been persisted.
483
+ */
484
+ clearPendingEvents(): void;
485
+ /**
486
+ * Validates an event before it is applied.
487
+ * Override this method to add custom validation logic.
488
+ * Return `ok(true)` if the event is valid, `err(message)` otherwise.
489
+ *
490
+ * @param event - The event to validate
491
+ * @returns Result indicating if the event is valid
492
+ *
493
+ * @example
494
+ * ```typescript
495
+ * protected validateEvent(event: OrderEvent): Result<true, string> {
496
+ * if (event.type === "OrderShipped" && this.state.status !== "confirmed") {
497
+ * return err("Order must be confirmed before shipping");
498
+ * }
499
+ * return ok(true);
500
+ * }
501
+ * ```
502
+ */
503
+ protected validateEvent(_event: TEvent): Result<true, string>;
504
+ /**
505
+ * Applies an event to change the state and adds it
506
+ * to the list of pending events.
507
+ * Returns a Result type instead of throwing an error.
508
+ *
509
+ * @param event - The domain event to apply
510
+ * @param isNew - Indicates whether the event is new (and needs to be persisted)
511
+ * or if it is being loaded from history
512
+ * @returns Result<void, string> - ok if successful, err with error message if validation fails or handler is missing
513
+ */
514
+ protected apply(event: TEvent, isNew?: boolean): Result<void, string>;
515
+ /**
516
+ * Applies an event to change the state and adds it
517
+ * to the list of pending events.
518
+ * Throws an error if validation fails or handler is missing.
519
+ *
520
+ * @param event - The domain event to apply
521
+ * @param isNew - Indicates whether the event is new (and needs to be persisted)
522
+ * or if it is being loaded from history
523
+ * @throws Error if event validation fails or handler is missing
524
+ */
525
+ protected applyUnsafe(event: TEvent, isNew?: boolean): void;
526
+ /**
527
+ * Manually bumps the aggregate version.
528
+ * Only needed if `autoVersionBump` is disabled.
529
+ */
530
+ protected bumpVersion(): void;
531
+ /**
532
+ * Reconstitutes the aggregate from an event history.
533
+ * Sets the version to the number of events in the history.
534
+ *
535
+ * @param history - An ordered list of past events
536
+ */
537
+ loadFromHistory(history: TEvent[]): Result<void, string>;
538
+ /**
539
+ * Checks if the aggregate has any pending events.
540
+ *
541
+ * @returns true if there are pending events, false otherwise
542
+ */
543
+ hasPendingEvents(): boolean;
544
+ /**
545
+ * Returns the number of pending events.
546
+ *
547
+ * @returns The count of pending events
548
+ */
549
+ getEventCount(): number;
550
+ /**
551
+ * Returns the latest pending event, if any.
552
+ *
553
+ * @returns The most recent event or undefined if no events exist
554
+ */
555
+ getLatestEvent(): TEvent | undefined;
556
+ /**
557
+ * Restores the aggregate from a snapshot and applies events that occurred after the snapshot.
558
+ * This is more efficient than replaying all events from the beginning.
559
+ *
560
+ * @param snapshot - The snapshot to restore from
561
+ * @param eventsAfterSnapshot - Events that occurred after the snapshot was taken
562
+ *
563
+ * @example
564
+ * ```typescript
565
+ * const snapshot = await snapshotRepository.getLatest(aggregateId);
566
+ * const eventsAfter = await eventStore.getEventsAfter(aggregateId, snapshot.version);
567
+ * aggregate.restoreFromSnapshotWithEvents(snapshot, eventsAfter);
568
+ * ```
569
+ */
570
+ restoreFromSnapshotWithEvents(snapshot: AggregateSnapshot<TState>, eventsAfterSnapshot: TEvent[]): Result<void, string>;
571
+ /**
572
+ * A map of event types to their corresponding handlers.
573
+ * Subclasses MUST implement this property.
574
+ */
575
+ protected abstract readonly handlers: {
576
+ [K in TEvent["type"]]: Handler<TState, Extract<TEvent, {
577
+ type: K;
578
+ }>>;
579
+ };
580
+ }
581
+
582
+ type Version = number & {
583
+ readonly __v: true;
584
+ };
585
+ /**
586
+ * Metadata associated with a domain event for traceability and correlation.
587
+ * Used in event-driven architectures to track event flow across services.
588
+ */
589
+ interface EventMetadata {
590
+ /**
591
+ * Correlation ID for tracing events across multiple services/components.
592
+ * Typically used to group related events in a distributed system.
593
+ */
594
+ correlationId?: string;
595
+ /**
596
+ * Causation ID referencing the event or command that caused this event.
597
+ * Used to build event chains and understand causality.
598
+ */
599
+ causationId?: string;
600
+ /**
601
+ * User ID of the person or system that triggered the event.
602
+ */
603
+ userId?: string;
604
+ /**
605
+ * Source service or component that produced the event.
606
+ */
607
+ source?: string;
608
+ /**
609
+ * Additional custom metadata fields.
610
+ * Allows extensibility for domain-specific metadata.
611
+ */
612
+ [key: string]: unknown;
613
+ }
614
+ /**
615
+ * Domain Event represents something meaningful that happened in the domain.
616
+ * Events are immutable and carry information about what occurred.
617
+ *
618
+ * @template T - The event type name (e.g., "OrderCreated")
619
+ * @template P - The event payload type
620
+ */
621
+ interface DomainEvent<T extends string, P> {
622
+ /**
623
+ * The type of the event, used for routing and handling.
624
+ */
625
+ type: T;
626
+ /**
627
+ * The event payload containing the domain data.
628
+ */
629
+ payload: P;
630
+ /**
631
+ * Timestamp when the event occurred.
632
+ */
633
+ occurredAt: Date;
634
+ /**
635
+ * Event schema version for handling schema evolution.
636
+ * Defaults to 1 if not specified. Higher versions indicate schema changes.
637
+ */
638
+ version?: number;
639
+ /**
640
+ * Optional metadata for traceability, correlation, and auditing.
641
+ * Includes correlationId, causationId, userId, source, and custom fields.
642
+ */
643
+ metadata?: EventMetadata;
644
+ }
645
+
646
+ /**
647
+ * Structural interface representing an aggregate with state and events.
648
+ * Used for type constraints in repositories and other infrastructure code.
649
+ *
650
+ * @template State - The type of the aggregate state
651
+ * @template Evt - The union type of all domain events
652
+ */
653
+ interface Aggregate<State, Evt extends DomainEvent<string, unknown>> {
654
+ state: Readonly<State>;
655
+ version: Version;
656
+ pendingEvents: ReadonlyArray<Evt>;
657
+ }
658
+ declare function aggregate<State, Evt extends DomainEvent<string, unknown>>(state: State, version?: Version): Aggregate<State, Evt>;
659
+ declare function withEvent<S, E extends DomainEvent<string, unknown>>(agg: Aggregate<S, E>, evt: E): Aggregate<S, E>;
660
+ declare function bump<S, E extends DomainEvent<string, unknown>>(agg: Aggregate<S, E>): Aggregate<S, E>;
661
+ /**
662
+ * Creates a domain event with default values.
663
+ * Sets occurredAt to current date and version to 1 if not provided.
664
+ *
665
+ * @param type - The event type
666
+ * @param payload - The event payload
667
+ * @param options - Optional event configuration
668
+ * @returns A domain event
669
+ *
670
+ * @example
671
+ * ```typescript
672
+ * const event = createDomainEvent("OrderCreated", { orderId: "123" });
673
+ * ```
674
+ */
675
+ declare function createDomainEvent<T extends string, P>(type: T, payload: P, options?: {
676
+ occurredAt?: Date;
677
+ version?: number;
678
+ metadata?: EventMetadata;
679
+ }): DomainEvent<T, P>;
680
+ /**
681
+ * Creates a domain event with metadata for traceability.
682
+ * Convenience function for creating events with correlation and causation IDs.
683
+ *
684
+ * @param type - The event type
685
+ * @param payload - The event payload
686
+ * @param metadata - Event metadata for traceability
687
+ * @param options - Optional event configuration
688
+ * @returns A domain event with metadata
689
+ *
690
+ * @example
691
+ * ```typescript
692
+ * const event = createDomainEventWithMetadata(
693
+ * "OrderCreated",
694
+ * { orderId: "123" },
695
+ * {
696
+ * correlationId: "corr-123",
697
+ * causationId: "cmd-456",
698
+ * userId: "user-789"
699
+ * }
700
+ * );
701
+ * ```
702
+ */
703
+ declare function createDomainEventWithMetadata<T extends string, P>(type: T, payload: P, metadata: EventMetadata, options?: {
704
+ occurredAt?: Date;
705
+ version?: number;
706
+ }): DomainEvent<T, P>;
707
+ /**
708
+ * Copies metadata from a source event to a new event.
709
+ * Useful for maintaining correlation chains in event-driven architectures.
710
+ *
711
+ * @param sourceEvent - The source event to copy metadata from
712
+ * @param additionalMetadata - Additional metadata to merge in
713
+ * @returns Event metadata with copied and merged values
714
+ *
715
+ * @example
716
+ * ```typescript
717
+ * const newEvent = createDomainEvent(
718
+ * "OrderShipped",
719
+ * { orderId: "123" },
720
+ * {
721
+ * metadata: copyMetadata(previousEvent, { causationId: previousEvent.type })
722
+ * }
723
+ * );
724
+ * ```
725
+ */
726
+ declare function copyMetadata(sourceEvent: DomainEvent<string, unknown>, additionalMetadata?: Partial<EventMetadata>): EventMetadata;
727
+ /**
728
+ * Merges multiple metadata objects into one.
729
+ * Later metadata objects override earlier ones for the same keys.
730
+ *
731
+ * @param metadataObjects - Array of metadata objects to merge
732
+ * @returns Merged event metadata
733
+ *
734
+ * @example
735
+ * ```typescript
736
+ * const metadata = mergeMetadata(
737
+ * { correlationId: "corr-123" },
738
+ * { userId: "user-456" },
739
+ * { source: "order-service" }
740
+ * );
741
+ * ```
742
+ */
743
+ declare function mergeMetadata(...metadataObjects: Array<EventMetadata | undefined>): EventMetadata;
744
+ /**
745
+ * Snapshot of an aggregate state at a specific point in time.
746
+ * Used for optimizing event replay by starting from a snapshot
747
+ * instead of replaying all events from the beginning.
748
+ *
749
+ * @template TState - The type of the aggregate state
750
+ */
751
+ interface AggregateSnapshot<TState> {
752
+ /**
753
+ * The state of the aggregate at the time of the snapshot.
754
+ */
755
+ state: TState;
756
+ /**
757
+ * The version of the aggregate when the snapshot was taken.
758
+ */
759
+ version: Version;
760
+ /**
761
+ * Timestamp when the snapshot was created.
762
+ */
763
+ snapshotAt: Date;
764
+ }
765
+ /**
766
+ * Checks if two aggregates are the same (same ID and version).
767
+ * Useful for optimistic concurrency control checks.
768
+ *
769
+ * @param a - First aggregate
770
+ * @param b - Second aggregate
771
+ * @returns true if both aggregates have the same ID and version
772
+ *
773
+ * @example
774
+ * ```typescript
775
+ * const aggregate1 = await repository.getById(id);
776
+ * // ... some operations ...
777
+ * const aggregate2 = await repository.getById(id);
778
+ *
779
+ * if (!sameAggregate(aggregate1, aggregate2)) {
780
+ * throw new Error("Aggregate was modified by another process");
781
+ * }
782
+ * ```
783
+ */
784
+ declare function sameAggregate<TId extends Id<string>>(a: {
785
+ id: TId;
786
+ version: Version;
787
+ }, b: {
788
+ id: TId;
789
+ version: Version;
790
+ }): boolean;
791
+
792
+ /**
793
+ * Marker interface for Commands.
794
+ * Commands represent write operations that change system state.
795
+ * They should be immutable and contain all data needed to perform the operation.
796
+ *
797
+ * This interface can be used as a type marker even when using external frameworks
798
+ * (e.g., RabbitMQ, AWS SQS) to ensure type safety across different bus implementations.
799
+ *
800
+ * @example
801
+ * ```typescript
802
+ * type CreateOrderCommand = Command & {
803
+ * type: "CreateOrder";
804
+ * customerId: string;
805
+ * items: OrderItem[];
806
+ * };
807
+ * ```
808
+ *
809
+ * @example Using with external frameworks (RabbitMQ, etc.)
810
+ * ```typescript
811
+ * // Define command using Command marker
812
+ * type CreateOrderCommand = Command & {
813
+ * type: "CreateOrder";
814
+ * customerId: string;
815
+ * };
816
+ *
817
+ * // Handler can be typed with CommandHandler even for external frameworks
818
+ * const handler: CommandHandler<CreateOrderCommand, OrderId> = async (cmd) => {
819
+ * // ... handler logic
820
+ * return ok(orderId);
821
+ * };
822
+ *
823
+ * // Register with RabbitMQ or other external bus
824
+ * rabbitMQChannel.consume("order.commands", async (message) => {
825
+ * const command = JSON.parse(message.content) as CreateOrderCommand;
826
+ * const result = await handler(command);
827
+ * // ... handle result
828
+ * });
829
+ * ```
830
+ */
831
+ interface Command {
832
+ readonly type: string;
833
+ }
834
+ /**
835
+ * Handler for executing commands.
836
+ * Commands return Result for explicit error handling.
837
+ * Commands may modify system state and should be idempotent when possible.
838
+ *
839
+ * This type can be used to mark handlers even when using external frameworks
840
+ * (e.g., RabbitMQ, AWS SQS, Kafka) to ensure type safety and consistency.
841
+ *
842
+ * @template C - The command type (must extend Command)
843
+ * @template R - The result type
844
+ *
845
+ * @example
846
+ * ```typescript
847
+ * const handler: CommandHandler<CreateOrderCommand, OrderId> = async (cmd) => {
848
+ * const order = Order.create(cmd.customerId, cmd.items);
849
+ * await repository.save(order);
850
+ * return ok(order.id);
851
+ * };
852
+ * ```
853
+ *
854
+ * @example Using with external frameworks
855
+ * ```typescript
856
+ * // Handler typed with CommandHandler for type safety
857
+ * const createOrderHandler: CommandHandler<CreateOrderCommand, OrderId> = async (cmd) => {
858
+ * // ... handler logic
859
+ * return ok(orderId);
860
+ * };
861
+ *
862
+ * // Can be used with any external bus/framework
863
+ * // RabbitMQ example:
864
+ * rabbitMQChannel.consume("commands", async (msg) => {
865
+ * const command = JSON.parse(msg.content) as CreateOrderCommand;
866
+ * const result = await createOrderHandler(command);
867
+ * // ... handle result
868
+ * });
869
+ *
870
+ * // AWS SQS example:
871
+ * sqs.receiveMessage({ QueueUrl: "..." }, async (err, data) => {
872
+ * const command = JSON.parse(data.Messages[0].Body) as CreateOrderCommand;
873
+ * const result = await createOrderHandler(command);
874
+ * // ... handle result
875
+ * });
876
+ * ```
877
+ */
878
+ type CommandHandler<C extends Command, R> = (cmd: C) => Promise<Result<R, string>>;
879
+
880
+ /**
881
+ * Command Bus interface for dispatching commands to their handlers.
882
+ * Provides a centralized way to execute commands with handler registration.
883
+ *
884
+ * @example
885
+ * ```typescript
886
+ * const bus = new CommandBus();
887
+ * bus.register("CreateOrder", createOrderHandler);
888
+ *
889
+ * const result = await bus.execute({
890
+ * type: "CreateOrder",
891
+ * customerId: "123",
892
+ * items: [...]
893
+ * });
894
+ * ```
895
+ */
896
+ interface ICommandBus {
897
+ /**
898
+ * Executes a command by dispatching it to the registered handler.
899
+ *
900
+ * @param command - The command to execute
901
+ * @returns Result containing the success value or error message
902
+ */
903
+ execute<C extends Command, R>(command: C): Promise<Result<R, string>>;
904
+ /**
905
+ * Registers a handler for a specific command type.
906
+ *
907
+ * @param commandType - The command type to register the handler for
908
+ * @param handler - The handler function for this command type
909
+ */
910
+ register<C extends Command, R>(commandType: C["type"], handler: CommandHandler<C, R>): void;
911
+ }
912
+ /**
913
+ * Simple in-memory command bus implementation.
914
+ * Handlers are stored in a Map and dispatched based on command type.
915
+ *
916
+ * **Note:** This is a basic implementation suitable for development and simple use cases.
917
+ * For production environments, consider implementing or using a more feature-rich bus that includes:
918
+ * - Middleware/Pipeline support (logging, validation, authorization)
919
+ * - Error handling and retry logic
920
+ * - Timeout handling
921
+ * - Metrics and observability
922
+ * - Transaction management
923
+ * - Dead letter queue support
924
+ *
925
+ * The `CommandHandler` type can still be used with external production-grade buses
926
+ * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.
927
+ *
928
+ * @example
929
+ * ```typescript
930
+ * const bus = new CommandBus();
931
+ * bus.register("CreateOrder", async (cmd) => {
932
+ * // ... handler logic
933
+ * return ok(orderId);
934
+ * });
935
+ *
936
+ * const result = await bus.execute({ type: "CreateOrder", ... });
937
+ * ```
938
+ */
939
+ declare class CommandBus implements ICommandBus {
940
+ private readonly handlers;
941
+ register<C extends Command, R>(commandType: C["type"], handler: CommandHandler<C, R>): void;
942
+ execute<C extends Command, R>(command: C): Promise<Result<R, string>>;
943
+ }
944
+
945
+ /**
946
+ * Event handler function type for subscribing to domain events.
947
+ *
948
+ * @template Evt - The type of domain event
949
+ */
950
+ type EventHandler<Evt> = (event: Evt) => Promise<void> | void;
951
+ /**
952
+ * Event Bus interface for publishing and subscribing to domain events.
953
+ * Supports multiple subscribers per event type (pub/sub pattern).
954
+ *
955
+ * @template Evt - The type of domain events
956
+ *
957
+ * @example
958
+ * ```typescript
959
+ * const bus = new EventBus<OrderEvent>();
960
+ *
961
+ * // Subscribe to specific event types
962
+ * bus.subscribe("OrderCreated", async (event) => {
963
+ * await sendEmail(event.payload.customerId);
964
+ * });
965
+ *
966
+ * bus.subscribe("OrderShipped", async (event) => {
967
+ * await updateInventory(event.payload.orderId);
968
+ * });
969
+ *
970
+ * // Publish events
971
+ * await bus.publish([orderCreatedEvent, orderShippedEvent]);
972
+ * ```
973
+ */
974
+ interface EventBus<Evt> {
975
+ /**
976
+ * Publishes events to all subscribed handlers.
977
+ * All handlers for each event type will be called.
978
+ *
979
+ * @param events - Array of events to publish
980
+ */
981
+ publish: (events: ReadonlyArray<Evt>) => Promise<void>;
982
+ /**
983
+ * Subscribes a handler to a specific event type.
984
+ * Multiple handlers can subscribe to the same event type.
985
+ *
986
+ * @param eventType - The event type to subscribe to
987
+ * @param handler - The handler function to call when events of this type are published
988
+ * @returns A function to unsubscribe the handler
989
+ *
990
+ * @example
991
+ * ```typescript
992
+ * const unsubscribe = bus.subscribe("OrderCreated", async (event) => {
993
+ * console.log("Order created:", event.payload.orderId);
994
+ * });
995
+ *
996
+ * // Later: unsubscribe
997
+ * unsubscribe();
998
+ * ```
999
+ */
1000
+ subscribe: <T extends Evt>(eventType: string, handler: EventHandler<T>) => () => void;
1001
+ }
1002
+ interface Outbox<Evt> {
1003
+ add: (events: ReadonlyArray<Evt>) => Promise<void>;
1004
+ }
1005
+ interface Clock {
1006
+ now: () => Date;
1007
+ }
1008
+
1009
+ interface UnitOfWork {
1010
+ transactional<T>(fn: () => Promise<T>): Promise<T>;
1011
+ }
1012
+ type RepoProvider<R> = (uow: UnitOfWork) => R;
1013
+
1014
+ /**
1015
+ * Helper function for executing commands within a transaction.
1016
+ * Handles event persistence via outbox and optional event bus publishing.
1017
+ *
1018
+ * @param deps - Dependencies including outbox, optional event bus, and unit of work
1019
+ * @param fn - Function that returns result and events
1020
+ * @returns The result wrapped in a transaction
1021
+ *
1022
+ * @example
1023
+ * ```typescript
1024
+ * const result = await withCommit(
1025
+ * { outbox, bus, uow },
1026
+ * async () => {
1027
+ * const order = Order.create(customerId, items);
1028
+ * await repository.save(order);
1029
+ * return {
1030
+ * result: order.id,
1031
+ * events: order.pendingEvents
1032
+ * };
1033
+ * }
1034
+ * );
1035
+ * ```
1036
+ */
1037
+ declare function withCommit<Evt, R>(deps: {
1038
+ outbox: Outbox<Evt>;
1039
+ bus?: EventBus<Evt>;
1040
+ uow: UnitOfWork;
1041
+ }, fn: () => Promise<{
1042
+ result: R;
1043
+ events: ReadonlyArray<Evt>;
1044
+ }>): Promise<R>;
1045
+
1046
+ /**
1047
+ * Marker interface for Queries.
1048
+ * Queries represent read operations that don't change system state.
1049
+ * They should be immutable and contain all data needed to perform the read.
1050
+ *
1051
+ * This interface can be used as a type marker even when using external frameworks
1052
+ * (e.g., RabbitMQ, AWS SQS) to ensure type safety across different bus implementations.
1053
+ *
1054
+ * @example
1055
+ * ```typescript
1056
+ * type GetOrderQuery = Query & {
1057
+ * type: "GetOrder";
1058
+ * orderId: OrderId;
1059
+ * };
1060
+ * ```
1061
+ *
1062
+ * @example Using with external frameworks
1063
+ * ```typescript
1064
+ * type GetOrderQuery = Query & {
1065
+ * type: "GetOrder";
1066
+ * orderId: OrderId;
1067
+ * };
1068
+ *
1069
+ * // Handler typed with QueryHandler for type safety
1070
+ * const handler: QueryHandler<GetOrderQuery, Order | null> = async (query) => {
1071
+ * return await repository.getById(query.orderId);
1072
+ * };
1073
+ *
1074
+ * // Can be used with any external framework
1075
+ * rabbitMQChannel.consume("queries", async (message) => {
1076
+ * const query = JSON.parse(message.content) as GetOrderQuery;
1077
+ * const result = await handler(query);
1078
+ * // ... handle result
1079
+ * });
1080
+ * ```
1081
+ */
1082
+ interface Query {
1083
+ readonly type: string;
1084
+ }
1085
+ /**
1086
+ * Handler for executing queries.
1087
+ * Queries return data directly (no Result type) as read operations
1088
+ * are not expected to fail in normal circumstances.
1089
+ * Queries should not modify system state and can be cached.
1090
+ *
1091
+ * This type can be used to mark handlers even when using external frameworks
1092
+ * (e.g., RabbitMQ, AWS SQS, Kafka) to ensure type safety and consistency.
1093
+ *
1094
+ * @template Q - The query type (must extend Query)
1095
+ * @template R - The result type
1096
+ *
1097
+ * @example
1098
+ * ```typescript
1099
+ * const handler: QueryHandler<GetOrderQuery, Order | null> = async (query) => {
1100
+ * return await repository.getById(query.orderId);
1101
+ * };
1102
+ * ```
1103
+ *
1104
+ * @example Using with external frameworks
1105
+ * ```typescript
1106
+ * // Handler typed with QueryHandler for type safety
1107
+ * const getOrderHandler: QueryHandler<GetOrderQuery, Order | null> = async (query) => {
1108
+ * return await repository.getById(query.orderId);
1109
+ * };
1110
+ *
1111
+ * // Can be used with any external bus/framework
1112
+ * rabbitMQChannel.consume("queries", async (msg) => {
1113
+ * const query = JSON.parse(msg.content) as GetOrderQuery;
1114
+ * const result = await getOrderHandler(query);
1115
+ * // ... handle result
1116
+ * });
1117
+ * ```
1118
+ */
1119
+ type QueryHandler<Q extends Query, R> = (query: Q) => Promise<R>;
1120
+
1121
+ /**
1122
+ * Query Bus interface for dispatching queries to their handlers.
1123
+ * Provides a centralized way to execute queries with handler registration.
1124
+ *
1125
+ * @example
1126
+ * ```typescript
1127
+ * const bus = new QueryBus();
1128
+ * bus.register("GetOrder", getOrderHandler);
1129
+ *
1130
+ * const order = await bus.execute({
1131
+ * type: "GetOrder",
1132
+ * orderId: "123"
1133
+ * });
1134
+ * ```
1135
+ */
1136
+ interface IQueryBus {
1137
+ /**
1138
+ * Executes a query by dispatching it to the registered handler.
1139
+ * Returns a Result type instead of throwing an error.
1140
+ *
1141
+ * @param query - The query to execute
1142
+ * @returns Result containing the query result if successful, or an error message if no handler is registered
1143
+ */
1144
+ execute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;
1145
+ /**
1146
+ * Executes a query by dispatching it to the registered handler.
1147
+ * Throws an error if no handler is registered.
1148
+ *
1149
+ * @param query - The query to execute
1150
+ * @returns The query result
1151
+ * @throws Error if no handler is registered for the query type
1152
+ */
1153
+ executeUnsafe<Q extends Query, R>(query: Q): Promise<R>;
1154
+ /**
1155
+ * Registers a handler for a specific query type.
1156
+ *
1157
+ * @param queryType - The query type to register the handler for
1158
+ * @param handler - The handler function for this query type
1159
+ */
1160
+ register<Q extends Query, R>(queryType: Q["type"], handler: QueryHandler<Q, R>): void;
1161
+ }
1162
+ /**
1163
+ * Type map for query types to their return types.
1164
+ * Used to improve type inference in QueryBus.
1165
+ */
1166
+ type QueryTypeMap = Record<string, unknown>;
1167
+ /**
1168
+ * Simple in-memory query bus implementation.
1169
+ * Handlers are stored in a Map and dispatched based on query type.
1170
+ *
1171
+ * **Note:** This is a basic implementation suitable for development and simple use cases.
1172
+ * For production environments, consider implementing or using a more feature-rich bus that includes:
1173
+ * - Middleware/Pipeline support (logging, caching, rate limiting)
1174
+ * - Error handling
1175
+ * - Timeout handling
1176
+ * - Metrics and observability
1177
+ * - Query result caching
1178
+ * - Rate limiting
1179
+ *
1180
+ * The `QueryHandler` type can still be used with external production-grade buses
1181
+ * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.
1182
+ *
1183
+ * @example
1184
+ * ```typescript
1185
+ * const bus = new QueryBus();
1186
+ * bus.register("GetOrder", async (query) => {
1187
+ * return await repository.getById(query.orderId);
1188
+ * });
1189
+ *
1190
+ * const order = await bus.execute({ type: "GetOrder", orderId: "123" });
1191
+ * ```
1192
+ */
1193
+ declare class QueryBus<TMap extends QueryTypeMap = QueryTypeMap> implements IQueryBus {
1194
+ private readonly handlers;
1195
+ register<Q extends Query, R>(queryType: Q["type"], handler: QueryHandler<Q, R>): void;
1196
+ execute<Q extends Query & {
1197
+ type: keyof TMap;
1198
+ }>(query: Q): Promise<Result<TMap[Q["type"]], string>>;
1199
+ execute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;
1200
+ executeUnsafe<Q extends Query, R>(query: Q): Promise<R>;
1201
+ }
1202
+
1203
+ /**
1204
+ * Guard function that validates a condition and returns a Result.
1205
+ * Returns `ok(true)` if the condition is met, otherwise `err(error)`.
1206
+ *
1207
+ * @param cond - The condition to check
1208
+ * @param error - Error message if condition fails
1209
+ * @returns Result<true, string>
1210
+ *
1211
+ * @example
1212
+ * ```typescript
1213
+ * const result = guard(id.length > 0, "ID cannot be empty");
1214
+ * if (!result.ok) {
1215
+ * return err(result.error);
1216
+ * }
1217
+ * ```
1218
+ */
1219
+ declare function guard(cond: boolean, error: string): Result<true, string>;
1220
+
1221
+ /**
1222
+ * Simple in-memory event bus implementation.
1223
+ * Supports multiple subscribers per event type (pub/sub pattern).
1224
+ *
1225
+ * @template Evt - The type of domain events (must extend DomainEvent)
1226
+ *
1227
+ * @example
1228
+ * ```typescript
1229
+ * const bus = new EventBusImpl<OrderEvent>();
1230
+ *
1231
+ * bus.subscribe("OrderCreated", async (event) => {
1232
+ * await sendEmail(event.payload.customerId);
1233
+ * });
1234
+ *
1235
+ * bus.subscribe("OrderCreated", async (event) => {
1236
+ * await logEvent(event);
1237
+ * });
1238
+ *
1239
+ * await bus.publish([orderCreatedEvent]);
1240
+ * // Both handlers will be called
1241
+ * ```
1242
+ */
1243
+ declare class EventBusImpl<Evt extends DomainEvent<string, unknown>> implements EventBus<Evt> {
1244
+ private readonly handlers;
1245
+ subscribe<T extends Evt>(eventType: string, handler: EventHandler<T>): () => void;
1246
+ publish(events: ReadonlyArray<Evt>): Promise<void>;
1247
+ }
1248
+
1249
+ /**
1250
+ * A Specification is a named, standalone object that represents a business rule for a query.
1251
+ * It is "translatable" into a concrete database query.
1252
+ */
1253
+ interface ISpecification<T> {
1254
+ readonly _type: T;
1255
+ }
1256
+
1257
+ /**
1258
+ * Repository interface for Aggregate Roots (Entities).
1259
+ *
1260
+ * Repositories work exclusively with Aggregate Root Entities. The Aggregate Root
1261
+ * is the Entity that represents the aggregate externally and is the only object
1262
+ * that can be loaded/saved through repositories.
1263
+ *
1264
+ * When loading an Aggregate Root, all child entities and value objects within
1265
+ * the aggregate state are loaded as well. When saving, the entire aggregate
1266
+ * (including all child entities) is persisted as a unit.
1267
+ *
1268
+ * Child entities cannot be loaded or saved independently - they exist only
1269
+ * within the aggregate boundary and are managed through the Aggregate Root.
1270
+ *
1271
+ * @template TState - The type of the aggregate state (contains child entities and value objects)
1272
+ * @template TEvent - The union type of all domain events
1273
+ * @template TAgg - The aggregate root type (must be an Aggregate Root Entity)
1274
+ * @template TId - The type of the aggregate root identifier
1275
+ */
1276
+ interface IRepository<TState, TEvent extends DomainEvent<string, unknown>, TAgg extends IAggregateRoot<TId> & Aggregate<TState, TEvent>, TId extends Id<string>> {
1277
+ getById(id: TId): Promise<TAgg | null>;
1278
+ findOne(spec: ISpecification<TAgg>): Promise<TAgg | null>;
1279
+ find(spec: ISpecification<TAgg>): Promise<TAgg[]>;
1280
+ save(aggregate: TAgg): Promise<void>;
1281
+ delete(id: TId): Promise<void>;
1282
+ }
1283
+
1284
+ type VO<T> = Readonly<T>;
1285
+ /**
1286
+ * Deep freezes an object and all its nested properties recursively.
1287
+ * This ensures true immutability for value objects with nested structures.
1288
+ * Handles circular references by tracking visited objects.
1289
+ */
1290
+ declare function deepFreeze<T>(obj: T, visited?: WeakSet<object>): Readonly<T>;
1291
+ /**
1292
+ * Creates a deeply immutable value object from the given data.
1293
+ * All nested objects and arrays are frozen recursively.
1294
+ *
1295
+ * @param t - The data to convert into a value object
1296
+ * @returns A deeply frozen, immutable value object
1297
+ *
1298
+ * @example
1299
+ * ```typescript
1300
+ * const address = vo({
1301
+ * street: "Main St",
1302
+ * city: "Berlin",
1303
+ * coordinates: { lat: 52.5, lng: 13.4 }
1304
+ * });
1305
+ * // address.coordinates.lat = 99; // ❌ Error: Cannot assign to read-only property
1306
+ * ```
1307
+ */
1308
+ declare function vo<T>(t: T): VO<T>;
1309
+ /**
1310
+ * Compares two value objects for equality based on their values.
1311
+ * Uses deep equality comparison that handles:
1312
+ * - Nested objects and arrays
1313
+ * - Primitives (including NaN)
1314
+ * - Dates, Maps, Sets, RegExp
1315
+ * - TypedArrays and DataView
1316
+ * - Symbol keys
1317
+ * - Circular references
1318
+ *
1319
+ * @param a - First value object
1320
+ * @param b - Second value object
1321
+ * @returns true if both objects have the same values, false otherwise
1322
+ *
1323
+ * @example
1324
+ * ```typescript
1325
+ * const money1 = vo({ amount: 100, currency: "USD" });
1326
+ * const money2 = vo({ amount: 100, currency: "USD" });
1327
+ * voEquals(money1, money2); // true
1328
+ *
1329
+ * const address1 = vo({
1330
+ * street: "Main St",
1331
+ * coordinates: { lat: 52.5, lng: 13.4 }
1332
+ * });
1333
+ * const address2 = vo({
1334
+ * street: "Main St",
1335
+ * coordinates: { lat: 52.5, lng: 13.4 }
1336
+ * });
1337
+ * voEquals(address1, address2); // true
1338
+ * ```
1339
+ */
1340
+ declare function voEquals<T>(a: VO<T>, b: VO<T>): boolean;
1341
+ /**
1342
+ * Compares two value objects for equality while ignoring specified keys.
1343
+ * Useful for comparing value objects that contain metadata or optional fields
1344
+ * that should not affect equality comparison.
1345
+ *
1346
+ * @param a - First value object
1347
+ * @param b - Second value object
1348
+ * @param options - Options specifying which keys to ignore during comparison
1349
+ * @returns true if both objects have the same values (after ignoring specified keys), false otherwise
1350
+ *
1351
+ * @example
1352
+ * ```typescript
1353
+ * // Value object with metadata
1354
+ * const address1 = vo({
1355
+ * street: "Main St",
1356
+ * city: "Berlin",
1357
+ * metadata: { createdAt: "2024-01-01", updatedAt: "2024-01-02" }
1358
+ * });
1359
+ *
1360
+ * const address2 = vo({
1361
+ * street: "Main St",
1362
+ * city: "Berlin",
1363
+ * metadata: { createdAt: "2024-01-01", updatedAt: "2024-01-03" }
1364
+ * });
1365
+ *
1366
+ * // Compare ignoring metadata timestamps
1367
+ * voEqualsExcept(address1, address2, {
1368
+ * ignoreKeys: ["updatedAt"],
1369
+ * ignoreKeyPredicate: (key, path) => path.includes("metadata")
1370
+ * }); // true
1371
+ *
1372
+ * // Compare ignoring all metadata
1373
+ * voEqualsExcept(address1, address2, {
1374
+ * ignoreKeyPredicate: (key, path) => path.includes("metadata")
1375
+ * }); // true
1376
+ * ```
1377
+ */
1378
+ declare function voEqualsExcept<T>(a: VO<T>, b: VO<T>, options: DeepEqualExceptOptions): boolean;
1379
+ /**
1380
+ * Creates a value object with optional validation.
1381
+ * Returns a Result type instead of throwing an error.
1382
+ *
1383
+ * @param t - The data to convert into a value object
1384
+ * @param validate - Validation function that returns true if valid
1385
+ * @param errorMessage - Optional custom error message if validation fails
1386
+ * @returns Result containing the value object if valid, or an error message if validation fails
1387
+ *
1388
+ * @example
1389
+ * ```typescript
1390
+ * const result = voWithValidation(
1391
+ * { amount: 100, currency: "USD" },
1392
+ * (m) => m.amount >= 0 && m.currency.length === 3,
1393
+ * "Invalid money: amount must be non-negative and currency must be 3 characters"
1394
+ * );
1395
+ *
1396
+ * if (result.ok) {
1397
+ * console.log(result.value); // Use the value object
1398
+ * } else {
1399
+ * console.error(result.error); // Handle validation error
1400
+ * }
1401
+ * ```
1402
+ */
1403
+ declare function voWithValidation<T>(t: T, validate: (value: T) => boolean, errorMessage?: string): Result<VO<T>, string>;
1404
+ /**
1405
+ * Creates a value object with optional validation.
1406
+ * Throws an error if validation fails.
1407
+ *
1408
+ * @param t - The data to convert into a value object
1409
+ * @param validate - Validation function that returns true if valid
1410
+ * @param errorMessage - Optional custom error message if validation fails
1411
+ * @returns A deeply frozen, immutable value object
1412
+ * @throws Error if validation fails
1413
+ *
1414
+ * @example
1415
+ * ```typescript
1416
+ * const money = voWithValidationUnsafe(
1417
+ * { amount: 100, currency: "USD" },
1418
+ * (m) => m.amount >= 0 && m.currency.length === 3,
1419
+ * "Invalid money: amount must be non-negative and currency must be 3 characters"
1420
+ * );
1421
+ * ```
1422
+ */
1423
+ declare function voWithValidationUnsafe<T>(t: T, validate: (value: T) => boolean, errorMessage?: string): VO<T>;
1424
+
1425
+ /**
1426
+ * Interface for Value Objects.
1427
+ * Value Objects are immutable and defined by their properties.
1428
+ *
1429
+ * @template T - The shape of the value object's properties
1430
+ */
1431
+ interface IValueObject<T extends object> {
1432
+ /**
1433
+ * The immutable properties of the value object.
1434
+ */
1435
+ readonly props: Readonly<T>;
1436
+ /**
1437
+ * Checks if this value object is equal to another.
1438
+ * Uses deep equality comparison on the properties.
1439
+ *
1440
+ * @param other - The other value object to compare
1441
+ * @returns true if the properties are deeply equal
1442
+ */
1443
+ equals(other: IValueObject<T>): boolean;
1444
+ /**
1445
+ * Creates a clone of the value object with optional property overrides.
1446
+ *
1447
+ * @param props - Optional properties to override
1448
+ * @returns A new instance of the value object
1449
+ */
1450
+ clone(props?: Partial<T>): IValueObject<T>;
1451
+ /**
1452
+ * Serializes the value object to its raw properties for JSON operations.
1453
+ *
1454
+ * @returns The raw properties object
1455
+ */
1456
+ toJSON(): Readonly<T>;
1457
+ }
1458
+ /**
1459
+ * Abstract base class for creating Value Objects.
1460
+ * Value Objects are immutable and defined by their properties.
1461
+ *
1462
+ * @template T - The shape of the value object's properties
1463
+ */
1464
+ declare abstract class ValueObject<T extends object> implements IValueObject<T> {
1465
+ readonly props: Readonly<T>;
1466
+ /**
1467
+ * Creates a new ValueObject.
1468
+ * The properties are deeply frozen to ensure immutability.
1469
+ *
1470
+ * @param props - The properties of the value object
1471
+ * @example
1472
+ * ```ts
1473
+ * class Money extends ValueObject<{ amount: number; currency: string }> {
1474
+ * constructor(props: { amount: number; currency: string }) {
1475
+ * super(props);
1476
+ * }
1477
+ *
1478
+ * protected validate(props: { amount: number; currency: string }): void {
1479
+ * if (props.amount < 0) throw new Error("Amount cannot be negative");
1480
+ * }
1481
+ * }
1482
+ * ```
1483
+ */
1484
+ constructor(props: T);
1485
+ /**
1486
+ * Optional validation hook that can be overridden by subclasses.
1487
+ * Should throw an error if validation fails.
1488
+ *
1489
+ * @param props - The properties to validate
1490
+ * @throws Error if validation fails
1491
+ */
1492
+ protected validate(props: T): void;
1493
+ /**
1494
+ * Checks if this value object is equal to another.
1495
+ * Uses deep equality comparison on the properties and checks for constructor equality.
1496
+ *
1497
+ * @param other - The other value object to compare
1498
+ * @returns true if the properties are deeply equal and constructors match
1499
+ */
1500
+ equals(other: ValueObject<T>): boolean;
1501
+ /**
1502
+ * Creates a clone of the value object with optional property overrides.
1503
+ *
1504
+ * @param props - Optional properties to override
1505
+ * @returns A new instance of the value object
1506
+ */
1507
+ clone(props?: Partial<T>): this;
1508
+ /**
1509
+ * Serializes the value object to its raw properties for JSON operations.
1510
+ *
1511
+ * @returns The raw properties object
1512
+ */
1513
+ toJSON(): Readonly<T>;
1514
+ }
1515
+
1516
+ export { type Aggregate, type AggregateConfig, AggregateEventSourced, type AggregateEventSourcedConfig, AggregateRoot, type AggregateSnapshot, type Clock, type Command, CommandBus, type CommandHandler, type DomainEvent, Entity, type EventBus, EventBusImpl, type EventHandler, type EventMetadata, type IAggregateEventSourced, type IAggregateRoot, type ICommandBus, type IEntity, type IQueryBus, type IRepository, type ISpecification, type IValueObject, type Id, type IdGenerator, type Identifiable, type Outbox, type Query, QueryBus, type QueryHandler, type RepoProvider, type UnitOfWork, type VO, ValueObject, type Version, aggregate, bump, copyMetadata, createDomainEvent, createDomainEventWithMetadata, deepFreeze, entityIds, findEntityById, guard, hasEntityId, mergeMetadata, removeEntityById, replaceEntityById, sameAggregate, sameEntity, updateEntityById, vo, voEquals, voEqualsExcept, voWithValidation, voWithValidationUnsafe, withCommit, withEvent };