@shirudo/ddd-kit 1.0.0-rc.2 โ 1.0.0-rc.4
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.
- package/README.md +0 -2
- package/dist/index.d.ts +74 -24
- package/dist/index.js +22 -11
- package/dist/index.js.map +1 -1
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -2,8 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
Composable TypeScript toolkit for tactical Domain-Driven Design.
|
|
4
4
|
|
|
5
|
-
๐ **[Full documentation site](https://shi-rudo.github.io/ddd-kit-ts/)** โ guides, API reference, design decisions.
|
|
6
|
-
|
|
7
5
|
> **Release Candidate**
|
|
8
6
|
>
|
|
9
7
|
> This library is in Release Candidate phase. The API is considered stable and ready for production evaluation. Please report any issues before the final 1.0.0 release.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Result } from '@shirudo/result';
|
|
2
|
+
import { BaseError } from '@shirudo/base-error';
|
|
2
3
|
import { DeepEqualExceptOptions } from './utils.js';
|
|
3
4
|
export { DeepOmitOptions, Key, PathSegment, deepEqual, deepEqualExcept, deepOmit } from './utils.js';
|
|
4
5
|
|
|
@@ -870,50 +871,99 @@ declare abstract class AggregateRoot<TState, TId extends Id<string>, TEvent = ne
|
|
|
870
871
|
}
|
|
871
872
|
|
|
872
873
|
/**
|
|
873
|
-
* Abstract base for
|
|
874
|
+
* Abstract base for **domain-invariant violations**. Domain methods
|
|
875
|
+
* (aggregates, entity validation hooks, value-object constructors)
|
|
876
|
+
* throw `DomainError`-derived exceptions when a business rule is
|
|
877
|
+
* violated. Consumers derive their own concrete errors โ e.g.
|
|
878
|
+
* `class OrderAlreadyShippedError extends DomainError<"OrderAlreadyShippedError"> {}` โ
|
|
879
|
+
* for `instanceof`-style catching at the App-Service boundary, where
|
|
880
|
+
* they typically map to HTTP 400 / business-rule responses.
|
|
881
|
+
*
|
|
882
|
+
* The library itself does **not** ship any concrete `DomainError`
|
|
883
|
+
* subclass โ the kit can't know your invariants. {@link MissingHandlerError},
|
|
884
|
+
* {@link AggregateNotFoundError}, and {@link ConcurrencyConflictError}
|
|
885
|
+
* deliberately sit on other branches of the hierarchy (see below) because
|
|
886
|
+
* they are not invariant violations.
|
|
887
|
+
*
|
|
888
|
+
* Extends `BaseError<Name>` from `@shirudo/base-error`, so derived
|
|
889
|
+
* classes get timestamps, `error.cause` traversal, `toJSON()`, i18n-
|
|
890
|
+
* aware `getUserMessage()`, and the `isRetryable` predicate for free.
|
|
891
|
+
*/
|
|
892
|
+
declare abstract class DomainError<Name extends string = string> extends BaseError<Name> {
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* Abstract base for **infrastructure / persistence failures** that the
|
|
896
|
+
* App-Service can recover from โ typically by retrying, by returning
|
|
897
|
+
* HTTP 404 / 409, or by surfacing a "please try again" UX. These are
|
|
898
|
+
* not domain-invariant violations (the business rules were not
|
|
899
|
+
* broken); they describe race conditions and missing rows at the
|
|
900
|
+
* storage boundary.
|
|
874
901
|
*
|
|
875
|
-
*
|
|
876
|
-
*
|
|
877
|
-
*
|
|
878
|
-
* failures have sprechende names and can be caught via `instanceof`.
|
|
902
|
+
* Library-internal concrete subclasses:
|
|
903
|
+
* - {@link AggregateNotFoundError}
|
|
904
|
+
* - {@link ConcurrencyConflictError}
|
|
879
905
|
*
|
|
880
|
-
*
|
|
881
|
-
* (`MissingHandlerError`, `AggregateNotFoundError`) โ everything else
|
|
882
|
-
* is consumer territory.
|
|
906
|
+
* Extends `BaseError<Name>` from `@shirudo/base-error`.
|
|
883
907
|
*/
|
|
884
|
-
declare abstract class
|
|
885
|
-
constructor(message: string, options?: ErrorOptions);
|
|
908
|
+
declare abstract class InfrastructureError<Name extends string = string> extends BaseError<Name> {
|
|
886
909
|
}
|
|
887
910
|
/**
|
|
888
|
-
* Thrown by `EventSourcedAggregate.apply()` when no handler is
|
|
889
|
-
* for the
|
|
890
|
-
* `handlers` map โ a programming
|
|
911
|
+
* Thrown by `EventSourcedAggregate.apply()` when no handler is
|
|
912
|
+
* registered for the event's type. This means the aggregate's subclass
|
|
913
|
+
* forgot to add an entry to its `handlers` map โ a programming /
|
|
914
|
+
* configuration bug, not a domain or infrastructure failure.
|
|
915
|
+
*
|
|
916
|
+
* Deliberately **not** on `DomainError` or `InfrastructureError` โ
|
|
917
|
+
* a generic `catch (e instanceof DomainError)` handler at the App
|
|
918
|
+
* layer must not mask a forgotten handler; this should crash loud and
|
|
919
|
+
* fail the calling Use Case so the bug surfaces in development. The
|
|
920
|
+
* replay methods (`loadFromHistory`, `restoreFromSnapshotWithEvents`)
|
|
921
|
+
* also let it propagate uncaught instead of wrapping it in `Result.Err`.
|
|
922
|
+
*
|
|
923
|
+
* Use `isBaseError(e)` from `@shirudo/base-error` to detect
|
|
924
|
+
* "any structured error from the kit or any other BaseError-using
|
|
925
|
+
* library" at the App boundary.
|
|
891
926
|
*/
|
|
892
|
-
declare class MissingHandlerError extends
|
|
927
|
+
declare class MissingHandlerError extends BaseError<"MissingHandlerError"> {
|
|
893
928
|
readonly eventType: string;
|
|
894
929
|
constructor(eventType: string);
|
|
895
930
|
}
|
|
896
931
|
/**
|
|
897
|
-
* Thrown by `IRepository.getByIdOrFail()` when an aggregate with the
|
|
898
|
-
* id does not exist.
|
|
899
|
-
* is
|
|
932
|
+
* Thrown by `IRepository.getByIdOrFail()` when an aggregate with the
|
|
933
|
+
* given id does not exist. `InfrastructureError` because the storage
|
|
934
|
+
* boundary, not a business rule, decided the row is absent. Use the
|
|
935
|
+
* nullable variant `getById()` if "not found" is a valid outcome.
|
|
936
|
+
*
|
|
937
|
+
* Ships with a user-safe message via `withUserMessage`. Not retryable โ
|
|
938
|
+
* retrying won't make the row appear.
|
|
900
939
|
*/
|
|
901
|
-
declare class AggregateNotFoundError extends
|
|
940
|
+
declare class AggregateNotFoundError extends InfrastructureError<"AggregateNotFoundError"> {
|
|
902
941
|
readonly aggregateType: string;
|
|
903
942
|
readonly id: string;
|
|
904
943
|
constructor(aggregateType: string, id: string);
|
|
905
944
|
}
|
|
906
945
|
/**
|
|
907
|
-
* Thrown by `IRepository.save()` when the aggregate's expected version
|
|
908
|
-
* not match the version currently persisted โ i.e. another writer
|
|
909
|
-
* the aggregate concurrently. The canonical
|
|
910
|
-
* signal;
|
|
946
|
+
* Thrown by `IRepository.save()` when the aggregate's expected version
|
|
947
|
+
* does not match the version currently persisted โ i.e. another writer
|
|
948
|
+
* updated the aggregate concurrently. The canonical optimistic-
|
|
949
|
+
* concurrency signal; the App-Service typically reloads, re-applies
|
|
950
|
+
* the use case, and retries, or surfaces HTTP 409 to the caller.
|
|
951
|
+
*
|
|
952
|
+
* `InfrastructureError` because the persistence layer (not a domain
|
|
953
|
+
* rule) detects the race. Marks itself as `retryable: true` so the
|
|
954
|
+
* `isRetryable` predicate from `@shirudo/base-error` picks it up.
|
|
911
955
|
*/
|
|
912
|
-
declare class ConcurrencyConflictError extends
|
|
956
|
+
declare class ConcurrencyConflictError extends InfrastructureError<"ConcurrencyConflictError"> {
|
|
913
957
|
readonly aggregateType: string;
|
|
914
958
|
readonly aggregateId: string;
|
|
915
959
|
readonly expectedVersion: number;
|
|
916
960
|
readonly actualVersion: number;
|
|
961
|
+
/**
|
|
962
|
+
* Marks this error as retryable so `isRetryable(err)` returns
|
|
963
|
+
* true. The canonical OCC pattern is to reload the aggregate, re-apply
|
|
964
|
+
* the use case, and retry on this exception.
|
|
965
|
+
*/
|
|
966
|
+
readonly retryable: true;
|
|
917
967
|
constructor(aggregateType: string, aggregateId: string, expectedVersion: number, actualVersion: number);
|
|
918
968
|
}
|
|
919
969
|
|
|
@@ -2192,4 +2242,4 @@ declare abstract class ValueObject<T extends object> implements IValueObject<T>
|
|
|
2192
2242
|
toJSON(): Readonly<T>;
|
|
2193
2243
|
}
|
|
2194
2244
|
|
|
2195
|
-
export { type AggregateConfig, AggregateNotFoundError, AggregateRoot, type AggregateSnapshot, type ClockFactory, type Command, CommandBus, type CommandHandler, ConcurrencyConflictError, type CreateDomainEventOptions, DeepEqualExceptOptions, DomainError, type DomainEvent, Entity, type EventBus, EventBusImpl, type EventHandler, type EventIdFactory, type EventMetadata, EventSourcedAggregate, type EventSourcedAggregateConfig, type IAggregateRoot, type ICommandBus, type IEntity, type IEventSourcedAggregate, type IQueryBus, type IQueryableRepository, type IRepository, type IValueObject, type Id, type IdGenerator, type Identifiable, MissingHandlerError, type OnceOptions, type Outbox, type OutboxRecord, type Query, QueryBus, type QueryHandler, type TransactionScope, type VO, ValueObject, type Version, copyMetadata, createDomainEvent, createDomainEventWithMetadata, deepFreeze, entityIds, findEntityById, freezeShallow, hasEntityId, mergeMetadata, removeEntityById, replaceEntityById, resetClockFactory, resetEventIdFactory, sameEntity, sameVersion, setClockFactory, setEventIdFactory, updateEntityById, vo, voEquals, voEqualsExcept, voWithValidation, withCommit };
|
|
2245
|
+
export { type AggregateConfig, AggregateNotFoundError, AggregateRoot, type AggregateSnapshot, type ClockFactory, type Command, CommandBus, type CommandHandler, ConcurrencyConflictError, type CreateDomainEventOptions, DeepEqualExceptOptions, DomainError, type DomainEvent, Entity, type EventBus, EventBusImpl, type EventHandler, type EventIdFactory, type EventMetadata, EventSourcedAggregate, type EventSourcedAggregateConfig, type IAggregateRoot, type ICommandBus, type IEntity, type IEventSourcedAggregate, type IQueryBus, type IQueryableRepository, type IRepository, type IValueObject, type Id, type IdGenerator, type Identifiable, InfrastructureError, MissingHandlerError, type OnceOptions, type Outbox, type OutboxRecord, type Query, QueryBus, type QueryHandler, type TransactionScope, type VO, ValueObject, type Version, copyMetadata, createDomainEvent, createDomainEventWithMetadata, deepFreeze, entityIds, findEntityById, freezeShallow, hasEntityId, mergeMetadata, removeEntityById, replaceEntityById, resetClockFactory, resetEventIdFactory, sameEntity, sameVersion, setClockFactory, setEventIdFactory, updateEntityById, vo, voEquals, voEqualsExcept, voWithValidation, withCommit };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { err, ok } from '@shirudo/result';
|
|
2
|
+
import { BaseError } from '@shirudo/base-error';
|
|
2
3
|
|
|
3
4
|
var __defProp = Object.defineProperty;
|
|
4
5
|
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
@@ -753,19 +754,17 @@ var AggregateRoot = class extends Entity {
|
|
|
753
754
|
this.setVersion(snapshot.version);
|
|
754
755
|
}
|
|
755
756
|
};
|
|
756
|
-
|
|
757
|
-
// src/core/errors.ts
|
|
758
|
-
var DomainError = class extends Error {
|
|
757
|
+
var DomainError = class extends BaseError {
|
|
759
758
|
static {
|
|
760
759
|
__name(this, "DomainError");
|
|
761
760
|
}
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
761
|
+
};
|
|
762
|
+
var InfrastructureError = class extends BaseError {
|
|
763
|
+
static {
|
|
764
|
+
__name(this, "InfrastructureError");
|
|
766
765
|
}
|
|
767
766
|
};
|
|
768
|
-
var MissingHandlerError = class extends
|
|
767
|
+
var MissingHandlerError = class extends BaseError {
|
|
769
768
|
constructor(eventType) {
|
|
770
769
|
super(`Missing handler for event type: ${eventType}`);
|
|
771
770
|
this.eventType = eventType;
|
|
@@ -774,17 +773,20 @@ var MissingHandlerError = class extends DomainError {
|
|
|
774
773
|
__name(this, "MissingHandlerError");
|
|
775
774
|
}
|
|
776
775
|
};
|
|
777
|
-
var AggregateNotFoundError = class extends
|
|
776
|
+
var AggregateNotFoundError = class extends InfrastructureError {
|
|
778
777
|
constructor(aggregateType, id) {
|
|
779
778
|
super(`Aggregate not found: ${aggregateType}(${id})`);
|
|
780
779
|
this.aggregateType = aggregateType;
|
|
781
780
|
this.id = id;
|
|
781
|
+
this.withUserMessage(
|
|
782
|
+
`The requested ${aggregateType.toLowerCase()} could not be found.`
|
|
783
|
+
);
|
|
782
784
|
}
|
|
783
785
|
static {
|
|
784
786
|
__name(this, "AggregateNotFoundError");
|
|
785
787
|
}
|
|
786
788
|
};
|
|
787
|
-
var ConcurrencyConflictError = class extends
|
|
789
|
+
var ConcurrencyConflictError = class extends InfrastructureError {
|
|
788
790
|
constructor(aggregateType, aggregateId, expectedVersion, actualVersion) {
|
|
789
791
|
super(
|
|
790
792
|
`Concurrency conflict on ${aggregateType}(${aggregateId}): expected version ${expectedVersion}, actual ${actualVersion}`
|
|
@@ -793,10 +795,19 @@ var ConcurrencyConflictError = class extends DomainError {
|
|
|
793
795
|
this.aggregateId = aggregateId;
|
|
794
796
|
this.expectedVersion = expectedVersion;
|
|
795
797
|
this.actualVersion = actualVersion;
|
|
798
|
+
this.withUserMessage(
|
|
799
|
+
"This resource was updated by another request. Please reload and try again."
|
|
800
|
+
);
|
|
796
801
|
}
|
|
797
802
|
static {
|
|
798
803
|
__name(this, "ConcurrencyConflictError");
|
|
799
804
|
}
|
|
805
|
+
/**
|
|
806
|
+
* Marks this error as retryable so `isRetryable(err)` returns
|
|
807
|
+
* true. The canonical OCC pattern is to reload the aggregate, re-apply
|
|
808
|
+
* the use case, and retry on this exception.
|
|
809
|
+
*/
|
|
810
|
+
retryable = true;
|
|
800
811
|
};
|
|
801
812
|
|
|
802
813
|
// src/aggregate/event-sourced-aggregate.ts
|
|
@@ -1140,6 +1151,6 @@ var EventBusImpl = class {
|
|
|
1140
1151
|
}
|
|
1141
1152
|
};
|
|
1142
1153
|
|
|
1143
|
-
export { AggregateNotFoundError, AggregateRoot, CommandBus, ConcurrencyConflictError, DomainError, Entity, EventBusImpl, EventSourcedAggregate, MissingHandlerError, QueryBus, ValueObject, copyMetadata, createDomainEvent, createDomainEventWithMetadata, deepEqual, deepEqualExcept, deepFreeze, deepOmit, entityIds, findEntityById, freezeShallow, hasEntityId, mergeMetadata, removeEntityById, replaceEntityById, resetClockFactory, resetEventIdFactory, sameEntity, sameVersion, setClockFactory, setEventIdFactory, updateEntityById, vo, voEquals, voEqualsExcept, voWithValidation, withCommit };
|
|
1154
|
+
export { AggregateNotFoundError, AggregateRoot, CommandBus, ConcurrencyConflictError, DomainError, Entity, EventBusImpl, EventSourcedAggregate, InfrastructureError, MissingHandlerError, QueryBus, ValueObject, copyMetadata, createDomainEvent, createDomainEventWithMetadata, deepEqual, deepEqualExcept, deepFreeze, deepOmit, entityIds, findEntityById, freezeShallow, hasEntityId, mergeMetadata, removeEntityById, replaceEntityById, resetClockFactory, resetEventIdFactory, sameEntity, sameVersion, setClockFactory, setEventIdFactory, updateEntityById, vo, voEquals, voEqualsExcept, voWithValidation, withCommit };
|
|
1144
1155
|
//# sourceMappingURL=index.js.map
|
|
1145
1156
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/array/is-built-in.ts","../src/utils/array/deep-equal.ts","../src/utils/array/deep-omit.ts","../src/utils/array/deep-equal-except.ts","../src/value-object/value-object.ts","../src/aggregate/domain-event.ts","../src/aggregate/aggregate.ts","../src/entity/entity.ts","../src/aggregate/aggregate-root.ts","../src/core/errors.ts","../src/aggregate/event-sourced-aggregate.ts","../src/app/command-bus.ts","../src/app/handler.ts","../src/app/query-bus.ts","../src/events/event-bus.ts"],"names":["tagA","tagB","len","clone","err","ok"],"mappings":";;;;;;AAaA,IAAM,aAAA,uBAAyC,GAAA,CAAI;AAAA,EAClD,eAAA;AAAA,EACA,iBAAA;AAAA,EACA,cAAA;AAAA,EACA,cAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,gBAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA,EACA,iBAAA;AAAA,EACA,sBAAA;AAAA,EACA,4BAAA;AAAA,EACA;AACD,CAAC,CAAA;AAWM,SAAS,eAAA,CAAgB,KAAa,GAAA,EAAsB;AAElE,EAAA,IAAI,GAAA,CAAI,QAAA,CAAS,QAAQ,CAAA,EAAG,OAAO,IAAA;AAEnC,EAAA,IAAI,WAAA,CAAY,MAAA,CAAO,GAAG,CAAA,EAAG,OAAO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CAAA;AAAA;AAC/E,WACD;AAAA,QACD,CAAA,EAAG,QAAQ,SAAS,CAAA;AAAA,MACrB;AAAA,IACD,CAAC,CAAA;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,QAAQ,MAAA,EAA2C;AACxD,IAAA,MAAM,SAAkB,EAAC;AAEzB,IAAA,KAAA,MAAW,SAAS,MAAA,EAAQ;AAC3B,MAAA,MAAM,eAAA,GAAkB,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,MAAM,IAAI,CAAA;AACpD,MAAA,IAAI,eAAA,EAAiB;AAGpB,QAAA,MAAM,OAAA,GAAU,MAAM,OAAA,CAAQ,UAAA;AAAA,UAC7B,eAAA,CAAgB,OAAM,CAAE,GAAA,CAAI,CAAC,OAAA,KAAY,OAAA,CAAQ,KAAK,CAAC;AAAA,SACxD;AACA,QAAA,KAAA,MAAW,UAAU,OAAA,EAAS;AAC7B,UAAA,IAAI,MAAA,CAAO,WAAW,UAAA,EAAY;AACjC,YAAA,MAAA,CAAO,IAAA;AAAA,cACN,MAAA,CAAO,MAAA,YAAkB,KAAA,GACtB,MAAA,CAAO,MAAA,GACP,IAAI,KAAA,CAAM,MAAA,CAAO,MAAA,CAAO,MAAM,CAAC;AAAA,aACnC;AAAA,UACD;AAAA,QACD;AAAA,MACD;AAAA,IACD;AAEA,IAAA,IAAI,MAAA,CAAO,WAAW,CAAA,EAAG;AACxB,MAAA,MAAM,OAAO,CAAC,CAAA;AAAA,IACf;AACA,IAAA,IAAI,MAAA,CAAO,SAAS,CAAA,EAAG;AACtB,MAAA,MAAM,IAAI,cAAA,CAAe,MAAA,EAAQ,gCAAgC,CAAA;AAAA,IAClE;AAAA,EACD;AACD","file":"index.js","sourcesContent":["/**\n * Set of `Object.prototype.toString.call(x)` tags that the library treats\n * as built-in atomic types. Members of this set are compared/cloned by\n * reference (or with type-specific logic) rather than walked structurally.\n *\n * The detection is purely tag-based โ `Object.prototype.toString` reads\n * `Symbol.toStringTag`, which gives the same answer across realms (an\n * iframe's `Date` has the same tag as the main window's `Date`). The\n * previous strategy also checked `globalThis[name] === constructor` and a\n * `proto !== Object.prototype` heuristic; both broke for cross-realm\n * objects and the latter additionally misclassified ordinary user classes\n * as built-ins. Tag-only is the simplest robust choice.\n */\nconst BUILT_IN_TAGS: ReadonlySet<string> = new Set([\n\t\"[object Date]\",\n\t\"[object RegExp]\",\n\t\"[object Map]\",\n\t\"[object Set]\",\n\t\"[object WeakMap]\",\n\t\"[object WeakSet]\",\n\t\"[object Promise]\",\n\t\"[object Error]\",\n\t\"[object Boolean]\",\n\t\"[object Number]\",\n\t\"[object String]\",\n\t\"[object ArrayBuffer]\",\n\t\"[object SharedArrayBuffer]\",\n\t\"[object DataView]\",\n]);\n\n/**\n * Returns `true` when `obj` is a built-in JavaScript type that should be\n * treated atomically (compared/cloned as a unit, not walked structurally).\n * Cross-realm safe.\n *\n * @param obj - The object to classify\n * @param tag - The result of `Object.prototype.toString.call(obj)` โ passed\n * in so callers that already computed it don't pay twice\n */\nexport function isBuiltInObject(obj: object, tag: string): boolean {\n\t// All TypedArrays produce tags ending in \"Array]\" โ future-proof match.\n\tif (tag.endsWith(\"Array]\")) return true;\n\t// ArrayBuffer view covers DataView + all TypedArrays as a belt-and-braces.\n\tif (ArrayBuffer.isView(obj)) return true;\n\treturn BUILT_IN_TAGS.has(tag);\n}\n","import { isBuiltInObject } from \"./is-built-in\";\n\nconst objProto = Object.prototype;\nconst objToString = objProto.toString;\nconst objHasOwn = objProto.hasOwnProperty;\n\n/**\n * Performs a deep equality check between two values.\n *\n * This function compares values recursively, handling:\n * - Primitives (with special handling for NaN)\n * - Arrays (nested arrays supported)\n * - Objects (plain objects and class instances)\n * - TypedArrays (Uint8Array, Int32Array, etc.)\n * - DataView\n * - Maps and Sets\n * - Dates and RegExp\n * - Wrapper objects (Boolean, Number, String)\n * - Circular references (detected and handled)\n *\n * @param a - The first value to compare\n * @param b - The second value to compare\n * @returns `true` if the values are deeply equal, `false` otherwise\n *\n * @example\n * ```ts\n * deepEqual([1, 2, 3], [1, 2, 3]); // true\n * deepEqual({ a: 1, b: [2, 3] }, { a: 1, b: [2, 3] }); // true\n * deepEqual(NaN, NaN); // true\n * deepEqual([1, 2], [1, 2, 3]); // false\n * ```\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n\treturn deepEqualInner(a, b, new WeakMap<object, WeakSet<object>>());\n}\n\n/**\n * Visited pair tracker for cycle detection. The cache is a pair-set:\n * for every left-hand object we keep the set of right-hand objects we\n * have already paired it with. Encountering an already-known pair returns\n * the cycle hypothesis (assume equal); a new (a, b') pair with b' โ any\n * previously cached b for that a is walked normally โ the previous shape\n * (`WeakMap<object, object>`) could only remember one B per A, which\n * could short-circuit unrelated comparisons that happened to revisit the\n * same A with a different B.\n */\ntype VisitedPairs = WeakMap<object, WeakSet<object>>;\n\n/**\n * Internal recursive function for deep equality comparison.\n *\n * @internal\n */\nfunction deepEqualInner(\n\ta: unknown,\n\tb: unknown,\n\tvisited: VisitedPairs,\n): boolean {\n\t// 1. Fast path: reference equality\n\tif (a === b) return true;\n\n\tconst typeA = typeof a;\n\tconst typeB = typeof b;\n\n\t// 2. If one is not an object โ primitive / function\n\tif (typeA !== \"object\" || a === null || typeB !== \"object\" || b === null) {\n\t\t// Special case: NaN should be equal\n\t\tif (typeA === \"number\" && typeB === \"number\") {\n\t\t\treturn Number.isNaN(a as number) && Number.isNaN(b as number);\n\t\t}\n\t\t// Everything else is directly unequal with !== (including functions)\n\t\treturn false;\n\t}\n\n\t// From here on: both are non-null objects\n\n\tconst objA = a as object;\n\tconst objB = b as object;\n\n\t// 3. Cycles: already seen this exact (a, b) pair?\n\tlet cachedBs = visited.get(objA);\n\tif (cachedBs?.has(objB)) {\n\t\t// Cycle hypothesis: pretend equal so the walk can terminate. If the\n\t\t// structure is actually unequal elsewhere, a different recursive\n\t\t// branch will surface the mismatch.\n\t\treturn true;\n\t}\n\tif (!cachedBs) {\n\t\tcachedBs = new WeakSet();\n\t\tvisited.set(objA, cachedBs);\n\t}\n\tcachedBs.add(objB);\n\n\t// 4. Handle Typed Arrays / DataView first\n\tif (ArrayBuffer.isView(objA) || ArrayBuffer.isView(objB)) {\n\t\tif (!ArrayBuffer.isView(objA) || !ArrayBuffer.isView(objB)) return false;\n\n\t\tconst tagA = objToString.call(objA);\n\t\tconst tagB = objToString.call(objB);\n\t\tif (tagA !== tagB) return false;\n\n\t\t// DataView: compare byte by byte\n\t\tif (tagA === \"[object DataView]\") {\n\t\t\tconst viewA = objA as DataView;\n\t\t\tconst viewB = objB as DataView;\n\t\t\tif (viewA.byteLength !== viewB.byteLength) return false;\n\n\t\t\tconst len = viewA.byteLength;\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\tif (viewA.getUint8(i) !== viewB.getUint8(i)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t// Typed Arrays: element by element (length + numeric index access are\n\t\t// part of the TypedArray contract; the indexed read is sound).\n\t\tconst arrA = objA as unknown as Record<number, unknown> & { length: number };\n\t\tconst arrB = objB as unknown as Record<number, unknown> & { length: number };\n\n\t\tconst len = arrA.length;\n\t\tif (len !== arrB.length) return false;\n\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tif (arrA[i] !== arrB[i]) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t// 5. Tag-based type detection (robust across realms)\n\tconst tagA = objToString.call(objA);\n\tconst tagB = objToString.call(objB);\n\tif (tagA !== tagB) return false;\n\n\tswitch (tagA) {\n\t\tcase \"[object Array]\": {\n\t\t\tconst arrA = objA as unknown[];\n\t\t\tconst arrB = objB as unknown[];\n\t\t\tconst len = arrA.length;\n\t\t\tif (len !== arrB.length) return false;\n\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\tif (!deepEqualInner(arrA[i], arrB[i], visited)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Map]\": {\n\t\t\tconst mapA = objA as Map<unknown, unknown>;\n\t\t\tconst mapB = objB as Map<unknown, unknown>;\n\n\t\t\tif (mapA.size !== mapB.size) return false;\n\n\t\t\tfor (const [key, valA] of mapA) {\n\t\t\t\t// Map keys according to JS semantics: reference / SameValueZero\n\t\t\t\tif (!mapB.has(key)) return false;\n\t\t\t\tconst valB = mapB.get(key);\n\t\t\t\tif (!deepEqualInner(valA, valB, visited)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Set]\": {\n\t\t\tconst setA = objA as Set<unknown>;\n\t\t\tconst setB = objB as Set<unknown>;\n\n\t\t\tif (setA.size !== setB.size) return false;\n\n\t\t\t// Set elements: same reference (JS semantics)\n\t\t\tfor (const value of setA) {\n\t\t\t\tif (!setB.has(value)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Date]\": {\n\t\t\tconst timeA = (objA as Date).getTime();\n\t\t\tconst timeB = (objB as Date).getTime();\n\t\t\treturn timeA === timeB;\n\t\t}\n\n\t\tcase \"[object RegExp]\": {\n\t\t\tconst regA = objA as RegExp;\n\t\t\tconst regB = objB as RegExp;\n\t\t\treturn regA.source === regB.source && regA.flags === regB.flags;\n\t\t}\n\n\t\tcase \"[object Boolean]\":\n\t\tcase \"[object Number]\":\n\t\tcase \"[object String]\": {\n\t\t\t// Wrapper objects (new Boolean/Number/String)\n\t\t\treturn (objA as any).valueOf() === (objB as any).valueOf();\n\t\t}\n\n\t\tdefault: {\n\t\t\t// 6. Check if this is an unhandled built-in type (future-proof)\n\t\t\t// If both are built-ins but not handled above, they should be compared by reference\n\t\t\t// (since we don't know their internal structure)\n\t\t\tif (isBuiltInObject(objA, tagA) && isBuiltInObject(objB, tagB)) {\n\t\t\t\t// Unhandled built-in types: compare by reference as fallback\n\t\t\t\t// This ensures new built-ins don't fall through to plain object comparison\n\t\t\t\treturn objA === objB;\n\t\t\t}\n\n\t\t\t// 7. Fallback: plain / custom objects โ compare own enumerable keys + values\n\t\t\tconst recA = objA as Record<string | symbol, unknown>;\n\t\t\tconst recB = objB as Record<string | symbol, unknown>;\n\n\t\t\tconst stringKeysA = Object.keys(objA as object);\n\t\t\tconst stringKeysB = Object.keys(objB as object);\n\t\t\tif (stringKeysA.length !== stringKeysB.length) return false;\n\n\t\t\tconst symbolKeysA = Object.getOwnPropertySymbols(objA as object);\n\t\t\tconst symbolKeysB = Object.getOwnPropertySymbols(objB as object);\n\t\t\tif (symbolKeysA.length !== symbolKeysB.length) return false;\n\n\t\t\t// Build the B-side symbol set once; the previous impl rebuilt the\n\t\t\t// array and ran .includes per key, which was quadratic.\n\t\t\tconst symbolKeysBSet = new Set<symbol>(symbolKeysB);\n\n\t\t\tfor (const key of stringKeysA) {\n\t\t\t\tif (!objHasOwn.call(objB, key)) return false;\n\t\t\t}\n\t\t\tfor (const key of symbolKeysA) {\n\t\t\t\tif (!symbolKeysBSet.has(key)) return false;\n\t\t\t}\n\n\t\t\tfor (const key of stringKeysA) {\n\t\t\t\tif (!deepEqualInner(recA[key], recB[key], visited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const key of symbolKeysA) {\n\t\t\t\tif (!deepEqualInner(recA[key], recB[key], visited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\t}\n}\n","import { isBuiltInObject } from \"./is-built-in\";\n\nexport type Key = string | symbol;\nexport type PathSegment = string | number | symbol;\n\nexport interface DeepOmitOptions {\n\t/**\n\t * Keys to ignore everywhere in the object tree.\n\t * Only applies to object properties, not Map/Set/TypedArray contents.\n\t */\n\treadonly ignoreKeys?: readonly Key[];\n\n\t/**\n\t * Fine-grained control: Key + path (without current key).\n\t * Example path: [\"user\", \"meta\", 0, \"data\"]\n\t */\n\treadonly ignoreKeyPredicate?: (\n\t\tkey: Key,\n\t\tpath: readonly PathSegment[],\n\t) => boolean;\n}\n\n/**\n * Creates a deep copy of `value` with certain keys removed according to the\n * provided rules.\n *\n * Walks the object tree and skips keys that match `ignoreKeys` /\n * `ignoreKeyPredicate`. Built-in atomic types (Date, RegExp, Map, Set,\n * TypedArrays, ArrayBuffer, DataView) are cloned by type rather than walked\n * โ their internal structure has no key filtering to apply. Cycles are\n * preserved: a cycle `a โ a` clones to `a' โ a'`.\n *\n * **Prototype-pollution safety.** `__proto__` and `constructor` keys\n * encountered as *own* properties of the input (typical of `JSON.parse`\n * output) are copied as inert data properties via `Object.defineProperty`\n * so the clone graph cannot bleed into `Object.prototype`.\n *\n * **Class instances.** When the input is a class instance, the clone is\n * built via `Object.create(proto)` so the prototype is preserved, but the\n * constructor is NOT re-invoked โ so class invariants enforced by the\n * constructor are not re-checked. `deepOmit` is therefore best used for\n * comparison/serialisation (`voEqualsExcept`, `deepEqualExcept`), not as\n * a general-purpose clone for behaviour-carrying objects.\n *\n * @param value - The value to create a deep copy from\n * @param options - Options specifying which keys to ignore\n * @returns A deep copy of `value` with specified keys removed\n */\nexport function deepOmit<T>(value: T, options: DeepOmitOptions): T {\n\tconst visited = new WeakMap<object, unknown>();\n\t// Materialise ignoreKeys as a Set once so the inner loop probes O(1).\n\tconst ignoreKeys = options.ignoreKeys\n\t\t? new Set<Key>(options.ignoreKeys)\n\t\t: undefined;\n\treturn omitInternal(value, options, ignoreKeys, [], visited) as T;\n}\n\nfunction omitInternal(\n\tvalue: unknown,\n\toptions: DeepOmitOptions,\n\tignoreKeys: ReadonlySet<Key> | undefined,\n\tpath: PathSegment[],\n\tvisited: WeakMap<object, unknown>,\n): unknown {\n\tif (value === null) return value;\n\tif (typeof value !== \"object\") return value;\n\n\tconst obj = value as object;\n\n\t// Cycles: return cached clone if already visited. Use `has` (not\n\t// `cached !== undefined`) so a legitimately-undefined cached clone\n\t// would not be misclassified as \"never seen\".\n\tif (visited.has(obj)) {\n\t\treturn visited.get(obj);\n\t}\n\n\tconst tag = Object.prototype.toString.call(obj);\n\n\t// Arrays: recursively process elements\n\tif (tag === \"[object Array]\") {\n\t\tconst arr = obj as unknown[];\n\t\tconst clone: unknown[] = new Array(arr.length);\n\t\tvisited.set(obj, clone);\n\t\tfor (let i = 0; i < arr.length; i++) {\n\t\t\tpath.push(i);\n\t\t\tclone[i] = omitInternal(arr[i], options, ignoreKeys, path, visited);\n\t\t\tpath.pop();\n\t\t}\n\t\treturn clone;\n\t}\n\n\t// Built-in atomic types: clone by type rather than walk.\n\tif (isBuiltInObject(obj, tag)) {\n\t\tconst builtInClone = cloneBuiltIn(obj, tag);\n\t\tvisited.set(obj, builtInClone);\n\t\treturn builtInClone;\n\t}\n\n\t// Plain / Custom Objects: filter keys, recursively process values.\n\tconst clone = Object.create(Object.getPrototypeOf(obj));\n\tvisited.set(obj, clone);\n\n\tconst stringKeys = Object.keys(obj);\n\tconst symbolKeys = Object.getOwnPropertySymbols(obj);\n\n\tfor (const key of stringKeys) {\n\t\tif (shouldIgnoreKey(key, path, ignoreKeys, options)) continue;\n\t\tpath.push(key);\n\t\tassignOwn(\n\t\t\tclone,\n\t\t\tkey,\n\t\t\tomitInternal(\n\t\t\t\t(obj as Record<PropertyKey, unknown>)[key],\n\t\t\t\toptions,\n\t\t\t\tignoreKeys,\n\t\t\t\tpath,\n\t\t\t\tvisited,\n\t\t\t),\n\t\t);\n\t\tpath.pop();\n\t}\n\tfor (const key of symbolKeys) {\n\t\tif (shouldIgnoreKey(key, path, ignoreKeys, options)) continue;\n\t\tpath.push(key);\n\t\tassignOwn(\n\t\t\tclone,\n\t\t\tkey,\n\t\t\tomitInternal(\n\t\t\t\t(obj as Record<PropertyKey, unknown>)[key],\n\t\t\t\toptions,\n\t\t\t\tignoreKeys,\n\t\t\t\tpath,\n\t\t\t\tvisited,\n\t\t\t),\n\t\t);\n\t\tpath.pop();\n\t}\n\n\treturn clone;\n}\n\n/**\n * Assigns `value` as an OWN data property on `target` without going through\n * any inherited setter โ critically, never invokes the `__proto__` setter\n * even when `key === \"__proto__\"`. Required to defeat prototype-pollution\n * payloads that ship `__proto__` as a parsed-JSON own key.\n */\nfunction assignOwn(target: object, key: PropertyKey, value: unknown): void {\n\tObject.defineProperty(target, key, {\n\t\tvalue,\n\t\twritable: true,\n\t\tenumerable: true,\n\t\tconfigurable: true,\n\t});\n}\n\n/**\n * Clones a built-in atomic type by case. Falls back to `structuredClone`\n * for anything not explicitly enumerated (e.g. ArrayBuffer, DataView,\n * Boolean/Number/String wrappers).\n */\nfunction cloneBuiltIn(obj: object, tag: string): unknown {\n\tswitch (tag) {\n\t\tcase \"[object Date]\":\n\t\t\treturn new Date((obj as Date).getTime());\n\t\tcase \"[object RegExp]\": {\n\t\t\tconst re = obj as RegExp;\n\t\t\tconst copy = new RegExp(re.source, re.flags);\n\t\t\tcopy.lastIndex = re.lastIndex;\n\t\t\treturn copy;\n\t\t}\n\t\tcase \"[object Map]\": {\n\t\t\tconst m = obj as Map<unknown, unknown>;\n\t\t\treturn new Map(m);\n\t\t}\n\t\tcase \"[object Set]\": {\n\t\t\tconst s = obj as Set<unknown>;\n\t\t\treturn new Set(s);\n\t\t}\n\t\tdefault:\n\t\t\treturn structuredClone(obj);\n\t}\n}\n\nfunction shouldIgnoreKey(\n\tkey: Key,\n\tpath: readonly PathSegment[],\n\tignoreKeys: ReadonlySet<Key> | undefined,\n\toptions: DeepOmitOptions,\n): boolean {\n\tif (ignoreKeys?.has(key)) return true;\n\tif (options.ignoreKeyPredicate?.(key, path)) return true;\n\treturn false;\n}\n","import { deepEqual } from \"./deep-equal\";\nimport { type DeepOmitOptions, deepOmit } from \"./deep-omit\";\n\nexport type DeepEqualExceptOptions = DeepOmitOptions;\n\n/**\n * Performs a deep equality comparison between two values after omitting specified keys.\n * \n * This function first removes the specified keys from both values using `deepOmit`,\n * then performs a deep equality check using `deepEqual`.\n * \n * @param a - The first value to compare\n * @param b - The second value to compare\n * @param options - Options specifying which keys to omit before comparison\n * @returns `true` if the values are deeply equal after omitting specified keys, `false` otherwise\n * \n * @example\n * ```ts\n * const obj1 = { id: 1, name: \"Alice\", updatedAt: \"2024-01-01\" };\n * const obj2 = { id: 2, name: \"Alice\", updatedAt: \"2024-01-02\" };\n * \n * deepEqualExcept(obj1, obj2, { ignoreKeys: [\"id\", \"updatedAt\"] }); // true\n * ```\n */\nexport function deepEqualExcept(\n\ta: unknown,\n\tb: unknown,\n\toptions: DeepEqualExceptOptions,\n): boolean {\n\tconst prunedA = deepOmit(a, options);\n\tconst prunedB = deepOmit(b, options);\n\treturn deepEqual(prunedA, prunedB);\n}\n","import { deepEqual } from \"../utils/array/deep-equal\";\nimport {\n deepEqualExcept,\n type DeepEqualExceptOptions,\n} from \"../utils/array/deep-equal-except\";\nimport { err, ok, type Result } from \"@shirudo/result\";\n\n// ============================================================================\n// Functional Value Object API\n// ============================================================================\n\nexport type VO<T> = Readonly<T>;\n\n/**\n * Deep freezes an object and all its nested properties recursively, then\n * returns it. Iterates both string-keyed and symbol-keyed own properties\n * so the freeze symmetry matches `deepEqual` (which also considers symbol\n * keys). Handles circular references by tracking visited objects.\n *\n * Note: `deepFreeze` mutates its argument in place โ it sets `[[Frozen]]`\n * on the object you pass in. Callers that need to avoid touching the\n * input (e.g. `vo()`) should deep-clone first.\n */\nexport function deepFreeze<T>(obj: T, visited = new WeakSet<object>()): Readonly<T> {\n if (obj === null || typeof obj !== \"object\") {\n return obj as Readonly<T>;\n }\n if (visited.has(obj as object)) {\n return obj as Readonly<T>;\n }\n visited.add(obj as object);\n\n // Reflect.ownKeys returns both string and symbol own keys.\n const keys = Reflect.ownKeys(obj);\n for (const key of keys) {\n const value = (obj as Record<string | symbol, unknown>)[key];\n if (value !== null && typeof value === \"object\") {\n deepFreeze(value, visited);\n }\n }\n\n return Object.freeze(obj) as Readonly<T>;\n}\n\n/**\n * Creates a deeply immutable value object from the given data.\n *\n * The input is first deep-cloned with `structuredClone`, then the clone\n * is frozen โ so calling `vo(input)` never freezes the caller's own\n * object graph as a side-effect. Mutating the input afterwards does not\n * bleed into the VO.\n *\n * @example\n * ```typescript\n * const nested = { lat: 52.5, lng: 13.4 };\n * const address = vo({ street: \"Main St\", coordinates: nested });\n * address.coordinates.lat = 99; // โ Cannot assign to read-only property\n * nested.lat = 0; // โ
caller's input still mutable\n * ```\n */\nexport function vo<T>(t: T): VO<T> {\n return deepFreeze(structuredClone(t));\n}\n\n/**\n * Compares two value objects for equality based on their values.\n * Uses deep equality comparison that handles:\n * - Nested objects and arrays\n * - Primitives (including NaN)\n * - Dates, Maps, Sets, RegExp\n * - TypedArrays and DataView\n * - Symbol keys\n * - Circular references\n *\n * @param a - First value object\n * @param b - Second value object\n * @returns true if both objects have the same values, false otherwise\n *\n * @example\n * ```typescript\n * const money1 = vo({ amount: 100, currency: \"USD\" });\n * const money2 = vo({ amount: 100, currency: \"USD\" });\n * voEquals(money1, money2); // true\n *\n * const address1 = vo({\n * street: \"Main St\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * const address2 = vo({\n * street: \"Main St\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * voEquals(address1, address2); // true\n * ```\n */\nexport function voEquals<T>(a: VO<T>, b: VO<T>): boolean {\n return deepEqual(a, b);\n}\n\n/**\n * Compares two value objects for equality while ignoring specified keys.\n * Useful for comparing value objects that contain metadata or optional fields\n * that should not affect equality comparison.\n *\n * @param a - First value object\n * @param b - Second value object\n * @param options - Options specifying which keys to ignore during comparison\n * @returns true if both objects have the same values (after ignoring specified keys), false otherwise\n *\n * @example\n * ```typescript\n * // Value object with metadata\n * const address1 = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * metadata: { createdAt: \"2024-01-01\", updatedAt: \"2024-01-02\" }\n * });\n *\n * const address2 = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * metadata: { createdAt: \"2024-01-01\", updatedAt: \"2024-01-03\" }\n * });\n *\n * // Compare ignoring metadata timestamps\n * voEqualsExcept(address1, address2, {\n * ignoreKeys: [\"updatedAt\"],\n * ignoreKeyPredicate: (key, path) => path.includes(\"metadata\")\n * }); // true\n *\n * // Compare ignoring all metadata\n * voEqualsExcept(address1, address2, {\n * ignoreKeyPredicate: (key, path) => path.includes(\"metadata\")\n * }); // true\n * ```\n */\nexport function voEqualsExcept<T>(\n a: VO<T>,\n b: VO<T>,\n options: DeepEqualExceptOptions,\n): boolean {\n return deepEqualExcept(a, b, options);\n}\n\n/**\n * Creates a value object with optional validation.\n * Returns a Result type instead of throwing an error.\n *\n * @param t - The data to convert into a value object\n * @param validate - Validation function that returns true if valid\n * @param errorMessage - Optional custom error message if validation fails\n * @returns Result containing the value object if valid, or an error message if validation fails\n *\n * @example\n * ```typescript\n * const result = voWithValidation(\n * { amount: 100, currency: \"USD\" },\n * (m) => m.amount >= 0 && m.currency.length === 3,\n * \"Invalid money: amount must be non-negative and currency must be 3 characters\"\n * );\n *\n * if (result.ok) {\n * console.log(result.value); // Use the value object\n * } else {\n * console.error(result.error); // Handle validation error\n * }\n * ```\n */\nexport function voWithValidation<T>(\n t: T,\n validate: (value: T) => boolean,\n errorMessage?: string,\n): Result<VO<T>, string> {\n if (!validate(t)) {\n return err(\n errorMessage ?? `Validation failed for value object: ${JSON.stringify(t)}`,\n );\n }\n return ok(vo(t));\n}\n\n// ============================================================================\n// Class-based Value Object API\n// ============================================================================\n\n/**\n * Interface for Value Objects.\n * Value Objects are immutable and defined by their properties.\n *\n * @template T - The shape of the value object's properties\n */\nexport interface IValueObject<T extends object> {\n /**\n * The immutable properties of the value object.\n */\n readonly props: Readonly<T>;\n\n /**\n * Checks if this value object is equal to another.\n * Uses deep equality comparison on the properties.\n *\n * @param other - The other value object to compare\n * @returns true if the properties are deeply equal\n */\n equals(other: IValueObject<T>): boolean;\n\n /**\n * Creates a clone of the value object with optional property overrides.\n *\n * @param props - Optional properties to override\n * @returns A new instance of the value object\n */\n clone(props?: Partial<T>): IValueObject<T>;\n\n /**\n * Serializes the value object to its raw properties for JSON operations.\n *\n * @returns The raw properties object\n */\n toJSON(): Readonly<T>;\n}\n\n/**\n * Abstract base class for creating Value Objects.\n * Value Objects are immutable and defined by their properties.\n *\n * @template T - The shape of the value object's properties\n */\nexport abstract class ValueObject<T extends object> implements IValueObject<T> {\n public readonly props: Readonly<T>;\n\n /**\n * Creates a new ValueObject.\n * The properties are deeply frozen to ensure immutability.\n *\n * @param props - The properties of the value object\n * @example\n * ```ts\n * class Money extends ValueObject<{ amount: number; currency: string }> {\n * constructor(props: { amount: number; currency: string }) {\n * super(props);\n * }\n *\n * protected validate(props: { amount: number; currency: string }): void {\n * if (props.amount < 0) throw new Error(\"Amount cannot be negative\");\n * }\n * }\n * ```\n */\n constructor(props: T) {\n this.validate(props);\n this.props = deepFreeze({ ...props });\n }\n\n /**\n * Optional validation hook that can be overridden by subclasses.\n * Should throw an error if validation fails.\n *\n * @param props - The properties to validate\n * @throws Error if validation fails\n */\n protected validate(props: T): void {\n // Default implementation does nothing\n }\n\n /**\n * Checks if this value object is equal to another.\n * Uses deep equality comparison on the properties and checks for constructor equality.\n *\n * @param other - The other value object to compare\n * @returns true if the properties are deeply equal and constructors match\n */\n public equals(other: ValueObject<T>): boolean {\n if (other === null || other === undefined) {\n return false;\n }\n\n if (this.constructor !== other.constructor) {\n return false;\n }\n\n return deepEqual(this.props, other.props);\n }\n\n /**\n * Creates a clone of the value object with optional property overrides.\n *\n * @param props - Optional properties to override\n * @returns A new instance of the value object\n */\n public clone(props?: Partial<T>): this {\n const Constructor = this.constructor as new (props: T) => this;\n return new Constructor({ ...this.props, ...(props || {}) });\n }\n\n /**\n * Serializes the value object to its raw properties for JSON operations.\n *\n * @returns The raw properties object\n */\n public toJSON(): Readonly<T> {\n return this.props;\n }\n\n\n}\n","import { deepFreeze } from \"../value-object/value-object\";\n\n/**\n * Factory function producing a fresh, unique event identifier for each call.\n *\n * The library ships a default that uses Web Crypto `crypto.randomUUID()`\n * (works on Node 19+, modern browsers in secure contexts, Deno, Bun,\n * Cloudflare Workers, Vercel Edge, and any runtime that implements Web\n * Crypto). Note that `crypto.randomUUID()` returns **UUID v4** (purely\n * random) โ for production event stores prefer a **time-ordered** id\n * format (UUID v7 / ULID / KSUID) so B-tree indexes on the eventId\n * column stay clustered and `ORDER BY eventId` matches creation order.\n * Swap one in via `setEventIdFactory(() => uuidv7())` or `() => ulid()`.\n */\nexport type EventIdFactory = () => string;\n\nconst defaultEventIdFactory: EventIdFactory = () => crypto.randomUUID();\nlet currentEventIdFactory: EventIdFactory = defaultEventIdFactory;\n\n/**\n * Replaces the global event-id factory used by `createDomainEvent` and\n * `createDomainEventWithMetadata`. Call once during application bootstrap,\n * for example:\n *\n * ```ts\n * import { ulid } from \"ulid\";\n * import { setEventIdFactory } from \"@shirudo/ddd-kit\";\n *\n * setEventIdFactory(() => ulid());\n * ```\n *\n * The per-call `options.eventId` override always wins over this factory.\n *\n * **Module-scoped โ last setter wins.** The factory lives as a single\n * module variable; importing two libraries that both call this races on\n * load order. For multi-tenant request isolation (e.g. one factory per\n * tenant in a single Worker invocation) **prefer the per-call\n * `options.eventId`** instead of mutating the global. Same caveat applies\n * to `setClockFactory`.\n */\nexport function setEventIdFactory(factory: EventIdFactory): void {\n\tcurrentEventIdFactory = factory;\n}\n\n/**\n * Restores the default event-id factory (`crypto.randomUUID()`).\n * Intended for use in test `afterEach` hooks.\n */\nexport function resetEventIdFactory(): void {\n\tcurrentEventIdFactory = defaultEventIdFactory;\n}\n\n/**\n * Clock function producing a fresh `Date` for each call. The library\n * defaults to `() => new Date()`; override globally via `setClockFactory`\n * for deterministic event-sourcing tests, time-travel debugging, or any\n * scenario where `occurredAt` must be reproducible.\n */\nexport type ClockFactory = () => Date;\n\nconst defaultClockFactory: ClockFactory = () => new Date();\nlet currentClockFactory: ClockFactory = defaultClockFactory;\n\n/**\n * Replaces the global clock factory used by `createDomainEvent` and\n * `createDomainEventWithMetadata`. Call once during application bootstrap\n * (or per-test in deterministic test suites):\n *\n * ```ts\n * import { setClockFactory } from \"@shirudo/ddd-kit\";\n *\n * setClockFactory(() => new Date(\"2026-01-01T00:00:00Z\"));\n * ```\n *\n * The per-call `options.occurredAt` override always wins over this\n * factory. Symmetric to `setEventIdFactory`.\n */\nexport function setClockFactory(factory: ClockFactory): void {\n\tcurrentClockFactory = factory;\n}\n\n/**\n * Restores the default clock factory (`() => new Date()`).\n * Intended for use in test `afterEach` hooks.\n */\nexport function resetClockFactory(): void {\n\tcurrentClockFactory = defaultClockFactory;\n}\n\n/**\n * Metadata associated with a domain event for traceability and correlation.\n * Used in event-driven architectures to track event flow across services.\n */\nexport interface EventMetadata {\n\t/**\n\t * Correlation ID for tracing events across multiple services/components.\n\t * Typically used to group related events in a distributed system.\n\t */\n\tcorrelationId?: string;\n\n\t/**\n\t * Causation ID referencing the event or command that caused this event.\n\t * Used to build event chains and understand causality.\n\t */\n\tcausationId?: string;\n\n\t/**\n\t * User ID of the person or system that triggered the event.\n\t */\n\tuserId?: string;\n\n\t/**\n\t * Source service or component that produced the event.\n\t */\n\tsource?: string;\n\n\t/**\n\t * Additional custom metadata fields.\n\t * Allows extensibility for domain-specific metadata.\n\t */\n\t[key: string]: unknown;\n}\n\n/**\n * Domain Event represents something meaningful that happened in the domain.\n * Events are immutable and carry information about what occurred.\n *\n * @template T - The event type name (e.g., \"OrderCreated\")\n * @template P - The event payload type\n */\nexport interface DomainEvent<T extends string, P = void> {\n\t/**\n\t * Unique identifier for this specific event instance. Used by idempotent\n\t * consumers, outbox dispatch tracking, and as the target of\n\t * `metadata.causationId`. Defaults to `crypto.randomUUID()` if not\n\t * supplied.\n\t */\n\teventId: string;\n\n\t/**\n\t * The type of the event, used for routing and handling.\n\t */\n\ttype: T;\n\n\t/**\n\t * Identifier of the aggregate that produced the event. Optional at the\n\t * library level โ set it whenever the producing aggregate is known so\n\t * downstream subscribers, outboxes, and projections can scope by entity.\n\t */\n\taggregateId?: string;\n\n\t/**\n\t * Name of the aggregate type that produced the event (e.g. \"Order\").\n\t * Pairs with `aggregateId` to fully qualify the source aggregate.\n\t */\n\taggregateType?: string;\n\n\t/**\n\t * The event payload containing the domain data. The field is always\n\t * present; its value is `undefined` when `P` is `void`.\n\t */\n\tpayload: P;\n\n\t/**\n\t * Timestamp when the event occurred.\n\t */\n\toccurredAt: Date;\n\n\t/**\n\t * Event schema version for handling schema evolution.\n\t * Required for safe schema migration in event-sourced systems.\n\t * Use 1 for the initial schema version.\n\t */\n\tversion: number;\n\n\t/**\n\t * Optional metadata for traceability, correlation, and auditing.\n\t * Includes correlationId, causationId, userId, source, and custom fields.\n\t */\n\tmetadata?: EventMetadata;\n}\n\n/**\n * Shared option bag for the `createDomainEvent*` factories.\n */\nexport interface CreateDomainEventOptions {\n\t/**\n\t * Override for the auto-generated `eventId`. Pass an existing id (for\n\t * replay, tests, or deterministic event sourcing) instead of letting the\n\t * factory call `crypto.randomUUID()`.\n\t */\n\teventId?: string;\n\n\t/**\n\t * Identifier of the aggregate that produced the event.\n\t */\n\taggregateId?: string;\n\n\t/**\n\t * Name of the aggregate type that produced the event.\n\t */\n\taggregateType?: string;\n\n\t/**\n\t * Override for the auto-generated `occurredAt` timestamp.\n\t */\n\toccurredAt?: Date;\n\n\t/**\n\t * Override for the default schema version (1).\n\t */\n\tversion?: number;\n\n\t/**\n\t * Event metadata โ correlation, causation, user, source, custom fields.\n\t */\n\tmetadata?: EventMetadata;\n}\n\n/**\n * Creates a domain event with default values.\n * Sets occurredAt to current date and version to 1 if not provided.\n *\n * @param type - The event type\n * @param payload - The event payload\n * @param options - Optional event configuration\n * @returns A domain event\n *\n * @example\n * ```typescript\n * const event = createDomainEvent(\"OrderCreated\", { orderId: \"123\" });\n * ```\n */\nexport function createDomainEvent<T extends string>(\n\ttype: T,\n\tpayload?: undefined,\n\toptions?: CreateDomainEventOptions,\n): DomainEvent<T, void>;\nexport function createDomainEvent<T extends string, P>(\n\ttype: T,\n\tpayload: P,\n\toptions?: CreateDomainEventOptions,\n): DomainEvent<T, P>;\nexport function createDomainEvent<T extends string, P>(\n\ttype: T,\n\tpayload?: P,\n\toptions?: CreateDomainEventOptions,\n): DomainEvent<T, P> {\n\tconst event: DomainEvent<T, P> = {\n\t\teventId: options?.eventId ?? currentEventIdFactory(),\n\t\ttype,\n\t\taggregateId: options?.aggregateId,\n\t\taggregateType: options?.aggregateType,\n\t\tpayload: payload as P,\n\t\toccurredAt: options?.occurredAt ?? currentClockFactory(),\n\t\tversion: options?.version ?? 1,\n\t\tmetadata: options?.metadata,\n\t};\n\t// Deep-freeze so a mutating subscriber cannot poison subsequent\n\t// handlers โ events are facts of the past and must be immutable\n\t// (Vernon, IDDD ยง8).\n\treturn deepFreeze(event) as DomainEvent<T, P>;\n}\n\n/**\n * Creates a domain event with metadata for traceability.\n * Convenience function for creating events with correlation and causation IDs.\n *\n * @example\n * ```typescript\n * const event = createDomainEventWithMetadata(\n * \"OrderCreated\",\n * { orderId: \"123\" },\n * { correlationId: \"corr-123\", causationId: \"cmd-456\", userId: \"user-789\" }\n * );\n * ```\n */\nexport function createDomainEventWithMetadata<T extends string, P>(\n\ttype: T,\n\tpayload: P,\n\tmetadata: EventMetadata,\n\toptions?: Omit<CreateDomainEventOptions, \"metadata\">,\n): DomainEvent<T, P> {\n\treturn createDomainEvent(type, payload, {\n\t\t...options,\n\t\tmetadata,\n\t});\n}\n\n/**\n * Copies metadata from a source event to a new event.\n * Useful for maintaining correlation chains in event-driven architectures.\n *\n * @example\n * ```typescript\n * const newEvent = createDomainEvent(\n * \"OrderShipped\",\n * { orderId: \"123\" },\n * { metadata: copyMetadata(previousEvent, { causationId: previousEvent.type }) }\n * );\n * ```\n */\nexport function copyMetadata(\n\tsourceEvent: DomainEvent<string, unknown>,\n\tadditionalMetadata?: Partial<EventMetadata>,\n): EventMetadata {\n\treturn {\n\t\t...(sourceEvent.metadata ?? {}),\n\t\t...(additionalMetadata ?? {}),\n\t};\n}\n\n/**\n * Merges multiple metadata objects into one.\n * Later metadata objects override earlier ones for the same keys.\n *\n * @example\n * ```typescript\n * const metadata = mergeMetadata(\n * { correlationId: \"corr-123\" },\n * { userId: \"user-456\" },\n * { source: \"order-service\" }\n * );\n * ```\n */\nexport function mergeMetadata(\n\t...metadataObjects: Array<EventMetadata | undefined>\n): EventMetadata {\n\treturn Object.assign({}, ...metadataObjects.filter(Boolean));\n}\n","import type { Id } from \"../core/id\";\n\n// Re-export domain event types for convenience\nexport * from \"./domain-event\";\n\n// Re-export interfaces from their respective files\nexport type { IAggregateRoot } from \"./aggregate-root\";\nexport type { IEventSourcedAggregate } from \"./event-sourced-aggregate\";\n\n// --- Aggregate types ---\n\nexport type Version = number & { readonly __v: true };\n\n/**\n * Snapshot of an aggregate state at a specific point in time.\n * Used for optimizing event replay by starting from a snapshot\n * instead of replaying all events from the beginning.\n *\n * @template TState - The type of the aggregate state\n */\nexport interface AggregateSnapshot<TState> {\n\t/**\n\t * The state of the aggregate at the time of the snapshot.\n\t */\n\tstate: TState;\n\n\t/**\n\t * The version of the aggregate when the snapshot was taken.\n\t */\n\tversion: Version;\n\n\t/**\n\t * Timestamp when the snapshot was created.\n\t */\n\tsnapshotAt: Date;\n}\n\n/**\n * Checks if two aggregates are at the same version (same ID and version).\n * Useful for optimistic concurrency control checks.\n *\n * Note: Two aggregates with the same ID ARE the same aggregate (identity).\n * This function checks if they are at the same version โ i.e., no concurrent modification.\n *\n * @example\n * ```typescript\n * const before = await repository.getById(id);\n * // ... some operations ...\n * const after = await repository.getById(id);\n *\n * if (!sameVersion(before, after)) {\n * throw new Error(\"Aggregate was modified by another process\");\n * }\n * ```\n */\nexport function sameVersion<TId extends Id<string>>(\n\ta: { id: TId; version: Version },\n\tb: { id: TId; version: Version },\n): boolean {\n\treturn a.id === b.id && a.version === b.version;\n}\n","/**\n * Entity utilities and interfaces for Domain-Driven Design.\n *\n * In Domain-Driven Design, there are two types of entities:\n *\n * 1. **Aggregate Root Entity**: The parent Entity of an aggregate.\n * - Has identity (id), state, and version\n * - Implemented by classes extending `AggregateRoot` or `EventSourcedAggregate`\n * - Represents the aggregate externally\n * - Loaded/saved through repositories\n *\n * 2. **Child Entities**: Entities within an aggregate.\n * - Have identity (id) and state, but no own version\n * - Can extend `EntityBase<TState, TId>` for class-based entities\n * - Or use functional style with `Identifiable<TId> & TProps`\n * - Exist only within the aggregate boundary\n * - Versioned through the Aggregate Root\n * - Cannot be referenced directly from outside the aggregate\n *\n * This module provides:\n * - `EntityBase<TState, TId>` - Base class for entities with state\n * - `Entity<TId>` - Simple class for entities without state management\n * - `Identifiable<TId>` - Minimal interface for objects with id\n * - Helper functions for working with collections of entities\n *\n * @example\n * ```typescript\n * // Class-based child entity with logic\n * class OrderItem extends EntityBase<OrderItemState, ItemId> {\n * constructor(id: ItemId, initialState: OrderItemState) {\n * super(id, initialState);\n * }\n *\n * updateQuantity(quantity: number): void {\n * this._state = { ...this._state, quantity };\n * }\n *\n * calculateSubtotal(): number {\n * return this._state.price * this._state.quantity;\n * }\n * }\n *\n * // Functional-style child entity (simpler, no logic)\n * type OrderItem = Identifiable<ItemId> & {\n * productId: string;\n * quantity: number;\n * price: number;\n * };\n *\n * // Aggregate Root (Entity with version)\n * class Order extends AggregateRoot<OrderState, OrderId> {\n * // Order is an Aggregate Root Entity\n * // OrderState contains OrderItem child entities\n * }\n * ```\n */\nimport type { Id } from \"../core/id\";\n\n/**\n * Functional definition of an Entity via its capability โ an object is\n * identifiable if it has an `id`.\n *\n * `TId` is constrained to `Id<string>` so the brand discipline that\n * `Id<Tag>` enforces is preserved end-to-end: an `Identifiable<UserId>`\n * cannot accidentally be paired with an `Identifiable<OrderId>` or with\n * a plain `string`.\n */\nexport type Identifiable<TId extends Id<string>> = {\n\treadonly id: TId;\n};\n\n/**\n * Interface for Entities with state.\n *\n * In Domain-Driven Design, Entities have:\n * - Identity (id): Distinguishes one entity from another\n * - State: The attributes/properties of the entity\n *\n * Unlike Value Objects (which are immutable and compared by value),\n * Entities are compared by identity and can have mutable state.\n *\n * @template TId - The type of the entity identifier\n * @template TState - The type of the entity state\n */\nexport interface IEntity<TId extends Id<string>, TState> extends Identifiable<TId> {\n\t/**\n\t * Unique identifier of the entity.\n\t */\n\treadonly id: TId;\n\n\t/**\n\t * The current state of the entity.\n\t */\n\treadonly state: TState;\n}\n\n/**\n * Abstract base class for Entities with state.\n *\n * Provides:\n * - Identity management (id)\n * - State management\n * - State validation hook\n * - Immutable state access through getter\n *\n * This is the foundation for all Entities in DDD:\n * - Child Entities within aggregates can extend this\n * - Aggregate Roots extend this and add version + events\n *\n * @template TState - The type of the entity state\n * @template TId - The type of the entity identifier\n *\n * @example\n * ```typescript\n * // Child Entity within an aggregate\n * class OrderItem extends Entity<OrderItemState, ItemId> {\n * constructor(id: ItemId, initialState: OrderItemState) {\n * super(id, initialState);\n * }\n *\n * updateQuantity(quantity: number): void {\n * this._state = { ...this._state, quantity };\n * }\n * }\n * ```\n */\nexport abstract class Entity<TState, TId extends Id<string>>\n\timplements IEntity<TId, TState> {\n\tpublic readonly id: TId;\n\n\t/**\n\t * Returns the current state of the entity.\n\t *\n\t * The state object is **shallowly frozen** โ direct property writes\n\t * (`entity.state.foo = โฆ`) throw in strict mode, but writes to nested\n\t * objects (`entity.state.address.zip = โฆ`) bypass the freeze. For deep\n\t * immutability either model nested data with `vo()` (which freezes\n\t * deeply) or reach for a structural-sharing library like Immer at the\n\t * App layer. The shallow contract is intentional: deep freezing on\n\t * every state write is too expensive for hot paths, and DDD aggregates\n\t * normally treat their own state as private (`Tell, Don't Ask`).\n\t */\n\tpublic get state(): TState {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * The state is 'protected' so that only the subclass can modify it.\n\t * Subclasses can mutate this directly or use helper methods.\n\t */\n\tprotected _state: TState;\n\n\tprotected constructor(id: TId, initialState: TState) {\n\t\tif (id === null || id === undefined) {\n\t\t\tthrow new Error(\"Entity ID cannot be null or undefined\");\n\t\t}\n\t\tthis.id = id;\n\t\tthis._state = freezeShallow(initialState);\n\t\tthis.validateState(this._state);\n\t}\n\n\t/**\n\t * Optional validation hook to ensure state invariants. Called during\n\t * construction (from `Entity`'s constructor) and again on every\n\t * `setState()` call. Throw to reject invalid state.\n\t *\n\t * **โ ๏ธ Must not read subclass instance fields via `this`.** The\n\t * constructor calls `validateState(initialState)` BEFORE the subclass's\n\t * field initializers run, so `this.someField` is `undefined` at that\n\t * point โ a classic TypeScript/JavaScript constructor-ordering footgun.\n\t * The `state` argument is the single source of truth; treat the method\n\t * as pure with respect to `this`.\n\t *\n\t * If your invariants genuinely depend on per-instance configuration\n\t * that isn't part of the state, pass that configuration into the state\n\t * itself (DDD-canonical: the aggregate's state contains everything it\n\t * needs) or perform the additional check after construction in a\n\t * dedicated factory method.\n\t *\n\t * @param state - The state to validate\n\t * @throws Error (or `DomainError` subclass) if validation fails\n\t */\n\tprotected validateState(_state: TState): void {\n\t\t// Default implementation does nothing\n\t}\n\n\t/**\n\t * Sets the state of the entity.\n\t * This is a convenience method for state mutations.\n\t * Automatically validates the newState using `validateState()`.\n\t *\n\t * @param newState - The new state\n\t */\n\tprotected setState(newState: TState): void {\n\t\tthis.validateState(newState);\n\t\tthis._state = freezeShallow(newState);\n\t}\n}\n\n/**\n * Shallow-freezes `value` when it's a non-null object or array, so that\n * direct property writes throw in strict mode. Returns the value as-is for\n * primitives. Used internally by `Entity` and its subclasses to prevent\n * outside mutation of state read through the `state` getter without paying\n * the cost of a deep clone on every read.\n *\n * Exported so that sibling classes (`EventSourcedAggregate`, `AggregateRoot`)\n * can apply the same freeze when they bypass `setState` and assign\n * `this._state` directly.\n */\nexport function freezeShallow<T>(value: T): T {\n\tif (value !== null && typeof value === \"object\") {\n\t\treturn Object.freeze(value);\n\t}\n\treturn value;\n}\n\n\n/**\n * Checks if two entities have the same ID.\n * Works with any object that has an 'id' property.\n *\n * @param a - First entity\n * @param b - Second entity\n * @returns true if both entities have the same ID, false otherwise\n *\n * @example\n * ```typescript\n * const item1: OrderItem = { id: itemId1, productId: \"prod-1\", quantity: 2 };\n * const item2: OrderItem = { id: itemId2, productId: \"prod-2\", quantity: 1 };\n *\n * sameEntity(item1, item2); // false\n * sameEntity(item1, item1); // true\n * ```\n */\nexport function sameEntity<TId extends Id<string>>(a: Identifiable<TId>, b: Identifiable<TId>): boolean {\n\treturn a.id === b.id;\n}\n\n/**\n * Finds an entity by ID in a collection.\n * Returns undefined if not found.\n *\n * @param entities - Array of entities to search\n * @param id - The ID to search for\n * @returns The entity if found, undefined otherwise\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const item = findEntityById(items, itemId1);\n * // item is { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ```\n */\nexport function findEntityById<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): T | undefined {\n\treturn entities.find((entity) => entity.id === id);\n}\n\n/**\n * Checks if an entity with the given ID exists in the collection.\n *\n * @param entities - Array of entities to search\n * @param id - The ID to check for\n * @returns true if an entity with the ID exists, false otherwise\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * hasEntityId(items, itemId1); // true\n * hasEntityId(items, itemId2); // false\n * ```\n */\nexport function hasEntityId<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): boolean {\n\treturn entities.some((entity) => entity.id === id);\n}\n\n/**\n * Removes an entity with the given ID from the collection.\n * Returns a new array without the entity.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to remove\n * @returns A new array without the entity with the given ID\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const updated = removeEntityById(items, itemId1);\n * // updated is [{ id: itemId2, productId: \"prod-2\", quantity: 1 }]\n * ```\n */\nexport function removeEntityById<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): T[] {\n\treturn entities.filter((entity) => entity.id !== id);\n}\n\n/**\n * Updates an entity with the given ID in the collection.\n * Returns a new array with the updated entity.\n * If the entity is not found, returns the original array unchanged.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to update\n * @param updater - Function that takes the entity and returns the updated entity\n * @returns A new array with the updated entity\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * const updated = updateEntityById(items, itemId1, (item) => ({\n * ...item,\n * quantity: item.quantity + 1\n * }));\n * // updated is [{ id: itemId1, productId: \"prod-1\", quantity: 3 }]\n * ```\n */\nexport function updateEntityById<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n\tupdater: (entity: T) => T,\n): T[] {\n\treturn entities.map((entity) => (entity.id === id ? updater(entity) : entity));\n}\n\n/**\n * Replaces an entity with the given ID in the collection.\n * Returns a new array with the replaced entity.\n * If the entity is not found, returns the original array unchanged.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to replace\n * @param replacement - The replacement entity\n * @returns A new array with the replaced entity\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * const updated = replaceEntityById(items, itemId1, {\n * id: itemId1,\n * productId: \"prod-1\",\n * quantity: 5\n * });\n * ```\n */\nexport function replaceEntityById<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n\treplacement: T,\n): T[] {\n\treturn entities.map((entity) => (entity.id === id ? replacement : entity));\n}\n\n/**\n * Extracts all IDs from a collection of entities.\n *\n * @param entities - Array of entities\n * @returns Array of entity IDs\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const ids = entityIds(items);\n * // ids is [itemId1, itemId2]\n * ```\n */\nexport function entityIds<TId extends Id<string>, T extends Identifiable<TId>>(entities: T[]): TId[] {\n\treturn entities.map((entity) => entity.id);\n}\n\n","import type { Id } from \"../core/id\";\nimport { Entity, freezeShallow } from \"../entity/entity\";\nimport type {\n\tAggregateSnapshot,\n\tVersion,\n} from \"./aggregate\";\n\n/**\n * Marker interface for Aggregate Roots.\n *\n * In Domain-Driven Design, an Aggregate Root is an Entity (the parent Entity of the aggregate).\n * It represents the aggregate externally and is the only object that external code\n * is allowed to hold references to. All access to child entities within the aggregate\n * must go through the Aggregate Root.\n *\n * An Aggregate consists of:\n * - One Aggregate Root (Entity with id + version)\n * - Optional child entities (Entities with id + state, but no own version)\n * - Optional value objects\n *\n * The Aggregate Root has identity (id), state, and version for optimistic concurrency control.\n * Child entities exist only within the aggregate boundary and are versioned through\n * the Aggregate Root.\n *\n * @template TId - The type of the aggregate root identifier\n *\n * @example\n * ```typescript\n * class Order extends AggregateRoot<OrderState, OrderId> implements IAggregateRoot<OrderId> {\n * // Order is an Aggregate Root (an Entity with version)\n * // OrderState contains child entities (e.g., OrderItem) and value objects\n * }\n * ```\n */\nexport interface IAggregateRoot<TId extends Id<string>> {\n\t/**\n\t * Unique identifier of the aggregate root entity.\n\t */\n\treadonly id: TId;\n\n\t/**\n\t * Version number for optimistic concurrency control.\n\t * Incremented on each state change to detect concurrent modifications.\n\t * This version applies to the entire aggregate, including all child entities.\n\t */\n\treadonly version: Version;\n\n\t/**\n\t * Post-save hook: a `Repository.save()` implementation calls this with\n\t * the persisted version after a successful write to push the new\n\t * version back into the aggregate and clear any recorded domain events\n\t * (they are now safely on the write side / in the outbox).\n\t *\n\t * Required by the interface so a Repository implementation can call it\n\t * via the published `IAggregateRoot` contract without taking the\n\t * abstract class as a compile-time dependency.\n\t *\n\t * @param version - The version assigned by the persistence layer\n\t */\n\tmarkPersisted(version: Version): void;\n}\n\n/**\n * Configuration options for AggregateRoot behavior.\n */\nexport interface AggregateConfig {\n\t/**\n\t * Whether `setState()` should bump the version automatically.\n\t *\n\t * Defaults to **`false`** for `AggregateRoot` โ because `setState()`\n\t * already takes an explicit `bumpVersion` argument per call, so adding\n\t * an \"always bump\" config on top would be redundant. Keep it `false`\n\t * unless you have a subclass that never passes `bumpVersion` and you\n\t * want every state change to advance the version anyway.\n\t *\n\t * (Contrast with `EventSourcedAggregate`, which defaults this to\n\t * `true` because every event-sourced state change is per definition a\n\t * versioned commit.)\n\t */\n\tautoVersionBump?: boolean;\n}\n\n/**\n * Base class for Aggregate Roots without Event Sourcing.\n *\n * In DDD (Evans), an Aggregate is a cluster of objects โ root entity, child entities,\n * and value objects โ treated as a unit for consistency. The **Aggregate Root** is the\n * root entity that represents the aggregate externally and is the only entry point\n * for external code. This class serves as both: it IS the root entity and it contains\n * the aggregate state (`TState`) which holds child entities and value objects.\n *\n * Provides:\n * - Identity (id) and state management (via `Entity`)\n * - Version management for optimistic concurrency control\n * - Domain event tracking for side-effects\n * - Snapshot support for performance optimization\n *\n * All changes to child entities within `TState` are versioned through this root.\n * Use `setState()` for state mutations to ensure invariant validation.\n *\n * For event sourcing, use `EventSourcedAggregate` instead.\n *\n * @template TState - The type of the aggregate state (contains child entities and value objects)\n * @template TId - The type of the aggregate root identifier\n * @template TEvent - The type of domain events recorded by this aggregate (defaults to unknown)\n *\n * @example\n * ```typescript\n * // Order is an Aggregate Root (an Entity with version)\n * class Order extends AggregateRoot<OrderState, OrderId> {\n * constructor(id: OrderId, initialState: OrderState) {\n * super(id, initialState);\n * }\n *\n * confirm(): void {\n * this.setState({ ...this.state, status: \"confirmed\" }, true);\n * }\n * }\n * ```\n */\nexport abstract class AggregateRoot<\n\tTState,\n\tTId extends Id<string>,\n\tTEvent = never,\n>\n\textends Entity<TState, TId>\n\timplements IAggregateRoot<TId> {\n\tprivate _version: Version = 0 as Version;\n\n\tpublic get version(): Version {\n\t\treturn this._version;\n\t}\n\n\tprotected setVersion(version: Version): void {\n\t\tthis._version = version;\n\t}\n\n\tprivate readonly _config: AggregateConfig;\n\tprivate readonly _autoVersionBump: boolean;\n\tprivate _domainEvents: TEvent[] = [];\n\n\t/**\n\t * Returns a read-only list of domain events recorded by this aggregate.\n\t * These events are side-effects of state changes.\n\t */\n\tpublic get domainEvents(): ReadonlyArray<TEvent> {\n\t\treturn Object.freeze(this._domainEvents.slice());\n\t}\n\n\t/**\n\t * Clears the list of recorded domain events.\n\t * Call this after dispatching the events.\n\t */\n\tpublic clearDomainEvents(): void {\n\t\tthis._domainEvents = [];\n\t}\n\n\t/**\n\t * Post-save hook called by a `Repository.save()` implementation to push\n\t * the persisted version back into the in-memory aggregate and clear the\n\t * recorded domain events (they are now safely on the write side / in\n\t * the outbox).\n\t *\n\t * Use this so `save()` can keep its `Promise<void>` return type: the\n\t * caller holds the aggregate reference, which is up to date after this\n\t * call.\n\t */\n\tpublic markPersisted(version: Version): void {\n\t\tthis.setVersion(version);\n\t\tthis._domainEvents = [];\n\t}\n\n\t/**\n\t * Mutates state and records the resulting domain events in the\n\t * **canonical record-after-mutation order**. Use this instead of calling\n\t * `setState` + `addDomainEvent` separately and you cannot trip the\n\t * \"event for a fact that never happened\" footgun.\n\t *\n\t * Order of operations:\n\t * 1. `setState(newState, true)` โ runs `validateState` first.\n\t * If it throws, the method propagates and **no event is recorded\n\t * and no version is bumped**.\n\t * 2. Each event in `events` is appended via `addDomainEvent`.\n\t *\n\t * `commit()` **always bumps the version**, regardless of the aggregate's\n\t * `autoVersionBump` config. Recording a domain event implies \"something\n\t * happened that the outside world cares about\", and optimistic-\n\t * concurrency callers must see a fresh version every time. The config\n\t * still governs the un-coupled `setState` path. If you need to mutate\n\t * state without bumping (e.g. cosmetic caches), call `setState(newState,\n\t * false)` and skip `commit` entirely.\n\t *\n\t * `events` accepts a single event or an array. Omit it (or pass `[]`)\n\t * for state-only mutations.\n\t *\n\t * @example\n\t * ```ts\n\t * confirm(): void {\n\t * if (this.state.status === \"confirmed\") {\n\t * throw new OrderAlreadyConfirmedError(this.id);\n\t * }\n\t * this.commit(\n\t * { ...this.state, status: \"confirmed\" },\n\t * { type: \"OrderConfirmed\", orderId: this.id },\n\t * );\n\t * }\n\t * ```\n\t *\n\t * `EventSourcedAggregate.apply()` enforces the same ordering\n\t * structurally; `commit()` is the opt-in equivalent on `AggregateRoot`,\n\t * where `setState` and `addDomainEvent` are otherwise decoupled and the\n\t * ordering is convention-only.\n\t *\n\t * @param newState - The new state (validated by `validateState`)\n\t * @param events - One event, an array of events, or none (default)\n\t */\n\tprotected commit(\n\t\tnewState: TState,\n\t\tevents: TEvent | readonly TEvent[] = [],\n\t): void {\n\t\tthis.setState(newState, true);\n\t\tconst list: readonly TEvent[] = Array.isArray(events)\n\t\t\t? events\n\t\t\t: [events as TEvent];\n\t\tfor (const ev of list) {\n\t\t\tthis.addDomainEvent(ev);\n\t\t}\n\t}\n\n\tprotected constructor(\n\t\tid: TId,\n\t\tinitialState: TState,\n\t\tconfig?: AggregateConfig,\n\t) {\n\t\tsuper(id, initialState);\n\t\tthis._config = config ?? {};\n\t\tthis._autoVersionBump = this._config.autoVersionBump ?? false;\n\t}\n\n\t/**\n\t * Records a domain event for later publication.\n\t *\n\t * **Ordering: record AFTER state mutation.** Vernon (IDDD ยง8) is\n\t * explicit: a domain event describes something that has just happened\n\t * to the aggregate โ its existence implies the state change already\n\t * occurred. Concretely:\n\t *\n\t * ```ts\n\t * confirm(): void {\n\t * if (this.state.status === \"confirmed\") {\n\t * throw new OrderAlreadyConfirmedError(this.id);\n\t * }\n\t * this.setState({ ...this.state, status: \"confirmed\" }, true);\n\t * this.addDomainEvent({ type: \"OrderConfirmed\", orderId: this.id });\n\t * // โ post-mutation. The event represents the committed fact.\n\t * }\n\t * ```\n\t *\n\t * Recording before mutation is a footgun: if a subsequent invariant\n\t * check throws, the event has already been queued but the state never\n\t * actually changed โ consumers see an event for a fact that did not\n\t * happen.\n\t *\n\t * `EventSourcedAggregate.apply()` enforces this ordering structurally;\n\t * `AggregateRoot` leaves it as a convention because the state-mutation\n\t * path (`setState`) is decoupled from event recording.\n\t *\n\t * @param event - The domain event to record\n\t */\n\tprotected addDomainEvent(event: TEvent): void {\n\t\tthis._domainEvents.push(event);\n\t}\n\n\t/**\n\t * Manually bumps the aggregate version.\n\t * Call this after state changes for Optimistic Concurrency Control.\n\t *\n\t * If `autoVersionBump` is enabled, this is called automatically\n\t * when using `setState()`.\n\t */\n\tprotected bumpVersion(): void {\n\t\tthis.setVersion((this._version + 1) as Version);\n\t}\n\n\t/**\n\t * Sets the state and optionally bumps the version automatically.\n\t * This is a convenience method for state mutations.\n\t * Automatically validates the newState using `validateState()`.\n\t * Overrides Entity.setState to add version bumping.\n\t *\n\t * @param newState - The new state\n\t * @param bumpVersion - Whether to bump the version (defaults to autoVersionBump config)\n\t */\n\tprotected setState(\n\t\tnewState: TState,\n\t\tbumpVersion?: boolean,\n\t): void {\n\t\tsuper.setState(newState);\n\t\tconst shouldBump = bumpVersion ?? this._autoVersionBump;\n\t\tif (shouldBump) {\n\t\t\tthis.bumpVersion();\n\t\t}\n\t}\n\n\t/**\n\t * Creates a snapshot of the current aggregate state.\n\t * Useful for performance optimization, backup/restore, and audit trails.\n\t *\n\t * @returns A snapshot containing the current state and version\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = aggregate.createSnapshot();\n\t * await snapshotRepository.save(aggregate.id, snapshot);\n\t * ```\n\t */\n\tpublic createSnapshot(): AggregateSnapshot<TState> {\n\t\treturn {\n\t\t\tstate: structuredClone(this._state),\n\t\t\tversion: this.version,\n\t\t\tsnapshotAt: new Date(),\n\t\t};\n\t}\n\n\t/**\n\t * Restores the aggregate from a snapshot.\n\t * This is useful for loading aggregates from snapshots instead of\n\t * rebuilding them from scratch.\n\t * Validates the restored state.\n\t *\n\t * @param snapshot - The snapshot to restore from\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = await snapshotRepository.getLatest(aggregateId);\n\t * aggregate.restoreFromSnapshot(snapshot);\n\t * ```\n\t */\n\tpublic restoreFromSnapshot(snapshot: AggregateSnapshot<TState>): void {\n\t\tthis.validateState(snapshot.state);\n\t\tthis._state = freezeShallow(snapshot.state);\n\t\tthis.setVersion(snapshot.version);\n\t}\n}\n","/**\n * Abstract base for all domain-layer exceptions in ddd-kit.\n *\n * Domain methods throw `DomainError`-derived exceptions when invariants are\n * violated. Consumers derive their own concrete errors from this base\n * (e.g. `OrderAlreadyShippedError extends DomainError`) so that domain\n * failures have sprechende names and can be caught via `instanceof`.\n *\n * The library itself uses this base only for its own internal errors\n * (`MissingHandlerError`, `AggregateNotFoundError`) โ everything else\n * is consumer territory.\n */\nexport abstract class DomainError extends Error {\n\tconstructor(message: string, options?: ErrorOptions) {\n\t\tsuper(message, options);\n\t\tthis.name = new.target.name;\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Thrown by `EventSourcedAggregate.apply()` when no handler is registered\n * for the given event type. Indicates a missing entry in the aggregate's\n * `handlers` map โ a programming error in the aggregate definition.\n */\nexport class MissingHandlerError extends DomainError {\n\tconstructor(public readonly eventType: string) {\n\t\tsuper(`Missing handler for event type: ${eventType}`);\n\t}\n}\n\n/**\n * Thrown by `IRepository.getByIdOrFail()` when an aggregate with the given\n * id does not exist. Use the nullable variant `getById()` if \"not found\"\n * is an expected outcome.\n */\nexport class AggregateNotFoundError extends DomainError {\n\tconstructor(\n\t\tpublic readonly aggregateType: string,\n\t\tpublic readonly id: string,\n\t) {\n\t\tsuper(`Aggregate not found: ${aggregateType}(${id})`);\n\t}\n}\n\n/**\n * Thrown by `IRepository.save()` when the aggregate's expected version does\n * not match the version currently persisted โ i.e. another writer updated\n * the aggregate concurrently. The canonical DDD optimistic-concurrency\n * signal; callers typically reload, re-apply the use case, and retry.\n */\nexport class ConcurrencyConflictError extends DomainError {\n\tconstructor(\n\t\tpublic readonly aggregateType: string,\n\t\tpublic readonly aggregateId: string,\n\t\tpublic readonly expectedVersion: number,\n\t\tpublic readonly actualVersion: number,\n\t) {\n\t\tsuper(\n\t\t\t`Concurrency conflict on ${aggregateType}(${aggregateId}): expected version ${expectedVersion}, actual ${actualVersion}`,\n\t\t);\n\t}\n}\n","import { err, ok, type Result } from \"@shirudo/result\";\nimport type { Id } from \"../core/id\";\nimport { DomainError, MissingHandlerError } from \"../core/errors\";\nimport { Entity, freezeShallow } from \"../entity/entity\";\nimport type { IAggregateRoot } from \"./aggregate-root\";\nimport type { DomainEvent } from \"./domain-event\";\nimport type {\n\tAggregateSnapshot,\n\tVersion,\n} from \"./aggregate\";\n\n/**\n * Interface for Event-Sourced Aggregate Roots.\n * Defines the contract for aggregates that manage state changes via event sourcing.\n *\n * @template TId - The type of the aggregate root identifier\n * @template TEvent - The union type of all domain events\n */\nexport interface IEventSourcedAggregate<\n\tTId extends Id<string>,\n\tTEvent extends DomainEvent<string, unknown>,\n> extends IAggregateRoot<TId> {\n\t/**\n\t * Returns a read-only list of new, not-yet-persisted events.\n\t */\n\treadonly pendingEvents: ReadonlyArray<TEvent>;\n\n\t/**\n\t * Reconstitutes the aggregate from an event history. Returns `Result`\n\t * because event-stream corruption is an expected recoverable failure\n\t * at the infrastructure boundary.\n\t *\n\t * @param history - An ordered list of past events\n\t */\n\tloadFromHistory(history: TEvent[]): Result<void, DomainError>;\n\n\t/**\n\t * Clears the list of pending events.\n\t */\n\tclearPendingEvents(): void;\n\n\t/**\n\t * Checks if the aggregate has any pending events.\n\t */\n\thasPendingEvents(): boolean;\n\n\t/**\n\t * Returns the number of pending events.\n\t */\n\tgetEventCount(): number;\n\n\t/**\n\t * Returns the latest pending event, if any.\n\t */\n\tgetLatestEvent(): TEvent | undefined;\n}\n\ntype Handler<TState, TEvent> = (state: TState, event: TEvent) => TState;\n\n/**\n * Configuration options for EventSourcedAggregate behavior.\n */\nexport interface EventSourcedAggregateConfig {\n\t/**\n\t * Whether `apply()` should bump the version per event.\n\t *\n\t * Defaults to **`true`** for `EventSourcedAggregate` โ each applied\n\t * event is by definition a versioned state change, so the canonical\n\t * event-sourcing pattern is \"one event = one version bump\". Set to\n\t * `false` only if your event store assigns version numbers itself\n\t * and you want the aggregate to track them via `bumpVersion()` /\n\t * `setVersion()` calls instead.\n\t *\n\t * (Contrast with `AggregateRoot`, which defaults this to `false`\n\t * because its `setState()` already takes a per-call `bumpVersion`\n\t * argument.)\n\t */\n\tautoVersionBump?: boolean;\n}\n\n/**\n * Base class for Event-Sourced Aggregate Roots (Vernon, IDDD Chapter 8).\n *\n * Like `AggregateRoot`, this is both the root entity and the aggregate boundary.\n * The difference is persistence: state is derived from events, not stored directly.\n * Events are the single source of truth โ all state changes go through `apply()` โ handler.\n *\n * Extends `Entity` directly (not `AggregateRoot`) so that `setState()` and\n * `addDomainEvent()` are not available. This enforces the event sourcing pattern\n * at the type level โ there is no way to mutate state without going through an event handler.\n *\n * `apply()` and `validateEvent()` throw `DomainError`-derived exceptions on\n * invariant violations. Subclasses override `validateEvent()` to throw their\n * own concrete subclasses (e.g. `OrderAlreadyConfirmedError`). Only the\n * infrastructure-boundary methods (`loadFromHistory`,\n * `restoreFromSnapshotWithEvents`) return `Result` โ they catch `DomainError`\n * during replay so callers can react to corrupted event streams without\n * try/catch.\n *\n * @template TState - The type of the aggregate state (contains child entities and value objects)\n * @template TEvent - The union type of all domain events\n * @template TId - The type of the aggregate root identifier\n *\n * @example\n * ```typescript\n * class OrderAlreadyConfirmedError extends DomainError {\n * constructor(id: OrderId) { super(`Order ${id} is already confirmed`); }\n * }\n *\n * class Order extends EventSourcedAggregate<OrderState, OrderEvent, OrderId> {\n * confirm(): void {\n * this.apply(createDomainEvent(\"OrderConfirmed\", {}));\n * }\n *\n * protected validateEvent(event: OrderEvent): void {\n * if (event.type === \"OrderConfirmed\" && this.state.status === \"confirmed\") {\n * throw new OrderAlreadyConfirmedError(this.id);\n * }\n * }\n *\n * protected readonly handlers = {\n * OrderConfirmed: (state: OrderState): OrderState => ({\n * ...state,\n * status: \"confirmed\",\n * }),\n * };\n * }\n * ```\n */\nexport abstract class EventSourcedAggregate<\n\tTState,\n\tTEvent extends DomainEvent<string, unknown>,\n\tTId extends Id<string>,\n> extends Entity<TState, TId>\n\timplements IEventSourcedAggregate<TId, TEvent> {\n\n\t// --- Version management (own, not inherited from AggregateRoot) ---\n\n\tprivate _version: Version = 0 as Version;\n\n\tpublic get version(): Version {\n\t\treturn this._version;\n\t}\n\n\tprivate setVersion(version: Version): void {\n\t\tthis._version = version;\n\t}\n\n\t// --- Event tracking ---\n\n\tprivate _pendingEvents: TEvent[] = [];\n\tprivate readonly _autoVersionBump: boolean;\n\n\tpublic get pendingEvents(): ReadonlyArray<TEvent> {\n\t\treturn Object.freeze(this._pendingEvents.slice());\n\t}\n\n\tpublic clearPendingEvents(): void {\n\t\tthis._pendingEvents = [];\n\t}\n\n\t/**\n\t * Post-save hook called by a `Repository.save()` implementation to push\n\t * the persisted version back into the in-memory aggregate and clear the\n\t * pending events (they are now in the event store / outbox). Lets\n\t * `save()` keep its `Promise<void>` return type.\n\t */\n\tpublic markPersisted(version: Version): void {\n\t\tthis.setVersion(version);\n\t\tthis._pendingEvents = [];\n\t}\n\n\tprotected constructor(\n\t\tid: TId,\n\t\tinitialState: TState,\n\t\tconfig?: EventSourcedAggregateConfig,\n\t) {\n\t\tsuper(id, initialState);\n\t\tthis._autoVersionBump = config?.autoVersionBump ?? true;\n\t}\n\n\t// --- Event application ---\n\n\t/**\n\t * Validates an event before it is applied. Default is no-op.\n\t * Subclasses override to throw a concrete `DomainError` subclass when\n\t * the event violates an invariant in the current state.\n\t */\n\tprotected validateEvent(_event: TEvent): void {\n\t\t// no-op by default\n\t}\n\n\t/**\n\t * Applies an event: validates, locates the handler, computes the next\n\t * state, then commits state + pending event + version bump atomically.\n\t *\n\t * Throws `DomainError` (or a subclass) on validation failure.\n\t * Throws `MissingHandlerError` if no handler is registered for `event.type`.\n\t *\n\t * State is not mutated if any step throws โ the handler is invoked into\n\t * a local and only assigned to `_state` once all checks pass.\n\t *\n\t * The method is generic in the event tag `K`, so concrete callers\n\t * (`this.apply(orderCreated)`) narrow to the literal tag and the\n\t * dispatched handler is typed as `Handler<TState, Extract<TEvent, { type: K }>>`\n\t * โ no `as` cast required at the call site.\n\t *\n\t * @param event - The domain event to apply\n\t * @param isNew - Whether the event is new (needs persisting) or replayed from history\n\t */\n\tprotected apply<K extends TEvent[\"type\"]>(\n\t\tevent: Extract<TEvent, { type: K }>,\n\t\tisNew = true,\n\t): void {\n\t\tthis.dispatchAndCommit(event, isNew);\n\t}\n\n\t/**\n\t * Internal dispatch path used by `apply()` and the replay methods\n\t * (`loadFromHistory`, `restoreFromSnapshotWithEvents`). The replay loop\n\t * iterates over `TEvent[]` and therefore cannot supply a narrowed `K`\n\t * generic, so this helper accepts `TEvent` and the discriminator is\n\t * resolved via the (statically-sound) `handlers` map.\n\t */\n\tprivate dispatchAndCommit(event: TEvent, isNew: boolean): void {\n\t\tthis.validateEvent(event);\n\n\t\tconst handler = this.handlers[event.type as keyof typeof this.handlers] as\n\t\t\t| Handler<TState, TEvent>\n\t\t\t| undefined;\n\t\tif (!handler) {\n\t\t\tthrow new MissingHandlerError(event.type);\n\t\t}\n\n\t\tconst nextState = handler(this._state, event);\n\n\t\t// Atomic commit: nothing above this line mutated aggregate state.\n\t\tthis._state = freezeShallow(nextState);\n\t\tif (isNew) {\n\t\t\tthis._pendingEvents.push(event);\n\t\t\tif (this._autoVersionBump) {\n\t\t\t\tthis.setVersion((this._version + 1) as Version);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Manually bumps the aggregate version.\n\t * Only needed if `autoVersionBump` is disabled.\n\t */\n\tprotected bumpVersion(): void {\n\t\tthis.setVersion((this._version + 1) as Version);\n\t}\n\n\t// --- History & Snapshots ---\n\n\t/**\n\t * Reconstitutes the aggregate from an event history. Catches `DomainError`\n\t * thrown during replay and returns it as an `Err` โ this is the\n\t * infrastructure boundary, where event-stream corruption is an expected\n\t * recoverable failure. Unexpected (non-DomainError) throws propagate.\n\t *\n\t * Version advances additively: the aggregate's pre-existing version plus\n\t * `history.length`. A fresh aggregate (v=0) loading 3 events ends at v=3;\n\t * an aggregate already at v=1 (e.g. after a creation event) loading\n\t * 2 events ends at v=3, not v=2.\n\t */\n\tpublic loadFromHistory(history: TEvent[]): Result<void, DomainError> {\n\t\tconst startVersion = this._version;\n\t\tfor (const event of history) {\n\t\t\ttry {\n\t\t\t\tthis.dispatchAndCommit(event, false);\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof DomainError) return err(e);\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\tthis.setVersion((startVersion + history.length) as Version);\n\t\treturn ok();\n\t}\n\n\tpublic hasPendingEvents(): boolean {\n\t\treturn this._pendingEvents.length > 0;\n\t}\n\n\tpublic getEventCount(): number {\n\t\treturn this._pendingEvents.length;\n\t}\n\n\tpublic getLatestEvent(): TEvent | undefined {\n\t\treturn this._pendingEvents[this._pendingEvents.length - 1];\n\t}\n\n\t/**\n\t * Creates a snapshot of the current aggregate state.\n\t */\n\tpublic createSnapshot(): AggregateSnapshot<TState> {\n\t\treturn {\n\t\t\tstate: structuredClone(this._state),\n\t\t\tversion: this._version,\n\t\t\tsnapshotAt: new Date(),\n\t\t};\n\t}\n\n\t/**\n\t * Restores the aggregate from a snapshot and applies events that occurred\n\t * after. Same infrastructure-boundary semantics as `loadFromHistory`:\n\t * catches `DomainError` and returns it as an `Err`; non-domain throws\n\t * propagate.\n\t *\n\t * All-or-nothing: if any event mid-stream throws a `DomainError`, the\n\t * aggregate is rolled back to its pre-call state + version. Partial\n\t * restoration is never observable to the caller.\n\t */\n\tpublic restoreFromSnapshotWithEvents(\n\t\tsnapshot: AggregateSnapshot<TState>,\n\t\teventsAfterSnapshot: TEvent[],\n\t): Result<void, DomainError> {\n\t\tconst previousState = this._state;\n\t\tconst previousVersion = this._version;\n\n\t\tthis._state = freezeShallow(snapshot.state);\n\t\tthis.setVersion(snapshot.version);\n\n\t\tfor (const event of eventsAfterSnapshot) {\n\t\t\ttry {\n\t\t\t\tthis.dispatchAndCommit(event, false);\n\t\t\t} catch (e) {\n\t\t\t\tthis._state = previousState;\n\t\t\t\tthis.setVersion(previousVersion);\n\t\t\t\tif (e instanceof DomainError) return err(e);\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\n\t\tthis.setVersion((snapshot.version + eventsAfterSnapshot.length) as Version);\n\t\treturn ok();\n\t}\n\n\t/**\n\t * A map of event types to their corresponding handlers.\n\t * Subclasses MUST implement this property.\n\t */\n\tprotected abstract readonly handlers: {\n\t\t[K in TEvent[\"type\"]]: Handler<TState, Extract<TEvent, { type: K }>>;\n\t};\n}\n","import { err, type Result } from \"@shirudo/result\";\nimport type { Command, CommandHandler } from \"./command\";\n\n/**\n * Type map for command types to their return types.\n * Used to improve type inference in CommandBus.\n *\n * @example\n * ```typescript\n * type MyCommandMap = {\n * CreateOrder: OrderId;\n * CancelOrder: void;\n * };\n *\n * const bus = new CommandBus<MyCommandMap>();\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<OrderId, string> โ automatically inferred\n * ```\n */\ntype CommandTypeMap = Record<string, unknown>;\n\n/**\n * Command Bus interface for dispatching commands to their handlers.\n * Provides a centralized way to execute commands with handler registration.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * Without a type map, the return type must be specified manually or defaults to `unknown`.\n *\n * @template TMap - Optional mapping from command type strings to return types\n *\n * @example\n * ```typescript\n * // With type map (recommended) โ return type is inferred\n * type MyCommands = { CreateOrder: OrderId; CancelOrder: void };\n * const bus = new CommandBus<MyCommands>();\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<OrderId, string>\n *\n * // Without type map โ works like before\n * const bus = new CommandBus();\n * bus.register(\"CreateOrder\", createOrderHandler);\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<unknown, string>\n * ```\n */\nexport interface ICommandBus<TMap extends CommandTypeMap = CommandTypeMap> {\n\t/**\n\t * Executes a command by dispatching it to the registered handler.\n\t * When a type map is provided, the return type is inferred from the command type.\n\t *\n\t * @param command - The command to execute\n\t * @returns Result containing the success value or error message\n\t */\n\texecute<C extends Command & { type: keyof TMap & string }>(\n\t\tcommand: C,\n\t): Promise<Result<TMap[C[\"type\"]], string>>;\n\texecute<C extends Command, R>(command: C): Promise<Result<R, string>>;\n\n\t/**\n\t * Registers a handler for a specific command type.\n\t *\n\t * When `TMap` is supplied, the `commandType` argument is restricted to\n\t * its keys and the handler signature is forced to match `TMap[K]` for the\n\t * return value โ typos and wrong-typed handlers are compile errors.\n\t * Without `TMap` the registration is loose (any string key, any return\n\t * type) so the no-config path keeps working.\n\t *\n\t * @param commandType - The command type to register the handler for\n\t * @param handler - The handler function for this command type\n\t */\n\tregister<\n\t\tK extends keyof TMap & string,\n\t\tC extends Command & { type: K } = Command & { type: K },\n\t>(\n\t\tcommandType: K,\n\t\thandler: CommandHandler<C, TMap[K]>,\n\t): void;\n}\n\n/**\n * Simple in-memory command bus implementation.\n * Handlers are stored in a Map and dispatched based on command type.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * When `TMap` is provided, `execute()` infers the result type from the command type.\n * Without `TMap`, it works like before (return type defaults to `unknown` or can be specified manually).\n *\n * **Note:** This is a basic implementation suitable for development and simple use cases.\n * For production environments, consider implementing or using a more feature-rich bus that includes:\n * - Middleware/Pipeline support (logging, validation, authorization)\n * - Error handling and retry logic\n * - Timeout handling\n * - Metrics and observability\n * - Transaction management\n * - Dead letter queue support\n *\n * The `CommandHandler` type can still be used with external production-grade buses\n * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.\n *\n * @template TMap - Optional mapping from command type strings to return types\n *\n * @example\n * ```typescript\n * // With type map โ full inference\n * type Commands = { CreateOrder: OrderId; CancelOrder: void };\n * const bus = new CommandBus<Commands>();\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<OrderId, string>\n *\n * // Without type map โ same as before\n * const bus = new CommandBus();\n * bus.register(\"CreateOrder\", async (cmd) => ok(orderId));\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * ```\n */\nexport class CommandBus<TMap extends CommandTypeMap = CommandTypeMap>\n\timplements ICommandBus<TMap>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, CommandHandler<any, any>>();\n\n\tregister<\n\t\tK extends keyof TMap & string,\n\t\tC extends Command & { type: K } = Command & { type: K },\n\t>(\n\t\tcommandType: K,\n\t\thandler: CommandHandler<C, TMap[K]>,\n\t): void {\n\t\tthis.handlers.set(commandType, handler);\n\t}\n\n\tasync execute<C extends Command & { type: keyof TMap & string }>(\n\t\tcommand: C,\n\t): Promise<Result<TMap[C[\"type\"]], string>>;\n\tasync execute<C extends Command, R>(\n\t\tcommand: C,\n\t): Promise<Result<R, string>>;\n\tasync execute<C extends Command, R>(\n\t\tcommand: C,\n\t): Promise<Result<R, string>> {\n\t\tconst handler = this.handlers.get(command.type);\n\t\tif (!handler) {\n\t\t\treturn err(`No handler registered for command type: ${command.type}`);\n\t\t}\n\t\ttry {\n\t\t\treturn await handler(command);\n\t\t} catch (error) {\n\t\t\treturn err(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t);\n\t\t}\n\t}\n}\n","import type { EventBus, Outbox } from \"../events/ports\";\nimport type { TransactionScope } from \"../repo/scope\";\n\n/**\n * Helper for executing a write Use Case inside a Unit of Work.\n *\n * Order of operations:\n * 1. `fn()` runs inside `uow.transactional(...)` โ domain mutations + repo\n * writes happen here.\n * 2. `outbox.add(events)` is also inside the transaction, so events\n * persist atomically with the state change (outbox pattern).\n * 3. The transaction commits.\n * 4. **After** the commit, `bus.publish(events)` fires for the in-process\n * fast path.\n *\n * Publishing AFTER commit prevents the classic \"publish before commit\"\n * footgun: in-process subscribers can never react to events from a\n * transaction that later rolled back. If `bus.publish` itself fails, the\n * outbox still holds the events and an outbox-dispatcher will deliver them\n * (eventual consistency).\n *\n * @example\n * ```typescript\n * const result = await withCommit(\n * { outbox, bus, uow },\n * async () => {\n * const order = Order.create(customerId, items);\n * await repository.save(order);\n * return { result: order.id, events: order.domainEvents };\n * }\n * );\n * ```\n */\nexport async function withCommit<Evt extends { type: string }, R>(\n\tdeps: {\n\t\toutbox: Outbox<Evt>;\n\t\tbus?: EventBus<Evt>;\n\t\tscope: TransactionScope;\n\t},\n\tfn: () => Promise<{ result: R; events: ReadonlyArray<Evt> }>,\n): Promise<R> {\n\tconst { result, events } = await deps.scope.transactional(async () => {\n\t\tconst fnResult = await fn();\n\t\tawait deps.outbox.add(fnResult.events);\n\t\treturn fnResult;\n\t});\n\n\tif (deps.bus) {\n\t\tawait deps.bus.publish(events);\n\t}\n\n\treturn result;\n}\n","import { err, ok, type Result } from \"@shirudo/result\";\nimport type { Query, QueryHandler } from \"./query\";\n\n/**\n * Type map for query types to their return types.\n * Used to improve type inference in QueryBus.\n *\n * @example\n * ```typescript\n * type MyQueryMap = {\n * GetOrder: Order | null;\n * ListOrders: Order[];\n * };\n *\n * const bus = new QueryBus<MyQueryMap>();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<Order | null, string> โ automatically inferred\n * ```\n */\ntype QueryTypeMap = Record<string, unknown>;\n\n/**\n * Query Bus interface for dispatching queries to their handlers.\n * Provides a centralized way to execute queries with handler registration.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * Without a type map, the return type must be specified manually or defaults to `unknown`.\n *\n * @template TMap - Optional mapping from query type strings to return types\n *\n * @example\n * ```typescript\n * // With type map (recommended) โ return type is inferred\n * type MyQueries = { GetOrder: Order | null; ListOrders: Order[] };\n * const bus = new QueryBus<MyQueries>();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<Order | null, string>\n *\n * // Without type map โ works like before\n * const bus = new QueryBus();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<unknown, string>\n * ```\n */\nexport interface IQueryBus<TMap extends QueryTypeMap = QueryTypeMap> {\n\t/**\n\t * Executes a query by dispatching it to the registered handler.\n\t * When a type map is provided, the return type is inferred from the query type.\n\t *\n\t * @param query - The query to execute\n\t * @returns Result containing the query result if successful, or an error message\n\t */\n\texecute<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<Result<TMap[Q[\"type\"]], string>>;\n\texecute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;\n\n\t/**\n\t * Executes a query by dispatching it to the registered handler.\n\t * Throws an error if no handler is registered.\n\t *\n\t * @param query - The query to execute\n\t * @returns The query result\n\t * @throws Error if no handler is registered for the query type\n\t */\n\texecuteUnsafe<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<TMap[Q[\"type\"]]>;\n\texecuteUnsafe<Q extends Query, R>(query: Q): Promise<R>;\n\n\t/**\n\t * Registers a handler for a specific query type.\n\t *\n\t * When `TMap` is supplied, the `queryType` argument is restricted to its\n\t * keys and the handler signature is forced to match `TMap[K]` for the\n\t * return value โ typos and wrong-typed handlers are compile errors.\n\t * Without `TMap` the registration is loose (any string key, any return\n\t * type) so the no-config path keeps working.\n\t *\n\t * @param queryType - The query type to register the handler for\n\t * @param handler - The handler function for this query type\n\t */\n\tregister<\n\t\tK extends keyof TMap & string,\n\t\tQ extends Query & { type: K } = Query & { type: K },\n\t>(\n\t\tqueryType: K,\n\t\thandler: QueryHandler<Q, TMap[K]>,\n\t): void;\n}\n\n/**\n * Simple in-memory query bus implementation.\n * Handlers are stored in a Map and dispatched based on query type.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * When `TMap` is provided, `execute()` and `executeUnsafe()` infer the result type from the query type.\n * Without `TMap`, it works like before (return type defaults to `unknown` or can be specified manually).\n *\n * **Note:** This is a basic implementation suitable for development and simple use cases.\n * For production environments, consider implementing or using a more feature-rich bus that includes:\n * - Middleware/Pipeline support (logging, caching, rate limiting)\n * - Error handling\n * - Timeout handling\n * - Metrics and observability\n * - Query result caching\n * - Rate limiting\n *\n * The `QueryHandler` type can still be used with external production-grade buses\n * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.\n *\n * @template TMap - Optional mapping from query type strings to return types\n *\n * @example\n * ```typescript\n * // With type map โ full inference\n * type Queries = { GetOrder: Order | null; ListOrders: Order[] };\n * const bus = new QueryBus<Queries>();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<Order | null, string>\n *\n * // Without type map โ same as before\n * const bus = new QueryBus();\n * bus.register(\"GetOrder\", async (query) => repository.getById(query.orderId));\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * ```\n */\nexport class QueryBus<TMap extends QueryTypeMap = QueryTypeMap>\n\timplements IQueryBus<TMap>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, QueryHandler<any, any>>();\n\n\tregister<\n\t\tK extends keyof TMap & string,\n\t\tQ extends Query & { type: K } = Query & { type: K },\n\t>(\n\t\tqueryType: K,\n\t\thandler: QueryHandler<Q, TMap[K]>,\n\t): void {\n\t\tthis.handlers.set(queryType, handler);\n\t}\n\n\tasync execute<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<Result<TMap[Q[\"type\"]], string>>;\n\tasync execute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;\n\tasync execute<Q extends Query, R>(query: Q): Promise<Result<R, string>> {\n\t\tconst handler = this.handlers.get(query.type);\n\t\tif (!handler) {\n\t\t\treturn err(`No handler registered for query type: ${query.type}`);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await handler(query);\n\t\t\treturn ok(result);\n\t\t} catch (error) {\n\t\t\treturn err(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t);\n\t\t}\n\t}\n\n\tasync executeUnsafe<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<TMap[Q[\"type\"]]>;\n\tasync executeUnsafe<Q extends Query, R>(query: Q): Promise<R>;\n\tasync executeUnsafe<Q extends Query, R>(query: Q): Promise<R> {\n\t\tconst handler = this.handlers.get(query.type);\n\t\tif (!handler) {\n\t\t\tthrow new Error(`No handler registered for query type: ${query.type}`);\n\t\t}\n\t\treturn handler(query);\n\t}\n}\n","import type { DomainEvent } from \"../aggregate/domain-event\";\nimport type { EventBus, EventHandler, OnceOptions } from \"./ports\";\n\n/**\n * Simple in-memory event bus implementation.\n * Supports multiple subscribers per event type (pub/sub pattern).\n *\n * @template Evt - The type of domain events (must extend DomainEvent)\n *\n * @example\n * ```typescript\n * const bus = new EventBusImpl<OrderEvent>();\n *\n * bus.subscribe(\"OrderCreated\", async (event) => {\n * await sendEmail(event.payload.customerId);\n * });\n *\n * bus.subscribe(\"OrderCreated\", async (event) => {\n * await logEvent(event);\n * });\n *\n * await bus.publish([orderCreatedEvent]);\n * // Both handlers will be called\n * ```\n */\nexport class EventBusImpl<Evt extends DomainEvent<string, unknown>>\n\timplements EventBus<Evt>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, EventHandler<any>[]>();\n\n\tsubscribe<K extends Evt[\"type\"]>(\n\t\teventType: K,\n\t\thandler: EventHandler<Extract<Evt, { type: K }>>,\n\t): () => void {\n\t\tconst type = eventType;\n\t\tif (!this.handlers.has(type)) {\n\t\t\tthis.handlers.set(type, []);\n\t\t}\n\t\tconst handlersForType = this.handlers.get(type)!;\n\t\tconst casted = handler as EventHandler<Evt>;\n\t\thandlersForType.push(casted);\n\n\t\t// Return unsubscribe โ removes exactly this subscription, even if the\n\t\t// same handler reference was subscribed multiple times (each call to\n\t\t// subscribe gets its own unsubscribe).\n\t\tlet removed = false;\n\t\treturn () => {\n\t\t\tif (removed) return;\n\t\t\tconst idx = handlersForType.indexOf(casted);\n\t\t\tif (idx !== -1) {\n\t\t\t\thandlersForType.splice(idx, 1);\n\t\t\t\tremoved = true;\n\t\t\t}\n\t\t\tif (handlersForType.length === 0) {\n\t\t\t\tthis.handlers.delete(type);\n\t\t\t}\n\t\t};\n\t}\n\n\tonce<K extends Evt[\"type\"]>(\n\t\teventType: K,\n\t\toptions?: OnceOptions,\n\t): Promise<Extract<Evt, { type: K }>> {\n\t\treturn new Promise<Extract<Evt, { type: K }>>((resolve, reject) => {\n\t\t\t// Reject synchronously if the signal is already aborted โ don't\n\t\t\t// even subscribe.\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\treject(options.signal.reason ?? new Error(\"EventBus.once aborted\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tlet settled = false;\n\t\t\tlet abortListener: (() => void) | undefined;\n\n\t\t\tconst cleanup = () => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tunsubscribe();\n\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\tif (abortListener && options?.signal) {\n\t\t\t\t\toptions.signal.removeEventListener(\"abort\", abortListener);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst unsubscribe = this.subscribe(eventType, (event) => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(event);\n\t\t\t});\n\n\t\t\tif (options?.signal) {\n\t\t\t\tabortListener = () => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\treject(\n\t\t\t\t\t\toptions.signal!.reason ?? new Error(\"EventBus.once aborted\"),\n\t\t\t\t\t);\n\t\t\t\t};\n\t\t\t\toptions.signal.addEventListener(\"abort\", abortListener);\n\t\t\t}\n\n\t\t\tif (typeof options?.timeoutMs === \"number\") {\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`EventBus.once timed out after ${options.timeoutMs}ms waiting for \"${eventType}\"`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}, options.timeoutMs);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * See {@link EventBus.publish} for the full ordering / parallelism /\n\t * error-aggregation contract this implementation realises:\n\t * - events in input order, sequentially;\n\t * - handlers within one event in parallel via `Promise.allSettled`;\n\t * - errors collected and thrown after the batch (single Error, or\n\t * `AggregateError` for multiple failures).\n\t */\n\tasync publish(events: ReadonlyArray<Evt>): Promise<void> {\n\t\tconst errors: Error[] = [];\n\n\t\tfor (const event of events) {\n\t\t\tconst handlersForType = this.handlers.get(event.type);\n\t\t\tif (handlersForType) {\n\t\t\t\t// Snapshot so a handler unsubscribing during dispatch doesn't\n\t\t\t\t// shift indices while we iterate.\n\t\t\t\tconst results = await Promise.allSettled(\n\t\t\t\t\thandlersForType.slice().map((handler) => handler(event)),\n\t\t\t\t);\n\t\t\t\tfor (const result of results) {\n\t\t\t\t\tif (result.status === \"rejected\") {\n\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\tresult.reason instanceof Error\n\t\t\t\t\t\t\t\t? result.reason\n\t\t\t\t\t\t\t\t: new Error(String(result.reason)),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (errors.length === 1) {\n\t\t\tthrow errors[0];\n\t\t}\n\t\tif (errors.length > 1) {\n\t\t\tthrow new AggregateError(errors, \"Multiple event handlers failed\");\n\t\t}\n\t}\n}\n\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/array/is-built-in.ts","../src/utils/array/deep-equal.ts","../src/utils/array/deep-omit.ts","../src/utils/array/deep-equal-except.ts","../src/value-object/value-object.ts","../src/aggregate/domain-event.ts","../src/aggregate/aggregate.ts","../src/entity/entity.ts","../src/aggregate/aggregate-root.ts","../src/core/errors.ts","../src/aggregate/event-sourced-aggregate.ts","../src/app/command-bus.ts","../src/app/handler.ts","../src/app/query-bus.ts","../src/events/event-bus.ts"],"names":["tagA","tagB","len","clone","err","ok"],"mappings":";;;;;;;AAaA,IAAM,aAAA,uBAAyC,GAAA,CAAI;AAAA,EAClD,eAAA;AAAA,EACA,iBAAA;AAAA,EACA,cAAA;AAAA,EACA,cAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA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;AAAA,aACnC;AAAA,UACD;AAAA,QACD;AAAA,MACD;AAAA,IACD;AAEA,IAAA,IAAI,MAAA,CAAO,WAAW,CAAA,EAAG;AACxB,MAAA,MAAM,OAAO,CAAC,CAAA;AAAA,IACf;AACA,IAAA,IAAI,MAAA,CAAO,SAAS,CAAA,EAAG;AACtB,MAAA,MAAM,IAAI,cAAA,CAAe,MAAA,EAAQ,gCAAgC,CAAA;AAAA,IAClE;AAAA,EACD;AACD","file":"index.js","sourcesContent":["/**\n * Set of `Object.prototype.toString.call(x)` tags that the library treats\n * as built-in atomic types. Members of this set are compared/cloned by\n * reference (or with type-specific logic) rather than walked structurally.\n *\n * The detection is purely tag-based โ `Object.prototype.toString` reads\n * `Symbol.toStringTag`, which gives the same answer across realms (an\n * iframe's `Date` has the same tag as the main window's `Date`). The\n * previous strategy also checked `globalThis[name] === constructor` and a\n * `proto !== Object.prototype` heuristic; both broke for cross-realm\n * objects and the latter additionally misclassified ordinary user classes\n * as built-ins. Tag-only is the simplest robust choice.\n */\nconst BUILT_IN_TAGS: ReadonlySet<string> = new Set([\n\t\"[object Date]\",\n\t\"[object RegExp]\",\n\t\"[object Map]\",\n\t\"[object Set]\",\n\t\"[object WeakMap]\",\n\t\"[object WeakSet]\",\n\t\"[object Promise]\",\n\t\"[object Error]\",\n\t\"[object Boolean]\",\n\t\"[object Number]\",\n\t\"[object String]\",\n\t\"[object ArrayBuffer]\",\n\t\"[object SharedArrayBuffer]\",\n\t\"[object DataView]\",\n]);\n\n/**\n * Returns `true` when `obj` is a built-in JavaScript type that should be\n * treated atomically (compared/cloned as a unit, not walked structurally).\n * Cross-realm safe.\n *\n * @param obj - The object to classify\n * @param tag - The result of `Object.prototype.toString.call(obj)` โ passed\n * in so callers that already computed it don't pay twice\n */\nexport function isBuiltInObject(obj: object, tag: string): boolean {\n\t// All TypedArrays produce tags ending in \"Array]\" โ future-proof match.\n\tif (tag.endsWith(\"Array]\")) return true;\n\t// ArrayBuffer view covers DataView + all TypedArrays as a belt-and-braces.\n\tif (ArrayBuffer.isView(obj)) return true;\n\treturn BUILT_IN_TAGS.has(tag);\n}\n","import { isBuiltInObject } from \"./is-built-in\";\n\nconst objProto = Object.prototype;\nconst objToString = objProto.toString;\nconst objHasOwn = objProto.hasOwnProperty;\n\n/**\n * Performs a deep equality check between two values.\n *\n * This function compares values recursively, handling:\n * - Primitives (with special handling for NaN)\n * - Arrays (nested arrays supported)\n * - Objects (plain objects and class instances)\n * - TypedArrays (Uint8Array, Int32Array, etc.)\n * - DataView\n * - Maps and Sets\n * - Dates and RegExp\n * - Wrapper objects (Boolean, Number, String)\n * - Circular references (detected and handled)\n *\n * @param a - The first value to compare\n * @param b - The second value to compare\n * @returns `true` if the values are deeply equal, `false` otherwise\n *\n * @example\n * ```ts\n * deepEqual([1, 2, 3], [1, 2, 3]); // true\n * deepEqual({ a: 1, b: [2, 3] }, { a: 1, b: [2, 3] }); // true\n * deepEqual(NaN, NaN); // true\n * deepEqual([1, 2], [1, 2, 3]); // false\n * ```\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n\treturn deepEqualInner(a, b, new WeakMap<object, WeakSet<object>>());\n}\n\n/**\n * Visited pair tracker for cycle detection. The cache is a pair-set:\n * for every left-hand object we keep the set of right-hand objects we\n * have already paired it with. Encountering an already-known pair returns\n * the cycle hypothesis (assume equal); a new (a, b') pair with b' โ any\n * previously cached b for that a is walked normally โ the previous shape\n * (`WeakMap<object, object>`) could only remember one B per A, which\n * could short-circuit unrelated comparisons that happened to revisit the\n * same A with a different B.\n */\ntype VisitedPairs = WeakMap<object, WeakSet<object>>;\n\n/**\n * Internal recursive function for deep equality comparison.\n *\n * @internal\n */\nfunction deepEqualInner(\n\ta: unknown,\n\tb: unknown,\n\tvisited: VisitedPairs,\n): boolean {\n\t// 1. Fast path: reference equality\n\tif (a === b) return true;\n\n\tconst typeA = typeof a;\n\tconst typeB = typeof b;\n\n\t// 2. If one is not an object โ primitive / function\n\tif (typeA !== \"object\" || a === null || typeB !== \"object\" || b === null) {\n\t\t// Special case: NaN should be equal\n\t\tif (typeA === \"number\" && typeB === \"number\") {\n\t\t\treturn Number.isNaN(a as number) && Number.isNaN(b as number);\n\t\t}\n\t\t// Everything else is directly unequal with !== (including functions)\n\t\treturn false;\n\t}\n\n\t// From here on: both are non-null objects\n\n\tconst objA = a as object;\n\tconst objB = b as object;\n\n\t// 3. Cycles: already seen this exact (a, b) pair?\n\tlet cachedBs = visited.get(objA);\n\tif (cachedBs?.has(objB)) {\n\t\t// Cycle hypothesis: pretend equal so the walk can terminate. If the\n\t\t// structure is actually unequal elsewhere, a different recursive\n\t\t// branch will surface the mismatch.\n\t\treturn true;\n\t}\n\tif (!cachedBs) {\n\t\tcachedBs = new WeakSet();\n\t\tvisited.set(objA, cachedBs);\n\t}\n\tcachedBs.add(objB);\n\n\t// 4. Handle Typed Arrays / DataView first\n\tif (ArrayBuffer.isView(objA) || ArrayBuffer.isView(objB)) {\n\t\tif (!ArrayBuffer.isView(objA) || !ArrayBuffer.isView(objB)) return false;\n\n\t\tconst tagA = objToString.call(objA);\n\t\tconst tagB = objToString.call(objB);\n\t\tif (tagA !== tagB) return false;\n\n\t\t// DataView: compare byte by byte\n\t\tif (tagA === \"[object DataView]\") {\n\t\t\tconst viewA = objA as DataView;\n\t\t\tconst viewB = objB as DataView;\n\t\t\tif (viewA.byteLength !== viewB.byteLength) return false;\n\n\t\t\tconst len = viewA.byteLength;\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\tif (viewA.getUint8(i) !== viewB.getUint8(i)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t// Typed Arrays: element by element (length + numeric index access are\n\t\t// part of the TypedArray contract; the indexed read is sound).\n\t\tconst arrA = objA as unknown as Record<number, unknown> & { length: number };\n\t\tconst arrB = objB as unknown as Record<number, unknown> & { length: number };\n\n\t\tconst len = arrA.length;\n\t\tif (len !== arrB.length) return false;\n\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tif (arrA[i] !== arrB[i]) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t// 5. Tag-based type detection (robust across realms)\n\tconst tagA = objToString.call(objA);\n\tconst tagB = objToString.call(objB);\n\tif (tagA !== tagB) return false;\n\n\tswitch (tagA) {\n\t\tcase \"[object Array]\": {\n\t\t\tconst arrA = objA as unknown[];\n\t\t\tconst arrB = objB as unknown[];\n\t\t\tconst len = arrA.length;\n\t\t\tif (len !== arrB.length) return false;\n\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\tif (!deepEqualInner(arrA[i], arrB[i], visited)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Map]\": {\n\t\t\tconst mapA = objA as Map<unknown, unknown>;\n\t\t\tconst mapB = objB as Map<unknown, unknown>;\n\n\t\t\tif (mapA.size !== mapB.size) return false;\n\n\t\t\tfor (const [key, valA] of mapA) {\n\t\t\t\t// Map keys according to JS semantics: reference / SameValueZero\n\t\t\t\tif (!mapB.has(key)) return false;\n\t\t\t\tconst valB = mapB.get(key);\n\t\t\t\tif (!deepEqualInner(valA, valB, visited)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Set]\": {\n\t\t\tconst setA = objA as Set<unknown>;\n\t\t\tconst setB = objB as Set<unknown>;\n\n\t\t\tif (setA.size !== setB.size) return false;\n\n\t\t\t// Set elements: same reference (JS semantics)\n\t\t\tfor (const value of setA) {\n\t\t\t\tif (!setB.has(value)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Date]\": {\n\t\t\tconst timeA = (objA as Date).getTime();\n\t\t\tconst timeB = (objB as Date).getTime();\n\t\t\treturn timeA === timeB;\n\t\t}\n\n\t\tcase \"[object RegExp]\": {\n\t\t\tconst regA = objA as RegExp;\n\t\t\tconst regB = objB as RegExp;\n\t\t\treturn regA.source === regB.source && regA.flags === regB.flags;\n\t\t}\n\n\t\tcase \"[object Boolean]\":\n\t\tcase \"[object Number]\":\n\t\tcase \"[object String]\": {\n\t\t\t// Wrapper objects (new Boolean/Number/String)\n\t\t\treturn (objA as any).valueOf() === (objB as any).valueOf();\n\t\t}\n\n\t\tdefault: {\n\t\t\t// 6. Check if this is an unhandled built-in type (future-proof)\n\t\t\t// If both are built-ins but not handled above, they should be compared by reference\n\t\t\t// (since we don't know their internal structure)\n\t\t\tif (isBuiltInObject(objA, tagA) && isBuiltInObject(objB, tagB)) {\n\t\t\t\t// Unhandled built-in types: compare by reference as fallback\n\t\t\t\t// This ensures new built-ins don't fall through to plain object comparison\n\t\t\t\treturn objA === objB;\n\t\t\t}\n\n\t\t\t// 7. Fallback: plain / custom objects โ compare own enumerable keys + values\n\t\t\tconst recA = objA as Record<string | symbol, unknown>;\n\t\t\tconst recB = objB as Record<string | symbol, unknown>;\n\n\t\t\tconst stringKeysA = Object.keys(objA as object);\n\t\t\tconst stringKeysB = Object.keys(objB as object);\n\t\t\tif (stringKeysA.length !== stringKeysB.length) return false;\n\n\t\t\tconst symbolKeysA = Object.getOwnPropertySymbols(objA as object);\n\t\t\tconst symbolKeysB = Object.getOwnPropertySymbols(objB as object);\n\t\t\tif (symbolKeysA.length !== symbolKeysB.length) return false;\n\n\t\t\t// Build the B-side symbol set once; the previous impl rebuilt the\n\t\t\t// array and ran .includes per key, which was quadratic.\n\t\t\tconst symbolKeysBSet = new Set<symbol>(symbolKeysB);\n\n\t\t\tfor (const key of stringKeysA) {\n\t\t\t\tif (!objHasOwn.call(objB, key)) return false;\n\t\t\t}\n\t\t\tfor (const key of symbolKeysA) {\n\t\t\t\tif (!symbolKeysBSet.has(key)) return false;\n\t\t\t}\n\n\t\t\tfor (const key of stringKeysA) {\n\t\t\t\tif (!deepEqualInner(recA[key], recB[key], visited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const key of symbolKeysA) {\n\t\t\t\tif (!deepEqualInner(recA[key], recB[key], visited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\t}\n}\n","import { isBuiltInObject } from \"./is-built-in\";\n\nexport type Key = string | symbol;\nexport type PathSegment = string | number | symbol;\n\nexport interface DeepOmitOptions {\n\t/**\n\t * Keys to ignore everywhere in the object tree.\n\t * Only applies to object properties, not Map/Set/TypedArray contents.\n\t */\n\treadonly ignoreKeys?: readonly Key[];\n\n\t/**\n\t * Fine-grained control: Key + path (without current key).\n\t * Example path: [\"user\", \"meta\", 0, \"data\"]\n\t */\n\treadonly ignoreKeyPredicate?: (\n\t\tkey: Key,\n\t\tpath: readonly PathSegment[],\n\t) => boolean;\n}\n\n/**\n * Creates a deep copy of `value` with certain keys removed according to the\n * provided rules.\n *\n * Walks the object tree and skips keys that match `ignoreKeys` /\n * `ignoreKeyPredicate`. Built-in atomic types (Date, RegExp, Map, Set,\n * TypedArrays, ArrayBuffer, DataView) are cloned by type rather than walked\n * โ their internal structure has no key filtering to apply. Cycles are\n * preserved: a cycle `a โ a` clones to `a' โ a'`.\n *\n * **Prototype-pollution safety.** `__proto__` and `constructor` keys\n * encountered as *own* properties of the input (typical of `JSON.parse`\n * output) are copied as inert data properties via `Object.defineProperty`\n * so the clone graph cannot bleed into `Object.prototype`.\n *\n * **Class instances.** When the input is a class instance, the clone is\n * built via `Object.create(proto)` so the prototype is preserved, but the\n * constructor is NOT re-invoked โ so class invariants enforced by the\n * constructor are not re-checked. `deepOmit` is therefore best used for\n * comparison/serialisation (`voEqualsExcept`, `deepEqualExcept`), not as\n * a general-purpose clone for behaviour-carrying objects.\n *\n * @param value - The value to create a deep copy from\n * @param options - Options specifying which keys to ignore\n * @returns A deep copy of `value` with specified keys removed\n */\nexport function deepOmit<T>(value: T, options: DeepOmitOptions): T {\n\tconst visited = new WeakMap<object, unknown>();\n\t// Materialise ignoreKeys as a Set once so the inner loop probes O(1).\n\tconst ignoreKeys = options.ignoreKeys\n\t\t? new Set<Key>(options.ignoreKeys)\n\t\t: undefined;\n\treturn omitInternal(value, options, ignoreKeys, [], visited) as T;\n}\n\nfunction omitInternal(\n\tvalue: unknown,\n\toptions: DeepOmitOptions,\n\tignoreKeys: ReadonlySet<Key> | undefined,\n\tpath: PathSegment[],\n\tvisited: WeakMap<object, unknown>,\n): unknown {\n\tif (value === null) return value;\n\tif (typeof value !== \"object\") return value;\n\n\tconst obj = value as object;\n\n\t// Cycles: return cached clone if already visited. Use `has` (not\n\t// `cached !== undefined`) so a legitimately-undefined cached clone\n\t// would not be misclassified as \"never seen\".\n\tif (visited.has(obj)) {\n\t\treturn visited.get(obj);\n\t}\n\n\tconst tag = Object.prototype.toString.call(obj);\n\n\t// Arrays: recursively process elements\n\tif (tag === \"[object Array]\") {\n\t\tconst arr = obj as unknown[];\n\t\tconst clone: unknown[] = new Array(arr.length);\n\t\tvisited.set(obj, clone);\n\t\tfor (let i = 0; i < arr.length; i++) {\n\t\t\tpath.push(i);\n\t\t\tclone[i] = omitInternal(arr[i], options, ignoreKeys, path, visited);\n\t\t\tpath.pop();\n\t\t}\n\t\treturn clone;\n\t}\n\n\t// Built-in atomic types: clone by type rather than walk.\n\tif (isBuiltInObject(obj, tag)) {\n\t\tconst builtInClone = cloneBuiltIn(obj, tag);\n\t\tvisited.set(obj, builtInClone);\n\t\treturn builtInClone;\n\t}\n\n\t// Plain / Custom Objects: filter keys, recursively process values.\n\tconst clone = Object.create(Object.getPrototypeOf(obj));\n\tvisited.set(obj, clone);\n\n\tconst stringKeys = Object.keys(obj);\n\tconst symbolKeys = Object.getOwnPropertySymbols(obj);\n\n\tfor (const key of stringKeys) {\n\t\tif (shouldIgnoreKey(key, path, ignoreKeys, options)) continue;\n\t\tpath.push(key);\n\t\tassignOwn(\n\t\t\tclone,\n\t\t\tkey,\n\t\t\tomitInternal(\n\t\t\t\t(obj as Record<PropertyKey, unknown>)[key],\n\t\t\t\toptions,\n\t\t\t\tignoreKeys,\n\t\t\t\tpath,\n\t\t\t\tvisited,\n\t\t\t),\n\t\t);\n\t\tpath.pop();\n\t}\n\tfor (const key of symbolKeys) {\n\t\tif (shouldIgnoreKey(key, path, ignoreKeys, options)) continue;\n\t\tpath.push(key);\n\t\tassignOwn(\n\t\t\tclone,\n\t\t\tkey,\n\t\t\tomitInternal(\n\t\t\t\t(obj as Record<PropertyKey, unknown>)[key],\n\t\t\t\toptions,\n\t\t\t\tignoreKeys,\n\t\t\t\tpath,\n\t\t\t\tvisited,\n\t\t\t),\n\t\t);\n\t\tpath.pop();\n\t}\n\n\treturn clone;\n}\n\n/**\n * Assigns `value` as an OWN data property on `target` without going through\n * any inherited setter โ critically, never invokes the `__proto__` setter\n * even when `key === \"__proto__\"`. Required to defeat prototype-pollution\n * payloads that ship `__proto__` as a parsed-JSON own key.\n */\nfunction assignOwn(target: object, key: PropertyKey, value: unknown): void {\n\tObject.defineProperty(target, key, {\n\t\tvalue,\n\t\twritable: true,\n\t\tenumerable: true,\n\t\tconfigurable: true,\n\t});\n}\n\n/**\n * Clones a built-in atomic type by case. Falls back to `structuredClone`\n * for anything not explicitly enumerated (e.g. ArrayBuffer, DataView,\n * Boolean/Number/String wrappers).\n */\nfunction cloneBuiltIn(obj: object, tag: string): unknown {\n\tswitch (tag) {\n\t\tcase \"[object Date]\":\n\t\t\treturn new Date((obj as Date).getTime());\n\t\tcase \"[object RegExp]\": {\n\t\t\tconst re = obj as RegExp;\n\t\t\tconst copy = new RegExp(re.source, re.flags);\n\t\t\tcopy.lastIndex = re.lastIndex;\n\t\t\treturn copy;\n\t\t}\n\t\tcase \"[object Map]\": {\n\t\t\tconst m = obj as Map<unknown, unknown>;\n\t\t\treturn new Map(m);\n\t\t}\n\t\tcase \"[object Set]\": {\n\t\t\tconst s = obj as Set<unknown>;\n\t\t\treturn new Set(s);\n\t\t}\n\t\tdefault:\n\t\t\treturn structuredClone(obj);\n\t}\n}\n\nfunction shouldIgnoreKey(\n\tkey: Key,\n\tpath: readonly PathSegment[],\n\tignoreKeys: ReadonlySet<Key> | undefined,\n\toptions: DeepOmitOptions,\n): boolean {\n\tif (ignoreKeys?.has(key)) return true;\n\tif (options.ignoreKeyPredicate?.(key, path)) return true;\n\treturn false;\n}\n","import { deepEqual } from \"./deep-equal\";\nimport { type DeepOmitOptions, deepOmit } from \"./deep-omit\";\n\nexport type DeepEqualExceptOptions = DeepOmitOptions;\n\n/**\n * Performs a deep equality comparison between two values after omitting specified keys.\n * \n * This function first removes the specified keys from both values using `deepOmit`,\n * then performs a deep equality check using `deepEqual`.\n * \n * @param a - The first value to compare\n * @param b - The second value to compare\n * @param options - Options specifying which keys to omit before comparison\n * @returns `true` if the values are deeply equal after omitting specified keys, `false` otherwise\n * \n * @example\n * ```ts\n * const obj1 = { id: 1, name: \"Alice\", updatedAt: \"2024-01-01\" };\n * const obj2 = { id: 2, name: \"Alice\", updatedAt: \"2024-01-02\" };\n * \n * deepEqualExcept(obj1, obj2, { ignoreKeys: [\"id\", \"updatedAt\"] }); // true\n * ```\n */\nexport function deepEqualExcept(\n\ta: unknown,\n\tb: unknown,\n\toptions: DeepEqualExceptOptions,\n): boolean {\n\tconst prunedA = deepOmit(a, options);\n\tconst prunedB = deepOmit(b, options);\n\treturn deepEqual(prunedA, prunedB);\n}\n","import { deepEqual } from \"../utils/array/deep-equal\";\nimport {\n deepEqualExcept,\n type DeepEqualExceptOptions,\n} from \"../utils/array/deep-equal-except\";\nimport { err, ok, type Result } from \"@shirudo/result\";\n\n// ============================================================================\n// Functional Value Object API\n// ============================================================================\n\nexport type VO<T> = Readonly<T>;\n\n/**\n * Deep freezes an object and all its nested properties recursively, then\n * returns it. Iterates both string-keyed and symbol-keyed own properties\n * so the freeze symmetry matches `deepEqual` (which also considers symbol\n * keys). Handles circular references by tracking visited objects.\n *\n * Note: `deepFreeze` mutates its argument in place โ it sets `[[Frozen]]`\n * on the object you pass in. Callers that need to avoid touching the\n * input (e.g. `vo()`) should deep-clone first.\n */\nexport function deepFreeze<T>(obj: T, visited = new WeakSet<object>()): Readonly<T> {\n if (obj === null || typeof obj !== \"object\") {\n return obj as Readonly<T>;\n }\n if (visited.has(obj as object)) {\n return obj as Readonly<T>;\n }\n visited.add(obj as object);\n\n // Reflect.ownKeys returns both string and symbol own keys.\n const keys = Reflect.ownKeys(obj);\n for (const key of keys) {\n const value = (obj as Record<string | symbol, unknown>)[key];\n if (value !== null && typeof value === \"object\") {\n deepFreeze(value, visited);\n }\n }\n\n return Object.freeze(obj) as Readonly<T>;\n}\n\n/**\n * Creates a deeply immutable value object from the given data.\n *\n * The input is first deep-cloned with `structuredClone`, then the clone\n * is frozen โ so calling `vo(input)` never freezes the caller's own\n * object graph as a side-effect. Mutating the input afterwards does not\n * bleed into the VO.\n *\n * @example\n * ```typescript\n * const nested = { lat: 52.5, lng: 13.4 };\n * const address = vo({ street: \"Main St\", coordinates: nested });\n * address.coordinates.lat = 99; // โ Cannot assign to read-only property\n * nested.lat = 0; // โ
caller's input still mutable\n * ```\n */\nexport function vo<T>(t: T): VO<T> {\n return deepFreeze(structuredClone(t));\n}\n\n/**\n * Compares two value objects for equality based on their values.\n * Uses deep equality comparison that handles:\n * - Nested objects and arrays\n * - Primitives (including NaN)\n * - Dates, Maps, Sets, RegExp\n * - TypedArrays and DataView\n * - Symbol keys\n * - Circular references\n *\n * @param a - First value object\n * @param b - Second value object\n * @returns true if both objects have the same values, false otherwise\n *\n * @example\n * ```typescript\n * const money1 = vo({ amount: 100, currency: \"USD\" });\n * const money2 = vo({ amount: 100, currency: \"USD\" });\n * voEquals(money1, money2); // true\n *\n * const address1 = vo({\n * street: \"Main St\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * const address2 = vo({\n * street: \"Main St\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * voEquals(address1, address2); // true\n * ```\n */\nexport function voEquals<T>(a: VO<T>, b: VO<T>): boolean {\n return deepEqual(a, b);\n}\n\n/**\n * Compares two value objects for equality while ignoring specified keys.\n * Useful for comparing value objects that contain metadata or optional fields\n * that should not affect equality comparison.\n *\n * @param a - First value object\n * @param b - Second value object\n * @param options - Options specifying which keys to ignore during comparison\n * @returns true if both objects have the same values (after ignoring specified keys), false otherwise\n *\n * @example\n * ```typescript\n * // Value object with metadata\n * const address1 = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * metadata: { createdAt: \"2024-01-01\", updatedAt: \"2024-01-02\" }\n * });\n *\n * const address2 = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * metadata: { createdAt: \"2024-01-01\", updatedAt: \"2024-01-03\" }\n * });\n *\n * // Compare ignoring metadata timestamps\n * voEqualsExcept(address1, address2, {\n * ignoreKeys: [\"updatedAt\"],\n * ignoreKeyPredicate: (key, path) => path.includes(\"metadata\")\n * }); // true\n *\n * // Compare ignoring all metadata\n * voEqualsExcept(address1, address2, {\n * ignoreKeyPredicate: (key, path) => path.includes(\"metadata\")\n * }); // true\n * ```\n */\nexport function voEqualsExcept<T>(\n a: VO<T>,\n b: VO<T>,\n options: DeepEqualExceptOptions,\n): boolean {\n return deepEqualExcept(a, b, options);\n}\n\n/**\n * Creates a value object with optional validation.\n * Returns a Result type instead of throwing an error.\n *\n * @param t - The data to convert into a value object\n * @param validate - Validation function that returns true if valid\n * @param errorMessage - Optional custom error message if validation fails\n * @returns Result containing the value object if valid, or an error message if validation fails\n *\n * @example\n * ```typescript\n * const result = voWithValidation(\n * { amount: 100, currency: \"USD\" },\n * (m) => m.amount >= 0 && m.currency.length === 3,\n * \"Invalid money: amount must be non-negative and currency must be 3 characters\"\n * );\n *\n * if (result.ok) {\n * console.log(result.value); // Use the value object\n * } else {\n * console.error(result.error); // Handle validation error\n * }\n * ```\n */\nexport function voWithValidation<T>(\n t: T,\n validate: (value: T) => boolean,\n errorMessage?: string,\n): Result<VO<T>, string> {\n if (!validate(t)) {\n return err(\n errorMessage ?? `Validation failed for value object: ${JSON.stringify(t)}`,\n );\n }\n return ok(vo(t));\n}\n\n// ============================================================================\n// Class-based Value Object API\n// ============================================================================\n\n/**\n * Interface for Value Objects.\n * Value Objects are immutable and defined by their properties.\n *\n * @template T - The shape of the value object's properties\n */\nexport interface IValueObject<T extends object> {\n /**\n * The immutable properties of the value object.\n */\n readonly props: Readonly<T>;\n\n /**\n * Checks if this value object is equal to another.\n * Uses deep equality comparison on the properties.\n *\n * @param other - The other value object to compare\n * @returns true if the properties are deeply equal\n */\n equals(other: IValueObject<T>): boolean;\n\n /**\n * Creates a clone of the value object with optional property overrides.\n *\n * @param props - Optional properties to override\n * @returns A new instance of the value object\n */\n clone(props?: Partial<T>): IValueObject<T>;\n\n /**\n * Serializes the value object to its raw properties for JSON operations.\n *\n * @returns The raw properties object\n */\n toJSON(): Readonly<T>;\n}\n\n/**\n * Abstract base class for creating Value Objects.\n * Value Objects are immutable and defined by their properties.\n *\n * @template T - The shape of the value object's properties\n */\nexport abstract class ValueObject<T extends object> implements IValueObject<T> {\n public readonly props: Readonly<T>;\n\n /**\n * Creates a new ValueObject.\n * The properties are deeply frozen to ensure immutability.\n *\n * @param props - The properties of the value object\n * @example\n * ```ts\n * class Money extends ValueObject<{ amount: number; currency: string }> {\n * constructor(props: { amount: number; currency: string }) {\n * super(props);\n * }\n *\n * protected validate(props: { amount: number; currency: string }): void {\n * if (props.amount < 0) throw new Error(\"Amount cannot be negative\");\n * }\n * }\n * ```\n */\n constructor(props: T) {\n this.validate(props);\n this.props = deepFreeze({ ...props });\n }\n\n /**\n * Optional validation hook that can be overridden by subclasses.\n * Should throw an error if validation fails.\n *\n * @param props - The properties to validate\n * @throws Error if validation fails\n */\n protected validate(props: T): void {\n // Default implementation does nothing\n }\n\n /**\n * Checks if this value object is equal to another.\n * Uses deep equality comparison on the properties and checks for constructor equality.\n *\n * @param other - The other value object to compare\n * @returns true if the properties are deeply equal and constructors match\n */\n public equals(other: ValueObject<T>): boolean {\n if (other === null || other === undefined) {\n return false;\n }\n\n if (this.constructor !== other.constructor) {\n return false;\n }\n\n return deepEqual(this.props, other.props);\n }\n\n /**\n * Creates a clone of the value object with optional property overrides.\n *\n * @param props - Optional properties to override\n * @returns A new instance of the value object\n */\n public clone(props?: Partial<T>): this {\n const Constructor = this.constructor as new (props: T) => this;\n return new Constructor({ ...this.props, ...(props || {}) });\n }\n\n /**\n * Serializes the value object to its raw properties for JSON operations.\n *\n * @returns The raw properties object\n */\n public toJSON(): Readonly<T> {\n return this.props;\n }\n\n\n}\n","import { deepFreeze } from \"../value-object/value-object\";\n\n/**\n * Factory function producing a fresh, unique event identifier for each call.\n *\n * The library ships a default that uses Web Crypto `crypto.randomUUID()`\n * (works on Node 19+, modern browsers in secure contexts, Deno, Bun,\n * Cloudflare Workers, Vercel Edge, and any runtime that implements Web\n * Crypto). Note that `crypto.randomUUID()` returns **UUID v4** (purely\n * random) โ for production event stores prefer a **time-ordered** id\n * format (UUID v7 / ULID / KSUID) so B-tree indexes on the eventId\n * column stay clustered and `ORDER BY eventId` matches creation order.\n * Swap one in via `setEventIdFactory(() => uuidv7())` or `() => ulid()`.\n */\nexport type EventIdFactory = () => string;\n\nconst defaultEventIdFactory: EventIdFactory = () => crypto.randomUUID();\nlet currentEventIdFactory: EventIdFactory = defaultEventIdFactory;\n\n/**\n * Replaces the global event-id factory used by `createDomainEvent` and\n * `createDomainEventWithMetadata`. Call once during application bootstrap,\n * for example:\n *\n * ```ts\n * import { ulid } from \"ulid\";\n * import { setEventIdFactory } from \"@shirudo/ddd-kit\";\n *\n * setEventIdFactory(() => ulid());\n * ```\n *\n * The per-call `options.eventId` override always wins over this factory.\n *\n * **Module-scoped โ last setter wins.** The factory lives as a single\n * module variable; importing two libraries that both call this races on\n * load order. For multi-tenant request isolation (e.g. one factory per\n * tenant in a single Worker invocation) **prefer the per-call\n * `options.eventId`** instead of mutating the global. Same caveat applies\n * to `setClockFactory`.\n */\nexport function setEventIdFactory(factory: EventIdFactory): void {\n\tcurrentEventIdFactory = factory;\n}\n\n/**\n * Restores the default event-id factory (`crypto.randomUUID()`).\n * Intended for use in test `afterEach` hooks.\n */\nexport function resetEventIdFactory(): void {\n\tcurrentEventIdFactory = defaultEventIdFactory;\n}\n\n/**\n * Clock function producing a fresh `Date` for each call. The library\n * defaults to `() => new Date()`; override globally via `setClockFactory`\n * for deterministic event-sourcing tests, time-travel debugging, or any\n * scenario where `occurredAt` must be reproducible.\n */\nexport type ClockFactory = () => Date;\n\nconst defaultClockFactory: ClockFactory = () => new Date();\nlet currentClockFactory: ClockFactory = defaultClockFactory;\n\n/**\n * Replaces the global clock factory used by `createDomainEvent` and\n * `createDomainEventWithMetadata`. Call once during application bootstrap\n * (or per-test in deterministic test suites):\n *\n * ```ts\n * import { setClockFactory } from \"@shirudo/ddd-kit\";\n *\n * setClockFactory(() => new Date(\"2026-01-01T00:00:00Z\"));\n * ```\n *\n * The per-call `options.occurredAt` override always wins over this\n * factory. Symmetric to `setEventIdFactory`.\n */\nexport function setClockFactory(factory: ClockFactory): void {\n\tcurrentClockFactory = factory;\n}\n\n/**\n * Restores the default clock factory (`() => new Date()`).\n * Intended for use in test `afterEach` hooks.\n */\nexport function resetClockFactory(): void {\n\tcurrentClockFactory = defaultClockFactory;\n}\n\n/**\n * Metadata associated with a domain event for traceability and correlation.\n * Used in event-driven architectures to track event flow across services.\n */\nexport interface EventMetadata {\n\t/**\n\t * Correlation ID for tracing events across multiple services/components.\n\t * Typically used to group related events in a distributed system.\n\t */\n\tcorrelationId?: string;\n\n\t/**\n\t * Causation ID referencing the event or command that caused this event.\n\t * Used to build event chains and understand causality.\n\t */\n\tcausationId?: string;\n\n\t/**\n\t * User ID of the person or system that triggered the event.\n\t */\n\tuserId?: string;\n\n\t/**\n\t * Source service or component that produced the event.\n\t */\n\tsource?: string;\n\n\t/**\n\t * Additional custom metadata fields.\n\t * Allows extensibility for domain-specific metadata.\n\t */\n\t[key: string]: unknown;\n}\n\n/**\n * Domain Event represents something meaningful that happened in the domain.\n * Events are immutable and carry information about what occurred.\n *\n * @template T - The event type name (e.g., \"OrderCreated\")\n * @template P - The event payload type\n */\nexport interface DomainEvent<T extends string, P = void> {\n\t/**\n\t * Unique identifier for this specific event instance. Used by idempotent\n\t * consumers, outbox dispatch tracking, and as the target of\n\t * `metadata.causationId`. Defaults to `crypto.randomUUID()` if not\n\t * supplied.\n\t */\n\teventId: string;\n\n\t/**\n\t * The type of the event, used for routing and handling.\n\t */\n\ttype: T;\n\n\t/**\n\t * Identifier of the aggregate that produced the event. Optional at the\n\t * library level โ set it whenever the producing aggregate is known so\n\t * downstream subscribers, outboxes, and projections can scope by entity.\n\t */\n\taggregateId?: string;\n\n\t/**\n\t * Name of the aggregate type that produced the event (e.g. \"Order\").\n\t * Pairs with `aggregateId` to fully qualify the source aggregate.\n\t */\n\taggregateType?: string;\n\n\t/**\n\t * The event payload containing the domain data. The field is always\n\t * present; its value is `undefined` when `P` is `void`.\n\t */\n\tpayload: P;\n\n\t/**\n\t * Timestamp when the event occurred.\n\t */\n\toccurredAt: Date;\n\n\t/**\n\t * Event schema version for handling schema evolution.\n\t * Required for safe schema migration in event-sourced systems.\n\t * Use 1 for the initial schema version.\n\t */\n\tversion: number;\n\n\t/**\n\t * Optional metadata for traceability, correlation, and auditing.\n\t * Includes correlationId, causationId, userId, source, and custom fields.\n\t */\n\tmetadata?: EventMetadata;\n}\n\n/**\n * Shared option bag for the `createDomainEvent*` factories.\n */\nexport interface CreateDomainEventOptions {\n\t/**\n\t * Override for the auto-generated `eventId`. Pass an existing id (for\n\t * replay, tests, or deterministic event sourcing) instead of letting the\n\t * factory call `crypto.randomUUID()`.\n\t */\n\teventId?: string;\n\n\t/**\n\t * Identifier of the aggregate that produced the event.\n\t */\n\taggregateId?: string;\n\n\t/**\n\t * Name of the aggregate type that produced the event.\n\t */\n\taggregateType?: string;\n\n\t/**\n\t * Override for the auto-generated `occurredAt` timestamp.\n\t */\n\toccurredAt?: Date;\n\n\t/**\n\t * Override for the default schema version (1).\n\t */\n\tversion?: number;\n\n\t/**\n\t * Event metadata โ correlation, causation, user, source, custom fields.\n\t */\n\tmetadata?: EventMetadata;\n}\n\n/**\n * Creates a domain event with default values.\n * Sets occurredAt to current date and version to 1 if not provided.\n *\n * @param type - The event type\n * @param payload - The event payload\n * @param options - Optional event configuration\n * @returns A domain event\n *\n * @example\n * ```typescript\n * const event = createDomainEvent(\"OrderCreated\", { orderId: \"123\" });\n * ```\n */\nexport function createDomainEvent<T extends string>(\n\ttype: T,\n\tpayload?: undefined,\n\toptions?: CreateDomainEventOptions,\n): DomainEvent<T, void>;\nexport function createDomainEvent<T extends string, P>(\n\ttype: T,\n\tpayload: P,\n\toptions?: CreateDomainEventOptions,\n): DomainEvent<T, P>;\nexport function createDomainEvent<T extends string, P>(\n\ttype: T,\n\tpayload?: P,\n\toptions?: CreateDomainEventOptions,\n): DomainEvent<T, P> {\n\tconst event: DomainEvent<T, P> = {\n\t\teventId: options?.eventId ?? currentEventIdFactory(),\n\t\ttype,\n\t\taggregateId: options?.aggregateId,\n\t\taggregateType: options?.aggregateType,\n\t\tpayload: payload as P,\n\t\toccurredAt: options?.occurredAt ?? currentClockFactory(),\n\t\tversion: options?.version ?? 1,\n\t\tmetadata: options?.metadata,\n\t};\n\t// Deep-freeze so a mutating subscriber cannot poison subsequent\n\t// handlers โ events are facts of the past and must be immutable\n\t// (Vernon, IDDD ยง8).\n\treturn deepFreeze(event) as DomainEvent<T, P>;\n}\n\n/**\n * Creates a domain event with metadata for traceability.\n * Convenience function for creating events with correlation and causation IDs.\n *\n * @example\n * ```typescript\n * const event = createDomainEventWithMetadata(\n * \"OrderCreated\",\n * { orderId: \"123\" },\n * { correlationId: \"corr-123\", causationId: \"cmd-456\", userId: \"user-789\" }\n * );\n * ```\n */\nexport function createDomainEventWithMetadata<T extends string, P>(\n\ttype: T,\n\tpayload: P,\n\tmetadata: EventMetadata,\n\toptions?: Omit<CreateDomainEventOptions, \"metadata\">,\n): DomainEvent<T, P> {\n\treturn createDomainEvent(type, payload, {\n\t\t...options,\n\t\tmetadata,\n\t});\n}\n\n/**\n * Copies metadata from a source event to a new event.\n * Useful for maintaining correlation chains in event-driven architectures.\n *\n * @example\n * ```typescript\n * const newEvent = createDomainEvent(\n * \"OrderShipped\",\n * { orderId: \"123\" },\n * { metadata: copyMetadata(previousEvent, { causationId: previousEvent.type }) }\n * );\n * ```\n */\nexport function copyMetadata(\n\tsourceEvent: DomainEvent<string, unknown>,\n\tadditionalMetadata?: Partial<EventMetadata>,\n): EventMetadata {\n\treturn {\n\t\t...(sourceEvent.metadata ?? {}),\n\t\t...(additionalMetadata ?? {}),\n\t};\n}\n\n/**\n * Merges multiple metadata objects into one.\n * Later metadata objects override earlier ones for the same keys.\n *\n * @example\n * ```typescript\n * const metadata = mergeMetadata(\n * { correlationId: \"corr-123\" },\n * { userId: \"user-456\" },\n * { source: \"order-service\" }\n * );\n * ```\n */\nexport function mergeMetadata(\n\t...metadataObjects: Array<EventMetadata | undefined>\n): EventMetadata {\n\treturn Object.assign({}, ...metadataObjects.filter(Boolean));\n}\n","import type { Id } from \"../core/id\";\n\n// Re-export domain event types for convenience\nexport * from \"./domain-event\";\n\n// Re-export interfaces from their respective files\nexport type { IAggregateRoot } from \"./aggregate-root\";\nexport type { IEventSourcedAggregate } from \"./event-sourced-aggregate\";\n\n// --- Aggregate types ---\n\nexport type Version = number & { readonly __v: true };\n\n/**\n * Snapshot of an aggregate state at a specific point in time.\n * Used for optimizing event replay by starting from a snapshot\n * instead of replaying all events from the beginning.\n *\n * @template TState - The type of the aggregate state\n */\nexport interface AggregateSnapshot<TState> {\n\t/**\n\t * The state of the aggregate at the time of the snapshot.\n\t */\n\tstate: TState;\n\n\t/**\n\t * The version of the aggregate when the snapshot was taken.\n\t */\n\tversion: Version;\n\n\t/**\n\t * Timestamp when the snapshot was created.\n\t */\n\tsnapshotAt: Date;\n}\n\n/**\n * Checks if two aggregates are at the same version (same ID and version).\n * Useful for optimistic concurrency control checks.\n *\n * Note: Two aggregates with the same ID ARE the same aggregate (identity).\n * This function checks if they are at the same version โ i.e., no concurrent modification.\n *\n * @example\n * ```typescript\n * const before = await repository.getById(id);\n * // ... some operations ...\n * const after = await repository.getById(id);\n *\n * if (!sameVersion(before, after)) {\n * throw new Error(\"Aggregate was modified by another process\");\n * }\n * ```\n */\nexport function sameVersion<TId extends Id<string>>(\n\ta: { id: TId; version: Version },\n\tb: { id: TId; version: Version },\n): boolean {\n\treturn a.id === b.id && a.version === b.version;\n}\n","/**\n * Entity utilities and interfaces for Domain-Driven Design.\n *\n * In Domain-Driven Design, there are two types of entities:\n *\n * 1. **Aggregate Root Entity**: The parent Entity of an aggregate.\n * - Has identity (id), state, and version\n * - Implemented by classes extending `AggregateRoot` or `EventSourcedAggregate`\n * - Represents the aggregate externally\n * - Loaded/saved through repositories\n *\n * 2. **Child Entities**: Entities within an aggregate.\n * - Have identity (id) and state, but no own version\n * - Can extend `EntityBase<TState, TId>` for class-based entities\n * - Or use functional style with `Identifiable<TId> & TProps`\n * - Exist only within the aggregate boundary\n * - Versioned through the Aggregate Root\n * - Cannot be referenced directly from outside the aggregate\n *\n * This module provides:\n * - `EntityBase<TState, TId>` - Base class for entities with state\n * - `Entity<TId>` - Simple class for entities without state management\n * - `Identifiable<TId>` - Minimal interface for objects with id\n * - Helper functions for working with collections of entities\n *\n * @example\n * ```typescript\n * // Class-based child entity with logic\n * class OrderItem extends EntityBase<OrderItemState, ItemId> {\n * constructor(id: ItemId, initialState: OrderItemState) {\n * super(id, initialState);\n * }\n *\n * updateQuantity(quantity: number): void {\n * this._state = { ...this._state, quantity };\n * }\n *\n * calculateSubtotal(): number {\n * return this._state.price * this._state.quantity;\n * }\n * }\n *\n * // Functional-style child entity (simpler, no logic)\n * type OrderItem = Identifiable<ItemId> & {\n * productId: string;\n * quantity: number;\n * price: number;\n * };\n *\n * // Aggregate Root (Entity with version)\n * class Order extends AggregateRoot<OrderState, OrderId> {\n * // Order is an Aggregate Root Entity\n * // OrderState contains OrderItem child entities\n * }\n * ```\n */\nimport type { Id } from \"../core/id\";\n\n/**\n * Functional definition of an Entity via its capability โ an object is\n * identifiable if it has an `id`.\n *\n * `TId` is constrained to `Id<string>` so the brand discipline that\n * `Id<Tag>` enforces is preserved end-to-end: an `Identifiable<UserId>`\n * cannot accidentally be paired with an `Identifiable<OrderId>` or with\n * a plain `string`.\n */\nexport type Identifiable<TId extends Id<string>> = {\n\treadonly id: TId;\n};\n\n/**\n * Interface for Entities with state.\n *\n * In Domain-Driven Design, Entities have:\n * - Identity (id): Distinguishes one entity from another\n * - State: The attributes/properties of the entity\n *\n * Unlike Value Objects (which are immutable and compared by value),\n * Entities are compared by identity and can have mutable state.\n *\n * @template TId - The type of the entity identifier\n * @template TState - The type of the entity state\n */\nexport interface IEntity<TId extends Id<string>, TState> extends Identifiable<TId> {\n\t/**\n\t * Unique identifier of the entity.\n\t */\n\treadonly id: TId;\n\n\t/**\n\t * The current state of the entity.\n\t */\n\treadonly state: TState;\n}\n\n/**\n * Abstract base class for Entities with state.\n *\n * Provides:\n * - Identity management (id)\n * - State management\n * - State validation hook\n * - Immutable state access through getter\n *\n * This is the foundation for all Entities in DDD:\n * - Child Entities within aggregates can extend this\n * - Aggregate Roots extend this and add version + events\n *\n * @template TState - The type of the entity state\n * @template TId - The type of the entity identifier\n *\n * @example\n * ```typescript\n * // Child Entity within an aggregate\n * class OrderItem extends Entity<OrderItemState, ItemId> {\n * constructor(id: ItemId, initialState: OrderItemState) {\n * super(id, initialState);\n * }\n *\n * updateQuantity(quantity: number): void {\n * this._state = { ...this._state, quantity };\n * }\n * }\n * ```\n */\nexport abstract class Entity<TState, TId extends Id<string>>\n\timplements IEntity<TId, TState> {\n\tpublic readonly id: TId;\n\n\t/**\n\t * Returns the current state of the entity.\n\t *\n\t * The state object is **shallowly frozen** โ direct property writes\n\t * (`entity.state.foo = โฆ`) throw in strict mode, but writes to nested\n\t * objects (`entity.state.address.zip = โฆ`) bypass the freeze. For deep\n\t * immutability either model nested data with `vo()` (which freezes\n\t * deeply) or reach for a structural-sharing library like Immer at the\n\t * App layer. The shallow contract is intentional: deep freezing on\n\t * every state write is too expensive for hot paths, and DDD aggregates\n\t * normally treat their own state as private (`Tell, Don't Ask`).\n\t */\n\tpublic get state(): TState {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * The state is 'protected' so that only the subclass can modify it.\n\t * Subclasses can mutate this directly or use helper methods.\n\t */\n\tprotected _state: TState;\n\n\tprotected constructor(id: TId, initialState: TState) {\n\t\tif (id === null || id === undefined) {\n\t\t\tthrow new Error(\"Entity ID cannot be null or undefined\");\n\t\t}\n\t\tthis.id = id;\n\t\tthis._state = freezeShallow(initialState);\n\t\tthis.validateState(this._state);\n\t}\n\n\t/**\n\t * Optional validation hook to ensure state invariants. Called during\n\t * construction (from `Entity`'s constructor) and again on every\n\t * `setState()` call. Throw to reject invalid state.\n\t *\n\t * **โ ๏ธ Must not read subclass instance fields via `this`.** The\n\t * constructor calls `validateState(initialState)` BEFORE the subclass's\n\t * field initializers run, so `this.someField` is `undefined` at that\n\t * point โ a classic TypeScript/JavaScript constructor-ordering footgun.\n\t * The `state` argument is the single source of truth; treat the method\n\t * as pure with respect to `this`.\n\t *\n\t * If your invariants genuinely depend on per-instance configuration\n\t * that isn't part of the state, pass that configuration into the state\n\t * itself (DDD-canonical: the aggregate's state contains everything it\n\t * needs) or perform the additional check after construction in a\n\t * dedicated factory method.\n\t *\n\t * @param state - The state to validate\n\t * @throws Error (or `DomainError` subclass) if validation fails\n\t */\n\tprotected validateState(_state: TState): void {\n\t\t// Default implementation does nothing\n\t}\n\n\t/**\n\t * Sets the state of the entity.\n\t * This is a convenience method for state mutations.\n\t * Automatically validates the newState using `validateState()`.\n\t *\n\t * @param newState - The new state\n\t */\n\tprotected setState(newState: TState): void {\n\t\tthis.validateState(newState);\n\t\tthis._state = freezeShallow(newState);\n\t}\n}\n\n/**\n * Shallow-freezes `value` when it's a non-null object or array, so that\n * direct property writes throw in strict mode. Returns the value as-is for\n * primitives. Used internally by `Entity` and its subclasses to prevent\n * outside mutation of state read through the `state` getter without paying\n * the cost of a deep clone on every read.\n *\n * Exported so that sibling classes (`EventSourcedAggregate`, `AggregateRoot`)\n * can apply the same freeze when they bypass `setState` and assign\n * `this._state` directly.\n */\nexport function freezeShallow<T>(value: T): T {\n\tif (value !== null && typeof value === \"object\") {\n\t\treturn Object.freeze(value);\n\t}\n\treturn value;\n}\n\n\n/**\n * Checks if two entities have the same ID.\n * Works with any object that has an 'id' property.\n *\n * @param a - First entity\n * @param b - Second entity\n * @returns true if both entities have the same ID, false otherwise\n *\n * @example\n * ```typescript\n * const item1: OrderItem = { id: itemId1, productId: \"prod-1\", quantity: 2 };\n * const item2: OrderItem = { id: itemId2, productId: \"prod-2\", quantity: 1 };\n *\n * sameEntity(item1, item2); // false\n * sameEntity(item1, item1); // true\n * ```\n */\nexport function sameEntity<TId extends Id<string>>(a: Identifiable<TId>, b: Identifiable<TId>): boolean {\n\treturn a.id === b.id;\n}\n\n/**\n * Finds an entity by ID in a collection.\n * Returns undefined if not found.\n *\n * @param entities - Array of entities to search\n * @param id - The ID to search for\n * @returns The entity if found, undefined otherwise\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const item = findEntityById(items, itemId1);\n * // item is { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ```\n */\nexport function findEntityById<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): T | undefined {\n\treturn entities.find((entity) => entity.id === id);\n}\n\n/**\n * Checks if an entity with the given ID exists in the collection.\n *\n * @param entities - Array of entities to search\n * @param id - The ID to check for\n * @returns true if an entity with the ID exists, false otherwise\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * hasEntityId(items, itemId1); // true\n * hasEntityId(items, itemId2); // false\n * ```\n */\nexport function hasEntityId<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): boolean {\n\treturn entities.some((entity) => entity.id === id);\n}\n\n/**\n * Removes an entity with the given ID from the collection.\n * Returns a new array without the entity.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to remove\n * @returns A new array without the entity with the given ID\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const updated = removeEntityById(items, itemId1);\n * // updated is [{ id: itemId2, productId: \"prod-2\", quantity: 1 }]\n * ```\n */\nexport function removeEntityById<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): T[] {\n\treturn entities.filter((entity) => entity.id !== id);\n}\n\n/**\n * Updates an entity with the given ID in the collection.\n * Returns a new array with the updated entity.\n * If the entity is not found, returns the original array unchanged.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to update\n * @param updater - Function that takes the entity and returns the updated entity\n * @returns A new array with the updated entity\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * const updated = updateEntityById(items, itemId1, (item) => ({\n * ...item,\n * quantity: item.quantity + 1\n * }));\n * // updated is [{ id: itemId1, productId: \"prod-1\", quantity: 3 }]\n * ```\n */\nexport function updateEntityById<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n\tupdater: (entity: T) => T,\n): T[] {\n\treturn entities.map((entity) => (entity.id === id ? updater(entity) : entity));\n}\n\n/**\n * Replaces an entity with the given ID in the collection.\n * Returns a new array with the replaced entity.\n * If the entity is not found, returns the original array unchanged.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to replace\n * @param replacement - The replacement entity\n * @returns A new array with the replaced entity\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * const updated = replaceEntityById(items, itemId1, {\n * id: itemId1,\n * productId: \"prod-1\",\n * quantity: 5\n * });\n * ```\n */\nexport function replaceEntityById<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n\treplacement: T,\n): T[] {\n\treturn entities.map((entity) => (entity.id === id ? replacement : entity));\n}\n\n/**\n * Extracts all IDs from a collection of entities.\n *\n * @param entities - Array of entities\n * @returns Array of entity IDs\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const ids = entityIds(items);\n * // ids is [itemId1, itemId2]\n * ```\n */\nexport function entityIds<TId extends Id<string>, T extends Identifiable<TId>>(entities: T[]): TId[] {\n\treturn entities.map((entity) => entity.id);\n}\n\n","import type { Id } from \"../core/id\";\nimport { Entity, freezeShallow } from \"../entity/entity\";\nimport type {\n\tAggregateSnapshot,\n\tVersion,\n} from \"./aggregate\";\n\n/**\n * Marker interface for Aggregate Roots.\n *\n * In Domain-Driven Design, an Aggregate Root is an Entity (the parent Entity of the aggregate).\n * It represents the aggregate externally and is the only object that external code\n * is allowed to hold references to. All access to child entities within the aggregate\n * must go through the Aggregate Root.\n *\n * An Aggregate consists of:\n * - One Aggregate Root (Entity with id + version)\n * - Optional child entities (Entities with id + state, but no own version)\n * - Optional value objects\n *\n * The Aggregate Root has identity (id), state, and version for optimistic concurrency control.\n * Child entities exist only within the aggregate boundary and are versioned through\n * the Aggregate Root.\n *\n * @template TId - The type of the aggregate root identifier\n *\n * @example\n * ```typescript\n * class Order extends AggregateRoot<OrderState, OrderId> implements IAggregateRoot<OrderId> {\n * // Order is an Aggregate Root (an Entity with version)\n * // OrderState contains child entities (e.g., OrderItem) and value objects\n * }\n * ```\n */\nexport interface IAggregateRoot<TId extends Id<string>> {\n\t/**\n\t * Unique identifier of the aggregate root entity.\n\t */\n\treadonly id: TId;\n\n\t/**\n\t * Version number for optimistic concurrency control.\n\t * Incremented on each state change to detect concurrent modifications.\n\t * This version applies to the entire aggregate, including all child entities.\n\t */\n\treadonly version: Version;\n\n\t/**\n\t * Post-save hook: a `Repository.save()` implementation calls this with\n\t * the persisted version after a successful write to push the new\n\t * version back into the aggregate and clear any recorded domain events\n\t * (they are now safely on the write side / in the outbox).\n\t *\n\t * Required by the interface so a Repository implementation can call it\n\t * via the published `IAggregateRoot` contract without taking the\n\t * abstract class as a compile-time dependency.\n\t *\n\t * @param version - The version assigned by the persistence layer\n\t */\n\tmarkPersisted(version: Version): void;\n}\n\n/**\n * Configuration options for AggregateRoot behavior.\n */\nexport interface AggregateConfig {\n\t/**\n\t * Whether `setState()` should bump the version automatically.\n\t *\n\t * Defaults to **`false`** for `AggregateRoot` โ because `setState()`\n\t * already takes an explicit `bumpVersion` argument per call, so adding\n\t * an \"always bump\" config on top would be redundant. Keep it `false`\n\t * unless you have a subclass that never passes `bumpVersion` and you\n\t * want every state change to advance the version anyway.\n\t *\n\t * (Contrast with `EventSourcedAggregate`, which defaults this to\n\t * `true` because every event-sourced state change is per definition a\n\t * versioned commit.)\n\t */\n\tautoVersionBump?: boolean;\n}\n\n/**\n * Base class for Aggregate Roots without Event Sourcing.\n *\n * In DDD (Evans), an Aggregate is a cluster of objects โ root entity, child entities,\n * and value objects โ treated as a unit for consistency. The **Aggregate Root** is the\n * root entity that represents the aggregate externally and is the only entry point\n * for external code. This class serves as both: it IS the root entity and it contains\n * the aggregate state (`TState`) which holds child entities and value objects.\n *\n * Provides:\n * - Identity (id) and state management (via `Entity`)\n * - Version management for optimistic concurrency control\n * - Domain event tracking for side-effects\n * - Snapshot support for performance optimization\n *\n * All changes to child entities within `TState` are versioned through this root.\n * Use `setState()` for state mutations to ensure invariant validation.\n *\n * For event sourcing, use `EventSourcedAggregate` instead.\n *\n * @template TState - The type of the aggregate state (contains child entities and value objects)\n * @template TId - The type of the aggregate root identifier\n * @template TEvent - The type of domain events recorded by this aggregate (defaults to unknown)\n *\n * @example\n * ```typescript\n * // Order is an Aggregate Root (an Entity with version)\n * class Order extends AggregateRoot<OrderState, OrderId> {\n * constructor(id: OrderId, initialState: OrderState) {\n * super(id, initialState);\n * }\n *\n * confirm(): void {\n * this.setState({ ...this.state, status: \"confirmed\" }, true);\n * }\n * }\n * ```\n */\nexport abstract class AggregateRoot<\n\tTState,\n\tTId extends Id<string>,\n\tTEvent = never,\n>\n\textends Entity<TState, TId>\n\timplements IAggregateRoot<TId> {\n\tprivate _version: Version = 0 as Version;\n\n\tpublic get version(): Version {\n\t\treturn this._version;\n\t}\n\n\tprotected setVersion(version: Version): void {\n\t\tthis._version = version;\n\t}\n\n\tprivate readonly _config: AggregateConfig;\n\tprivate readonly _autoVersionBump: boolean;\n\tprivate _domainEvents: TEvent[] = [];\n\n\t/**\n\t * Returns a read-only list of domain events recorded by this aggregate.\n\t * These events are side-effects of state changes.\n\t */\n\tpublic get domainEvents(): ReadonlyArray<TEvent> {\n\t\treturn Object.freeze(this._domainEvents.slice());\n\t}\n\n\t/**\n\t * Clears the list of recorded domain events.\n\t * Call this after dispatching the events.\n\t */\n\tpublic clearDomainEvents(): void {\n\t\tthis._domainEvents = [];\n\t}\n\n\t/**\n\t * Post-save hook called by a `Repository.save()` implementation to push\n\t * the persisted version back into the in-memory aggregate and clear the\n\t * recorded domain events (they are now safely on the write side / in\n\t * the outbox).\n\t *\n\t * Use this so `save()` can keep its `Promise<void>` return type: the\n\t * caller holds the aggregate reference, which is up to date after this\n\t * call.\n\t */\n\tpublic markPersisted(version: Version): void {\n\t\tthis.setVersion(version);\n\t\tthis._domainEvents = [];\n\t}\n\n\t/**\n\t * Mutates state and records the resulting domain events in the\n\t * **canonical record-after-mutation order**. Use this instead of calling\n\t * `setState` + `addDomainEvent` separately and you cannot trip the\n\t * \"event for a fact that never happened\" footgun.\n\t *\n\t * Order of operations:\n\t * 1. `setState(newState, true)` โ runs `validateState` first.\n\t * If it throws, the method propagates and **no event is recorded\n\t * and no version is bumped**.\n\t * 2. Each event in `events` is appended via `addDomainEvent`.\n\t *\n\t * `commit()` **always bumps the version**, regardless of the aggregate's\n\t * `autoVersionBump` config. Recording a domain event implies \"something\n\t * happened that the outside world cares about\", and optimistic-\n\t * concurrency callers must see a fresh version every time. The config\n\t * still governs the un-coupled `setState` path. If you need to mutate\n\t * state without bumping (e.g. cosmetic caches), call `setState(newState,\n\t * false)` and skip `commit` entirely.\n\t *\n\t * `events` accepts a single event or an array. Omit it (or pass `[]`)\n\t * for state-only mutations.\n\t *\n\t * @example\n\t * ```ts\n\t * confirm(): void {\n\t * if (this.state.status === \"confirmed\") {\n\t * throw new OrderAlreadyConfirmedError(this.id);\n\t * }\n\t * this.commit(\n\t * { ...this.state, status: \"confirmed\" },\n\t * { type: \"OrderConfirmed\", orderId: this.id },\n\t * );\n\t * }\n\t * ```\n\t *\n\t * `EventSourcedAggregate.apply()` enforces the same ordering\n\t * structurally; `commit()` is the opt-in equivalent on `AggregateRoot`,\n\t * where `setState` and `addDomainEvent` are otherwise decoupled and the\n\t * ordering is convention-only.\n\t *\n\t * @param newState - The new state (validated by `validateState`)\n\t * @param events - One event, an array of events, or none (default)\n\t */\n\tprotected commit(\n\t\tnewState: TState,\n\t\tevents: TEvent | readonly TEvent[] = [],\n\t): void {\n\t\tthis.setState(newState, true);\n\t\tconst list: readonly TEvent[] = Array.isArray(events)\n\t\t\t? events\n\t\t\t: [events as TEvent];\n\t\tfor (const ev of list) {\n\t\t\tthis.addDomainEvent(ev);\n\t\t}\n\t}\n\n\tprotected constructor(\n\t\tid: TId,\n\t\tinitialState: TState,\n\t\tconfig?: AggregateConfig,\n\t) {\n\t\tsuper(id, initialState);\n\t\tthis._config = config ?? {};\n\t\tthis._autoVersionBump = this._config.autoVersionBump ?? false;\n\t}\n\n\t/**\n\t * Records a domain event for later publication.\n\t *\n\t * **Ordering: record AFTER state mutation.** Vernon (IDDD ยง8) is\n\t * explicit: a domain event describes something that has just happened\n\t * to the aggregate โ its existence implies the state change already\n\t * occurred. Concretely:\n\t *\n\t * ```ts\n\t * confirm(): void {\n\t * if (this.state.status === \"confirmed\") {\n\t * throw new OrderAlreadyConfirmedError(this.id);\n\t * }\n\t * this.setState({ ...this.state, status: \"confirmed\" }, true);\n\t * this.addDomainEvent({ type: \"OrderConfirmed\", orderId: this.id });\n\t * // โ post-mutation. The event represents the committed fact.\n\t * }\n\t * ```\n\t *\n\t * Recording before mutation is a footgun: if a subsequent invariant\n\t * check throws, the event has already been queued but the state never\n\t * actually changed โ consumers see an event for a fact that did not\n\t * happen.\n\t *\n\t * `EventSourcedAggregate.apply()` enforces this ordering structurally;\n\t * `AggregateRoot` leaves it as a convention because the state-mutation\n\t * path (`setState`) is decoupled from event recording.\n\t *\n\t * @param event - The domain event to record\n\t */\n\tprotected addDomainEvent(event: TEvent): void {\n\t\tthis._domainEvents.push(event);\n\t}\n\n\t/**\n\t * Manually bumps the aggregate version.\n\t * Call this after state changes for Optimistic Concurrency Control.\n\t *\n\t * If `autoVersionBump` is enabled, this is called automatically\n\t * when using `setState()`.\n\t */\n\tprotected bumpVersion(): void {\n\t\tthis.setVersion((this._version + 1) as Version);\n\t}\n\n\t/**\n\t * Sets the state and optionally bumps the version automatically.\n\t * This is a convenience method for state mutations.\n\t * Automatically validates the newState using `validateState()`.\n\t * Overrides Entity.setState to add version bumping.\n\t *\n\t * @param newState - The new state\n\t * @param bumpVersion - Whether to bump the version (defaults to autoVersionBump config)\n\t */\n\tprotected setState(\n\t\tnewState: TState,\n\t\tbumpVersion?: boolean,\n\t): void {\n\t\tsuper.setState(newState);\n\t\tconst shouldBump = bumpVersion ?? this._autoVersionBump;\n\t\tif (shouldBump) {\n\t\t\tthis.bumpVersion();\n\t\t}\n\t}\n\n\t/**\n\t * Creates a snapshot of the current aggregate state.\n\t * Useful for performance optimization, backup/restore, and audit trails.\n\t *\n\t * @returns A snapshot containing the current state and version\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = aggregate.createSnapshot();\n\t * await snapshotRepository.save(aggregate.id, snapshot);\n\t * ```\n\t */\n\tpublic createSnapshot(): AggregateSnapshot<TState> {\n\t\treturn {\n\t\t\tstate: structuredClone(this._state),\n\t\t\tversion: this.version,\n\t\t\tsnapshotAt: new Date(),\n\t\t};\n\t}\n\n\t/**\n\t * Restores the aggregate from a snapshot.\n\t * This is useful for loading aggregates from snapshots instead of\n\t * rebuilding them from scratch.\n\t * Validates the restored state.\n\t *\n\t * @param snapshot - The snapshot to restore from\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = await snapshotRepository.getLatest(aggregateId);\n\t * aggregate.restoreFromSnapshot(snapshot);\n\t * ```\n\t */\n\tpublic restoreFromSnapshot(snapshot: AggregateSnapshot<TState>): void {\n\t\tthis.validateState(snapshot.state);\n\t\tthis._state = freezeShallow(snapshot.state);\n\t\tthis.setVersion(snapshot.version);\n\t}\n}\n","import { BaseError } from \"@shirudo/base-error\";\n\n/**\n * Abstract base for **domain-invariant violations**. Domain methods\n * (aggregates, entity validation hooks, value-object constructors)\n * throw `DomainError`-derived exceptions when a business rule is\n * violated. Consumers derive their own concrete errors โ e.g.\n * `class OrderAlreadyShippedError extends DomainError<\"OrderAlreadyShippedError\"> {}` โ\n * for `instanceof`-style catching at the App-Service boundary, where\n * they typically map to HTTP 400 / business-rule responses.\n *\n * The library itself does **not** ship any concrete `DomainError`\n * subclass โ the kit can't know your invariants. {@link MissingHandlerError},\n * {@link AggregateNotFoundError}, and {@link ConcurrencyConflictError}\n * deliberately sit on other branches of the hierarchy (see below) because\n * they are not invariant violations.\n *\n * Extends `BaseError<Name>` from `@shirudo/base-error`, so derived\n * classes get timestamps, `error.cause` traversal, `toJSON()`, i18n-\n * aware `getUserMessage()`, and the `isRetryable` predicate for free.\n */\nexport abstract class DomainError<\n\tName extends string = string,\n> extends BaseError<Name> {}\n\n/**\n * Abstract base for **infrastructure / persistence failures** that the\n * App-Service can recover from โ typically by retrying, by returning\n * HTTP 404 / 409, or by surfacing a \"please try again\" UX. These are\n * not domain-invariant violations (the business rules were not\n * broken); they describe race conditions and missing rows at the\n * storage boundary.\n *\n * Library-internal concrete subclasses:\n * - {@link AggregateNotFoundError}\n * - {@link ConcurrencyConflictError}\n *\n * Extends `BaseError<Name>` from `@shirudo/base-error`.\n */\nexport abstract class InfrastructureError<\n\tName extends string = string,\n> extends BaseError<Name> {}\n\n/**\n * Thrown by `EventSourcedAggregate.apply()` when no handler is\n * registered for the event's type. This means the aggregate's subclass\n * forgot to add an entry to its `handlers` map โ a programming /\n * configuration bug, not a domain or infrastructure failure.\n *\n * Deliberately **not** on `DomainError` or `InfrastructureError` โ\n * a generic `catch (e instanceof DomainError)` handler at the App\n * layer must not mask a forgotten handler; this should crash loud and\n * fail the calling Use Case so the bug surfaces in development. The\n * replay methods (`loadFromHistory`, `restoreFromSnapshotWithEvents`)\n * also let it propagate uncaught instead of wrapping it in `Result.Err`.\n *\n * Use `isBaseError(e)` from `@shirudo/base-error` to detect\n * \"any structured error from the kit or any other BaseError-using\n * library\" at the App boundary.\n */\nexport class MissingHandlerError extends BaseError<\"MissingHandlerError\"> {\n\tconstructor(public readonly eventType: string) {\n\t\tsuper(`Missing handler for event type: ${eventType}`);\n\t}\n}\n\n/**\n * Thrown by `IRepository.getByIdOrFail()` when an aggregate with the\n * given id does not exist. `InfrastructureError` because the storage\n * boundary, not a business rule, decided the row is absent. Use the\n * nullable variant `getById()` if \"not found\" is a valid outcome.\n *\n * Ships with a user-safe message via `withUserMessage`. Not retryable โ\n * retrying won't make the row appear.\n */\nexport class AggregateNotFoundError extends InfrastructureError<\"AggregateNotFoundError\"> {\n\tconstructor(\n\t\tpublic readonly aggregateType: string,\n\t\tpublic readonly id: string,\n\t) {\n\t\tsuper(`Aggregate not found: ${aggregateType}(${id})`);\n\t\tthis.withUserMessage(\n\t\t\t`The requested ${aggregateType.toLowerCase()} could not be found.`,\n\t\t);\n\t}\n}\n\n/**\n * Thrown by `IRepository.save()` when the aggregate's expected version\n * does not match the version currently persisted โ i.e. another writer\n * updated the aggregate concurrently. The canonical optimistic-\n * concurrency signal; the App-Service typically reloads, re-applies\n * the use case, and retries, or surfaces HTTP 409 to the caller.\n *\n * `InfrastructureError` because the persistence layer (not a domain\n * rule) detects the race. Marks itself as `retryable: true` so the\n * `isRetryable` predicate from `@shirudo/base-error` picks it up.\n */\nexport class ConcurrencyConflictError extends InfrastructureError<\"ConcurrencyConflictError\"> {\n\t/**\n\t * Marks this error as retryable so `isRetryable(err)` returns\n\t * true. The canonical OCC pattern is to reload the aggregate, re-apply\n\t * the use case, and retry on this exception.\n\t */\n\treadonly retryable = true as const;\n\n\tconstructor(\n\t\tpublic readonly aggregateType: string,\n\t\tpublic readonly aggregateId: string,\n\t\tpublic readonly expectedVersion: number,\n\t\tpublic readonly actualVersion: number,\n\t) {\n\t\tsuper(\n\t\t\t`Concurrency conflict on ${aggregateType}(${aggregateId}): expected version ${expectedVersion}, actual ${actualVersion}`,\n\t\t);\n\t\tthis.withUserMessage(\n\t\t\t\"This resource was updated by another request. Please reload and try again.\",\n\t\t);\n\t}\n}\n","import { err, ok, type Result } from \"@shirudo/result\";\nimport type { Id } from \"../core/id\";\nimport { DomainError, MissingHandlerError } from \"../core/errors\";\nimport { Entity, freezeShallow } from \"../entity/entity\";\nimport type { IAggregateRoot } from \"./aggregate-root\";\nimport type { DomainEvent } from \"./domain-event\";\nimport type {\n\tAggregateSnapshot,\n\tVersion,\n} from \"./aggregate\";\n\n/**\n * Interface for Event-Sourced Aggregate Roots.\n * Defines the contract for aggregates that manage state changes via event sourcing.\n *\n * @template TId - The type of the aggregate root identifier\n * @template TEvent - The union type of all domain events\n */\nexport interface IEventSourcedAggregate<\n\tTId extends Id<string>,\n\tTEvent extends DomainEvent<string, unknown>,\n> extends IAggregateRoot<TId> {\n\t/**\n\t * Returns a read-only list of new, not-yet-persisted events.\n\t */\n\treadonly pendingEvents: ReadonlyArray<TEvent>;\n\n\t/**\n\t * Reconstitutes the aggregate from an event history. Returns `Result`\n\t * because event-stream corruption is an expected recoverable failure\n\t * at the infrastructure boundary.\n\t *\n\t * @param history - An ordered list of past events\n\t */\n\tloadFromHistory(history: TEvent[]): Result<void, DomainError>;\n\n\t/**\n\t * Clears the list of pending events.\n\t */\n\tclearPendingEvents(): void;\n\n\t/**\n\t * Checks if the aggregate has any pending events.\n\t */\n\thasPendingEvents(): boolean;\n\n\t/**\n\t * Returns the number of pending events.\n\t */\n\tgetEventCount(): number;\n\n\t/**\n\t * Returns the latest pending event, if any.\n\t */\n\tgetLatestEvent(): TEvent | undefined;\n}\n\ntype Handler<TState, TEvent> = (state: TState, event: TEvent) => TState;\n\n/**\n * Configuration options for EventSourcedAggregate behavior.\n */\nexport interface EventSourcedAggregateConfig {\n\t/**\n\t * Whether `apply()` should bump the version per event.\n\t *\n\t * Defaults to **`true`** for `EventSourcedAggregate` โ each applied\n\t * event is by definition a versioned state change, so the canonical\n\t * event-sourcing pattern is \"one event = one version bump\". Set to\n\t * `false` only if your event store assigns version numbers itself\n\t * and you want the aggregate to track them via `bumpVersion()` /\n\t * `setVersion()` calls instead.\n\t *\n\t * (Contrast with `AggregateRoot`, which defaults this to `false`\n\t * because its `setState()` already takes a per-call `bumpVersion`\n\t * argument.)\n\t */\n\tautoVersionBump?: boolean;\n}\n\n/**\n * Base class for Event-Sourced Aggregate Roots (Vernon, IDDD Chapter 8).\n *\n * Like `AggregateRoot`, this is both the root entity and the aggregate boundary.\n * The difference is persistence: state is derived from events, not stored directly.\n * Events are the single source of truth โ all state changes go through `apply()` โ handler.\n *\n * Extends `Entity` directly (not `AggregateRoot`) so that `setState()` and\n * `addDomainEvent()` are not available. This enforces the event sourcing pattern\n * at the type level โ there is no way to mutate state without going through an event handler.\n *\n * `apply()` and `validateEvent()` throw `DomainError`-derived exceptions on\n * invariant violations. Subclasses override `validateEvent()` to throw their\n * own concrete subclasses (e.g. `OrderAlreadyConfirmedError`). Only the\n * infrastructure-boundary methods (`loadFromHistory`,\n * `restoreFromSnapshotWithEvents`) return `Result` โ they catch `DomainError`\n * during replay so callers can react to corrupted event streams without\n * try/catch.\n *\n * @template TState - The type of the aggregate state (contains child entities and value objects)\n * @template TEvent - The union type of all domain events\n * @template TId - The type of the aggregate root identifier\n *\n * @example\n * ```typescript\n * class OrderAlreadyConfirmedError extends DomainError {\n * constructor(id: OrderId) { super(`Order ${id} is already confirmed`); }\n * }\n *\n * class Order extends EventSourcedAggregate<OrderState, OrderEvent, OrderId> {\n * confirm(): void {\n * this.apply(createDomainEvent(\"OrderConfirmed\", {}));\n * }\n *\n * protected validateEvent(event: OrderEvent): void {\n * if (event.type === \"OrderConfirmed\" && this.state.status === \"confirmed\") {\n * throw new OrderAlreadyConfirmedError(this.id);\n * }\n * }\n *\n * protected readonly handlers = {\n * OrderConfirmed: (state: OrderState): OrderState => ({\n * ...state,\n * status: \"confirmed\",\n * }),\n * };\n * }\n * ```\n */\nexport abstract class EventSourcedAggregate<\n\tTState,\n\tTEvent extends DomainEvent<string, unknown>,\n\tTId extends Id<string>,\n> extends Entity<TState, TId>\n\timplements IEventSourcedAggregate<TId, TEvent> {\n\n\t// --- Version management (own, not inherited from AggregateRoot) ---\n\n\tprivate _version: Version = 0 as Version;\n\n\tpublic get version(): Version {\n\t\treturn this._version;\n\t}\n\n\tprivate setVersion(version: Version): void {\n\t\tthis._version = version;\n\t}\n\n\t// --- Event tracking ---\n\n\tprivate _pendingEvents: TEvent[] = [];\n\tprivate readonly _autoVersionBump: boolean;\n\n\tpublic get pendingEvents(): ReadonlyArray<TEvent> {\n\t\treturn Object.freeze(this._pendingEvents.slice());\n\t}\n\n\tpublic clearPendingEvents(): void {\n\t\tthis._pendingEvents = [];\n\t}\n\n\t/**\n\t * Post-save hook called by a `Repository.save()` implementation to push\n\t * the persisted version back into the in-memory aggregate and clear the\n\t * pending events (they are now in the event store / outbox). Lets\n\t * `save()` keep its `Promise<void>` return type.\n\t */\n\tpublic markPersisted(version: Version): void {\n\t\tthis.setVersion(version);\n\t\tthis._pendingEvents = [];\n\t}\n\n\tprotected constructor(\n\t\tid: TId,\n\t\tinitialState: TState,\n\t\tconfig?: EventSourcedAggregateConfig,\n\t) {\n\t\tsuper(id, initialState);\n\t\tthis._autoVersionBump = config?.autoVersionBump ?? true;\n\t}\n\n\t// --- Event application ---\n\n\t/**\n\t * Validates an event before it is applied. Default is no-op.\n\t * Subclasses override to throw a concrete `DomainError` subclass when\n\t * the event violates an invariant in the current state.\n\t */\n\tprotected validateEvent(_event: TEvent): void {\n\t\t// no-op by default\n\t}\n\n\t/**\n\t * Applies an event: validates, locates the handler, computes the next\n\t * state, then commits state + pending event + version bump atomically.\n\t *\n\t * Throws `DomainError` (or a subclass) on validation failure.\n\t * Throws `MissingHandlerError` if no handler is registered for `event.type`.\n\t *\n\t * State is not mutated if any step throws โ the handler is invoked into\n\t * a local and only assigned to `_state` once all checks pass.\n\t *\n\t * The method is generic in the event tag `K`, so concrete callers\n\t * (`this.apply(orderCreated)`) narrow to the literal tag and the\n\t * dispatched handler is typed as `Handler<TState, Extract<TEvent, { type: K }>>`\n\t * โ no `as` cast required at the call site.\n\t *\n\t * @param event - The domain event to apply\n\t * @param isNew - Whether the event is new (needs persisting) or replayed from history\n\t */\n\tprotected apply<K extends TEvent[\"type\"]>(\n\t\tevent: Extract<TEvent, { type: K }>,\n\t\tisNew = true,\n\t): void {\n\t\tthis.dispatchAndCommit(event, isNew);\n\t}\n\n\t/**\n\t * Internal dispatch path used by `apply()` and the replay methods\n\t * (`loadFromHistory`, `restoreFromSnapshotWithEvents`). The replay loop\n\t * iterates over `TEvent[]` and therefore cannot supply a narrowed `K`\n\t * generic, so this helper accepts `TEvent` and the discriminator is\n\t * resolved via the (statically-sound) `handlers` map.\n\t */\n\tprivate dispatchAndCommit(event: TEvent, isNew: boolean): void {\n\t\tthis.validateEvent(event);\n\n\t\tconst handler = this.handlers[event.type as keyof typeof this.handlers] as\n\t\t\t| Handler<TState, TEvent>\n\t\t\t| undefined;\n\t\tif (!handler) {\n\t\t\tthrow new MissingHandlerError(event.type);\n\t\t}\n\n\t\tconst nextState = handler(this._state, event);\n\n\t\t// Atomic commit: nothing above this line mutated aggregate state.\n\t\tthis._state = freezeShallow(nextState);\n\t\tif (isNew) {\n\t\t\tthis._pendingEvents.push(event);\n\t\t\tif (this._autoVersionBump) {\n\t\t\t\tthis.setVersion((this._version + 1) as Version);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Manually bumps the aggregate version.\n\t * Only needed if `autoVersionBump` is disabled.\n\t */\n\tprotected bumpVersion(): void {\n\t\tthis.setVersion((this._version + 1) as Version);\n\t}\n\n\t// --- History & Snapshots ---\n\n\t/**\n\t * Reconstitutes the aggregate from an event history. Catches `DomainError`\n\t * thrown during replay and returns it as an `Err` โ this is the\n\t * infrastructure boundary, where event-stream corruption is an expected\n\t * recoverable failure. Unexpected (non-DomainError) throws propagate.\n\t *\n\t * Version advances additively: the aggregate's pre-existing version plus\n\t * `history.length`. A fresh aggregate (v=0) loading 3 events ends at v=3;\n\t * an aggregate already at v=1 (e.g. after a creation event) loading\n\t * 2 events ends at v=3, not v=2.\n\t */\n\tpublic loadFromHistory(history: TEvent[]): Result<void, DomainError> {\n\t\tconst startVersion = this._version;\n\t\tfor (const event of history) {\n\t\t\ttry {\n\t\t\t\tthis.dispatchAndCommit(event, false);\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof DomainError) return err(e);\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\tthis.setVersion((startVersion + history.length) as Version);\n\t\treturn ok();\n\t}\n\n\tpublic hasPendingEvents(): boolean {\n\t\treturn this._pendingEvents.length > 0;\n\t}\n\n\tpublic getEventCount(): number {\n\t\treturn this._pendingEvents.length;\n\t}\n\n\tpublic getLatestEvent(): TEvent | undefined {\n\t\treturn this._pendingEvents[this._pendingEvents.length - 1];\n\t}\n\n\t/**\n\t * Creates a snapshot of the current aggregate state.\n\t */\n\tpublic createSnapshot(): AggregateSnapshot<TState> {\n\t\treturn {\n\t\t\tstate: structuredClone(this._state),\n\t\t\tversion: this._version,\n\t\t\tsnapshotAt: new Date(),\n\t\t};\n\t}\n\n\t/**\n\t * Restores the aggregate from a snapshot and applies events that occurred\n\t * after. Same infrastructure-boundary semantics as `loadFromHistory`:\n\t * catches `DomainError` and returns it as an `Err`; non-domain throws\n\t * propagate.\n\t *\n\t * All-or-nothing: if any event mid-stream throws a `DomainError`, the\n\t * aggregate is rolled back to its pre-call state + version. Partial\n\t * restoration is never observable to the caller.\n\t */\n\tpublic restoreFromSnapshotWithEvents(\n\t\tsnapshot: AggregateSnapshot<TState>,\n\t\teventsAfterSnapshot: TEvent[],\n\t): Result<void, DomainError> {\n\t\tconst previousState = this._state;\n\t\tconst previousVersion = this._version;\n\n\t\tthis._state = freezeShallow(snapshot.state);\n\t\tthis.setVersion(snapshot.version);\n\n\t\tfor (const event of eventsAfterSnapshot) {\n\t\t\ttry {\n\t\t\t\tthis.dispatchAndCommit(event, false);\n\t\t\t} catch (e) {\n\t\t\t\tthis._state = previousState;\n\t\t\t\tthis.setVersion(previousVersion);\n\t\t\t\tif (e instanceof DomainError) return err(e);\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\n\t\tthis.setVersion((snapshot.version + eventsAfterSnapshot.length) as Version);\n\t\treturn ok();\n\t}\n\n\t/**\n\t * A map of event types to their corresponding handlers.\n\t * Subclasses MUST implement this property.\n\t */\n\tprotected abstract readonly handlers: {\n\t\t[K in TEvent[\"type\"]]: Handler<TState, Extract<TEvent, { type: K }>>;\n\t};\n}\n","import { err, type Result } from \"@shirudo/result\";\nimport type { Command, CommandHandler } from \"./command\";\n\n/**\n * Type map for command types to their return types.\n * Used to improve type inference in CommandBus.\n *\n * @example\n * ```typescript\n * type MyCommandMap = {\n * CreateOrder: OrderId;\n * CancelOrder: void;\n * };\n *\n * const bus = new CommandBus<MyCommandMap>();\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<OrderId, string> โ automatically inferred\n * ```\n */\ntype CommandTypeMap = Record<string, unknown>;\n\n/**\n * Command Bus interface for dispatching commands to their handlers.\n * Provides a centralized way to execute commands with handler registration.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * Without a type map, the return type must be specified manually or defaults to `unknown`.\n *\n * @template TMap - Optional mapping from command type strings to return types\n *\n * @example\n * ```typescript\n * // With type map (recommended) โ return type is inferred\n * type MyCommands = { CreateOrder: OrderId; CancelOrder: void };\n * const bus = new CommandBus<MyCommands>();\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<OrderId, string>\n *\n * // Without type map โ works like before\n * const bus = new CommandBus();\n * bus.register(\"CreateOrder\", createOrderHandler);\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<unknown, string>\n * ```\n */\nexport interface ICommandBus<TMap extends CommandTypeMap = CommandTypeMap> {\n\t/**\n\t * Executes a command by dispatching it to the registered handler.\n\t * When a type map is provided, the return type is inferred from the command type.\n\t *\n\t * @param command - The command to execute\n\t * @returns Result containing the success value or error message\n\t */\n\texecute<C extends Command & { type: keyof TMap & string }>(\n\t\tcommand: C,\n\t): Promise<Result<TMap[C[\"type\"]], string>>;\n\texecute<C extends Command, R>(command: C): Promise<Result<R, string>>;\n\n\t/**\n\t * Registers a handler for a specific command type.\n\t *\n\t * When `TMap` is supplied, the `commandType` argument is restricted to\n\t * its keys and the handler signature is forced to match `TMap[K]` for the\n\t * return value โ typos and wrong-typed handlers are compile errors.\n\t * Without `TMap` the registration is loose (any string key, any return\n\t * type) so the no-config path keeps working.\n\t *\n\t * @param commandType - The command type to register the handler for\n\t * @param handler - The handler function for this command type\n\t */\n\tregister<\n\t\tK extends keyof TMap & string,\n\t\tC extends Command & { type: K } = Command & { type: K },\n\t>(\n\t\tcommandType: K,\n\t\thandler: CommandHandler<C, TMap[K]>,\n\t): void;\n}\n\n/**\n * Simple in-memory command bus implementation.\n * Handlers are stored in a Map and dispatched based on command type.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * When `TMap` is provided, `execute()` infers the result type from the command type.\n * Without `TMap`, it works like before (return type defaults to `unknown` or can be specified manually).\n *\n * **Note:** This is a basic implementation suitable for development and simple use cases.\n * For production environments, consider implementing or using a more feature-rich bus that includes:\n * - Middleware/Pipeline support (logging, validation, authorization)\n * - Error handling and retry logic\n * - Timeout handling\n * - Metrics and observability\n * - Transaction management\n * - Dead letter queue support\n *\n * The `CommandHandler` type can still be used with external production-grade buses\n * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.\n *\n * @template TMap - Optional mapping from command type strings to return types\n *\n * @example\n * ```typescript\n * // With type map โ full inference\n * type Commands = { CreateOrder: OrderId; CancelOrder: void };\n * const bus = new CommandBus<Commands>();\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<OrderId, string>\n *\n * // Without type map โ same as before\n * const bus = new CommandBus();\n * bus.register(\"CreateOrder\", async (cmd) => ok(orderId));\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * ```\n */\nexport class CommandBus<TMap extends CommandTypeMap = CommandTypeMap>\n\timplements ICommandBus<TMap>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, CommandHandler<any, any>>();\n\n\tregister<\n\t\tK extends keyof TMap & string,\n\t\tC extends Command & { type: K } = Command & { type: K },\n\t>(\n\t\tcommandType: K,\n\t\thandler: CommandHandler<C, TMap[K]>,\n\t): void {\n\t\tthis.handlers.set(commandType, handler);\n\t}\n\n\tasync execute<C extends Command & { type: keyof TMap & string }>(\n\t\tcommand: C,\n\t): Promise<Result<TMap[C[\"type\"]], string>>;\n\tasync execute<C extends Command, R>(\n\t\tcommand: C,\n\t): Promise<Result<R, string>>;\n\tasync execute<C extends Command, R>(\n\t\tcommand: C,\n\t): Promise<Result<R, string>> {\n\t\tconst handler = this.handlers.get(command.type);\n\t\tif (!handler) {\n\t\t\treturn err(`No handler registered for command type: ${command.type}`);\n\t\t}\n\t\ttry {\n\t\t\treturn await handler(command);\n\t\t} catch (error) {\n\t\t\treturn err(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t);\n\t\t}\n\t}\n}\n","import type { EventBus, Outbox } from \"../events/ports\";\nimport type { TransactionScope } from \"../repo/scope\";\n\n/**\n * Helper for executing a write Use Case inside a Unit of Work.\n *\n * Order of operations:\n * 1. `fn()` runs inside `uow.transactional(...)` โ domain mutations + repo\n * writes happen here.\n * 2. `outbox.add(events)` is also inside the transaction, so events\n * persist atomically with the state change (outbox pattern).\n * 3. The transaction commits.\n * 4. **After** the commit, `bus.publish(events)` fires for the in-process\n * fast path.\n *\n * Publishing AFTER commit prevents the classic \"publish before commit\"\n * footgun: in-process subscribers can never react to events from a\n * transaction that later rolled back. If `bus.publish` itself fails, the\n * outbox still holds the events and an outbox-dispatcher will deliver them\n * (eventual consistency).\n *\n * @example\n * ```typescript\n * const result = await withCommit(\n * { outbox, bus, uow },\n * async () => {\n * const order = Order.create(customerId, items);\n * await repository.save(order);\n * return { result: order.id, events: order.domainEvents };\n * }\n * );\n * ```\n */\nexport async function withCommit<Evt extends { type: string }, R>(\n\tdeps: {\n\t\toutbox: Outbox<Evt>;\n\t\tbus?: EventBus<Evt>;\n\t\tscope: TransactionScope;\n\t},\n\tfn: () => Promise<{ result: R; events: ReadonlyArray<Evt> }>,\n): Promise<R> {\n\tconst { result, events } = await deps.scope.transactional(async () => {\n\t\tconst fnResult = await fn();\n\t\tawait deps.outbox.add(fnResult.events);\n\t\treturn fnResult;\n\t});\n\n\tif (deps.bus) {\n\t\tawait deps.bus.publish(events);\n\t}\n\n\treturn result;\n}\n","import { err, ok, type Result } from \"@shirudo/result\";\nimport type { Query, QueryHandler } from \"./query\";\n\n/**\n * Type map for query types to their return types.\n * Used to improve type inference in QueryBus.\n *\n * @example\n * ```typescript\n * type MyQueryMap = {\n * GetOrder: Order | null;\n * ListOrders: Order[];\n * };\n *\n * const bus = new QueryBus<MyQueryMap>();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<Order | null, string> โ automatically inferred\n * ```\n */\ntype QueryTypeMap = Record<string, unknown>;\n\n/**\n * Query Bus interface for dispatching queries to their handlers.\n * Provides a centralized way to execute queries with handler registration.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * Without a type map, the return type must be specified manually or defaults to `unknown`.\n *\n * @template TMap - Optional mapping from query type strings to return types\n *\n * @example\n * ```typescript\n * // With type map (recommended) โ return type is inferred\n * type MyQueries = { GetOrder: Order | null; ListOrders: Order[] };\n * const bus = new QueryBus<MyQueries>();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<Order | null, string>\n *\n * // Without type map โ works like before\n * const bus = new QueryBus();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<unknown, string>\n * ```\n */\nexport interface IQueryBus<TMap extends QueryTypeMap = QueryTypeMap> {\n\t/**\n\t * Executes a query by dispatching it to the registered handler.\n\t * When a type map is provided, the return type is inferred from the query type.\n\t *\n\t * @param query - The query to execute\n\t * @returns Result containing the query result if successful, or an error message\n\t */\n\texecute<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<Result<TMap[Q[\"type\"]], string>>;\n\texecute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;\n\n\t/**\n\t * Executes a query by dispatching it to the registered handler.\n\t * Throws an error if no handler is registered.\n\t *\n\t * @param query - The query to execute\n\t * @returns The query result\n\t * @throws Error if no handler is registered for the query type\n\t */\n\texecuteUnsafe<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<TMap[Q[\"type\"]]>;\n\texecuteUnsafe<Q extends Query, R>(query: Q): Promise<R>;\n\n\t/**\n\t * Registers a handler for a specific query type.\n\t *\n\t * When `TMap` is supplied, the `queryType` argument is restricted to its\n\t * keys and the handler signature is forced to match `TMap[K]` for the\n\t * return value โ typos and wrong-typed handlers are compile errors.\n\t * Without `TMap` the registration is loose (any string key, any return\n\t * type) so the no-config path keeps working.\n\t *\n\t * @param queryType - The query type to register the handler for\n\t * @param handler - The handler function for this query type\n\t */\n\tregister<\n\t\tK extends keyof TMap & string,\n\t\tQ extends Query & { type: K } = Query & { type: K },\n\t>(\n\t\tqueryType: K,\n\t\thandler: QueryHandler<Q, TMap[K]>,\n\t): void;\n}\n\n/**\n * Simple in-memory query bus implementation.\n * Handlers are stored in a Map and dispatched based on query type.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * When `TMap` is provided, `execute()` and `executeUnsafe()` infer the result type from the query type.\n * Without `TMap`, it works like before (return type defaults to `unknown` or can be specified manually).\n *\n * **Note:** This is a basic implementation suitable for development and simple use cases.\n * For production environments, consider implementing or using a more feature-rich bus that includes:\n * - Middleware/Pipeline support (logging, caching, rate limiting)\n * - Error handling\n * - Timeout handling\n * - Metrics and observability\n * - Query result caching\n * - Rate limiting\n *\n * The `QueryHandler` type can still be used with external production-grade buses\n * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.\n *\n * @template TMap - Optional mapping from query type strings to return types\n *\n * @example\n * ```typescript\n * // With type map โ full inference\n * type Queries = { GetOrder: Order | null; ListOrders: Order[] };\n * const bus = new QueryBus<Queries>();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<Order | null, string>\n *\n * // Without type map โ same as before\n * const bus = new QueryBus();\n * bus.register(\"GetOrder\", async (query) => repository.getById(query.orderId));\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * ```\n */\nexport class QueryBus<TMap extends QueryTypeMap = QueryTypeMap>\n\timplements IQueryBus<TMap>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, QueryHandler<any, any>>();\n\n\tregister<\n\t\tK extends keyof TMap & string,\n\t\tQ extends Query & { type: K } = Query & { type: K },\n\t>(\n\t\tqueryType: K,\n\t\thandler: QueryHandler<Q, TMap[K]>,\n\t): void {\n\t\tthis.handlers.set(queryType, handler);\n\t}\n\n\tasync execute<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<Result<TMap[Q[\"type\"]], string>>;\n\tasync execute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;\n\tasync execute<Q extends Query, R>(query: Q): Promise<Result<R, string>> {\n\t\tconst handler = this.handlers.get(query.type);\n\t\tif (!handler) {\n\t\t\treturn err(`No handler registered for query type: ${query.type}`);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await handler(query);\n\t\t\treturn ok(result);\n\t\t} catch (error) {\n\t\t\treturn err(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t);\n\t\t}\n\t}\n\n\tasync executeUnsafe<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<TMap[Q[\"type\"]]>;\n\tasync executeUnsafe<Q extends Query, R>(query: Q): Promise<R>;\n\tasync executeUnsafe<Q extends Query, R>(query: Q): Promise<R> {\n\t\tconst handler = this.handlers.get(query.type);\n\t\tif (!handler) {\n\t\t\tthrow new Error(`No handler registered for query type: ${query.type}`);\n\t\t}\n\t\treturn handler(query);\n\t}\n}\n","import type { DomainEvent } from \"../aggregate/domain-event\";\nimport type { EventBus, EventHandler, OnceOptions } from \"./ports\";\n\n/**\n * Simple in-memory event bus implementation.\n * Supports multiple subscribers per event type (pub/sub pattern).\n *\n * @template Evt - The type of domain events (must extend DomainEvent)\n *\n * @example\n * ```typescript\n * const bus = new EventBusImpl<OrderEvent>();\n *\n * bus.subscribe(\"OrderCreated\", async (event) => {\n * await sendEmail(event.payload.customerId);\n * });\n *\n * bus.subscribe(\"OrderCreated\", async (event) => {\n * await logEvent(event);\n * });\n *\n * await bus.publish([orderCreatedEvent]);\n * // Both handlers will be called\n * ```\n */\nexport class EventBusImpl<Evt extends DomainEvent<string, unknown>>\n\timplements EventBus<Evt>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, EventHandler<any>[]>();\n\n\tsubscribe<K extends Evt[\"type\"]>(\n\t\teventType: K,\n\t\thandler: EventHandler<Extract<Evt, { type: K }>>,\n\t): () => void {\n\t\tconst type = eventType;\n\t\tif (!this.handlers.has(type)) {\n\t\t\tthis.handlers.set(type, []);\n\t\t}\n\t\tconst handlersForType = this.handlers.get(type)!;\n\t\tconst casted = handler as EventHandler<Evt>;\n\t\thandlersForType.push(casted);\n\n\t\t// Return unsubscribe โ removes exactly this subscription, even if the\n\t\t// same handler reference was subscribed multiple times (each call to\n\t\t// subscribe gets its own unsubscribe).\n\t\tlet removed = false;\n\t\treturn () => {\n\t\t\tif (removed) return;\n\t\t\tconst idx = handlersForType.indexOf(casted);\n\t\t\tif (idx !== -1) {\n\t\t\t\thandlersForType.splice(idx, 1);\n\t\t\t\tremoved = true;\n\t\t\t}\n\t\t\tif (handlersForType.length === 0) {\n\t\t\t\tthis.handlers.delete(type);\n\t\t\t}\n\t\t};\n\t}\n\n\tonce<K extends Evt[\"type\"]>(\n\t\teventType: K,\n\t\toptions?: OnceOptions,\n\t): Promise<Extract<Evt, { type: K }>> {\n\t\treturn new Promise<Extract<Evt, { type: K }>>((resolve, reject) => {\n\t\t\t// Reject synchronously if the signal is already aborted โ don't\n\t\t\t// even subscribe.\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\treject(options.signal.reason ?? new Error(\"EventBus.once aborted\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tlet settled = false;\n\t\t\tlet abortListener: (() => void) | undefined;\n\n\t\t\tconst cleanup = () => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tunsubscribe();\n\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\tif (abortListener && options?.signal) {\n\t\t\t\t\toptions.signal.removeEventListener(\"abort\", abortListener);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst unsubscribe = this.subscribe(eventType, (event) => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(event);\n\t\t\t});\n\n\t\t\tif (options?.signal) {\n\t\t\t\tabortListener = () => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\treject(\n\t\t\t\t\t\toptions.signal!.reason ?? new Error(\"EventBus.once aborted\"),\n\t\t\t\t\t);\n\t\t\t\t};\n\t\t\t\toptions.signal.addEventListener(\"abort\", abortListener);\n\t\t\t}\n\n\t\t\tif (typeof options?.timeoutMs === \"number\") {\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`EventBus.once timed out after ${options.timeoutMs}ms waiting for \"${eventType}\"`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}, options.timeoutMs);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * See {@link EventBus.publish} for the full ordering / parallelism /\n\t * error-aggregation contract this implementation realises:\n\t * - events in input order, sequentially;\n\t * - handlers within one event in parallel via `Promise.allSettled`;\n\t * - errors collected and thrown after the batch (single Error, or\n\t * `AggregateError` for multiple failures).\n\t */\n\tasync publish(events: ReadonlyArray<Evt>): Promise<void> {\n\t\tconst errors: Error[] = [];\n\n\t\tfor (const event of events) {\n\t\t\tconst handlersForType = this.handlers.get(event.type);\n\t\t\tif (handlersForType) {\n\t\t\t\t// Snapshot so a handler unsubscribing during dispatch doesn't\n\t\t\t\t// shift indices while we iterate.\n\t\t\t\tconst results = await Promise.allSettled(\n\t\t\t\t\thandlersForType.slice().map((handler) => handler(event)),\n\t\t\t\t);\n\t\t\t\tfor (const result of results) {\n\t\t\t\t\tif (result.status === \"rejected\") {\n\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\tresult.reason instanceof Error\n\t\t\t\t\t\t\t\t? result.reason\n\t\t\t\t\t\t\t\t: new Error(String(result.reason)),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (errors.length === 1) {\n\t\t\tthrow errors[0];\n\t\t}\n\t\tif (errors.length > 1) {\n\t\t\tthrow new AggregateError(errors, \"Multiple event handlers failed\");\n\t\t}\n\t}\n}\n\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shirudo/ddd-kit",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.4",
|
|
4
4
|
"description": "Composable TypeScript toolkit for tactical DDD",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -35,6 +35,7 @@
|
|
|
35
35
|
},
|
|
36
36
|
"devDependencies": {
|
|
37
37
|
"@biomejs/biome": "2.1.4",
|
|
38
|
+
"@shirudo/base-error": "^4.6.0",
|
|
38
39
|
"@shirudo/result": "^0.0.6",
|
|
39
40
|
"tsup": "^8.5.0",
|
|
40
41
|
"typedoc": "^0.28.19",
|
|
@@ -49,11 +50,12 @@
|
|
|
49
50
|
"contributors": [
|
|
50
51
|
"Shirudo"
|
|
51
52
|
],
|
|
52
|
-
"homepage": "https://github.com/shi-rudo/ddd-kit-ts",
|
|
53
|
+
"homepage": "https://github.com/shi-rudo/ddd-kit-ts#readme",
|
|
53
54
|
"bugs": {
|
|
54
55
|
"url": "https://github.com/shi-rudo/ddd-kit-ts/issues"
|
|
55
56
|
},
|
|
56
57
|
"peerDependencies": {
|
|
58
|
+
"@shirudo/base-error": "^4.6.0",
|
|
57
59
|
"@shirudo/result": "^0.0.6"
|
|
58
60
|
},
|
|
59
61
|
"scripts": {
|