@hexafy/core 1.0.0-rc.4 → 1.0.0-rc.6

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.
Files changed (2) hide show
  1. package/README.md +326 -59
  2. package/package.json +8 -5
package/README.md CHANGED
@@ -1,128 +1,395 @@
1
1
  # @hexafy/core
2
2
 
3
- A small, opinionated toolkit for building hexagonal architecture applications in TypeScript.
3
+ Core hexagonal architecture primitives for TypeScript: use cases, domain building blocks, and infrastructure ports/adapters.
4
4
 
5
- This package gives you the core building blocks for domain logic, application use cases, repositories, and error handling without bringing in a framework.
5
+ ## Why this package exists
6
6
 
7
- ## What it includes
7
+ `@hexafy/core` is the foundation of the Hexafy package family. It keeps business logic framework-agnostic and provides:
8
8
 
9
- - `Usecase` base class for application logic
10
- - `UsecaseResult` helpers: `success`, `failure`, `unwrap`, `isSuccess`, `isFailure`
11
- - domain error types such as `ValidationError`, `NotFoundError`, `ConflictError`, and `ApplicationError`
12
- - repository and unit-of-work base abstractions
13
- - logging, clock, identifier, and metrics ports with adapters
9
+ - Application orchestration (`UseCase`, `ServiceBase`)
10
+ - Use-case outcome contract (`UseCaseResult`)
11
+ - Domain errors and primitives (`ApplicationError`, `Entity`, `AggregateRoot`, `ValueObject`, `RepositoryBase`, `Brand`, `ErrorCodes`)
12
+ - Domain error helpers (`isDomainError`, `getDomainErrorCode`)
13
+ - Transaction boundaries (`UnitOfWorkBase`)
14
+ - Cross-cutting ports and default adapters (logging, metrics, clock, identifier)
14
15
 
15
16
  ## Installation
16
17
 
17
18
  ```bash
18
19
  npm install @hexafy/core
19
- # or
20
- bun add @hexafy/core
21
- # or
22
- yarn add @hexafy/core
23
20
  ```
24
21
 
25
- ## Quick start
22
+ ## Core Concepts
23
+
24
+ ### UseCase - Lifecycle & Execution
25
+
26
+ Use cases define single-responsibility business operations with built-in lifecycle management, timeouts, and cancellation.
26
27
 
27
28
  ```ts
28
29
  import {
29
- Usecase,
30
- type UsecaseExecutionConfiguration
30
+ type LoggingPort,
31
+ UseCase,
32
+ type UseCaseConfiguration
31
33
  } from '@hexafy/core/application';
32
- import { type LoggerPort, ValidationError } from '@hexafy/core/domain';
34
+ import {
35
+ RepositoryBase,
36
+ type RepositoryPort,
37
+ type UniqueIdentifier,
38
+ ValidationError
39
+ } from '@hexafy/core/domain';
40
+ import { ConsoleLoggingAdapter } from '@hexafy/core/infrastructure';
33
41
 
34
- interface CreateUserInput {
42
+ interface User {
43
+ id: UniqueIdentifier;
35
44
  email: string;
36
45
  name: string;
37
46
  }
38
47
 
39
- interface User {
40
- id: string;
48
+ interface CreateUserInput {
41
49
  email: string;
42
50
  name: string;
43
51
  }
44
52
 
45
- class CreateUserUseCase extends Usecase<CreateUserInput, User> {
46
- constructor(config?: UsecaseExecutionConfiguration) {
53
+ interface CreateUserOutput {
54
+ id: UniqueIdentifier;
55
+ }
56
+
57
+ class UserRepository extends RepositoryBase<User, UniqueIdentifier> {
58
+ // Override methods (save, findById, etc.) only if you need custom logic
59
+ }
60
+
61
+ class CreateUserUseCase extends UseCase<CreateUserInput, CreateUserOutput> {
62
+ constructor(
63
+ private readonly userRepository: RepositoryPort<User, UniqueIdentifier>,
64
+ config?: UseCaseConfiguration
65
+ ) {
47
66
  super(config);
48
67
  }
49
68
 
69
+ // Implement business logic here
50
70
  protected async executeInternal(
51
71
  input: CreateUserInput,
52
- logger: LoggerPort
53
- ): Promise<User> {
72
+ logger: LoggingPort
73
+ ): Promise<CreateUserOutput> {
54
74
  if (!input.email.includes('@')) {
55
75
  throw new ValidationError('Invalid email');
56
76
  }
57
77
 
58
- logger.info('User created', { email: input.email });
59
-
60
- return {
61
- id: 'user_123',
78
+ const user = {
79
+ id: crypto.randomUUID() as UniqueIdentifier,
62
80
  email: input.email,
63
81
  name: input.name
64
- };
82
+ } satisfies User;
83
+
84
+ await this.userRepository.save(user);
85
+ logger.info('User created', { email: input.email });
86
+
87
+ return { id: user.id };
65
88
  }
66
89
  }
67
90
 
68
- const useCase = new CreateUserUseCase();
91
+ // Wire everything together at the boundary
92
+ const userRepository = new UserRepository();
93
+ const useCase = new CreateUserUseCase(userRepository, {
94
+ // Logging is provided by base class and injected into executeInternal
95
+ logging: ConsoleLoggingAdapter,
96
+ // Safety net: 5 second timeout with automatic cancellation
97
+ timeoutMs: 5000
98
+ });
99
+
69
100
  const result = await useCase.execute({
70
- email: 'john@example.com',
101
+ email: 'user@example.com',
71
102
  name: 'John'
72
103
  });
73
104
 
74
105
  if (result.success) {
75
- console.log(result.value);
76
- } else {
77
- console.error(result.error.message);
106
+ console.log('Created:', result.value);
78
107
  }
108
+ // else handle error
79
109
  ```
80
110
 
81
- ## Core pattern
111
+ ### Cancellation & Timeouts
112
+
113
+ Cancellation via `AbortSignal` and automatic timeouts:
82
114
 
83
- The package is built around a simple application flow:
115
+ ```ts
116
+ // Cancellation
117
+ const controller = new AbortController();
118
+ const result = await useCase.execute(input, { signal: controller.signal });
119
+ controller.abort();
84
120
 
85
- - business logic lives in a `Usecase`
86
- - the use case returns a value on success
87
- - thrown errors are converted into a failed `UsecaseResult`
88
- - infrastructure concerns stay outside the domain layer
121
+ // Timeout in constructor
122
+ const useCase = new MyUseCase({ timeoutMs: 10000 });
123
+ ```
89
124
 
90
- Example:
125
+ ### ServiceBase
126
+
127
+ For reusable services without full use case lifecycle. Services can be injected into use cases.
91
128
 
92
129
  ```ts
93
- import { failure, success } from '@hexafy/core/application';
130
+ import {
131
+ type ClockPort,
132
+ type MetricsPort,
133
+ ServiceBase
134
+ } from '@hexafy/core/application';
94
135
 
95
- const ok = success({ id: '1' });
96
- const bad = failure(new Error('Something went wrong'));
136
+ interface Product {
137
+ id: string;
138
+ name: string;
139
+ price: number;
140
+ }
141
+
142
+ class PricingService extends ServiceBase {
143
+ constructor(
144
+ clock: ClockPort,
145
+ metrics: MetricsPort,
146
+ config?: { logging?: any; clock?: ClockPort; metrics?: MetricsPort }
147
+ ) {
148
+ super(config);
149
+ }
150
+
151
+ // Calculate total price for products
152
+ async calculateTotal(items: Product[]): Promise<number> {
153
+ const startTime = this.clock.now();
154
+
155
+ const total = items.reduce((sum, p) => sum + p.price, 0);
97
156
 
98
- if (ok.success) {
99
- console.log(ok.value.id);
157
+ this.metrics.increment('orders_calculated_total');
158
+ this.metrics.histogram(
159
+ 'calculation_duration',
160
+ this.clock.now() - startTime
161
+ );
162
+
163
+ return total;
164
+ }
165
+ }
166
+
167
+ // Use the service in a use case
168
+ class CheckoutUseCase {
169
+ constructor(
170
+ private readonly pricingService: PricingService,
171
+ private readonly paymentPort: PaymentPort
172
+ ) {}
173
+
174
+ async execute(items: Product[], userId: string): Promise<OrderId> {
175
+ const total = await this.pricingService.calculateTotal(items);
176
+
177
+ const orderId = await this.paymentPort.charge(userId, total);
178
+ return orderId;
179
+ }
100
180
  }
101
181
  ```
102
182
 
103
- ## Package layout
183
+ ### Ports & Adapters
104
184
 
105
- This package exposes focused subpaths:
185
+ Define ports for external concerns and implement them in infrastructure:
186
+
187
+ ```ts
188
+ // Define your port interface
189
+ interface NotificationPort {
190
+ sendEmail(recipient: string, subject: string, body: string): Promise<void>;
191
+ sendSms(phone: string, message: string): Promise<void>;
192
+ }
193
+
194
+ // Implement in your infrastructure layer
195
+ class SendGridNotificationAdapter implements NotificationPort {
196
+ async sendEmail(recipient: string, subject: string, body: string) {
197
+ await sendGrid.send({ to: recipient, subject, body });
198
+ }
199
+
200
+ async sendSms(phone: string, message: string) {
201
+ await twilio.send({ to: phone, message });
202
+ }
203
+ }
204
+
205
+ // Inject the port into your use case
206
+ class UserRegistrationUseCase extends UseCase<RegisterInput, UserId> {
207
+ constructor(
208
+ private readonly notificationPort: NotificationPort, // <-- Injected
209
+ config?: UseCaseConfiguration
210
+ ) {
211
+ super(config);
212
+ }
213
+
214
+ protected async executeInternal(input: RegisterInput): Promise<UserId> {
215
+ const userId = await this.userRepository.save(/* ... */);
216
+
217
+ // Use the port in your business logic
218
+ await this.notificationPort.sendEmail(
219
+ input.email,
220
+ 'Welcome!',
221
+ 'Thanks for signing up!'
222
+ );
223
+
224
+ return userId;
225
+ }
226
+ }
227
+
228
+ // Wire at the application boundary
229
+ const notificationAdapter = new SendGridNotificationAdapter();
230
+ const useCase = new UserRegistrationUseCase(notificationAdapter);
231
+ ```
232
+
233
+ ### Domain Errors
234
+
235
+ Typed error classes for expected failures:
106
236
 
107
237
  ```ts
108
- import { failure, success, Usecase } from '@hexafy/core/application';
109
238
  import {
110
- ApplicationError,
111
- type LoggerPort,
112
- RepositoryBase,
113
- type RepositoryPort,
239
+ ConflictError,
240
+ NotFoundError,
114
241
  ValidationError
115
242
  } from '@hexafy/core/domain';
116
- import { ConsoleLoggingAdapter } from '@hexafy/core/infrastructure';
243
+
244
+ throw new ValidationError('Invalid input', { context: { field: 'email' } });
245
+ throw new NotFoundError('User', { cause: dbError });
246
+ ```
247
+
248
+ ## Error Handling
249
+
250
+ `execute()` returns `UseCaseResult<TSuccess, TFailure>` - never throws exceptions:
251
+
252
+ ```ts
253
+ import {
254
+ UseCaseCancelledError,
255
+ UseCaseTimeoutError
256
+ } from '@hexafy/core/application';
257
+
258
+ const result = await useCase.execute(input, { signal });
259
+
260
+ if (!result.success) {
261
+ if (result.error instanceof UseCaseTimeoutError) {
262
+ // Operation exceeded timeoutMs
263
+ } else if (result.error instanceof UseCaseCancelledError) {
264
+ // Request was cancelled
265
+ } else {
266
+ // Domain/application error from executeInternal (ValidationError, NotFoundError, etc.)
267
+ }
268
+ }
269
+ ```
270
+
271
+ ### Error Classes
272
+
273
+ Typed error classes for expected failures:
274
+
275
+ ```ts
276
+ import {
277
+ ConflictError,
278
+ NotFoundError,
279
+ ValidationError
280
+ } from '@hexafy/core/domain';
281
+
282
+ throw new ValidationError('Invalid input', { context: { field: 'email' } });
283
+ throw new NotFoundError('User', { cause: dbError });
117
284
  ```
118
285
 
119
- ## Recommended usage
286
+ ### Error Flow
287
+
288
+ 1. **In `executeInternal`**: Throw typed domain errors (`ValidationError`, `NotFoundError`, etc.)
289
+ 2. **Wrapped automatically**: Errors flow through `result.error` intact
290
+ 3. **At boundaries**: Map error codes to HTTP status, format responses
291
+
292
+ ### Custom Error Hierarchies
293
+
294
+ Extend `ApplicationError` for your business domain:
295
+
296
+ ```ts
297
+ import { ApplicationError, ErrorCodes } from '@hexafy/core/domain';
298
+
299
+ export class InsufficientBalanceError extends ApplicationError {
300
+ constructor(
301
+ message = 'Insufficient balance',
302
+ options?: { balance: number; required: number }
303
+ ) {
304
+ super(message, {
305
+ ...options,
306
+ code: options?.code ?? ErrorCodes.CONFLICT_ERROR
307
+ });
308
+ }
309
+ }
310
+
311
+ // Usage
312
+ const balance = await accountRepository.getBalance(accountId);
313
+ if (balance < required) {
314
+ throw new InsufficientBalanceError('Insufficient funds', {
315
+ balance,
316
+ required
317
+ });
318
+ }
319
+ ```
320
+
321
+ ### HTTP Mapping
322
+
323
+ Map error codes to HTTP status at your adapter:
324
+
325
+ ```ts
326
+ import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';
327
+
328
+ function mapErrorToStatus(error: Error): number {
329
+ switch (error.code) {
330
+ case ErrorCodes.VALIDATION_ERROR:
331
+ return 400;
332
+ case ErrorCodes.UNAUTHORIZED_ERROR:
333
+ return 401;
334
+ case ErrorCodes.FORBIDDEN_ERROR:
335
+ return 403;
336
+ case ErrorCodes.NOT_FOUND_ERROR:
337
+ return 404;
338
+ case ErrorCodes.CONFLICT_ERROR:
339
+ return 409;
340
+ case ErrorCodes.INFRASTRUCTURE_ERROR:
341
+ return 500;
342
+ default:
343
+ return 500;
344
+ }
345
+ }
346
+
347
+ // NestJS exception filter
348
+ @Catch()
349
+ export class DomainExceptionFilter implements ExceptionFilter {
350
+ catch(exception: unknown, host: ArgumentsHost) {
351
+ const ctx = host.switchToHttp();
352
+ const response = ctx.getResponse<Response>();
353
+
354
+ const statusCode = mapErrorToStatus(exception as Error);
355
+ const error = exception as Error & { code?: string };
356
+
357
+ response.status(statusCode).json({
358
+ success: false,
359
+ error: error.message,
360
+ code: error.code
361
+ });
362
+ }
363
+ }
364
+ ```
365
+
366
+ ## Public API
367
+
368
+ Three subpath entry points:
369
+
370
+ - `@hexafy/core/application` – UseCase, ServiceBase, ports, configuration
371
+ - `@hexafy/core/domain` – Domain primitives, errors, repository ports
372
+ - `@hexafy/core/infrastructure` – Default adapters (logging, clock, metrics, identifier)
373
+
374
+ ## Export Reference
120
375
 
121
- - keep domain rules and validation in `Usecase` or domain types
122
- - let infrastructure code throw unexpected exceptions
123
- - use domain errors for expected business failures
124
- - keep adapters on the edges of the system
125
- - prefer small, explicit ports over framework-specific abstractions
376
+ | Export | Entry Point | When to Use |
377
+ | -------------------------------------------------------------------------- | ----------------- | ----------------------------------------------- |
378
+ | `UseCase`, `UseCaseConfiguration` | `/application` | Business operations with result contract |
379
+ | `ServiceBase`, `ServiceConfiguration` | `/application` | Reusable services |
380
+ | `UseCaseResult`, `UseCaseExecutionOptions` | `/application` | Handling outcomes, passing context/signal |
381
+ | `UseCaseCancelledError`, `UseCaseTimeoutError` | `/application` | Handling execution boundary failures |
382
+ | `ClockPort`, `IdentifierPort`, `LoggingPort`, `MetricsPort` | `/application` | Dependency inversion for cross-cutting concerns |
383
+ | `ApplicationError`, `ErrorCodes` | `/domain` | Error handling, custom error hierarchies |
384
+ | Domain errors (`ValidationError`, `NotFoundError`, etc.) | `/domain` | Expected business failures |
385
+ | `isDomainError`, `getDomainErrorCode` | `/domain` | Type guards and error metadata extraction |
386
+ | `Entity`, `AggregateRoot`, `ValueObject`, `UniqueIdentifier`, `Brand` | `/domain` | Rich domain models |
387
+ | `ApplicationErrorOptions` | `/domain` | Error configuration typing |
388
+ | `RepositoryBase`, `RepositoryPort` | `/domain` | Persistence abstractions |
389
+ | `UnitOfWorkBase` | `/domain` | Transaction boundaries |
390
+ | `SystemClockAdapter`, `SystemIdentifierAdapter` | `/infrastructure` | Production defaults |
391
+ | `ConsoleLoggingAdapter`, `JSONConsoleLoggingAdapter`, `NoOpLoggingAdapter` | `/infrastructure` | Built-in logging implementations |
392
+ | `NoOpMetricsAdapter` | `/infrastructure` | Disable metrics while keeping port contract |
126
393
 
127
394
  ## License
128
395
 
package/package.json CHANGED
@@ -1,13 +1,16 @@
1
1
  {
2
2
  "name": "@hexafy/core",
3
- "version": "1.0.0-rc.4",
4
- "description": "Core hexagonal architecture constructs for TypeScript",
3
+ "version": "1.0.0-rc.6",
4
+ "description": "Hexagonal (ports and adapters) architecture primitives for TypeScript: use cases, domain entities, and infrastructure adapters.",
5
5
  "keywords": [
6
6
  "clean-architecture",
7
- "ddd",
7
+ "domain-driven-design",
8
8
  "hexagonal-architecture",
9
+ "ports-adapter",
10
+ "ports-and-adapters",
9
11
  "typescript",
10
- "use-case"
12
+ "use case",
13
+ "use case pattern"
11
14
  ],
12
15
  "license": "MIT",
13
16
  "author": "Philipp Teßner-Müller",
@@ -43,7 +46,7 @@
43
46
  "devDependencies": {
44
47
  "@hexafy/tsdown-config": "0.0.0",
45
48
  "@hexafy/typescript-config": "0.0.0",
46
- "typescript": "^7.0.2"
49
+ "typescript": "7.0.2"
47
50
  },
48
51
  "engines": {
49
52
  "bun": ">=1.3",