archstone 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Contract for entities that can be created.
3
+ *
4
+ * @template T - The entity type
5
+ */
6
+ interface Creatable<T> {
7
+ /**
8
+ * Persists a new entity for the first time.
9
+ *
10
+ * @param entity - The entity to create
11
+ */
12
+ create(entity: T): Promise<void>;
13
+ }
14
+ /**
15
+ * Contract for entities that can be deleted.
16
+ *
17
+ * @template T - The entity type
18
+ */
19
+ interface Deletable<T> {
20
+ /**
21
+ * Deletes an entity from the repository.
22
+ *
23
+ * @param entity - The entity to delete
24
+ */
25
+ delete(entity: T): Promise<void>;
26
+ }
27
+ /**
28
+ * Contract for entities that can be retrieved by their unique identifier.
29
+ *
30
+ * @template T - The entity type
31
+ */
32
+ interface Findable<T> {
33
+ /**
34
+ * Finds an entity by its unique identifier.
35
+ *
36
+ * @param id - The unique identifier of the entity
37
+ * @returns The entity if found, `null` otherwise
38
+ */
39
+ findById(id: string): Promise<T | null>;
40
+ }
41
+ /**
42
+ * Contract for entities that can be persisted.
43
+ *
44
+ * @template T - The entity type
45
+ */
46
+ interface Saveable<T> {
47
+ /**
48
+ * Persists an existing entity.
49
+ *
50
+ * @param entity - The entity to save
51
+ */
52
+ save(entity: T): Promise<void>;
53
+ }
54
+ /**
55
+ * Full CRUD repository contract, composing all segregated interfaces.
56
+ *
57
+ * Use this when the repository needs to support all operations. For more
58
+ * constrained repositories, prefer composing only the interfaces you need.
59
+ *
60
+ * @template T - The entity type
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * // full CRUD
65
+ * interface UserRepository extends Repository<User> {
66
+ * findByEmail(email: string): Promise<User | null>
67
+ * }
68
+ *
69
+ * // read-only
70
+ * interface ReportRepository extends Findable<Report> {
71
+ * findByPeriod(start: Date, end: Date): Promise<Report[]>
72
+ * }
73
+ *
74
+ * // append-only
75
+ * interface AuditRepository extends Creatable<AuditLog> {}
76
+ * ```
77
+ */
78
+ interface Repository<T> extends Findable<T>, Saveable<T>, Creatable<T>, Deletable<T> {}
79
+ /**
80
+ * Base contract for all use case errors.
81
+ *
82
+ * Implement this interface to define semantic, domain-aware errors
83
+ * that can be returned as the left side of an {@link Either}.
84
+ *
85
+ * @example
86
+ * ```ts
87
+ * class UserNotFoundError implements UseCaseError {
88
+ * message = "User not found."
89
+ * }
90
+ *
91
+ * type FindUserResult = Either<UserNotFoundError, User>
92
+ * ```
93
+ */
94
+ interface UseCaseError {
95
+ message: string;
96
+ }
97
+ /**
98
+ * Represents the left side of an {@link Either} — conventionally used for
99
+ * failure or error values.
100
+ *
101
+ * @template L - The type of the failure value
102
+ * @template R - The type of the success value
103
+ */
104
+ declare class Left<
105
+ L,
106
+ R
107
+ > {
108
+ readonly value: L;
109
+ constructor(value: L);
110
+ isRight(): this is Right<L, R>;
111
+ isLeft(): this is Left<L, R>;
112
+ }
113
+ /**
114
+ * Represents the right side of an {@link Either} — conventionally used for
115
+ * success values.
116
+ *
117
+ * @template L - The type of the failure value
118
+ * @template R - The type of the success value
119
+ */
120
+ declare class Right<
121
+ L,
122
+ R
123
+ > {
124
+ readonly value: R;
125
+ constructor(value: R);
126
+ isRight(): this is Right<L, R>;
127
+ isLeft(): this is Left<L, R>;
128
+ }
129
+ /**
130
+ * A discriminated union that represents a value of one of two possible types.
131
+ *
132
+ * Commonly used as a type-safe alternative to throwing exceptions — the left
133
+ * side carries an error, and the right side carries a success value.
134
+ *
135
+ * Use the {@link left} and {@link right} helper functions to construct values,
136
+ * and `isLeft()` / `isRight()` to narrow the type.
137
+ *
138
+ * @template L - The type of the failure value
139
+ * @template R - The type of the success value
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * type FindUserResult = Either<NotFoundError, User>
144
+ *
145
+ * function findUser(id: string): FindUserResult {
146
+ * const user = db.find(id)
147
+ * if (!user) return left(new NotFoundError("User", id))
148
+ * return right(user)
149
+ * }
150
+ *
151
+ * const result = findUser("123")
152
+ *
153
+ * if (result.isLeft()) {
154
+ * console.error(result.value) // NotFoundError
155
+ * } else {
156
+ * console.log(result.value) // User
157
+ * }
158
+ * ```
159
+ */
160
+ type Either<
161
+ L,
162
+ R
163
+ > = Left<L, R> | Right<L, R>;
164
+ /**
165
+ * Represents the expected output shape of any use case.
166
+ * Always an {@link Either} — left for errors, right for success.
167
+ */
168
+ type UseCaseOutput = Either<UseCaseError | never, unknown | null>;
169
+ /**
170
+ * Base contract for all application use cases.
171
+ *
172
+ * A use case orchestrates domain logic for a single application operation.
173
+ * It receives a typed input, interacts with the domain, and returns an
174
+ * {@link Either} — never throwing exceptions directly.
175
+ *
176
+ * The left side carries a {@link UseCaseError} on failure.
177
+ * The right side carries the success value.
178
+ *
179
+ * @template Input - The shape of the data required to execute the use case
180
+ * @template Output - The expected {@link Either} output, constrained to {@link UseCaseOutput}
181
+ *
182
+ * @example
183
+ * ```ts
184
+ * type Input = { userId: string }
185
+ * type Output = Either<UserNotFoundError, User>
186
+ *
187
+ * class GetUserUseCase implements UseCase<Input, Output> {
188
+ * constructor(private userRepository: UserRepository) {}
189
+ *
190
+ * async execute({ userId }: Input): Promise<Output> {
191
+ * const user = await this.userRepository.findById(userId)
192
+ * if (!user) return left(new UserNotFoundError(userId))
193
+ * return right(user)
194
+ * }
195
+ * }
196
+ * ```
197
+ */
198
+ interface UseCase<
199
+ Input,
200
+ Output extends UseCaseOutput
201
+ > {
202
+ execute(input: Input): Promise<Output>;
203
+ }
204
+ export { UseCaseError, UseCase, Saveable, Repository, Findable, Deletable, Creatable };
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import"../../shared/chunk-wsjyhnpq.js";
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Represents a unique identifier for a domain entity.
3
+ *
4
+ * Wraps a UUID v7 string, which is time-sortable and ideal for database
5
+ * indexing. A new identifier is generated automatically if no value is provided.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * // auto-generated
10
+ * const id = new UniqueEntityId()
11
+ *
12
+ * // from existing value (e.g. reconstructing from database)
13
+ * const id = new UniqueEntityId("0195d810-5b3e-7000-8e3e-1a2b3c4d5e6f")
14
+ * ```
15
+ */
16
+ declare class UniqueEntityId {
17
+ private readonly value;
18
+ constructor(value?: string);
19
+ /**
20
+ * Returns the identifier as a primitive string.
21
+ * Useful for serialization and database persistence.
22
+ */
23
+ toValue(): string;
24
+ /**
25
+ * Returns the string representation of the identifier.
26
+ */
27
+ toString(): string;
28
+ /**
29
+ * Compares this identifier with another by value equality.
30
+ *
31
+ * @param id - The identifier to compare against
32
+ * @returns `true` if both identifiers have the same value
33
+ */
34
+ equals(id: UniqueEntityId): boolean;
35
+ }
36
+ /**
37
+ * Base contract for all domain events.
38
+ *
39
+ * A domain event represents something meaningful that happened in the domain.
40
+ * Events are raised by aggregate roots and dispatched after successful persistence,
41
+ * enabling decoupled side effects such as notifications, projections, and integrations.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * class UserCreatedEvent implements DomainEvent {
46
+ * occurredAt = new Date()
47
+ *
48
+ * constructor(private readonly user: User) {}
49
+ *
50
+ * getAggregateId(): UniqueEntityId {
51
+ * return this.user.id
52
+ * }
53
+ * }
54
+ * ```
55
+ */
56
+ interface DomainEvent {
57
+ /**
58
+ * Returns the identifier of the aggregate root that raised this event.
59
+ */
60
+ getAggregateId(): UniqueEntityId;
61
+ /**
62
+ * The date and time when the event occurred.
63
+ */
64
+ occurredAt: Date;
65
+ }
66
+ /**
67
+ * Callback function invoked when a domain event is dispatched.
68
+ */
69
+ type DomainEventCallback = (event: DomainEvent) => void;
70
+ /**
71
+ * Central registry and dispatcher for domain events.
72
+ *
73
+ * Aggregates register themselves for dispatch after raising events.
74
+ * The infrastructure layer is responsible for calling {@link dispatchEventsForAggregate}
75
+ * after successfully persisting an aggregate, ensuring events are only
76
+ * dispatched after a successful transaction.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * // register a handler
81
+ * DomainEvents.register(
82
+ * (event) => sendWelcomeEmail(event as UserCreatedEvent),
83
+ * UserCreatedEvent.name,
84
+ * )
85
+ *
86
+ * // dispatch after persistence
87
+ * await userRepository.create(user)
88
+ * DomainEvents.dispatchEventsForAggregate(user.id)
89
+ * ```
90
+ */
91
+ declare class DomainEventsImplementation {
92
+ private readonly handlersMap;
93
+ private readonly markedAggregates;
94
+ /**
95
+ * Marks an aggregate root to have its events dispatched.
96
+ * Called automatically by {@link AggregateRoot.addDomainEvent}.
97
+ *
98
+ * @param aggregate - The aggregate to mark for dispatch
99
+ */
100
+ markAggregateForDispatch(aggregate: AggregateRoot<unknown>): void;
101
+ /**
102
+ * Dispatches all pending events for the aggregate with the given id,
103
+ * clears its events, and removes it from the dispatch list.
104
+ *
105
+ * Should be called by the infrastructure layer after persisting the aggregate.
106
+ *
107
+ * @param id - The identifier of the aggregate to dispatch events for
108
+ */
109
+ dispatchEventsForAggregate(id: UniqueEntityId): void;
110
+ /**
111
+ * Registers an event handler for a given event class name.
112
+ *
113
+ * @param callback - The function to invoke when the event is dispatched
114
+ * @param eventClassName - The name of the event class to listen for
115
+ */
116
+ register(callback: DomainEventCallback, eventClassName: string): void;
117
+ /**
118
+ * Removes all registered event handlers.
119
+ * Useful for test isolation.
120
+ */
121
+ clearHandlers(): void;
122
+ /**
123
+ * Removes all aggregates from the dispatch list.
124
+ * Useful for test isolation.
125
+ */
126
+ clearMarkedAggregates(): void;
127
+ private dispatchAggregateEvents;
128
+ private removeAggregateFromMarkedDispatchList;
129
+ private findMarkedAggregateByID;
130
+ private dispatch;
131
+ }
132
+ /**
133
+ * Singleton instance of the domain events registry.
134
+ * Use this to register handlers and dispatch events across the application.
135
+ */
136
+ declare const DomainEvents: DomainEventsImplementation;
137
+ /**
138
+ * Base contract for all event handlers.
139
+ *
140
+ * An event handler is responsible for subscribing to domain events
141
+ * and executing side effects in response — such as sending emails,
142
+ * updating read models, or triggering external integrations.
143
+ *
144
+ * All handlers must implement {@link setupSubscriptions} to register
145
+ * their callbacks in the {@link DomainEvents} registry.
146
+ *
147
+ * @example
148
+ * ```ts
149
+ * class OnUserCreated implements EventHandler {
150
+ * constructor(private readonly mailer: Mailer) {}
151
+ *
152
+ * setupSubscriptions(): void {
153
+ * DomainEvents.register(
154
+ * (event) => this.sendWelcomeEmail(event as UserCreatedEvent),
155
+ * UserCreatedEvent.name,
156
+ * )
157
+ * }
158
+ *
159
+ * private async sendWelcomeEmail(event: UserCreatedEvent): Promise<void> {
160
+ * await this.mailer.send(event.user.email)
161
+ * }
162
+ * }
163
+ * ```
164
+ */
165
+ interface EventHandler {
166
+ /**
167
+ * Registers all event subscriptions for this handler.
168
+ * Should be called once during application bootstrap.
169
+ */
170
+ setupSubscriptions(): void;
171
+ }
172
+ /**
173
+ * Base class for all domain entities.
174
+ *
175
+ * An entity is an object defined by its identity rather than its attributes.
176
+ * Two entities are considered equal if they share the same `id`, regardless
177
+ * of their other properties.
178
+ *
179
+ * All entities must implement a static `create` factory method to encapsulate
180
+ * construction logic and keep the constructor protected.
181
+ *
182
+ * @template Props - The shape of the entity's properties
183
+ *
184
+ * @example
185
+ * ```ts
186
+ * interface UserProps {
187
+ * id: UniqueEntityId
188
+ * name: string
189
+ * email: string
190
+ * createdAt: Date
191
+ * }
192
+ *
193
+ * class User extends Entity<UserProps> {
194
+ * get name() { return this.props.name }
195
+ * get email() { return this.props.email }
196
+ *
197
+ * static create(props: Optional<UserProps, "id" | "createdAt">): User {
198
+ * return new User(
199
+ * { ...props, createdAt: props.createdAt ?? new Date() },
200
+ * props.id ?? new UniqueEntityId(),
201
+ * )
202
+ * }
203
+ * }
204
+ * ```
205
+ */
206
+ declare abstract class Entity<Props> {
207
+ private readonly _id;
208
+ protected props: Props;
209
+ get id(): UniqueEntityId;
210
+ protected constructor(props: Props, id?: UniqueEntityId);
211
+ /**
212
+ * Compares this entity with another by identity.
213
+ *
214
+ * @param entity - The entity to compare against
215
+ * @returns `true` if both entities share the same `id`
216
+ */
217
+ equals(entity: Entity<unknown>): boolean;
218
+ }
219
+ /**
220
+ * Base class for all aggregate roots in the domain.
221
+ *
222
+ * An aggregate root is the entry point to an aggregate — a cluster of domain
223
+ * objects that are treated as a single unit. It is responsible for enforcing
224
+ * invariants and coordinating domain events within its boundary.
225
+ *
226
+ * Domain events are collected internally and dispatched after the aggregate
227
+ * is persisted, ensuring side effects only occur after a successful transaction.
228
+ *
229
+ * @template Props - The shape of the aggregate's properties
230
+ *
231
+ * @example
232
+ * ```ts
233
+ * class User extends AggregateRoot<UserProps> {
234
+ * static create(props: Optional<UserProps, "id" | "createdAt">): User {
235
+ * const user = new User(
236
+ * { ...props, createdAt: props.createdAt ?? new Date() },
237
+ * props.id ?? new UniqueEntityId(),
238
+ * )
239
+ *
240
+ * user.addDomainEvent(new UserCreatedEvent(user))
241
+ *
242
+ * return user
243
+ * }
244
+ * }
245
+ * ```
246
+ */
247
+ declare abstract class AggregateRoot<Props> extends Entity<Props> {
248
+ private readonly _domainEvents;
249
+ /**
250
+ * Returns all domain events that have been raised by this aggregate
251
+ * and are pending dispatch.
252
+ */
253
+ get domainEvents(): DomainEvent[];
254
+ /**
255
+ * Registers a domain event to be dispatched after the aggregate is persisted.
256
+ * Automatically marks this aggregate for dispatch in the {@link DomainEvents} registry.
257
+ *
258
+ * @param domainEvent - The domain event to register
259
+ */
260
+ protected addDomainEvent(domainEvent: DomainEvent): void;
261
+ /**
262
+ * Clears all pending domain events from this aggregate.
263
+ * Should be called by the infrastructure layer after events are dispatched.
264
+ */
265
+ clearEvents(): void;
266
+ }
267
+ export { EventHandler, Entity, DomainEvents, DomainEvent, AggregateRoot };
@@ -0,0 +1,12 @@
1
+ // @bun
2
+ import {
3
+ AggregateRoot,
4
+ DomainEvents,
5
+ Entity
6
+ } from "../../shared/chunk-9cq8r162.js";
7
+ import"../../shared/chunk-wzqmg7ms.js";
8
+ export {
9
+ Entity,
10
+ DomainEvents,
11
+ AggregateRoot
12
+ };