@hexafy/core 1.0.0-rc.0 → 1.0.0-rc.2
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 +63 -304
- package/package.json +3 -2
- package/dist/application.d.mts +0 -170
- package/dist/application.d.mts.map +0 -1
- package/dist/application.mjs +0 -146
- package/dist/application.mjs.map +0 -1
- package/dist/domain.d.mts +0 -500
- package/dist/domain.d.mts.map +0 -1
- package/dist/domain.mjs +0 -350
- package/dist/domain.mjs.map +0 -1
- package/dist/infrastructure.d.mts +0 -38
- package/dist/infrastructure.d.mts.map +0 -1
- package/dist/infrastructure.mjs +0 -98
- package/dist/infrastructure.mjs.map +0 -1
- package/dist/metrics.port-CfI8yKMA.d.mts +0 -114
- package/dist/metrics.port-CfI8yKMA.d.mts.map +0 -1
- package/dist/noop.metrics.adapter-MgMrk-sq.mjs +0 -53
- package/dist/noop.metrics.adapter-MgMrk-sq.mjs.map +0 -1
package/dist/application.mjs
DELETED
|
@@ -1,146 +0,0 @@
|
|
|
1
|
-
import { i as SystemClockAdapter, n as ConsoleLoggingAdapter, r as SystemIdentifierAdapter, t as NoOpMetricsAdapter } from "./noop.metrics.adapter-MgMrk-sq.mjs";
|
|
2
|
-
// src/application/utils/usecase-result.utils.ts
|
|
3
|
-
/**
|
|
4
|
-
* Result type indicating a successful use case execution.
|
|
5
|
-
*
|
|
6
|
-
* @template T - The type of the success value
|
|
7
|
-
* @param value - The successfully computed value
|
|
8
|
-
*/
|
|
9
|
-
function success(value) {
|
|
10
|
-
return {
|
|
11
|
-
success: true,
|
|
12
|
-
value
|
|
13
|
-
};
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* Result type indicating a failed use case execution.
|
|
17
|
-
*
|
|
18
|
-
* @template TError - The type of the error
|
|
19
|
-
* @param error - The error that occurred
|
|
20
|
-
*/
|
|
21
|
-
function failure(error) {
|
|
22
|
-
return {
|
|
23
|
-
success: false,
|
|
24
|
-
error
|
|
25
|
-
};
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Extracts the value from a successful UsecaseResult.
|
|
29
|
-
*
|
|
30
|
-
* @template TSuccess - The type of the success value
|
|
31
|
-
* @template TError - The type of the error
|
|
32
|
-
* @param result - The result to unwrap
|
|
33
|
-
* @returns The success value
|
|
34
|
-
* @throws {Error} If the result represents a failure
|
|
35
|
-
*/
|
|
36
|
-
function unwrap(result) {
|
|
37
|
-
if (result.success) return result.value;
|
|
38
|
-
throw result.error;
|
|
39
|
-
}
|
|
40
|
-
// src/application/usecase.ts
|
|
41
|
-
/**
|
|
42
|
-
* Abstract base class for all use cases.
|
|
43
|
-
*
|
|
44
|
-
* Provides structured logging, execution IDs, and duration tracking.
|
|
45
|
-
*
|
|
46
|
-
* Simple semantics:
|
|
47
|
-
*
|
|
48
|
-
* - Return a value → success (wrapped automatically)
|
|
49
|
-
* - Throw an error → failure (wrapped automatically)
|
|
50
|
-
*
|
|
51
|
-
* Logging is enabled by default (uses console logger) for developer
|
|
52
|
-
* convenience. To disable logging, explicitly pass NOOP_LOGGER.
|
|
53
|
-
*
|
|
54
|
-
* The framework logs the fact of failure, not the error details. Consumers
|
|
55
|
-
* handle error logging at the call site by inspecting the Result type.
|
|
56
|
-
*
|
|
57
|
-
* @example
|
|
58
|
-
* ```typescript
|
|
59
|
-
* // Default: uses consoleLogger (logs to console)
|
|
60
|
-
* const useCase = new CreateUserUseCase({});
|
|
61
|
-
* await useCase.execute({ email: 'user@example.com' });
|
|
62
|
-
* // → Logs to console
|
|
63
|
-
*
|
|
64
|
-
* // Disable logging (for tests or silent mode)
|
|
65
|
-
* const silentUseCase = new CreateUserUseCase({
|
|
66
|
-
* logger: NOOP_LOGGER
|
|
67
|
-
* });
|
|
68
|
-
* await silentUseCase.execute({ email: 'user@example.com' });
|
|
69
|
-
* // → No output
|
|
70
|
-
*
|
|
71
|
-
* // Custom logger
|
|
72
|
-
* const useCase = new CreateUserUseCase({
|
|
73
|
-
* logger: myCustomLogger
|
|
74
|
-
* });
|
|
75
|
-
* ```;
|
|
76
|
-
*
|
|
77
|
-
* @template TInput - The input type for the use case
|
|
78
|
-
* @template TOutput - The output type for the use case
|
|
79
|
-
*/
|
|
80
|
-
var Usecase = class {
|
|
81
|
-
dependencies;
|
|
82
|
-
constructor(dependencies = {}) {
|
|
83
|
-
this.dependencies = dependencies;
|
|
84
|
-
}
|
|
85
|
-
/**
|
|
86
|
-
* Execute the use case.
|
|
87
|
-
*
|
|
88
|
-
* @param input - The input data for the use case
|
|
89
|
-
* @param executionContext - Additional context to include in logs
|
|
90
|
-
* @param cancellationToken - Optional token for requesting cancellation
|
|
91
|
-
* @returns Promise resolving to a Result (success or failure)
|
|
92
|
-
*/
|
|
93
|
-
async execute(input, executionContext, cancellationToken) {
|
|
94
|
-
const startTime = this.getNow();
|
|
95
|
-
const executionId = this.getExecutionId();
|
|
96
|
-
const baseContext = {
|
|
97
|
-
executionId,
|
|
98
|
-
...executionContext ?? {}
|
|
99
|
-
};
|
|
100
|
-
const logger = this.getOrCreateLoggingAdapter();
|
|
101
|
-
const metrics = this.getOrCreateMetricsAdapter();
|
|
102
|
-
if (cancellationToken?.isCancelled) {
|
|
103
|
-
metrics.increment("usecase_cancelled", { executionId: String(executionId) });
|
|
104
|
-
return failure(new Error(cancellationToken.reason ?? "Cancellation requested"));
|
|
105
|
-
}
|
|
106
|
-
try {
|
|
107
|
-
const result = await this.executeInternal(input, logger, cancellationToken);
|
|
108
|
-
const durationMs = this.getNow() - startTime;
|
|
109
|
-
logger.info("Execution completed", {
|
|
110
|
-
...baseContext,
|
|
111
|
-
durationMs
|
|
112
|
-
});
|
|
113
|
-
metrics.histogram("usecase_duration", durationMs);
|
|
114
|
-
return success(result);
|
|
115
|
-
} catch (error) {
|
|
116
|
-
const durationMs = this.getNow() - startTime;
|
|
117
|
-
logger.error("Execution failed", {
|
|
118
|
-
...baseContext,
|
|
119
|
-
durationMs
|
|
120
|
-
});
|
|
121
|
-
metrics.increment("usecase_errors", { executionId: String(executionId) });
|
|
122
|
-
return failure(this.normalizeError(error));
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
getNow() {
|
|
126
|
-
return this.dependencies.clock?.now() ?? SystemClockAdapter.now();
|
|
127
|
-
}
|
|
128
|
-
getExecutionId() {
|
|
129
|
-
return this.dependencies.identifier?.generate(this.getNowAdapter()) ?? SystemIdentifierAdapter.generate(this.getNowAdapter());
|
|
130
|
-
}
|
|
131
|
-
getNowAdapter() {
|
|
132
|
-
return this.dependencies.clock ?? SystemClockAdapter;
|
|
133
|
-
}
|
|
134
|
-
getOrCreateLoggingAdapter() {
|
|
135
|
-
return this.dependencies.logging ?? ConsoleLoggingAdapter;
|
|
136
|
-
}
|
|
137
|
-
getOrCreateMetricsAdapter() {
|
|
138
|
-
return this.dependencies.metrics ?? NoOpMetricsAdapter;
|
|
139
|
-
}
|
|
140
|
-
normalizeError(error) {
|
|
141
|
-
return error instanceof Error ? error : new Error(String(error));
|
|
142
|
-
}
|
|
143
|
-
};
|
|
144
|
-
export { Usecase, failure, success, unwrap };
|
|
145
|
-
|
|
146
|
-
//# sourceMappingURL=application.mjs.map
|
package/dist/application.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"application.mjs","names":[],"sources":["../src/application/utils/usecase-result.utils.ts","../src/application/usecase.ts"],"sourcesContent":["import type { UsecaseResult } from '../types';\n\n/**\n * Type guard to check if a UsecaseResult represents success.\n *\n * @template T - The type of the success value\n * @template E - The type of the error\n * @param result - The result to check\n * @returns True if the result is a success\n */\nexport function isSuccess<T, E extends Error>(\n result: UsecaseResult<T, E>\n): result is { success: true; value: T } {\n return result.success === true;\n}\n\n/**\n * Type guard to check if a UsecaseResult represents failure.\n *\n * @template T - The type of the success value\n * @template E - The type of the error\n * @param result - The result to check\n * @returns True if the result is a failure\n */\nexport function isFailure<T, E extends Error>(\n result: UsecaseResult<T, E>\n): result is { success: false; error: E } {\n return result.success === false;\n}\n\n/**\n * Result type indicating a successful use case execution.\n *\n * @template T - The type of the success value\n * @param value - The successfully computed value\n */\nexport function success<T>(value: T): UsecaseResult<T, never> {\n return { success: true, value };\n}\n\n/**\n * Result type indicating a failed use case execution.\n *\n * @template TError - The type of the error\n * @param error - The error that occurred\n */\nexport function failure<TError extends Error>(\n error: TError\n): UsecaseResult<never, TError> {\n return { success: false, error };\n}\n\n/**\n * Extracts the value from a successful UsecaseResult.\n *\n * @template TSuccess - The type of the success value\n * @template TError - The type of the error\n * @param result - The result to unwrap\n * @returns The success value\n * @throws {Error} If the result represents a failure\n */\nexport function unwrap<TSuccess, TError>(\n result: UsecaseResult<TSuccess, TError>\n): TSuccess {\n if (result.success) {\n return result.value;\n }\n throw result.error;\n}\n","import type {\n ClockPort,\n IdentifierPort,\n LoggingPort,\n MetricsPort\n} from '../domain/ports';\nimport type { UniqueIdentifier } from '../domain/primitives';\nimport {\n ConsoleLoggingAdapter,\n NoOpMetricsAdapter,\n SystemClockAdapter,\n SystemIdentifierAdapter\n} from '../infrastructure/adapters';\nimport type { CancellationToken, UsecaseResult } from './types';\nimport { failure, success } from './utils';\n\n/** Configuration for use case execution. */\nexport interface UsecaseExecutionConfiguration {\n clock?: ClockPort;\n /**\n * Optional logging instance. If not provided, consoleLogger is used by\n * default for developer convenience. Set to NOOP_LOGGER to explicitly disable\n * logging.\n */\n logging?: LoggingPort;\n /**\n * Optional metrics port for observability. If not provided, NOOP_METRICS is\n * used (no metrics recorded). Pass a custom implementation to enable metrics\n * collection.\n */\n metrics?: MetricsPort;\n identifier?: IdentifierPort;\n}\n\n/** Alias for UsecaseExecutionConfiguration for backwards compatibility. */\nexport type UsecaseExecutionDependencies = UsecaseExecutionConfiguration;\n\n/**\n * Abstract base class for all use cases.\n *\n * Provides structured logging, execution IDs, and duration tracking.\n *\n * Simple semantics:\n *\n * - Return a value → success (wrapped automatically)\n * - Throw an error → failure (wrapped automatically)\n *\n * Logging is enabled by default (uses console logger) for developer\n * convenience. To disable logging, explicitly pass NOOP_LOGGER.\n *\n * The framework logs the fact of failure, not the error details. Consumers\n * handle error logging at the call site by inspecting the Result type.\n *\n * @example\n * ```typescript\n * // Default: uses consoleLogger (logs to console)\n * const useCase = new CreateUserUseCase({});\n * await useCase.execute({ email: 'user@example.com' });\n * // → Logs to console\n *\n * // Disable logging (for tests or silent mode)\n * const silentUseCase = new CreateUserUseCase({\n * logger: NOOP_LOGGER\n * });\n * await silentUseCase.execute({ email: 'user@example.com' });\n * // → No output\n *\n * // Custom logger\n * const useCase = new CreateUserUseCase({\n * logger: myCustomLogger\n * });\n * ```;\n *\n * @template TInput - The input type for the use case\n * @template TOutput - The output type for the use case\n */\nexport abstract class Usecase<TInput = void, TOutput = void> {\n constructor(\n protected readonly dependencies: UsecaseExecutionConfiguration = {}\n ) {}\n\n /**\n * Abstract method to implement.\n *\n * Simple semantics:\n *\n * - Return a value → success (wrapped automatically)\n * - Throw an error → failure (wrapped automatically)\n *\n * Use the logger to log business logic and errors as needed.\n */\n protected abstract executeInternal(\n input: TInput,\n logger: LoggingPort,\n cancellationToken?: CancellationToken\n ): Promise<TOutput>;\n\n /**\n * Execute the use case.\n *\n * @param input - The input data for the use case\n * @param executionContext - Additional context to include in logs\n * @param cancellationToken - Optional token for requesting cancellation\n * @returns Promise resolving to a Result (success or failure)\n */\n async execute(\n input: TInput,\n executionContext?: Record<string, unknown>,\n cancellationToken?: CancellationToken\n ): Promise<UsecaseResult<TOutput, Error>> {\n const startTime = this.getNow();\n const executionId = this.getExecutionId();\n const baseContext = { executionId, ...(executionContext ?? {}) };\n const logger = this.getOrCreateLoggingAdapter();\n const metrics = this.getOrCreateMetricsAdapter();\n\n if (cancellationToken?.isCancelled) {\n metrics.increment('usecase_cancelled', {\n executionId: String(executionId)\n });\n return failure(\n new Error(cancellationToken.reason ?? 'Cancellation requested')\n );\n }\n\n try {\n const result = await this.executeInternal(\n input,\n logger,\n cancellationToken\n );\n\n const durationMs = this.getNow() - startTime;\n logger.info('Execution completed', { ...baseContext, durationMs });\n metrics.histogram('usecase_duration', durationMs);\n\n return success(result);\n } catch (error) {\n const durationMs = this.getNow() - startTime;\n logger.error('Execution failed', { ...baseContext, durationMs });\n metrics.increment('usecase_errors', { executionId: String(executionId) });\n\n return failure(this.normalizeError(error));\n }\n }\n\n private getNow(): number {\n return this.dependencies.clock?.now() ?? SystemClockAdapter.now();\n }\n\n private getExecutionId(): UniqueIdentifier {\n return (\n this.dependencies.identifier?.generate(this.getNowAdapter()) ??\n SystemIdentifierAdapter.generate(this.getNowAdapter())\n );\n }\n\n private getNowAdapter(): ClockPort {\n return this.dependencies.clock ?? SystemClockAdapter;\n }\n\n private getOrCreateLoggingAdapter(): LoggingPort {\n return this.dependencies.logging ?? ConsoleLoggingAdapter;\n }\n\n private getOrCreateMetricsAdapter(): MetricsPort {\n return this.dependencies.metrics ?? NoOpMetricsAdapter;\n }\n\n private normalizeError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n }\n}\n"],"mappings":";;;;;;;;AAoCA,SAAgB,QAAW,OAAmC;CAC5D,OAAO;EAAE,SAAS;EAAM;CAAM;AAChC;;;;;;;AAQA,SAAgB,QACd,OAC8B;CAC9B,OAAO;EAAE,SAAS;EAAO;CAAM;AACjC;;;;;;;;;;AAWA,SAAgB,OACd,QACU;CACV,IAAI,OAAO,SACT,OAAO,OAAO;CAEhB,MAAM,OAAO;AACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACQA,IAAsB,UAAtB,MAA6D;CAEtC;CADrB,YACE,eAAiE,CAAC,GAClE;EADmB,KAAA,eAAA;CAClB;;;;;;;;;CA0BH,MAAM,QACJ,OACA,kBACA,mBACwC;EACxC,MAAM,YAAY,KAAK,OAAO;EAC9B,MAAM,cAAc,KAAK,eAAe;EACxC,MAAM,cAAc;GAAE;GAAa,GAAI,oBAAoB,CAAC;EAAG;EAC/D,MAAM,SAAS,KAAK,0BAA0B;EAC9C,MAAM,UAAU,KAAK,0BAA0B;EAE/C,IAAI,mBAAmB,aAAa;GAClC,QAAQ,UAAU,qBAAqB,EACrC,aAAa,OAAO,WAAW,EACjC,CAAC;GACD,OAAO,QACL,IAAI,MAAM,kBAAkB,UAAU,wBAAwB,CAChE;EACF;EAEA,IAAI;GACF,MAAM,SAAS,MAAM,KAAK,gBACxB,OACA,QACA,iBACF;GAEA,MAAM,aAAa,KAAK,OAAO,IAAI;GACnC,OAAO,KAAK,uBAAuB;IAAE,GAAG;IAAa;GAAW,CAAC;GACjE,QAAQ,UAAU,oBAAoB,UAAU;GAEhD,OAAO,QAAQ,MAAM;EACvB,SAAS,OAAO;GACd,MAAM,aAAa,KAAK,OAAO,IAAI;GACnC,OAAO,MAAM,oBAAoB;IAAE,GAAG;IAAa;GAAW,CAAC;GAC/D,QAAQ,UAAU,kBAAkB,EAAE,aAAa,OAAO,WAAW,EAAE,CAAC;GAExE,OAAO,QAAQ,KAAK,eAAe,KAAK,CAAC;EAC3C;CACF;CAEA,SAAyB;EACvB,OAAO,KAAK,aAAa,OAAO,IAAI,KAAK,mBAAmB,IAAI;CAClE;CAEA,iBAA2C;EACzC,OACE,KAAK,aAAa,YAAY,SAAS,KAAK,cAAc,CAAC,KAC3D,wBAAwB,SAAS,KAAK,cAAc,CAAC;CAEzD;CAEA,gBAAmC;EACjC,OAAO,KAAK,aAAa,SAAS;CACpC;CAEA,4BAAiD;EAC/C,OAAO,KAAK,aAAa,WAAW;CACtC;CAEA,4BAAiD;EAC/C,OAAO,KAAK,aAAa,WAAW;CACtC;CAEA,eAAuB,OAAuB;EAC5C,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;CACjE;AACF"}
|
package/dist/domain.d.mts
DELETED
|
@@ -1,500 +0,0 @@
|
|
|
1
|
-
import { a as ClockPort, i as UniqueIdentifier, n as LoggingPort, r as IdentifierPort, t as MetricsPort } from "./metrics.port-CfI8yKMA.mjs";
|
|
2
|
-
/**
|
|
3
|
-
* Base entity class for domain objects.
|
|
4
|
-
*
|
|
5
|
-
* Entities are objects defined by their identity rather than their attributes.
|
|
6
|
-
* Two entities with the same ID are considered equal, even if their properties
|
|
7
|
-
* differ. Entities are the building blocks of domain models.
|
|
8
|
-
*
|
|
9
|
-
* @example
|
|
10
|
-
* ```typescript
|
|
11
|
-
* class User extends Entity<UserId> {
|
|
12
|
-
* constructor(
|
|
13
|
-
* id: UserId,
|
|
14
|
-
* public email: string,
|
|
15
|
-
* public name: string
|
|
16
|
-
* ) {
|
|
17
|
-
* super(id);
|
|
18
|
-
* }
|
|
19
|
-
*
|
|
20
|
-
* equals(other: User): boolean {
|
|
21
|
-
* return this.id === other.id;
|
|
22
|
-
* }
|
|
23
|
-
* }
|
|
24
|
-
* ```
|
|
25
|
-
*
|
|
26
|
-
* @template Id - The unique identifier type for the entity
|
|
27
|
-
*/
|
|
28
|
-
declare abstract class Entity<Id extends UniqueIdentifier = UniqueIdentifier> {
|
|
29
|
-
private readonly _id;
|
|
30
|
-
protected constructor(id: Id);
|
|
31
|
-
getId(): Id;
|
|
32
|
-
abstract toJSON(): Record<string, unknown>;
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Aggregate Root is an entity that defines a boundary within which other
|
|
36
|
-
* entities (value objects and aggregates) maintain consistency.
|
|
37
|
-
*
|
|
38
|
-
* Aggregate roots are central to Domain-Driven Design (DDD) and enforce
|
|
39
|
-
* invariants for the entire aggregate. All changes to child entities must go
|
|
40
|
-
* through the aggregate root to ensure data integrity.
|
|
41
|
-
*
|
|
42
|
-
* @example
|
|
43
|
-
* ```typescript
|
|
44
|
-
* class Order extends AggregateRoot<OrderId> {
|
|
45
|
-
* private constructor(id: OrderId, items: OrderItem[]) {
|
|
46
|
-
* super(id);
|
|
47
|
-
* this.items = items;
|
|
48
|
-
* }
|
|
49
|
-
*
|
|
50
|
-
* static create(id: OrderId, items: OrderItem[]): Order {
|
|
51
|
-
* // Validation logic here
|
|
52
|
-
* return new Order(id, items);
|
|
53
|
-
* }
|
|
54
|
-
*
|
|
55
|
-
* addItem(item: OrderItem): void {
|
|
56
|
-
* this.items.push(item);
|
|
57
|
-
* this.updateTimestamp();
|
|
58
|
-
* }
|
|
59
|
-
* }
|
|
60
|
-
* ```
|
|
61
|
-
*
|
|
62
|
-
* @template Id - The unique identifier type for the aggregate
|
|
63
|
-
*/
|
|
64
|
-
declare abstract class AggregateRoot<Id extends UniqueIdentifier = UniqueIdentifier> extends Entity<Id> {
|
|
65
|
-
private readonly _createdAt;
|
|
66
|
-
private _updatedAt;
|
|
67
|
-
protected constructor(id: Id, createdAt?: Date, updatedAt?: Date);
|
|
68
|
-
get createdAt(): Date;
|
|
69
|
-
get updatedAt(): Date;
|
|
70
|
-
protected updateTimestamp(): void;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Brand type for type-safe type narrowing.
|
|
74
|
-
*
|
|
75
|
-
* Creates a branded type that is not assignable to the base type, enabling
|
|
76
|
-
* compile-time validation of type correctness.
|
|
77
|
-
*
|
|
78
|
-
* @example
|
|
79
|
-
* ```typescript
|
|
80
|
-
* type UserId = Brand<string, 'UserId'>;
|
|
81
|
-
* type OrderId = Brand<string, 'OrderId'>;
|
|
82
|
-
*
|
|
83
|
-
* // Type-safe usage
|
|
84
|
-
* function createUser(id: UserId): void {
|
|
85
|
-
* // id is guaranteed to be a UserId
|
|
86
|
-
* }
|
|
87
|
-
*
|
|
88
|
-
* // Error: cannot use plain string
|
|
89
|
-
* createUser('123' as UserId); // ❌ Error
|
|
90
|
-
* createUser('123' as UserId); // ✅ Correct
|
|
91
|
-
* ```
|
|
92
|
-
*
|
|
93
|
-
* @template T - The underlying type to brand
|
|
94
|
-
* @template B - The brand name (string literal)
|
|
95
|
-
*/
|
|
96
|
-
declare const brandKey: unique symbol;
|
|
97
|
-
type Brand<T, B extends string> = T & {
|
|
98
|
-
readonly [brandKey]: B;
|
|
99
|
-
};
|
|
100
|
-
/**
|
|
101
|
-
* Base value object class for domain objects.
|
|
102
|
-
*
|
|
103
|
-
* Value objects are objects defined by their attributes rather than identity.
|
|
104
|
-
* Two value objects with the same attributes are considered equal. Value
|
|
105
|
-
* objects are immutable and used to model concepts that don't have identity.
|
|
106
|
-
*
|
|
107
|
-
* @example
|
|
108
|
-
* ```typescript
|
|
109
|
-
* class Money extends ValueObject {
|
|
110
|
-
* constructor(
|
|
111
|
-
* public readonly amount: number,
|
|
112
|
-
* public readonly currency: string
|
|
113
|
-
* ) {
|
|
114
|
-
* super();
|
|
115
|
-
* if (amount < 0) {
|
|
116
|
-
* throw new ValidationError('Amount cannot be negative');
|
|
117
|
-
* }
|
|
118
|
-
* }
|
|
119
|
-
*
|
|
120
|
-
* equals(other: Money): boolean {
|
|
121
|
-
* return (
|
|
122
|
-
* this.amount === other.amount && this.currency === other.currency
|
|
123
|
-
* );
|
|
124
|
-
* }
|
|
125
|
-
*
|
|
126
|
-
* add(other: Money): Money {
|
|
127
|
-
* if (this.currency !== other.currency) {
|
|
128
|
-
* throw new ValidationError('Cannot add different currencies');
|
|
129
|
-
* }
|
|
130
|
-
* return new Money(this.amount + other.amount, this.currency);
|
|
131
|
-
* }
|
|
132
|
-
* }
|
|
133
|
-
* ```
|
|
134
|
-
*/
|
|
135
|
-
declare abstract class ValueObject {
|
|
136
|
-
abstract toJSON(): Record<string, unknown>;
|
|
137
|
-
}
|
|
138
|
-
/**
|
|
139
|
-
* Options for configuring application errors.
|
|
140
|
-
*
|
|
141
|
-
* @param code - An optional error code for programmatic handling
|
|
142
|
-
* @param context - Optional structured context data for debugging
|
|
143
|
-
* @param cause - Optional underlying cause for error chaining
|
|
144
|
-
*/
|
|
145
|
-
interface ApplicationErrorOptions {
|
|
146
|
-
code?: string;
|
|
147
|
-
context?: Record<string, unknown>;
|
|
148
|
-
cause?: unknown;
|
|
149
|
-
}
|
|
150
|
-
/**
|
|
151
|
-
* Details extracted from error configuration.
|
|
152
|
-
*
|
|
153
|
-
* Represents either structured error options (context, cause) or a raw error
|
|
154
|
-
* value.
|
|
155
|
-
*/
|
|
156
|
-
type ApplicationErrorDetails = Omit<ApplicationErrorOptions, 'code'> | unknown;
|
|
157
|
-
/**
|
|
158
|
-
* Base error class for application/domain boundaries.
|
|
159
|
-
*
|
|
160
|
-
* Provides standardized error handling with error codes and context. Consumers
|
|
161
|
-
* may use this class or provide their own errors with a compatible shape.
|
|
162
|
-
*
|
|
163
|
-
* @example
|
|
164
|
-
* ```typescript
|
|
165
|
-
* // With custom code
|
|
166
|
-
* throw new ApplicationError('Invalid operation', { code: 'INVALID_OP' });
|
|
167
|
-
*
|
|
168
|
-
* // With context
|
|
169
|
-
* throw new ApplicationError('Payment failed', {
|
|
170
|
-
* code: 'PAYMENT_ERROR',
|
|
171
|
-
* context: { amount: 100, currency: 'USD' }
|
|
172
|
-
* });
|
|
173
|
-
*
|
|
174
|
-
* // With cause (error chaining)
|
|
175
|
-
* try {
|
|
176
|
-
* await someOperation();
|
|
177
|
-
* } catch (e) {
|
|
178
|
-
* throw new ApplicationError('Operation failed', { cause: e });
|
|
179
|
-
* }
|
|
180
|
-
* ```;
|
|
181
|
-
*
|
|
182
|
-
* @param message - The error message
|
|
183
|
-
* @param options - Optional error configuration
|
|
184
|
-
*/
|
|
185
|
-
export declare class ApplicationError extends Error {
|
|
186
|
-
readonly code: string;
|
|
187
|
-
readonly context: Record<string, unknown> | undefined;
|
|
188
|
-
/**
|
|
189
|
-
* Constructs a new ApplicationError.
|
|
190
|
-
*
|
|
191
|
-
* @param message - The error message
|
|
192
|
-
* @param options - Optional error configuration (code, context, cause)
|
|
193
|
-
*/
|
|
194
|
-
constructor(message: string, options?: ApplicationErrorOptions);
|
|
195
|
-
}
|
|
196
|
-
/**
|
|
197
|
-
* Validation error for input validation failures.
|
|
198
|
-
*
|
|
199
|
-
* @example
|
|
200
|
-
* ```typescript
|
|
201
|
-
* // Simple validation error
|
|
202
|
-
* throw new ValidationError('Email is required');
|
|
203
|
-
*
|
|
204
|
-
* // With validation details
|
|
205
|
-
* throw new ValidationError('Validation failed', {
|
|
206
|
-
* context: {
|
|
207
|
-
* field: 'email',
|
|
208
|
-
* reason: 'Invalid email format'
|
|
209
|
-
* }
|
|
210
|
-
* });
|
|
211
|
-
* ```;
|
|
212
|
-
*
|
|
213
|
-
* @param message - Optional error message (default: 'Validation failed')
|
|
214
|
-
* @param details - Optional validation details or raw value
|
|
215
|
-
*/
|
|
216
|
-
export declare class ValidationError extends ApplicationError {
|
|
217
|
-
constructor(message?: string, details?: ApplicationErrorDetails);
|
|
218
|
-
}
|
|
219
|
-
/**
|
|
220
|
-
* Not found error for missing resources.
|
|
221
|
-
*
|
|
222
|
-
* @example
|
|
223
|
-
* ```typescript
|
|
224
|
-
* // Standard message
|
|
225
|
-
* throw new NotFoundError('User');
|
|
226
|
-
* // → "User not found"
|
|
227
|
-
*
|
|
228
|
-
* // Custom message
|
|
229
|
-
* throw new NotFoundError('The specified order was not found');
|
|
230
|
-
* ```;
|
|
231
|
-
*
|
|
232
|
-
* @param resourceOrMessage - Resource name or custom error message
|
|
233
|
-
* @param details - Optional error details
|
|
234
|
-
*/
|
|
235
|
-
export declare class NotFoundError extends ApplicationError {
|
|
236
|
-
constructor(resourceOrMessage?: string, details?: ApplicationErrorDetails);
|
|
237
|
-
}
|
|
238
|
-
/**
|
|
239
|
-
* Conflict error for resource conflicts (e.g., duplicate entries).
|
|
240
|
-
*
|
|
241
|
-
* @example
|
|
242
|
-
* ```typescript
|
|
243
|
-
* throw new ConflictError('Email already registered');
|
|
244
|
-
* ```;
|
|
245
|
-
*
|
|
246
|
-
* @param message - Optional error message (default: 'Conflict detected')
|
|
247
|
-
* @param details - Optional error details
|
|
248
|
-
*/
|
|
249
|
-
export declare class ConflictError extends ApplicationError {
|
|
250
|
-
constructor(message?: string, details?: ApplicationErrorDetails);
|
|
251
|
-
}
|
|
252
|
-
/**
|
|
253
|
-
* Unauthorized error for authentication failures.
|
|
254
|
-
*
|
|
255
|
-
* @example
|
|
256
|
-
* ```typescript
|
|
257
|
-
* throw new UnauthorizedError('Invalid authentication token');
|
|
258
|
-
* ```;
|
|
259
|
-
*
|
|
260
|
-
* @param message - Optional error message (default: 'Unauthorized')
|
|
261
|
-
* @param details - Optional error details
|
|
262
|
-
*/
|
|
263
|
-
export declare class UnauthorizedError extends ApplicationError {
|
|
264
|
-
constructor(message?: string, details?: ApplicationErrorDetails);
|
|
265
|
-
}
|
|
266
|
-
/**
|
|
267
|
-
* Forbidden error for authorization failures.
|
|
268
|
-
*
|
|
269
|
-
* @example
|
|
270
|
-
* ```typescript
|
|
271
|
-
* throw new ForbiddenError('Insufficient permissions');
|
|
272
|
-
* ```;
|
|
273
|
-
*
|
|
274
|
-
* @param message - Optional error message (default: 'Forbidden')
|
|
275
|
-
* @param details - Optional error details
|
|
276
|
-
*/
|
|
277
|
-
export declare class ForbiddenError extends ApplicationError {
|
|
278
|
-
constructor(message?: string, details?: ApplicationErrorDetails);
|
|
279
|
-
}
|
|
280
|
-
/**
|
|
281
|
-
* Invariant error for violated business invariants.
|
|
282
|
-
*
|
|
283
|
-
* @example
|
|
284
|
-
* ```typescript
|
|
285
|
-
* throw new InvariantError('Order cannot be modified after shipment');
|
|
286
|
-
* ```;
|
|
287
|
-
*
|
|
288
|
-
* @param message - Optional error message (default: 'Invariant violated')
|
|
289
|
-
* @param details - Optional error details
|
|
290
|
-
*/
|
|
291
|
-
export declare class InvariantError extends ApplicationError {
|
|
292
|
-
constructor(message?: string, details?: ApplicationErrorDetails);
|
|
293
|
-
}
|
|
294
|
-
/**
|
|
295
|
-
* Infrastructure error for external service failures.
|
|
296
|
-
*
|
|
297
|
-
* @example
|
|
298
|
-
* ```typescript
|
|
299
|
-
* throw new InfrastructureError('Database connection failed', e);
|
|
300
|
-
* ```;
|
|
301
|
-
*
|
|
302
|
-
* @param message - Optional error message (default: 'Infrastructure failure')
|
|
303
|
-
* @param details - Optional error details or underlying error
|
|
304
|
-
*/
|
|
305
|
-
export declare class InfrastructureError extends ApplicationError {
|
|
306
|
-
constructor(message?: string, details?: ApplicationErrorDetails);
|
|
307
|
-
}
|
|
308
|
-
interface DomainErrorLike extends Error {
|
|
309
|
-
code?: string;
|
|
310
|
-
context?: Record<string, unknown>;
|
|
311
|
-
}
|
|
312
|
-
export declare function isDomainError(value: unknown): value is DomainErrorLike;
|
|
313
|
-
export declare function getDomainErrorCode(error: Error): string | undefined;
|
|
314
|
-
/**
|
|
315
|
-
* Base repository class providing common CRUD operations.
|
|
316
|
-
*
|
|
317
|
-
* This class implements the Repository interface and can be extended to provide
|
|
318
|
-
* domain-specific implementations while maintaining the core repository
|
|
319
|
-
* contract. It provides default implementations for common operations like
|
|
320
|
-
* `exists`, `update`, and others.
|
|
321
|
-
*
|
|
322
|
-
* @example
|
|
323
|
-
* ```typescript
|
|
324
|
-
* class UserRepository extends RepositoryBase<User, UserId> {
|
|
325
|
-
* async findById(id: UserId): Promise<User | null> {
|
|
326
|
-
* const data = await db.users.findOne({ id: id.value });
|
|
327
|
-
* return data ? new User(id, data.email, data.name) : null;
|
|
328
|
-
* }
|
|
329
|
-
*
|
|
330
|
-
* async findAll(): Promise<User[]> {
|
|
331
|
-
* const users = await db.users.find({});
|
|
332
|
-
* return users.map((u) => new User(new UserId(u.id), u.email, u.name));
|
|
333
|
-
* }
|
|
334
|
-
*
|
|
335
|
-
* async save(entity: User): Promise<User> {
|
|
336
|
-
* const data = {
|
|
337
|
-
* id: entity.id.value,
|
|
338
|
-
* email: entity.email,
|
|
339
|
-
* name: entity.name
|
|
340
|
-
* };
|
|
341
|
-
* await db.users.upsert(data);
|
|
342
|
-
* return entity;
|
|
343
|
-
* }
|
|
344
|
-
*
|
|
345
|
-
* async delete(id: Id): Promise<void> {
|
|
346
|
-
* await db.users.delete({ id: id.value });
|
|
347
|
-
* }
|
|
348
|
-
* }
|
|
349
|
-
* ```;
|
|
350
|
-
*
|
|
351
|
-
* @template Entity - The entity type managed by this repository
|
|
352
|
-
* @template Id - The unique identifier type for the entity
|
|
353
|
-
*/
|
|
354
|
-
export declare abstract class RepositoryBase<Entity$1 extends Entity<UniqueIdentifier>, Id extends UniqueIdentifier = UniqueIdentifier> {
|
|
355
|
-
/**
|
|
356
|
-
* Find an entity by its unique identifier
|
|
357
|
-
*
|
|
358
|
-
* @abstract
|
|
359
|
-
*/
|
|
360
|
-
abstract findById(id: Id): Promise<Entity$1 | null>;
|
|
361
|
-
/**
|
|
362
|
-
* Find all entities
|
|
363
|
-
*
|
|
364
|
-
* @abstract
|
|
365
|
-
*/
|
|
366
|
-
abstract findAll(): Promise<Entity$1[]>;
|
|
367
|
-
/**
|
|
368
|
-
* Save an entity (create or update)
|
|
369
|
-
*
|
|
370
|
-
* @abstract
|
|
371
|
-
*/
|
|
372
|
-
abstract save(entity: Entity$1): Promise<Entity$1>;
|
|
373
|
-
/**
|
|
374
|
-
* Delete an entity by its unique identifier
|
|
375
|
-
*
|
|
376
|
-
* @abstract
|
|
377
|
-
*/
|
|
378
|
-
abstract delete(id: Id): Promise<void>;
|
|
379
|
-
/** Check if an entity exists by its identifier */
|
|
380
|
-
exists(id: Id): Promise<boolean>;
|
|
381
|
-
/** Update an entity (alias for save with type safety) */
|
|
382
|
-
update(entity: Entity$1): Promise<Entity$1>;
|
|
383
|
-
}
|
|
384
|
-
/**
|
|
385
|
-
* Port for repository-based data access.
|
|
386
|
-
*
|
|
387
|
-
* Defines the contract for data persistence operations following the Repository
|
|
388
|
-
* pattern. Provides abstraction over data sources and enables domain logic to
|
|
389
|
-
* remain decoupled from infrastructure concerns.
|
|
390
|
-
*
|
|
391
|
-
* @example
|
|
392
|
-
* ```typescript
|
|
393
|
-
* // Implement for a specific entity
|
|
394
|
-
* class UserRepository implements RepositoryPort<User, UserId> {
|
|
395
|
-
* async findById(id: UserId): Promise<User | null> {
|
|
396
|
-
* const data = await db.users.findOne({ id: id.value });
|
|
397
|
-
* return data ? new User(id, data.email, data.name) : null;
|
|
398
|
-
* }
|
|
399
|
-
*
|
|
400
|
-
* async findAll(): Promise<User[]> {
|
|
401
|
-
* return db.users.find({}).map((u) => new User(u.id, u.email, u.name));
|
|
402
|
-
* }
|
|
403
|
-
*
|
|
404
|
-
* async save(entity: User): Promise<User> {
|
|
405
|
-
* await db.users.upsert(entity.toJSON());
|
|
406
|
-
* return entity;
|
|
407
|
-
* }
|
|
408
|
-
*
|
|
409
|
-
* async delete(id: UserId): Promise<void> {
|
|
410
|
-
* await db.users.delete({ id: id.value });
|
|
411
|
-
* }
|
|
412
|
-
* }
|
|
413
|
-
* ```
|
|
414
|
-
*
|
|
415
|
-
* @template Entity - The entity type managed by this repository
|
|
416
|
-
* @template UniqueIdentifier - The unique identifier type for the entity
|
|
417
|
-
*/
|
|
418
|
-
interface RepositoryPort<Entity, UniqueIdentifier> {
|
|
419
|
-
/**
|
|
420
|
-
* Find an entity by its unique identifier
|
|
421
|
-
*
|
|
422
|
-
* @param id - The entity's unique identifier
|
|
423
|
-
* @returns Promise resolving to the entity or null if not found
|
|
424
|
-
*/
|
|
425
|
-
findById(id: UniqueIdentifier): Promise<Entity | null>;
|
|
426
|
-
/**
|
|
427
|
-
* Find all entities (basic CRUD - no pagination or filtering)
|
|
428
|
-
*
|
|
429
|
-
* For query operations with filters, pagination, and sorting, implement
|
|
430
|
-
* additional methods or use a separate query repository
|
|
431
|
-
*
|
|
432
|
-
* @returns Promise resolving to array of all entities
|
|
433
|
-
*/
|
|
434
|
-
findAll(): Promise<Entity[]>;
|
|
435
|
-
/**
|
|
436
|
-
* Save an entity (create or update)
|
|
437
|
-
*
|
|
438
|
-
* @param entity - The entity to save
|
|
439
|
-
* @returns Promise resolving to the saved entity (with updated fields)
|
|
440
|
-
*/
|
|
441
|
-
save(entity: Entity): Promise<Entity>;
|
|
442
|
-
/**
|
|
443
|
-
* Delete an entity by its unique identifier
|
|
444
|
-
*
|
|
445
|
-
* @param id - The entity's unique identifier
|
|
446
|
-
* @returns Promise that resolves when the entity is deleted
|
|
447
|
-
*/
|
|
448
|
-
delete(id: UniqueIdentifier): Promise<void>;
|
|
449
|
-
}
|
|
450
|
-
/**
|
|
451
|
-
* Base unit of work class providing default transaction implementations.
|
|
452
|
-
*
|
|
453
|
-
* This class provides the UnitOfWork interface implementation with a default
|
|
454
|
-
* transaction pattern that commits on success and rolls back on failure.
|
|
455
|
-
*
|
|
456
|
-
* Extending this class ensures consistent transactional behavior across all
|
|
457
|
-
* operations while allowing custom commit/rollback logic per implementation.
|
|
458
|
-
*
|
|
459
|
-
* @example
|
|
460
|
-
* ```typescript
|
|
461
|
-
* class SqlUnitOfWork extends UnitOfWorkBase {
|
|
462
|
-
* constructor(private readonly connection: SqlConnection) {}
|
|
463
|
-
*
|
|
464
|
-
* async commit(): Promise<void> {
|
|
465
|
-
* await this.connection.commit();
|
|
466
|
-
* }
|
|
467
|
-
*
|
|
468
|
-
* async rollback(): Promise<void> {
|
|
469
|
-
* await this.connection.rollback();
|
|
470
|
-
* }
|
|
471
|
-
* }
|
|
472
|
-
*
|
|
473
|
-
* // Usage
|
|
474
|
-
* const uw = new SqlUnitOfWork(connection);
|
|
475
|
-
* const result = await uw.transaction(async (txn) => {
|
|
476
|
-
* const user = new User(generateId());
|
|
477
|
-
* await repository.save(user);
|
|
478
|
-
* return user;
|
|
479
|
-
* });
|
|
480
|
-
* // Returns user and commits transaction
|
|
481
|
-
* ```
|
|
482
|
-
*/
|
|
483
|
-
export declare abstract class UnitOfWorkBase {
|
|
484
|
-
/**
|
|
485
|
-
* Commit all pending changes
|
|
486
|
-
*
|
|
487
|
-
* @abstract
|
|
488
|
-
*/
|
|
489
|
-
abstract commit(): Promise<void>;
|
|
490
|
-
/**
|
|
491
|
-
* Rollback all pending changes
|
|
492
|
-
*
|
|
493
|
-
* @abstract
|
|
494
|
-
*/
|
|
495
|
-
abstract rollback(): Promise<void>;
|
|
496
|
-
/** Execute a function within a transaction */
|
|
497
|
-
transaction<T>(fn: (uw: UnitOfWorkBase) => Promise<T>): Promise<T>;
|
|
498
|
-
}
|
|
499
|
-
export type { AggregateRoot, ApplicationErrorDetails, ApplicationErrorOptions, Brand, ClockPort, DomainErrorLike, Entity, IdentifierPort, LoggingPort as LoggerPort, MetricsPort, RepositoryPort, UniqueIdentifier, ValueObject };
|
|
500
|
-
//# sourceMappingURL=domain.d.mts.map
|
package/dist/domain.d.mts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"domain.d.mts","names":["EntityType","Entity"],"sources":["../src/domain/primitives/entity.ts","../src/domain/primitives/aggregate-root.ts","../src/domain/primitives/brand.type.ts","../src/domain/primitives/value-object.ts","../src/domain/errors/application.error.ts","../src/domain/errors/domain-error.guard.ts","../src/domain/repository/repository.base.ts","../src/domain/repository/repository.port.ts","../src/domain/unit-of-work/unit-of-work.base.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;uBA4BsB,OAAO,WAAW,mBAAmB;mBACxC;YAER,YAAa,IAAI;EAI1B,SAAS;WAIA,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBCNC,cACpB,WAAW,mBAAmB,0BACtB,OAAO;mBACE;UACT;YAEC,YACP,IAAI,IACJ,YAAW,MACX,YAAW;MAOT,aAAa;MAIb,aAAa;YAIP;;;;;;;;;;;;;;;;;;;;;;;;;;cCjCE;KAEF,MAAM,GAAG,oBAAoB;YAAgB,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBCS9C;WACX,UAAU;;;;;;;;;UC7BJ;EACf;EACA,UAAU;EACV;;;;;;;;KASU,0BACV,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA8BM,yBAAyB;WAC3B;WACA,SAAS;;;;;;;EAQlB,YAAY,iBAAiB,UAAS;;;;;;;;;;;;;;;;;;;;;;qBA8B3B,wBAAwB;EACnC,YACE,kBACA,UAAU;;;;;;;;;;;;;;;;;;qBAuBD,sBAAsB;EACjC,YACE,4BACA,UAAU;;;;;;;;;;;;;qBAmBD,sBAAsB;EACjC,YACE,kBACA,UAAU;;;;;;;;;;;;;qBAkBD,0BAA0B;EACrC,YAAY,kBAA0B,UAAU;;;;;;;;;;;;;qBAiBrC,uBAAuB;EAClC,YAAY,kBAAuB,UAAU;;;;;;;;;;;;;qBAiBlC,uBAAuB;EAClC,YACE,kBACA,UAAU;;;;;;;;;;;;;qBAkBD,4BAA4B;EACvC,YACE,kBACA,UAAU;;UCzNG,wBAAwB;EACvC;EACA,UAAU;;wBAqBI,cAAc,iBAAiB,SAAS;wBAiBxC,mBAAmB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8BCApB,eACpB,iBAAeA,OAAW,mBAC1B,WAAW,mBAAmB;;;;;;WAOrB,SAAS,IAAI,KAAK,QAAQC;;;;;;WAO1B,WAAW,QAAQA;;;;;;WAOnB,KAAK,QAAQA,WAAS,QAAQA;;;;;;WAO9B,OAAO,IAAI,KAAK;;EAGnB,OAAO,IAAI,KAAK;;EAMhB,OAAO,QAAQA,WAAS,QAAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UC/CvB,eAAe,QAAQ;;;;;;;EAOtC,SAAS,IAAI,mBAAmB,QAAQ;;;;;;;;;EAUxC,WAAW,QAAQ;;;;;;;EAQnB,KAAK,QAAQ,SAAS,QAAQ;;;;;;;EAQ9B,OAAO,IAAI,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8BCjCV;;;;;;WAMX,UAAU;;;;;;WAOV,YAAY;;EAGf,YAAY,GAAG,KAAK,IAAI,mBAAmB,QAAQ,KAAK,QAAQ"}
|