@sincpro/client-framework 1.1.0 → 1.3.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 (53) hide show
  1. package/AGENTS.md +51 -17
  2. package/MANIFESTO.md +9 -7
  3. package/README.md +261 -131
  4. package/dist/client/services/guarded.d.ts +1 -1
  5. package/dist/client/services/propagation.js +4 -3
  6. package/dist/codegen/services/scaffold.d.ts +12 -10
  7. package/dist/codegen/services/scaffold.js +29 -51
  8. package/dist/context/entrypoint/context.d.ts +5 -4
  9. package/dist/core/domain/bus.d.ts +5 -3
  10. package/dist/core/domain/bus.js +8 -1
  11. package/dist/core/domain/dto.d.ts +71 -9
  12. package/dist/core/domain/dto.js +25 -5
  13. package/dist/core/domain/errors.d.ts +2 -2
  14. package/dist/core/domain/pipeline.d.ts +8 -5
  15. package/dist/core/domain/services.d.ts +40 -13
  16. package/dist/core/domain/services.js +31 -7
  17. package/dist/core/entrypoint/bounded-context.d.ts +71 -41
  18. package/dist/core/entrypoint/bounded-context.js +155 -56
  19. package/dist/core/entrypoint/screens.js +0 -5
  20. package/dist/core/index.d.ts +4 -3
  21. package/dist/core/index.js +4 -3
  22. package/dist/core/infrastructure/listeners.d.ts +6 -5
  23. package/dist/core/infrastructure/listeners.js +2 -2
  24. package/dist/core/services/dto-keys.d.ts +44 -0
  25. package/dist/core/services/dto-keys.js +97 -0
  26. package/dist/core/services/execution.d.ts +15 -10
  27. package/dist/core/services/execution.js +36 -23
  28. package/dist/core/services/interceptors.d.ts +2 -2
  29. package/dist/core/services/interceptors.js +5 -5
  30. package/dist/core/services/listening.d.ts +6 -8
  31. package/dist/core/services/listening.js +3 -2
  32. package/dist/event_driven/adapters/stored-queue.d.ts +8 -7
  33. package/dist/event_driven/adapters/stored-queue.js +8 -12
  34. package/dist/event_driven/domain/envelope.d.ts +2 -2
  35. package/dist/event_driven/domain/envelope.js +7 -1
  36. package/dist/event_driven/domain/messages.d.ts +34 -0
  37. package/dist/event_driven/domain/messages.js +1 -0
  38. package/dist/event_driven/domain/queue.d.ts +9 -5
  39. package/dist/event_driven/entrypoint/publisher.d.ts +3 -3
  40. package/dist/event_driven/entrypoint/publisher.js +5 -1
  41. package/dist/event_driven/entrypoint/subscriber.d.ts +66 -19
  42. package/dist/event_driven/entrypoint/subscriber.js +122 -15
  43. package/dist/event_driven/index.d.ts +11 -7
  44. package/dist/event_driven/index.js +9 -6
  45. package/dist/event_driven/services/messages.d.ts +41 -0
  46. package/dist/event_driven/services/messages.js +147 -0
  47. package/dist/observability/adapters/memory.d.ts +1 -1
  48. package/dist/observability/domain/logging.d.ts +2 -2
  49. package/dist/observability/services/logging.d.ts +6 -3
  50. package/dist/observability/services/logging.js +1 -1
  51. package/dist/observability/services/trace-context.d.ts +10 -0
  52. package/dist/observability/services/trace-context.js +29 -0
  53. package/package.json +2 -2
@@ -1,20 +1,17 @@
1
+ import { BIND, type Execution } from "../../context/domain/execution.js";
1
2
  import type { ContextValues } from "../../context/domain/store.js";
2
3
  import { type Context } from "../../context/entrypoint/context.js";
3
4
  import { type CommandBus } from "../domain/bus.js";
4
- import { type Answer, type AnyCommand, Command, type CommandClass, DomainEvent, type EventClass, type Executable, type ResponseClass } from "../domain/dto.js";
5
+ import { type Answer, type AnyCommand, type Command, type CommandClass, type CommandDescriptor, type DomainEvent, type DtoKey, type EventClass, type EventDescriptor, type Executable, type ExecutableOf, type RemoteCommand, type RemoteEvent, type ResponseClass } from "../domain/dto.js";
5
6
  import type { ErrorClass, ErrorHandler } from "../domain/errors.js";
6
7
  import type { Cause, ExecuteOptions, ExecutionCompleted, ExecutionFailed, ExecutionStarted, Extension, Interceptor, Listener } from "../domain/pipeline.js";
7
- import { type ExecutableClass } from "../services/listening.js";
8
8
  import type { LayerLogger } from "../../observability/domain/logging.js";
9
9
  interface Executor<C extends Executable, R> {
10
10
  execute(executable: C): R | Promise<R>;
11
11
  }
12
- type ServiceClass<C extends Executable, R> = {
13
- new (): Executor<C, R>;
14
- readonly serviceName: string;
15
- };
16
- /** What a service is registered for: a Command's class or a domain event's. */
17
- type DtoClass = ExecutableClass;
12
+ type ServiceClass<C extends Executable, R> = new () => Executor<C, R>;
13
+ /** What a registration is for when it names none: everything; else the DTOs it names. */
14
+ type Of<K> = [K] extends [never] ? Executable : ExecutableOf<K>;
18
15
  /** The service a registration takes the place of, as the backend's `replaces=`. */
19
16
  export type RegistrationOptions = {
20
17
  replaces?: abstract new (...args: never[]) => object;
@@ -25,22 +22,23 @@ export type Registrar<T extends Executable> = <S extends ServiceClass<NoInfer<T>
25
22
  * A bounded context: the bus of its Commands and domain events, as sincpro_framework's
26
23
  * `UseFramework`.
27
24
  *
28
- * const project = new BoundedContext<ProjectDependencies>("project");
29
- * project.addDependency("client", clientOf(transport));
30
- * project.feature(CommandCancelIssue)(CancelIssue); // or @project.feature(...)
31
- * project.feature(IssueClosed)(NotifyWatchers); // a subscriber of an event
32
- * project.feature(CommandCancelIssue, { replaces: CancelIssue })(CancelAndArchive);
33
- * project.addFeatureErrorHandler(toEmptyWhenMissing);
34
- * project.expectErrors(IssueLocked); // refused, never reported
35
- * await project.execute(new CommandCancelIssue("x")); // ResponseCancelIssue
36
- * await project.execute(new IssueClosed("x")); // what its subscriber returns
37
- * project.logger.info("Catalog preloaded");
25
+ * const projectBoundedContext = new BoundedContext<ProjectDependencies>("project");
26
+ * projectBoundedContext.addDependency("client", clientOf(operations));
27
+ * projectBoundedContext.feature(CommandCancelIssue)(CancelIssue); // or a decorator
28
+ * projectBoundedContext.feature(IssueClosed)(ArchiveIssue); // a use case of an event
29
+ * projectBoundedContext.feature(CommandCancelIssue, { replaces: CancelIssue })(CancelAndArchive);
30
+ * projectBoundedContext.addFeatureErrorHandler(toEmptyWhenMissing);
31
+ * projectBoundedContext.expectErrors(IssueLocked); // refused, never reported
32
+ * await projectBoundedContext.execute(new CommandCancelIssue("x")); // ResponseCancelIssue
33
+ * await projectBoundedContext.execute(new IssueClosed("x")); // what its use case returns
34
+ * projectBoundedContext.logger.info("Catalog preloaded");
38
35
  *
39
36
  * Context: registrations, dependencies, handlers and expected errors are snapshotted per
40
37
  * generation; a call keeps the generation it started with, and what is added later answers from
41
- * the next call — as the backend's `build_root_bus`. A domain event is executed as a Command is:
42
- * one subscriber per bounded context, through the same pipeline; carrying it to every bounded
43
- * context that hears it (a queue, an outbox) is the platform's.
38
+ * the next call — as the backend's `build_root_bus`. A service takes one DTO or N — Commands,
39
+ * domain events, generated ones —; registering it for an event is the subscription, and the
40
+ * queue's `Subscriber` executes the event here when it arrives. Injected into another run — a
41
+ * Feature of another bounded context — it is bound to that run (`BIND`).
44
42
  */
45
43
  export declare class BoundedContext<D extends object = Record<never, never>, C extends object = ContextValues> {
46
44
  readonly name: string;
@@ -63,36 +61,53 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
63
61
  replaces: D[K];
64
62
  }): this;
65
63
  /**
66
- * Registers the Feature that executes a Command — or that subscribes to a domain event. With
67
- * `replaces`, it takes the place of the service registered now for it.
64
+ * Registers the Feature that executes a DTO — or each DTO listed, as the backend's
65
+ * `feature([CommandX, EventY])`: a Command's class, a domain event's (the use case of the event:
66
+ * registering it is the subscription), or a generated one's entry (`operations.X`, `events.X`).
67
+ * With `replaces`, it takes the place of the service registered now for each.
68
+ *
69
+ * @billingBoundedContext.feature([CommandIssueInvoice, OrderPaid])
70
+ * class IssueInvoice extends Feature<CommandIssueInvoice | OrderPaid, ResponseInvoice> { … }
68
71
  */
72
+ feature<const K extends readonly DtoKey[]>(dtos: K, options?: RegistrationOptions): Registrar<ExecutableOf<K[number]>>;
69
73
  feature<T extends AnyCommand>(command: CommandClass<T>, options?: RegistrationOptions): Registrar<T>;
70
74
  feature<E extends DomainEvent>(event: EventClass<E>, options?: RegistrationOptions): Registrar<E>;
71
- /** Registers the ApplicationService of a Command or a domain event; `replaces` as `feature`. */
75
+ feature<I = unknown, R = unknown>(command: CommandDescriptor, options?: RegistrationOptions): Registrar<RemoteCommand<I, R>>;
76
+ feature<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor, options?: RegistrationOptions): Registrar<E>;
77
+ /** Registers the ApplicationService of a DTO or of each DTO listed; as `feature`. */
78
+ appService<const K extends readonly DtoKey[]>(dtos: K, options?: RegistrationOptions): Registrar<ExecutableOf<K[number]>>;
72
79
  appService<T extends AnyCommand>(command: CommandClass<T>, options?: RegistrationOptions): Registrar<T>;
73
80
  appService<E extends DomainEvent>(event: EventClass<E>, options?: RegistrationOptions): Registrar<E>;
74
- /** The service registered now for a Command or an event class — what a `replaces` names. */
75
- handlerOf(dto: DtoClass): (abstract new (...args: never[]) => object) | undefined;
81
+ appService<I = unknown, R = unknown>(command: CommandDescriptor, options?: RegistrationOptions): Registrar<RemoteCommand<I, R>>;
82
+ appService<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor, options?: RegistrationOptions): Registrar<E>;
83
+ /** The service registered now for a DTO — what a `replaces` names. */
84
+ handlerOf(dto: DtoKey): (abstract new (...args: never[]) => object) | undefined;
85
+ /**
86
+ * What an event of that wire name is rebuilt as here — its class, or the generated entry it
87
+ * was registered with —, or `undefined` when nothing here hears it: the backend's
88
+ * `event_type(name)`.
89
+ */
90
+ eventTypeOf(name: string): EventClass<DomainEvent> | EventDescriptor | undefined;
76
91
  /**
77
- * The event class registered here under a wire name, or `undefined` when nothing here hears it
78
- * — what a platform's queue rebuilds a stored event as, as the backend's `event_type(name)`.
92
+ * What a Command of that identity (`<context>.<Command>`) is rebuilt as here — its class, or
93
+ * the generated entry it was registered with —, or `undefined` when nothing here executes it.
79
94
  */
80
- eventTypeOf(name: string): EventClass<DomainEvent> | undefined;
95
+ commandTypeOf(identity: string): CommandClass<AnyCommand> | CommandDescriptor | undefined;
81
96
  /**
82
97
  * Runs `interceptor` around every execution of these classes — of every one when none is
83
98
  * named —, outermost first in the order registered. It may look, veto (throw), adjust what it
84
99
  * passes on (of the same class) or answer by itself. Registered after a call, it wraps from
85
100
  * the next one.
86
101
  */
87
- interceptor<T extends Executable = Executable>(...dtos: (abstract new (...args: never[]) => T)[]): <F extends Interceptor<T>>(interceptor: F) => F;
102
+ interceptor<K extends DtoKey = never>(...dtos: K[]): <F extends Interceptor<Of<K>>>(interceptor: F) => F;
88
103
  /** Stops `interceptor` wherever it was registered; from the next call. */
89
104
  withoutInterceptor(interceptor: (...args: never[]) => unknown): this;
90
105
  /** Hears every run of these classes (every one when none is named) begin. Answers how to stop. */
91
- onStart(listener: Listener<ExecutionStarted>, ...dtos: DtoClass[]): () => void;
106
+ onStart(listener: Listener<ExecutionStarted>, ...dtos: DtoKey[]): () => void;
92
107
  /** Hears every run of these classes whose service answered — not an answer a handler gave. */
93
- onCompletion(listener: Listener<ExecutionCompleted>, ...dtos: DtoClass[]): () => void;
108
+ onCompletion(listener: Listener<ExecutionCompleted>, ...dtos: DtoKey[]): () => void;
94
109
  /** Hears every failure that escapes a call — after every handler —, once, where it failed. */
95
- onFailure(listener: Listener<ExecutionFailed>, ...dtos: DtoClass[]): () => void;
110
+ onFailure(listener: Listener<ExecutionFailed>, ...dtos: DtoKey[]): () => void;
96
111
  /**
97
112
  * Wires a component into this bounded context — its dependencies, services, interceptors,
98
113
  * listeners, handlers — in one place: a module of an application, a plugin. `fresh()` copies
@@ -111,14 +126,24 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
111
126
  */
112
127
  expectErrors(...types: ErrorClass[]): this;
113
128
  /**
114
- * Executes a Command — its Response, inferred —, or a domain event — its subscriber's answer.
115
- * `{ signal }` cancels the run (it ends `aborted`); a delivered event's envelope continues its
116
- * flow (`execute(event, envelope)`).
129
+ * Executes a Command — its Response, inferred —, a domain event — what its use case answers —,
130
+ * or a generated one (`commandOf(operations.X, input)`, an event's data). `{ signal }` cancels
131
+ * the run (it ends `aborted`); a delivered message's cause continues its flow
132
+ * (`execute(event, envelope)`).
117
133
  */
118
134
  execute<R>(command: Command<R>, returnType?: ResponseClass<NoInfer<R>>): Promise<R>;
119
135
  execute<R>(command: Command<R>, options: ExecuteOptions): Promise<R>;
120
- execute(event: DomainEvent, options?: ExecuteOptions | Cause): Promise<unknown>;
136
+ execute<I, R>(command: RemoteCommand<I, R>, options?: ExecuteOptions): Promise<R>;
137
+ execute(event: DomainEvent | RemoteEvent, options?: ExecuteOptions | Cause): Promise<unknown>;
121
138
  scoped(context: Partial<C>): CommandBus;
139
+ /**
140
+ * This bounded context as `execution` calls it — what it is as a dependency of another run (a
141
+ * Feature of another bounded context, as `common_mcp` is in the backend's helpdesk): what it
142
+ * executes is a child of that run — its span under the caller's, the same flow (`correlationId`), caused by it,
143
+ * cancelled with it, its errors reported once along it. It still runs with its own
144
+ * dependencies, context, interceptors and handlers.
145
+ */
146
+ [BIND](execution: Execution): this;
122
147
  buildRootBus(): void;
123
148
  fresh(): BoundedContext<D, C>;
124
149
  /** What escaped a call, told once, from where it first failed. */
@@ -126,10 +151,15 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
126
151
  private addErrorHandler;
127
152
  private registrar;
128
153
  /**
129
- * 1. The service is of the layer it is registered in, for a Command or a domain event class.
130
- * 2. The class has no service yet — or, with `replaces`, the one it has is that one.
131
- * 3. Its `serviceName` is given and no other service has it; an event's `eventName` is given
132
- * and no other event class here has it — the name means one event.
154
+ * 1. The service is of the layer it is registered in, for a DTO: a Command's or a domain event's
155
+ * class, or a generated one's entry.
156
+ * 2. The DTO has no service yet — or, with `replaces`, the one it has is that one.
157
+ * 3. Its name is the framework's to take, at registration: the class's name as the code wrote it
158
+ * (a standard decorator's `context.name`, which a minifier does not touch), else the class's
159
+ * `name` — a production build keeps class names (`keep_classnames`, `keepNames`). No other
160
+ * service here has it; the same service may take N DTOs.
161
+ * 4. An event's wire name is given, and no other event here has it; a Command's identity, when
162
+ * it declares one, likewise: a name or an identity means one DTO.
133
163
  * Final: registered, said on its spans when it replaced another; the next call answers with it.
134
164
  */
135
165
  private registerService;
@@ -1,9 +1,11 @@
1
+ import { BIND } from "../../context/domain/execution.js";
1
2
  import { contextAt, } from "../../context/entrypoint/context.js";
2
3
  import { processContext, processStore, } from "../../context/infrastructure/process.js";
3
4
  import { FeatureBus, optionsOf, } from "../domain/bus.js";
4
- import { Command, DomainEvent, } from "../domain/dto.js";
5
+ import { EVENT_NAME, } from "../domain/dto.js";
5
6
  import { ApplicationService, Feature, RESERVED_MEMBERS, } from "../domain/services.js";
6
7
  import { processHearing } from "../infrastructure/listeners.js";
8
+ import { describeDto, identityOf, isCommandClass, isCommandDescriptor, isDtoKey, keyIdentity, } from "../services/dto-keys.js";
7
9
  import { handled } from "../services/error-handlers.js";
8
10
  import { executeService, failedAt } from "../services/execution.js";
9
11
  import { announceTo, concerns, listenIn, } from "../services/listening.js";
@@ -15,33 +17,31 @@ function isExecutor(value) {
15
17
  "execute" in value &&
16
18
  typeof value.execute === "function");
17
19
  }
18
- function isEventClass(dto) {
19
- return dto.prototype instanceof DomainEvent;
20
- }
21
20
  function nameOf(Service) {
22
21
  const named = Service;
23
- return String(named?.serviceName ?? named?.name ?? Service);
22
+ return String(named?.name ?? Service);
24
23
  }
25
24
  /**
26
25
  * A bounded context: the bus of its Commands and domain events, as sincpro_framework's
27
26
  * `UseFramework`.
28
27
  *
29
- * const project = new BoundedContext<ProjectDependencies>("project");
30
- * project.addDependency("client", clientOf(transport));
31
- * project.feature(CommandCancelIssue)(CancelIssue); // or @project.feature(...)
32
- * project.feature(IssueClosed)(NotifyWatchers); // a subscriber of an event
33
- * project.feature(CommandCancelIssue, { replaces: CancelIssue })(CancelAndArchive);
34
- * project.addFeatureErrorHandler(toEmptyWhenMissing);
35
- * project.expectErrors(IssueLocked); // refused, never reported
36
- * await project.execute(new CommandCancelIssue("x")); // ResponseCancelIssue
37
- * await project.execute(new IssueClosed("x")); // what its subscriber returns
38
- * project.logger.info("Catalog preloaded");
28
+ * const projectBoundedContext = new BoundedContext<ProjectDependencies>("project");
29
+ * projectBoundedContext.addDependency("client", clientOf(operations));
30
+ * projectBoundedContext.feature(CommandCancelIssue)(CancelIssue); // or a decorator
31
+ * projectBoundedContext.feature(IssueClosed)(ArchiveIssue); // a use case of an event
32
+ * projectBoundedContext.feature(CommandCancelIssue, { replaces: CancelIssue })(CancelAndArchive);
33
+ * projectBoundedContext.addFeatureErrorHandler(toEmptyWhenMissing);
34
+ * projectBoundedContext.expectErrors(IssueLocked); // refused, never reported
35
+ * await projectBoundedContext.execute(new CommandCancelIssue("x")); // ResponseCancelIssue
36
+ * await projectBoundedContext.execute(new IssueClosed("x")); // what its use case returns
37
+ * projectBoundedContext.logger.info("Catalog preloaded");
39
38
  *
40
39
  * Context: registrations, dependencies, handlers and expected errors are snapshotted per
41
40
  * generation; a call keeps the generation it started with, and what is added later answers from
42
- * the next call — as the backend's `build_root_bus`. A domain event is executed as a Command is:
43
- * one subscriber per bounded context, through the same pipeline; carrying it to every bounded
44
- * context that hears it (a queue, an outbox) is the platform's.
41
+ * the next call — as the backend's `build_root_bus`. A service takes one DTO or N — Commands,
42
+ * domain events, generated ones —; registering it for an event is the subscription, and the
43
+ * queue's `Subscriber` executes the event here when it arrives. Injected into another run — a
44
+ * Feature of another bounded context — it is bound to that run (`BIND`).
45
45
  */
46
46
  export class BoundedContext {
47
47
  name;
@@ -118,17 +118,31 @@ export class BoundedContext {
118
118
  appService(dto, options) {
119
119
  return this.registrar(dto, "application_service", options);
120
120
  }
121
- /** The service registered now for a Command or an event class — what a `replaces` names. */
121
+ /** The service registered now for a DTO — what a `replaces` names. */
122
122
  handlerOf(dto) {
123
123
  return this.registrations.get(dto)?.Service;
124
124
  }
125
125
  /**
126
- * The event class registered here under a wire name, or `undefined` when nothing here hears it
127
- * — what a platform's queue rebuilds a stored event as, as the backend's `event_type(name)`.
126
+ * What an event of that wire name is rebuilt as here — its class, or the generated entry it
127
+ * was registered with —, or `undefined` when nothing here hears it: the backend's
128
+ * `event_type(name)`.
128
129
  */
129
130
  eventTypeOf(name) {
130
131
  for (const dto of this.registrations.keys()) {
131
- if (isEventClass(dto) && dto.eventName === name)
132
+ const known = keyIdentity(dto);
133
+ if (known.kind === "event" && known.wire === name)
134
+ return dto;
135
+ }
136
+ return undefined;
137
+ }
138
+ /**
139
+ * What a Command of that identity (`<context>.<Command>`) is rebuilt as here — its class, or
140
+ * the generated entry it was registered with —, or `undefined` when nothing here executes it.
141
+ */
142
+ commandTypeOf(identity) {
143
+ for (const dto of this.registrations.keys()) {
144
+ const known = keyIdentity(dto);
145
+ if (known.kind === "command" && known.wire === identity)
132
146
  return dto;
133
147
  }
134
148
  return undefined;
@@ -211,6 +225,31 @@ export class BoundedContext {
211
225
  const scope = { ...context };
212
226
  return new FeatureBus((executable, options) => this.generation().root(executable, scope, options));
213
227
  }
228
+ /**
229
+ * This bounded context as `execution` calls it — what it is as a dependency of another run (a
230
+ * Feature of another bounded context, as `common_mcp` is in the backend's helpdesk): what it
231
+ * executes is a child of that run — its span under the caller's, the same flow (`correlationId`), caused by it,
232
+ * cancelled with it, its errors reported once along it. It still runs with its own
233
+ * dependencies, context, interceptors and handlers.
234
+ */
235
+ [BIND](execution) {
236
+ const caller = execution;
237
+ const execute = (executable, second) => this.generation().root(executable, {}, { ...optionsOf(second), caller });
238
+ const scoped = (context) => {
239
+ const scope = { ...context };
240
+ return new FeatureBus((executable, options) => this.generation().root(executable, scope, { ...options, caller }));
241
+ };
242
+ return new Proxy(this, {
243
+ get(target, property) {
244
+ if (property === "execute")
245
+ return execute;
246
+ if (property === "scoped")
247
+ return scoped;
248
+ const value = Reflect.get(target, property, target);
249
+ return typeof value === "function" ? value.bind(target) : value;
250
+ },
251
+ });
252
+ }
214
253
  buildRootBus() {
215
254
  this.generation();
216
255
  }
@@ -263,8 +302,26 @@ export class BoundedContext {
263
302
  return this;
264
303
  }
265
304
  registrar(dto, layer, options = {}) {
305
+ const dtos = Array.isArray(dto) ? dto : [dto];
306
+ if (dtos.length === 0)
307
+ throw new TypeError("A service is registered for one DTO at least");
266
308
  return (Service, decorator) => {
267
- const register = () => this.registerService(dto, Service, layer, options.replaces);
309
+ // All the DTOs listed, or none: a refused one leaves the registrations as they were.
310
+ const register = () => {
311
+ const before = [...this.registrations];
312
+ const revision = this.revision;
313
+ try {
314
+ for (const one of dtos)
315
+ this.registerService(one, Service, layer, options.replaces, decorator?.name);
316
+ }
317
+ catch (error) {
318
+ this.registrations.clear();
319
+ for (const [dto, registration] of before)
320
+ this.registrations.set(dto, registration);
321
+ this.revision = revision;
322
+ throw error;
323
+ }
324
+ };
268
325
  // Standard decorators run before static fields have initialized.
269
326
  if (decorator)
270
327
  decorator.addInitializer(register);
@@ -274,21 +331,47 @@ export class BoundedContext {
274
331
  };
275
332
  }
276
333
  /**
277
- * 1. The service is of the layer it is registered in, for a Command or a domain event class.
278
- * 2. The class has no service yet — or, with `replaces`, the one it has is that one.
279
- * 3. Its `serviceName` is given and no other service has it; an event's `eventName` is given
280
- * and no other event class here has it — the name means one event.
334
+ * 1. The service is of the layer it is registered in, for a DTO: a Command's or a domain event's
335
+ * class, or a generated one's entry.
336
+ * 2. The DTO has no service yet — or, with `replaces`, the one it has is that one.
337
+ * 3. Its name is the framework's to take, at registration: the class's name as the code wrote it
338
+ * (a standard decorator's `context.name`, which a minifier does not touch), else the class's
339
+ * `name` — a production build keeps class names (`keep_classnames`, `keepNames`). No other
340
+ * service here has it; the same service may take N DTOs.
341
+ * 4. An event's wire name is given, and no other event here has it; a Command's identity, when
342
+ * it declares one, likewise: a name or an identity means one DTO.
281
343
  * Final: registered, said on its spans when it replaced another; the next call answers with it.
282
344
  */
283
- registerService(dto, Service, layer, replaces) {
345
+ registerService(dto, Service, layer, replaces, written) {
284
346
  const Base = layer === "feature" ? Feature : ApplicationService;
285
347
  if (!(Service.prototype instanceof Base) ||
286
348
  (layer === "feature" && Service.prototype instanceof ApplicationService)) {
287
349
  throw new TypeError(`The service is not an ${layer}`);
288
350
  }
289
- const event = isEventClass(dto);
290
- if (!event && !(dto.prototype instanceof Command)) {
291
- throw new TypeError("A service is registered for a Command or a DomainEvent class");
351
+ if (!isDtoKey(dto)) {
352
+ throw new TypeError("A service is registered for a Command or a DomainEvent: its class, or a generated one's entry");
353
+ }
354
+ // A Command's identity is the framework's, as the backend's `registered_name`:
355
+ // `<context>.<Command>` — the key a generated contract's `operations` carry too.
356
+ if (isCommandClass(dto) && !Object.hasOwn(dto, "commandName") && dto.name !== "") {
357
+ Object.defineProperty(dto, "commandName", {
358
+ value: `${this.name}.${dto.name}`,
359
+ configurable: true,
360
+ });
361
+ }
362
+ const known = keyIdentity(dto);
363
+ if (known.kind === "event" &&
364
+ (typeof known.wire !== "string" || known.wire.trim() === "")) {
365
+ throw new Error("A domain event needs a nonempty eventName");
366
+ }
367
+ if (known.kind === "event" && !EVENT_NAME.test(known.wire ?? "")) {
368
+ throw new Error(`${known.wire} is not an event's name: <context>.<aggregate>.vN.<fact>`);
369
+ }
370
+ if (isCommandDescriptor(dto) && dto.identity.trim() === "") {
371
+ throw new Error("A generated Command needs its identity");
372
+ }
373
+ if (isCommandClass(dto) && known.wire !== undefined && known.wire.trim() === "") {
374
+ throw new Error("A Command's commandName, when declared, is nonempty");
292
375
  }
293
376
  const current = this.registrations.get(dto);
294
377
  if (replaces !== undefined && current?.Service !== replaces) {
@@ -297,24 +380,25 @@ export class BoundedContext {
297
380
  if (replaces === undefined && current) {
298
381
  throw new Error("Command already registered: one executor across both layers");
299
382
  }
300
- const name = Service.serviceName;
383
+ const name = written ?? Service.name;
301
384
  if (typeof name !== "string" || name.trim() === "") {
302
- throw new Error("A service needs a nonempty registered name");
385
+ throw new Error("A service is a named class: its name is its use case in spans and logs");
303
386
  }
304
387
  for (const [other, registration] of this.registrations) {
305
- if (registration !== current && registration.name === name) {
388
+ if (registration !== current &&
389
+ registration.Service !== Service &&
390
+ registration.name === name) {
306
391
  throw new Error(`Service name already registered: ${name}`);
307
392
  }
308
- if (event &&
309
- other !== dto &&
310
- isEventClass(other) &&
311
- other.eventName === dto.eventName) {
312
- throw new Error(`Event name already registered: ${dto.eventName}`);
393
+ if (other === dto || known.wire === undefined)
394
+ continue;
395
+ const theirs = keyIdentity(other);
396
+ if (theirs.kind === known.kind && theirs.wire === known.wire) {
397
+ throw new Error(known.kind === "event"
398
+ ? `Event name already registered: ${known.wire}`
399
+ : `Command identity already registered: ${known.wire}`);
313
400
  }
314
401
  }
315
- if (event && (typeof dto.eventName !== "string" || dto.eventName.trim() === "")) {
316
- throw new Error("A domain event needs a nonempty eventName");
317
- }
318
402
  this.registrations.set(dto, {
319
403
  name,
320
404
  layer,
@@ -354,28 +438,43 @@ export class BoundedContext {
354
438
  announceTo(everyContext.completed, heard);
355
439
  },
356
440
  };
441
+ // One instance per service, whatever number of DTOs it takes: a singleton of its generation.
357
442
  const instances = new Map();
358
- for (const registration of registrations.values()) {
359
- const instance = new registration.Service();
360
- if (!isExecutor(instance)) {
361
- throw new Error(`Registered service is unavailable: ${registration.name}`);
443
+ // A generated DTO has no class: it is found by its kind and wire identity.
444
+ const generated = new Map();
445
+ for (const [dto, registration] of registrations) {
446
+ if (!instances.has(registration.Service)) {
447
+ const instance = new registration.Service();
448
+ if (!isExecutor(instance)) {
449
+ throw new Error(`Registered service is unavailable: ${registration.name}`);
450
+ }
451
+ instances.set(registration.Service, instance);
362
452
  }
363
- instances.set(registration, instance);
453
+ const known = keyIdentity(dto);
454
+ if (known.type === undefined)
455
+ generated.set(`${known.kind}:${known.wire}`, registration);
364
456
  }
365
457
  const dispatch = async (executable, parent, featureOnly = false, scope = {}, options = {}) => {
366
- // Exact constructor identity: a subclass of a registered class is another one.
367
- const target = registrations.get(Object.getPrototypeOf(executable)?.constructor);
458
+ // Exact constructor identity — a subclass of a registered class is another one —; a
459
+ // generated DTO, by its kind and wire identity.
460
+ const known = identityOf(executable);
461
+ const target = known === undefined
462
+ ? undefined
463
+ : known.type !== undefined
464
+ ? registrations.get(known.type)
465
+ : generated.get(`${known.kind}:${known.wire}`);
368
466
  if (!target)
369
- throw new Error("No executor registered for this command class");
467
+ throw new Error(`No executor registered for ${describeDto(executable)}`);
370
468
  if (featureOnly && target.layer !== "feature") {
371
469
  throw new Error("An ApplicationService may compose only Features");
372
470
  }
373
- const service = instances.get(target);
471
+ const service = instances.get(target.Service);
374
472
  if (!service) {
375
473
  throw new Error(`Registered service is unavailable: ${target.name}`);
376
474
  }
377
475
  const attributes = {
378
- ...(executable instanceof DomainEvent ? { "sincpro.event": executable.name } : {}),
476
+ ...(known?.kind === "event" && known.wire ? { "sincpro.event": known.wire } : {}),
477
+ ...(known?.kind === "command" && known.wire ? { "sincpro.command": known.wire } : {}),
379
478
  ...(target.replaces ? { "sincpro.replaces": target.replaces } : {}),
380
479
  };
381
480
  return executeService(service, executable, {
@@ -386,10 +485,10 @@ export class BoundedContext {
386
485
  dependencies,
387
486
  context: () => ({ ...processContext.values, ...this.context.values, ...scope }),
388
487
  ...(parent ? { parent } : {}),
389
- // Only an event comes from outside with a cause; a child continues its parent.
390
- ...(options.cause && executable instanceof DomainEvent && !parent
391
- ? { cause: options.cause }
392
- : {}),
488
+ // A root called from another run continues it; a child continues its parent.
489
+ ...(options.caller && !parent ? { caller: options.caller } : {}),
490
+ // A delivered message — an event, a Command — continues the flow of what caused it.
491
+ ...(options.cause && !parent ? { cause: options.cause } : {}),
393
492
  ...(options.signal ? { signal: options.signal } : {}),
394
493
  featureBus: (execution) => new FeatureBus((child, options) => dispatch(child, execution, true, {}, options)),
395
494
  expected,
@@ -63,21 +63,18 @@ class Send extends Command {
63
63
  }
64
64
  }
65
65
  class EntityList extends Feature {
66
- static serviceName = "EntityReads.list";
67
66
  execute(dto) {
68
67
  this.span.set({ "http.route": dto.route });
69
68
  return this.transport.list(dto.route, dto.criteria, dto.signal, dto.options);
70
69
  }
71
70
  }
72
71
  class EntityGet extends Feature {
73
- static serviceName = "EntityReads.one";
74
72
  execute(dto) {
75
73
  this.span.set({ "http.route": dto.route });
76
74
  return this.transport.one(dto.route, dto.signal, dto.options);
77
75
  }
78
76
  }
79
77
  class EntityRead extends Feature {
80
- static serviceName = "EntityReads.read";
81
78
  execute(dto) {
82
79
  this.span.set({ "http.route": dto.route });
83
80
  const transport = this.transport;
@@ -88,7 +85,6 @@ class EntityRead extends Feature {
88
85
  }
89
86
  }
90
87
  class EntityExport extends Feature {
91
- static serviceName = "EntityReads.download";
92
88
  execute(dto) {
93
89
  this.span.set({ "http.route": dto.route });
94
90
  const transport = this.transport;
@@ -99,7 +95,6 @@ class EntityExport extends Feature {
99
95
  }
100
96
  }
101
97
  class EntitySend extends Feature {
102
- static serviceName = "EntityWrites.send";
103
98
  execute(dto) {
104
99
  this.span.set({ "http.method": dto.method, "http.route": dto.route });
105
100
  return this.transport.send(dto.method, dto.route, dto.body, dto.signal, dto.options);
@@ -3,16 +3,17 @@
3
3
  * Responses, Features and ApplicationServices, a bounded context that is their bus, its error
4
4
  * handlers — and the process they run in.
5
5
  *
6
- * domain/ DTOs, the bus, the service bases, the error-handler contract
6
+ * domain/ DTOs (classes, and generated ones the bus recognizes), the bus, the service
7
+ * bases (`servicesWith`: typed with a context's dependencies), the error handlers
7
8
  * services/ the execution pipeline, dependency binding, the handler chain
8
9
  * entrypoint/ `BoundedContext`, `screensTransport`
9
10
  * infrastructure/ `configureProcess`, `configureLogger`
10
11
  */
11
12
  export { type CommandBus, FeatureBus } from "./domain/bus.js";
12
- export { Command, DataTransferObject, DomainEvent, type EventClass, Response, } from "./domain/dto.js";
13
+ export { type AnyCommand, Command, COMMAND_IDENTITY, type CommandClass, type CommandDescriptor, type CommandNamed, commandOf, DataTransferObject, DomainEvent, type DtoKey, type EventClass, type EventDescriptor, type Executable, type ExecutableOf, type RemoteCommand, type RemoteEvent, Response, } from "./domain/dto.js";
13
14
  export type { ErrorClass, ErrorHandler } from "./domain/errors.js";
14
15
  export type { CallNext, Cause, ExecuteOptions, ExecutionCompleted, ExecutionFailed, ExecutionStarted, Extension, InterceptedRun, Interceptor, Listener, PipelineLayer, } from "./domain/pipeline.js";
15
- export { ApplicationService, Feature } from "./domain/services.js";
16
+ export { ApplicationService, type ApplicationServiceWith, Feature, type FeatureWith, type ServiceInput, servicesWith, } from "./domain/services.js";
16
17
  export { BoundedContext, type Registrar, type RegistrationOptions, } from "./entrypoint/bounded-context.js";
17
18
  export { screensTransport } from "./entrypoint/screens.js";
18
19
  export { processListeners } from "./infrastructure/listeners.js";
@@ -3,14 +3,15 @@
3
3
  * Responses, Features and ApplicationServices, a bounded context that is their bus, its error
4
4
  * handlers — and the process they run in.
5
5
  *
6
- * domain/ DTOs, the bus, the service bases, the error-handler contract
6
+ * domain/ DTOs (classes, and generated ones the bus recognizes), the bus, the service
7
+ * bases (`servicesWith`: typed with a context's dependencies), the error handlers
7
8
  * services/ the execution pipeline, dependency binding, the handler chain
8
9
  * entrypoint/ `BoundedContext`, `screensTransport`
9
10
  * infrastructure/ `configureProcess`, `configureLogger`
10
11
  */
11
12
  export { FeatureBus } from "./domain/bus.js";
12
- export { Command, DataTransferObject, DomainEvent, Response, } from "./domain/dto.js";
13
- export { ApplicationService, Feature } from "./domain/services.js";
13
+ export { Command, COMMAND_IDENTITY, commandOf, DataTransferObject, DomainEvent, Response, } from "./domain/dto.js";
14
+ export { ApplicationService, Feature, servicesWith, } from "./domain/services.js";
14
15
  export { BoundedContext, } from "./entrypoint/bounded-context.js";
15
16
  export { screensTransport } from "./entrypoint/screens.js";
16
17
  export { processListeners } from "./infrastructure/listeners.js";
@@ -1,12 +1,13 @@
1
+ import type { DtoKey } from "../domain/dto.js";
1
2
  import type { ExecutionCompleted, ExecutionFailed, ExecutionStarted, Listener } from "../domain/pipeline.js";
2
- import { type ExecutableClass, type Hearing } from "../services/listening.js";
3
+ import { type Hearing } from "../services/listening.js";
3
4
  /**
4
5
  * Who hears every bounded context of this process — the backend's process listeners: an
5
6
  * activity indicator, a toast, an audit that must not be wired into each context.
6
7
  *
7
8
  * const stop = processListeners.onFailure((failed) => toast(failed.execution?.useCase));
8
9
  *
9
- * Context: a bounded context's own listeners (`project.onStart`) hear it alone; these hear all of
10
+ * Context: a bounded context's own listeners (`projectBoundedContext.onStart`) hear it alone; these hear all of
10
11
  * them, after its own. They live as long as the process — `configureProcess` does not clear
11
12
  * them —, so whoever adds one keeps the function that stops it.
12
13
  */
@@ -19,10 +20,10 @@ declare const hearing: {
19
20
  export declare function processHearing(): typeof hearing;
20
21
  export declare const processListeners: {
21
22
  /** Hears every run of every bounded context begin. Answers how to stop. */
22
- onStart(listener: Listener<ExecutionStarted>, ...dtos: ExecutableClass[]): () => void;
23
+ onStart(listener: Listener<ExecutionStarted>, ...dtos: DtoKey[]): () => void;
23
24
  /** Hears every service that answered, in every bounded context. */
24
- onCompletion(listener: Listener<ExecutionCompleted>, ...dtos: ExecutableClass[]): () => void;
25
+ onCompletion(listener: Listener<ExecutionCompleted>, ...dtos: DtoKey[]): () => void;
25
26
  /** Hears every failure that escapes a call, once, where it failed. */
26
- onFailure(listener: Listener<ExecutionFailed>, ...dtos: ExecutableClass[]): () => void;
27
+ onFailure(listener: Listener<ExecutionFailed>, ...dtos: DtoKey[]): () => void;
27
28
  };
28
29
  export {};