@hexaijs/application 0.1.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.
Files changed (123) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +331 -0
  3. package/dist/abstract-application-context.d.ts +13 -0
  4. package/dist/abstract-application-context.d.ts.map +1 -0
  5. package/dist/abstract-application-context.js +35 -0
  6. package/dist/abstract-application-context.js.map +1 -0
  7. package/dist/application-context.d.ts +2 -0
  8. package/dist/application-context.d.ts.map +1 -0
  9. package/dist/application-context.js +6 -0
  10. package/dist/application-context.js.map +1 -0
  11. package/dist/application-event-publisher.d.ts +16 -0
  12. package/dist/application-event-publisher.d.ts.map +1 -0
  13. package/dist/application-event-publisher.js +37 -0
  14. package/dist/application-event-publisher.js.map +1 -0
  15. package/dist/application.d.ts +59 -0
  16. package/dist/application.d.ts.map +1 -0
  17. package/dist/application.js +237 -0
  18. package/dist/application.js.map +1 -0
  19. package/dist/command-handler.d.ts +5 -0
  20. package/dist/command-handler.d.ts.map +1 -0
  21. package/dist/command-handler.js +3 -0
  22. package/dist/command-handler.js.map +1 -0
  23. package/dist/command.d.ts +12 -0
  24. package/dist/command.d.ts.map +1 -0
  25. package/dist/command.js +46 -0
  26. package/dist/command.js.map +1 -0
  27. package/dist/error.d.ts +37 -0
  28. package/dist/error.d.ts.map +1 -0
  29. package/dist/error.js +28 -0
  30. package/dist/error.js.map +1 -0
  31. package/dist/event-handler.d.ts +6 -0
  32. package/dist/event-handler.d.ts.map +1 -0
  33. package/dist/event-handler.js +3 -0
  34. package/dist/event-handler.js.map +1 -0
  35. package/dist/event-publisher.d.ts +4 -0
  36. package/dist/event-publisher.d.ts.map +1 -0
  37. package/dist/event-publisher.js +3 -0
  38. package/dist/event-publisher.js.map +1 -0
  39. package/dist/index.d.ts +18 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +34 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/intercepted-application.d.ts +33 -0
  44. package/dist/intercepted-application.d.ts.map +1 -0
  45. package/dist/intercepted-application.js +111 -0
  46. package/dist/intercepted-application.js.map +1 -0
  47. package/dist/interceptor.d.ts +25 -0
  48. package/dist/interceptor.d.ts.map +1 -0
  49. package/dist/interceptor.js +3 -0
  50. package/dist/interceptor.js.map +1 -0
  51. package/dist/logging/create-logger.d.ts +16 -0
  52. package/dist/logging/create-logger.d.ts.map +1 -0
  53. package/dist/logging/create-logger.js +48 -0
  54. package/dist/logging/create-logger.js.map +1 -0
  55. package/dist/logging/index.d.ts +7 -0
  56. package/dist/logging/index.d.ts.map +1 -0
  57. package/dist/logging/index.js +32 -0
  58. package/dist/logging/index.js.map +1 -0
  59. package/dist/logging/logger.d.ts +42 -0
  60. package/dist/logging/logger.d.ts.map +1 -0
  61. package/dist/logging/logger.js +3 -0
  62. package/dist/logging/logger.js.map +1 -0
  63. package/dist/logging/logging-interceptor.d.ts +9 -0
  64. package/dist/logging/logging-interceptor.d.ts.map +1 -0
  65. package/dist/logging/logging-interceptor.js +48 -0
  66. package/dist/logging/logging-interceptor.js.map +1 -0
  67. package/dist/logging/logging-utils.d.ts +16 -0
  68. package/dist/logging/logging-utils.d.ts.map +1 -0
  69. package/dist/logging/logging-utils.js +91 -0
  70. package/dist/logging/logging-utils.js.map +1 -0
  71. package/dist/logging/trace-interceptor.d.ts +16 -0
  72. package/dist/logging/trace-interceptor.d.ts.map +1 -0
  73. package/dist/logging/trace-interceptor.js +53 -0
  74. package/dist/logging/trace-interceptor.js.map +1 -0
  75. package/dist/message-handler.d.ts +4 -0
  76. package/dist/message-handler.d.ts.map +1 -0
  77. package/dist/message-handler.js +3 -0
  78. package/dist/message-handler.js.map +1 -0
  79. package/dist/messaging-support.d.ts +11 -0
  80. package/dist/messaging-support.d.ts.map +1 -0
  81. package/dist/messaging-support.js +40 -0
  82. package/dist/messaging-support.js.map +1 -0
  83. package/dist/query-handler.d.ts +5 -0
  84. package/dist/query-handler.d.ts.map +1 -0
  85. package/dist/query-handler.js +3 -0
  86. package/dist/query-handler.js.map +1 -0
  87. package/dist/query.d.ts +12 -0
  88. package/dist/query.d.ts.map +1 -0
  89. package/dist/query.js +46 -0
  90. package/dist/query.js.map +1 -0
  91. package/dist/request.d.ts +3 -0
  92. package/dist/request.d.ts.map +1 -0
  93. package/dist/request.js +19 -0
  94. package/dist/request.js.map +1 -0
  95. package/dist/result.d.ts +18 -0
  96. package/dist/result.d.ts.map +1 -0
  97. package/dist/result.js +28 -0
  98. package/dist/result.js.map +1 -0
  99. package/dist/selector-based-event-handler.d.ts +29 -0
  100. package/dist/selector-based-event-handler.d.ts.map +1 -0
  101. package/dist/selector-based-event-handler.js +78 -0
  102. package/dist/selector-based-event-handler.js.map +1 -0
  103. package/dist/simple-composite-application.d.ts +15 -0
  104. package/dist/simple-composite-application.d.ts.map +1 -0
  105. package/dist/simple-composite-application.js +61 -0
  106. package/dist/simple-composite-application.js.map +1 -0
  107. package/dist/test/expectations.d.ts +10 -0
  108. package/dist/test/expectations.d.ts.map +1 -0
  109. package/dist/test/expectations.js +33 -0
  110. package/dist/test/expectations.js.map +1 -0
  111. package/dist/test/fixtures/index.d.ts +24 -0
  112. package/dist/test/fixtures/index.d.ts.map +1 -0
  113. package/dist/test/fixtures/index.js +40 -0
  114. package/dist/test/fixtures/index.js.map +1 -0
  115. package/dist/test/fixtures/interceptor-test-helpers.d.ts +34 -0
  116. package/dist/test/fixtures/interceptor-test-helpers.d.ts.map +1 -0
  117. package/dist/test/fixtures/interceptor-test-helpers.js +59 -0
  118. package/dist/test/fixtures/interceptor-test-helpers.js.map +1 -0
  119. package/dist/test/index.d.ts +3 -0
  120. package/dist/test/index.d.ts.map +1 -0
  121. package/dist/test/index.js +19 -0
  122. package/dist/test/index.js.map +1 -0
  123. package/package.json +64 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Sangwoo Hyun
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,331 @@
1
+ # @hexaijs/application
2
+
3
+ > Application layer infrastructure for building CQRS applications with hexagonal architecture
4
+
5
+ ## Overview
6
+
7
+ `@hexaijs/application` provides the application layer components for building CQRS (Command Query Responsibility Segregation) applications. It bridges the gap between your domain model and external interfaces (HTTP, CLI, message queues) by providing a structured way to handle commands, queries, and events.
8
+
9
+ The package centers around three key patterns:
10
+
11
+ 1. **Application** - A facade that routes messages to their handlers and manages execution context
12
+ 2. **ApplicationContext** - Scopes handler execution with transactional boundaries and event publishing
13
+ 3. **Interceptors** - Cross-cutting concerns that wrap message handling (logging, tracing, authorization)
14
+
15
+ These components work together to ensure each command/query executes in isolation with proper transaction management, while events flow through the system with causation and correlation tracking.
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install @hexaijs/application
21
+ ```
22
+
23
+ ## Core Concepts
24
+
25
+ ### Command and Query
26
+
27
+ `Command` and `Query` extend the core `Message` class to represent different intents. Commands change state; queries read state.
28
+
29
+ ```typescript
30
+ import { Command, Query } from "@hexaijs/application";
31
+
32
+ // Command - changes state
33
+ export class CreateOrderCommand extends Command<{
34
+ customerId: string;
35
+ items: { productId: string; quantity: number }[];
36
+ }> {
37
+ static readonly type = "order.create-order";
38
+ }
39
+
40
+ // Query - reads state
41
+ export class GetOrderQuery extends Query<{
42
+ orderId: string;
43
+ }> {
44
+ static readonly type = "order.get-order";
45
+ }
46
+ ```
47
+
48
+ Both support security contexts for authorization:
49
+
50
+ ```typescript
51
+ // Attach security context
52
+ const command = new CreateOrderCommand({
53
+ customerId: "customer-123",
54
+ items: []
55
+ }).withSecurityContext({ userId: "user-456", roles: ["admin"] });
56
+
57
+ // Access in handler
58
+ const user = command.getSecurityContext();
59
+ ```
60
+
61
+ ### CommandHandler and QueryHandler
62
+
63
+ Handlers implement the `execute` method to process messages:
64
+
65
+ ```typescript
66
+ import { CommandHandler, QueryHandler } from "@hexaijs/application";
67
+
68
+ interface OrderContext {
69
+ getOrderRepository(): OrderRepository;
70
+ }
71
+
72
+ class CreateOrderHandler implements CommandHandler<
73
+ CreateOrderCommand,
74
+ { orderId: string },
75
+ OrderContext
76
+ > {
77
+ async execute(
78
+ command: CreateOrderCommand,
79
+ ctx: OrderContext
80
+ ): Promise<{ orderId: string }> {
81
+ const repository = ctx.getOrderRepository();
82
+ const order = Order.create(command.getPayload());
83
+ await repository.add(order);
84
+ return { orderId: order.getId().getValue() };
85
+ }
86
+ }
87
+
88
+ class GetOrderHandler implements QueryHandler<
89
+ GetOrderQuery,
90
+ OrderDto,
91
+ OrderContext
92
+ > {
93
+ async execute(
94
+ query: GetOrderQuery,
95
+ ctx: OrderContext
96
+ ): Promise<OrderDto> {
97
+ const repository = ctx.getOrderRepository();
98
+ const order = await repository.get(query.getPayload().orderId);
99
+ return toDto(order);
100
+ }
101
+ }
102
+ ```
103
+
104
+ ### EventHandler
105
+
106
+ Event handlers react to domain events. The `canHandle` method filters which events the handler processes:
107
+
108
+ ```typescript
109
+ import { Message } from "@hexaijs/core";
110
+ import { EventHandler } from "@hexaijs/application";
111
+
112
+ class SendOrderConfirmationEmail implements EventHandler<OrderPlaced, OrderContext> {
113
+ canHandle(message: Message): boolean {
114
+ return message.getMessageType() === OrderPlaced.getType();
115
+ }
116
+
117
+ async handle(event: OrderPlaced, ctx: OrderContext): Promise<void> {
118
+ const payload = event.getPayload();
119
+ await ctx.getEmailService().send({
120
+ to: payload.customerEmail,
121
+ template: "order-confirmation",
122
+ data: { orderId: payload.orderId }
123
+ });
124
+ }
125
+ }
126
+ ```
127
+
128
+ ### ApplicationBuilder
129
+
130
+ `ApplicationBuilder` assembles handlers and context into an `Application` using a fluent API:
131
+
132
+ ```typescript
133
+ import { ApplicationBuilder } from "@hexaijs/application";
134
+
135
+ const application = new ApplicationBuilder()
136
+ .withApplicationContext(new OrderApplicationContext())
137
+ .withCommandHandler(CreateOrderCommand, () => new CreateOrderHandler())
138
+ .withCommandHandler(CancelOrderCommand, () => new CancelOrderHandler())
139
+ .withQueryHandler(GetOrderQuery, () => new GetOrderHandler())
140
+ .withEventHandler(() => new SendOrderConfirmationEmail())
141
+ .build();
142
+ ```
143
+
144
+ Each handler is registered with a factory function. This allows fresh handler instances per request, preventing state leakage between requests.
145
+
146
+ ### Application
147
+
148
+ The `Application` interface provides three methods for dispatching messages:
149
+
150
+ ```typescript
151
+ import { Application, Result } from "@hexaijs/application";
152
+
153
+ // Execute commands
154
+ const result: Result<{ orderId: string }> = await application.executeCommand(
155
+ new CreateOrderCommand({ customerId: "c-123", items: [] })
156
+ );
157
+
158
+ // Execute queries
159
+ const orderResult: Result<OrderDto> = await application.executeQuery(
160
+ new GetOrderQuery({ orderId: "order-456" })
161
+ );
162
+
163
+ // Handle events (typically called by infrastructure)
164
+ await application.handleEvent(orderPlacedEvent);
165
+ ```
166
+
167
+ ### Result
168
+
169
+ All operations return a `Result` type that is either `SuccessResult` or `ErrorResult`:
170
+
171
+ ```typescript
172
+ const result = await application.executeCommand(command);
173
+
174
+ if (result.isSuccess) {
175
+ console.log("Order created:", result.data.orderId);
176
+ }
177
+
178
+ if (result.isError) {
179
+ console.error("Failed:", result.error.message);
180
+ }
181
+
182
+ // Or throw on error
183
+ const data = result.getOrThrow();
184
+ ```
185
+
186
+ ### AbstractApplicationContext
187
+
188
+ Extend `AbstractApplicationContext` to define your application's dependencies. The context provides event publishing and hooks for transaction management:
189
+
190
+ ```typescript
191
+ import { AbstractApplicationContext } from "@hexaijs/application";
192
+ import { UnitOfWork } from "@hexaijs/core";
193
+
194
+ export abstract class OrderApplicationContext extends AbstractApplicationContext {
195
+ abstract getUnitOfWork(): UnitOfWork;
196
+ abstract getOrderRepository(): OrderRepository;
197
+ abstract getEmailService(): EmailService;
198
+ }
199
+ ```
200
+
201
+ The context provides `publish()` for emitting domain events:
202
+
203
+ ```typescript
204
+ // Inside a handler
205
+ await ctx.publish(
206
+ new OrderPlaced({
207
+ orderId: order.getId().getValue(),
208
+ customerId: command.getPayload().customerId
209
+ })
210
+ );
211
+ ```
212
+
213
+ Events published through the context automatically receive causation and correlation headers, enabling distributed tracing.
214
+
215
+ ## Interceptors
216
+
217
+ Interceptors wrap message handling for cross-cutting concerns. They follow a middleware pattern:
218
+
219
+ ```typescript
220
+ import { CommandInterceptor, CommandInterceptionContext, Result } from "@hexaijs/application";
221
+
222
+ const loggingInterceptor: CommandInterceptor = async (
223
+ ctx: CommandInterceptionContext,
224
+ next: () => Promise<Result<unknown>>
225
+ ): Promise<Result<unknown>> => {
226
+ console.log("Executing:", ctx.message.getMessageType());
227
+ const start = Date.now();
228
+
229
+ const result = await next();
230
+
231
+ console.log(`Completed in ${Date.now() - start}ms`);
232
+ return result;
233
+ };
234
+
235
+ // Register with builder
236
+ const app = new ApplicationBuilder()
237
+ .withApplicationContext(context)
238
+ .withCommandHandler(CreateOrderCommand, () => new CreateOrderHandler())
239
+ .withCommandInterceptor(loggingInterceptor)
240
+ .build();
241
+ ```
242
+
243
+ Four interceptor types are available:
244
+
245
+ | Type | Applies To |
246
+ |------|------------|
247
+ | `CommandInterceptor` | Command execution only |
248
+ | `QueryInterceptor` | Query execution only |
249
+ | `EventInterceptor` | Event handling only |
250
+ | `Interceptor` | All message types |
251
+
252
+ ## Advanced Patterns
253
+
254
+ ### SelectorBasedEventHandler
255
+
256
+ For handlers that respond to multiple event types, use `SelectorBasedEventHandler` with the `@When` decorator:
257
+
258
+ ```typescript
259
+ import { Message } from "@hexaijs/core";
260
+ import { SelectorBasedEventHandler, When, eventTypeMatches } from "@hexaijs/application";
261
+
262
+ class OrderEventHandler extends SelectorBasedEventHandler<Message, OrderContext> {
263
+ @When(eventTypeMatches(OrderPlaced.getType()))
264
+ async onOrderPlaced(event: OrderPlaced, ctx: OrderContext): Promise<void> {
265
+ // Handle order placed
266
+ }
267
+
268
+ @When(eventTypeMatches(OrderCancelled.getType()))
269
+ async onOrderCancelled(event: OrderCancelled, ctx: OrderContext): Promise<void> {
270
+ // Handle order cancelled
271
+ }
272
+ }
273
+ ```
274
+
275
+ The `eventTypeMatches` helper supports strings, arrays, and regex patterns:
276
+
277
+ ```typescript
278
+ @When(eventTypeMatches("order.order-placed"))
279
+ @When(eventTypeMatches(["order.order-placed", "order.order-updated"]))
280
+ @When(eventTypeMatches(/^order\./))
281
+ ```
282
+
283
+ ### SimpleCompositeApplication
284
+
285
+ Compose multiple bounded context applications into one:
286
+
287
+ ```typescript
288
+ import { SimpleCompositeApplication } from "@hexaijs/application";
289
+
290
+ const compositeApp = new SimpleCompositeApplication({
291
+ "order.": orderApplication, // handles order.* messages
292
+ "inventory.": inventoryApplication,
293
+ "shipping.": shippingApplication,
294
+ });
295
+
296
+ // Routes to appropriate application based on message type prefix
297
+ await compositeApp.executeCommand(new CreateOrderCommand(...));
298
+ ```
299
+
300
+ For event handling across bounded contexts, provide a `UnitOfWork` to ensure all handlers execute in the same transaction:
301
+
302
+ ```typescript
303
+ compositeApp.setUnitOfWork(unitOfWork);
304
+ await compositeApp.handleEvent(event);
305
+ ```
306
+
307
+ ## API Highlights
308
+
309
+ | Export | Description |
310
+ |--------|-------------|
311
+ | `Application` | Interface for command/query execution and event handling |
312
+ | `ApplicationBuilder` | Fluent builder for assembling applications |
313
+ | `Command<P, SC>` | Base class for commands with payload and security context |
314
+ | `Query<P, SC>` | Base class for queries with payload and security context |
315
+ | `CommandHandler<I, O, Ctx>` | Interface for command handlers |
316
+ | `QueryHandler<I, O, Ctx>` | Interface for query handlers |
317
+ | `EventHandler<E, Ctx>` | Interface for event handlers |
318
+ | `AbstractApplicationContext` | Base class for application contexts |
319
+ | `Result<R, E>` | Union type of `SuccessResult` or `ErrorResult` |
320
+ | `SelectorBasedEventHandler` | Base class for decorator-based event routing |
321
+ | `SimpleCompositeApplication` | Composes multiple applications by message prefix |
322
+ | `CommandInterceptor` | Interceptor type for commands |
323
+ | `QueryInterceptor` | Interceptor type for queries |
324
+ | `EventInterceptor` | Interceptor type for events |
325
+ | `Interceptor` | Interceptor type for all messages |
326
+
327
+ ## See Also
328
+
329
+ - [@hexaijs/core](../core/README.md) - Core domain primitives this package builds upon
330
+ - [@hexaijs/postgres](../postgres/README.md) - PostgreSQL implementation for ApplicationContext
331
+ - [@hexaijs/plugin-application-builder](../plugin-application-builder/README.md) - Decorators for automatic handler registration
@@ -0,0 +1,13 @@
1
+ import { Message } from "@hexaijs/core";
2
+ import { ApplicationEventPublisher } from "./application-event-publisher";
3
+ export declare abstract class AbstractApplicationContext {
4
+ protected eventPublisher: ApplicationEventPublisher;
5
+ constructor(eventPublisher?: ApplicationEventPublisher);
6
+ setEventPublisher(eventPublisher: ApplicationEventPublisher): void;
7
+ protected clone(): this;
8
+ enterCommandExecutionScope<C extends Message>(command: C, fn: (ctx: this) => Promise<void>): Promise<void>;
9
+ publish(...events: Message[]): Promise<void>;
10
+ protected onEnter(message: Message): Promise<void>;
11
+ protected onExit(message: Message): Promise<void>;
12
+ }
13
+ //# sourceMappingURL=abstract-application-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"abstract-application-context.d.ts","sourceRoot":"","sources":["../src/abstract-application-context.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAExC,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,8BAAsB,0BAA0B;IAC5C,SAAS,CAAC,cAAc,EAAE,yBAAyB,CAAC;gBAExC,cAAc,CAAC,EAAE,yBAAyB;IAI/C,iBAAiB,CAAC,cAAc,EAAE,yBAAyB,GAAG,IAAI;IAIzE,SAAS,CAAC,KAAK,IAAI,IAAI;IAIV,0BAA0B,CAAC,CAAC,SAAS,OAAO,EACrD,OAAO,EAAE,CAAC,EACV,EAAE,EAAE,CAAC,GAAG,EAAE,IAAI,KAAK,OAAO,CAAC,IAAI,CAAC,GACjC,OAAO,CAAC,IAAI,CAAC;IAUH,OAAO,CAAC,GAAG,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;cAIzC,OAAO,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;cAKxC,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;CAG1D"}
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AbstractApplicationContext = void 0;
4
+ const lodash_1 = require("lodash");
5
+ const application_event_publisher_1 = require("./application-event-publisher");
6
+ class AbstractApplicationContext {
7
+ eventPublisher;
8
+ constructor(eventPublisher) {
9
+ this.eventPublisher = eventPublisher ?? new application_event_publisher_1.ApplicationEventPublisher();
10
+ }
11
+ setEventPublisher(eventPublisher) {
12
+ this.eventPublisher = eventPublisher;
13
+ }
14
+ clone() {
15
+ return (0, lodash_1.clone)(this);
16
+ }
17
+ async enterCommandExecutionScope(command, fn) {
18
+ const newContext = this.clone();
19
+ await newContext.onEnter(command);
20
+ await fn(newContext);
21
+ await newContext.onExit(command);
22
+ }
23
+ async publish(...events) {
24
+ await this.eventPublisher.publish(...events);
25
+ }
26
+ async onEnter(message) {
27
+ this.eventPublisher = this.eventPublisher.deriveFrom(message);
28
+ }
29
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
30
+ async onExit(message) {
31
+ return;
32
+ }
33
+ }
34
+ exports.AbstractApplicationContext = AbstractApplicationContext;
35
+ //# sourceMappingURL=abstract-application-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"abstract-application-context.js","sourceRoot":"","sources":["../src/abstract-application-context.ts"],"names":[],"mappings":";;;AAAA,mCAA+B;AAG/B,+EAA0E;AAE1E,MAAsB,0BAA0B;IAClC,cAAc,CAA4B;IAEpD,YAAY,cAA0C;QAClD,IAAI,CAAC,cAAc,GAAG,cAAc,IAAI,IAAI,uDAAyB,EAAE,CAAC;IAC5E,CAAC;IAEM,iBAAiB,CAAC,cAAyC;QAC9D,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACzC,CAAC;IAES,KAAK;QACX,OAAO,IAAA,cAAK,EAAC,IAAI,CAAC,CAAC;IACvB,CAAC;IAEM,KAAK,CAAC,0BAA0B,CACnC,OAAU,EACV,EAAgC;QAEhC,MAAM,UAAU,GAAS,IAAI,CAAC,KAAK,EAAE,CAAC;QAEtC,MAAM,UAAU,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAElC,MAAM,EAAE,CAAC,UAAU,CAAC,CAAC;QAErB,MAAM,UAAU,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;IAEM,KAAK,CAAC,OAAO,CAAC,GAAG,MAAiB;QACrC,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC;IACjD,CAAC;IAES,KAAK,CAAC,OAAO,CAAC,OAAgB;QACpC,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IAClE,CAAC;IAED,6DAA6D;IACnD,KAAK,CAAC,MAAM,CAAC,OAAgB;QACnC,OAAO;IACX,CAAC;CACJ;AAxCD,gEAwCC"}
@@ -0,0 +1,2 @@
1
+ export { AbstractApplicationContext } from "./abstract-application-context";
2
+ //# sourceMappingURL=application-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"application-context.d.ts","sourceRoot":"","sources":["../src/application-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC"}
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AbstractApplicationContext = void 0;
4
+ var abstract_application_context_1 = require("./abstract-application-context");
5
+ Object.defineProperty(exports, "AbstractApplicationContext", { enumerable: true, get: function () { return abstract_application_context_1.AbstractApplicationContext; } });
6
+ //# sourceMappingURL=application-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"application-context.js","sourceRoot":"","sources":["../src/application-context.ts"],"names":[],"mappings":";;;AAAA,+EAA4E;AAAnE,0IAAA,0BAA0B,OAAA"}
@@ -0,0 +1,16 @@
1
+ import { AnyMessage, Message } from "@hexaijs/core";
2
+ import { EventPublisher } from "./event-publisher";
3
+ interface PublishCallback {
4
+ (event: AnyMessage): void | Promise<void>;
5
+ }
6
+ export declare class ApplicationEventPublisher implements EventPublisher<Message> {
7
+ private callbacks;
8
+ private context?;
9
+ deriveFrom(message: Message): ApplicationEventPublisher;
10
+ subscribe(callback: PublishCallback): () => void;
11
+ private unsubscribe;
12
+ publish(...events: Message[]): Promise<void>;
13
+ private runCallbacks;
14
+ }
15
+ export {};
16
+ //# sourceMappingURL=application-event-publisher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"application-event-publisher.d.ts","sourceRoot":"","sources":["../src/application-event-publisher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAEpD,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD,UAAU,eAAe;IACrB,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7C;AAED,qBAAa,yBAA0B,YAAW,cAAc,CAAC,OAAO,CAAC;IACrE,OAAO,CAAC,SAAS,CAAmC;IACpD,OAAO,CAAC,OAAO,CAAC,CAAU;IAEnB,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,yBAAyB;IAQvD,SAAS,CAAC,QAAQ,EAAE,eAAe,GAAG,MAAM,IAAI;IAKvD,OAAO,CAAC,WAAW;IAIN,OAAO,CAAC,GAAG,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;YAgB3C,YAAY;CAG7B"}
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApplicationEventPublisher = void 0;
4
+ const messaging_support_1 = require("./messaging-support");
5
+ class ApplicationEventPublisher {
6
+ callbacks = new Set();
7
+ context;
8
+ deriveFrom(message) {
9
+ const derived = new ApplicationEventPublisher();
10
+ derived.context = message;
11
+ derived.callbacks = new Set(this.callbacks);
12
+ return derived;
13
+ }
14
+ subscribe(callback) {
15
+ this.callbacks.add(callback);
16
+ return () => this.unsubscribe(callback);
17
+ }
18
+ unsubscribe(callback) {
19
+ this.callbacks.delete(callback);
20
+ }
21
+ async publish(...events) {
22
+ for (let event of events) {
23
+ if (this.context) {
24
+ const trace = (0, messaging_support_1.asTrace)(this.context);
25
+ event = event
26
+ .withHeader("causation", trace)
27
+ .withHeader("correlation", this.context.getHeader("correlation") || trace);
28
+ }
29
+ await this.runCallbacks(event);
30
+ }
31
+ }
32
+ async runCallbacks(event) {
33
+ await Promise.all([...this.callbacks].map((cb) => cb(event)));
34
+ }
35
+ }
36
+ exports.ApplicationEventPublisher = ApplicationEventPublisher;
37
+ //# sourceMappingURL=application-event-publisher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"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C,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAClE,CAAC;CACJ;AAxCD,8DAwCC"}
@@ -0,0 +1,59 @@
1
+ import { Message, MessageClass } from "@hexaijs/core";
2
+ import { AbstractApplicationContext } from "./abstract-application-context";
3
+ import { CommandHandler } from "./command-handler";
4
+ import { Command } from "./command";
5
+ import { QueryHandler } from "./query-handler";
6
+ import { Query } from "./query";
7
+ import { ApplicationErrorTransformer } from "./error";
8
+ import { EventHandler } from "./event-handler";
9
+ import { CommandInterceptor, QueryInterceptor, EventInterceptor, Interceptor } from "./interceptor";
10
+ import { SuccessResult, ErrorResult, Result } from "./result";
11
+ export { SuccessResult, ErrorResult, Result };
12
+ type Factory<T> = () => T;
13
+ type CommandHandlerFactory = Factory<CommandHandler>;
14
+ type QueryHandlerFactory = Factory<QueryHandler>;
15
+ interface CommandClass extends MessageClass {
16
+ new (...args: any[]): Command;
17
+ }
18
+ interface QueryClass extends MessageClass {
19
+ new (...args: any[]): Query;
20
+ }
21
+ export type EventHandlingResult = unknown;
22
+ export interface CommandDispatcher {
23
+ executeCommand<T = unknown>(command: Command): Promise<Result<T>>;
24
+ }
25
+ export interface QueryDispatcher {
26
+ executeQuery<T = unknown>(query: Query): Promise<Result<T>>;
27
+ }
28
+ export interface EventDispatcher {
29
+ handleEvent(event: Message): Promise<Result<EventHandlingResult>>;
30
+ }
31
+ export interface Application extends CommandDispatcher, QueryDispatcher, EventDispatcher {
32
+ }
33
+ export declare class ApplicationBuilder {
34
+ private commandHandlers;
35
+ private queryHandlers;
36
+ private eventHandlers;
37
+ private eventHandlerNames;
38
+ private applicationContext;
39
+ private errorTransformer;
40
+ private commandInterceptors;
41
+ private queryInterceptors;
42
+ private eventInterceptors;
43
+ private commonInterceptors;
44
+ static readonly defaultErrorTransformer: ApplicationErrorTransformer;
45
+ withCommandHandler(commandClass: CommandClass, commandHandlerFactory: CommandHandlerFactory): this;
46
+ private assertNoHandlerRegisteredFor;
47
+ withQueryHandler(queryClass: QueryClass, queryHandlerFactory: QueryHandlerFactory): this;
48
+ private assertNoQueryHandlerRegisteredFor;
49
+ withApplicationContext(applicationContext: AbstractApplicationContext): this;
50
+ withErrorTransformer(errorTransformer: ApplicationErrorTransformer): this;
51
+ withEventHandler(eventHandlerFactory: () => EventHandler, eventHandlerName?: string): this;
52
+ private assertNoEventHandlerWithSameNameRegistered;
53
+ withCommandInterceptor(interceptor: CommandInterceptor): this;
54
+ withQueryInterceptor(interceptor: QueryInterceptor): this;
55
+ withEventInterceptor(interceptor: EventInterceptor): this;
56
+ withInterceptor(interceptor: Interceptor): this;
57
+ build(): Application;
58
+ }
59
+ //# sourceMappingURL=application.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"application.d.ts","sourceRoot":"","sources":["../src/application.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAEtD,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAGH,2BAA2B,EAC9B,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EACH,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,WAAW,EACd,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAE9D,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC;AAE9C,KAAK,OAAO,CAAC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