@sincpro/client-framework 1.2.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 (51) hide show
  1. package/AGENTS.md +38 -21
  2. package/MANIFESTO.md +4 -4
  3. package/README.md +183 -158
  4. package/dist/client/services/propagation.js +4 -3
  5. package/dist/codegen/services/scaffold.d.ts +12 -10
  6. package/dist/codegen/services/scaffold.js +23 -40
  7. package/dist/core/domain/bus.d.ts +5 -3
  8. package/dist/core/domain/bus.js +8 -1
  9. package/dist/core/domain/dto.d.ts +68 -6
  10. package/dist/core/domain/dto.js +22 -2
  11. package/dist/core/domain/pipeline.d.ts +5 -2
  12. package/dist/core/domain/services.d.ts +39 -13
  13. package/dist/core/domain/services.js +30 -6
  14. package/dist/core/entrypoint/bounded-context.d.ts +54 -35
  15. package/dist/core/entrypoint/bounded-context.js +120 -52
  16. package/dist/core/entrypoint/screens.js +0 -5
  17. package/dist/core/index.d.ts +4 -3
  18. package/dist/core/index.js +4 -3
  19. package/dist/core/infrastructure/listeners.d.ts +5 -4
  20. package/dist/core/infrastructure/listeners.js +1 -1
  21. package/dist/core/services/dto-keys.d.ts +44 -0
  22. package/dist/core/services/dto-keys.js +97 -0
  23. package/dist/core/services/execution.d.ts +10 -21
  24. package/dist/core/services/execution.js +29 -32
  25. package/dist/core/services/interceptors.d.ts +2 -2
  26. package/dist/core/services/interceptors.js +5 -5
  27. package/dist/core/services/listening.d.ts +6 -8
  28. package/dist/core/services/listening.js +3 -2
  29. package/dist/event_driven/adapters/stored-queue.d.ts +5 -5
  30. package/dist/event_driven/adapters/stored-queue.js +5 -10
  31. package/dist/event_driven/domain/envelope.d.ts +2 -2
  32. package/dist/event_driven/domain/envelope.js +7 -1
  33. package/dist/event_driven/domain/messages.d.ts +34 -0
  34. package/dist/event_driven/domain/messages.js +1 -0
  35. package/dist/event_driven/domain/queue.d.ts +9 -5
  36. package/dist/event_driven/entrypoint/publisher.d.ts +2 -2
  37. package/dist/event_driven/entrypoint/publisher.js +4 -0
  38. package/dist/event_driven/entrypoint/subscriber.d.ts +66 -27
  39. package/dist/event_driven/entrypoint/subscriber.js +117 -21
  40. package/dist/event_driven/index.d.ts +11 -10
  41. package/dist/event_driven/index.js +9 -9
  42. package/dist/event_driven/services/messages.d.ts +41 -0
  43. package/dist/event_driven/services/messages.js +147 -0
  44. package/dist/observability/domain/logging.d.ts +4 -8
  45. package/dist/observability/services/logging.d.ts +3 -3
  46. package/dist/observability/services/logging.js +1 -1
  47. package/dist/observability/services/trace-context.d.ts +10 -0
  48. package/dist/observability/services/trace-context.js +29 -0
  49. package/package.json +2 -2
  50. package/dist/event_driven/entrypoint/subscriptions.d.ts +0 -110
  51. package/dist/event_driven/entrypoint/subscriptions.js +0 -184
package/AGENTS.md CHANGED
@@ -33,7 +33,7 @@ module has only the layers it needs, and says what it offers in its own `index.t
33
33
  | `src/client/` | `Transport`, `entity()`, the contract (domain); REST, memory, Parquet; discovery, propagation |
34
34
  | `src/model/` | Model definitions: `defineMeta`, from a JSON Schema, the store of known ones |
35
35
  | `src/core/` | DTOs and events, bus, services, handlers, extension points; pipeline; `BoundedContext`; process |
36
- | `src/event_driven/` | `Envelope`, `EventQueue`/`Subscribes` ports; queues; `Publisher`, `Subscriber`, `Subscriptions` |
36
+ | `src/event_driven/` | `Envelope`, messages, `EventQueue`/`Subscribes` ports; queues; `Publisher`, `Subscriber` |
37
37
  | `src/codegen/` | The generator and its CLI (`sincpro-client generate`) — the only place Node is allowed |
38
38
  | `src/testing/` | The public entry of the in-memory observability adapters |
39
39
  | `tests/` | vitest in Node, one folder per module; `tests/support/` holds fakes and forge's contracts |
@@ -70,27 +70,46 @@ module has only the layers it needs, and says what it offers in its own `index.t
70
70
  - **A service is a singleton of its generation.** What a method writes on `this` lands on the
71
71
  instance, shared by the next call, the call beside it and every `scoped` variant — as in
72
72
  sincpro_framework. What belongs to one request goes in its arguments or its context.
73
- - **A span uses stable service metadata, not constructor.name.** `serviceName = "Cancel"` gives
74
- `project/Cancel`, identity `project.Cancel`. Commands and events route by exact constructor
75
- identity. An event declares `static eventName` (its wire name) for the same reason; `name` is
76
- reserved for it.
73
+ - **A service's name is the framework's, taken at registration.** A standard decorator hands it
74
+ the class's name as the code wrote it (`context.name`, untouched by a minifier); otherwise the
75
+ class's `name` — so a production build keeps class names (`keep_classnames`, `keepNames`).
76
+ `class Cancel` gives `project/Cancel`, identity `project.Cancel`. Nothing on a service declares
77
+ it. Commands and events route by exact constructor identity — a generated one by its identity
78
+ or wire name.
79
+ - **An event's name is declared; a Command's identity is the framework's.** `static eventName` is
80
+ required and dotted (`<context>.<aggregate>.vN.<fact>`); `name` is reserved for it. A Command's
81
+ identity is given when a bounded context registers it — `<context>.<Command>`, the backend's
82
+ `registered_name`, the key a generated contract carries —; `static commandName` fixes another.
77
83
  - **A replacement names what it replaces.** `feature(dto, { replaces: Service })` is refused
78
- unless `Service` is registered now for `dto`; its spans carry `sincpro.replaces`. A service
79
- meant to be subclassed declares `static readonly serviceName: string = "…"`, or the literal
80
- type stops a subclass from renaming itself.
84
+ unless `Service` is registered now for each DTO listed — all of them or none; its spans carry
85
+ `sincpro.replaces`.
86
+ - **A service takes N DTOs; a DTO has one service.** `feature([CommandX, EventY])`, as the
87
+ backend's `DTORegistration`; one instance per service and generation.
88
+ - **Dependencies are the context's.** `servicesWith<Dependencies>()` gives the bases every
89
+ dependency typed — the backend's `class Feature(_Feature, DependencyContextType)` —; a service
90
+ never declares one. A scaffold writes `dependencies.ts` and `framework.ts`; the instance lives in
91
+ `framework.ts` because ES modules run their imports first.
81
92
  - **How events are carried is here; where they are kept is the platform's.** One use case of an
82
- event per bounded context, one `EventSubscriber` per event per `Subscriptions`; a `Subscriber`
83
- executes an event in each. `storedQueue` holds the rules — store first, deliver in order,
93
+ event per bounded context; the queue's one `Subscriber` executes an event in each. `storedQueue` holds the rules — store first, deliver in order,
84
94
  retry what may succeed, set aside what never will, never run one who heard it twice — over an
85
95
  `EventStore` the platform plugs (SQLite, IndexedDB, memory). A store only keeps records; it
86
96
  never decides.
87
- - **A subscriber is an entrypoint, not a use case.** An `EventSubscriber` reads the event and
88
- executes Commands on a bounded context it was given, as a cron does on a tick; what to decide,
89
- and a workflow of several use cases, is a Feature or an ApplicationService it executes. Its run
90
- is layer `entrypoint`: no interceptor wraps it, no listener hears it, no error handler answers
91
- it. An event may instead be the input of a use case (`feature(Event)(Service)`) when the use
92
- case exists because of it. A `Subscriptions` is named apart from every bounded context: the
93
- queue keeps who heard an event by name, and `Subscriber` refuses two of one name.
97
+ - **The Subscriber is the queue's only entrypoint.** It hears a list of events or every event its
98
+ bounded contexts registered, recognizes a message (an event by name, a Command by identity),
99
+ rebuilds and executes it — as the backend's `Subscriber(*buses)` / `QueueGateway`. Nobody
100
+ writes a subscriber per event: registering a use case for the event is the subscription. A
101
+ Command from a queue runs only when declared (`commands`), in the one bus that registered it;
102
+ `CommandNotConsumed` otherwise. Two bounded contexts never share a name.
103
+ - **Messages are the backend's: CloudEvents 1.0.** One shape for Commands and events — `type` is
104
+ the event's name or the Command's identity —; the route differs (N buses, or the one that
105
+ registered it, when declared). `readMessage` reads structured and binary mode (`ce_` headers),
106
+ as `Envelope.of`. A delivered message's `correlationid`, `causationid` and `traceparent` become
107
+ the run's `Cause`: its flow and its trace continue. Written and read only through
108
+ `eventMessageOf`/`commandMessageOf`, `readMessage` and `eventFrom`/`commandFrom`.
109
+ - **A cron is a platform's, and not every platform has one.** Mobile's scheduler wakes a closed
110
+ app (`CronWorker`, its job a Command); a browser runs nothing in a closed tab, so on the web a
111
+ refresh is a screen's and scheduled work is the backend's. No cron piece lives here until web
112
+ needs one — then a registry and a `Scheduler` port.
94
113
  - **A bounded context injected into a run is bound to it** (`BIND`): what it executes is a child
95
114
  of the caller — span, flow, cause, signal, one report — with its own dependencies, context and
96
115
  handlers. A failure keeps the outcome where it first failed, so a caller does not report what
@@ -101,10 +120,8 @@ module has only the layers it needs, and says what it offers in its own `index.t
101
120
  backend's semantics: `COUNTED_KINDS`, half-open with one probe) guards a transport
102
121
  (`guardedTransport`) or an adapter; its `CircuitOpen` declares `unavailable` and a wait, so
103
122
  nothing else needs to know a circuit exists.
104
- - **Delivery is at least once.** A stored event may run twice after a crash. A use case of the
105
- event keys its effect by `this.execution.causationId` (the envelope's id); an `EventSubscriber`
106
- finds the same id in its own run and hands it in the Command it executes — the use case's
107
- `causationId` is the subscriber's run —, or the effect is keyed by the entity the event names.
123
+ - **Delivery is at least once.** A stored message may run twice after a crash. The use case keys
124
+ its effect by `this.execution.causationId` (the message's id) or by the entity the event names.
108
125
  `maxAttempts` sets aside what keeps failing. One process drains a store. `execution` is
109
126
  reserved.
110
127
  - **A failure says its kind, whatever the wire.** `failureOf` reads a declared `failureKind`, the
package/MANIFESTO.md CHANGED
@@ -34,7 +34,7 @@ server-side render, in a script and in a test, unchanged.**
34
34
  `bus_pipeline`: interceptors control a run (look, veto, adjust, answer); listeners hear it
35
35
  start, answer or fail, and never change it; an extension wires a component in one place.
36
36
  3. **Observability, as ports.** `Tracer`, `ErrorReporter` and `Logger` are the contracts: one span per use
37
- case, named `<bounded context>/<serviceName>`; the unexpected reported
37
+ case, named `<bounded context>/<Service>`; the unexpected reported
38
38
  with its trace id; what the server already explained (a validation, a conflict), or what a
39
39
  bounded context declares expected, not reported.
40
40
  The platform plugs the implementation — OpenTelemetry, GlitchTip, a queue on the phone, memory
@@ -73,9 +73,9 @@ server-side render, in a script and in a test, unchanged.**
73
73
  the injected process ports. Remote clients and mapping remain distinct.
74
74
  11. **Event-driven, as ports (`event_driven`).** How every platform publishes domain events and
75
75
  subscribes to them the same way: the envelope that travels beside an event (its flow and
76
- its cause), the `EventQueue` and `Subscribes` ports, a `Publisher` a Feature holds, the
77
- `EventSubscriber` — the entrypoint that hears an event and calls use cases, as a cron does on
78
- a tick — and its `Subscriptions`, a `Subscriber` over everyone who hears, the queue that
76
+ its cause), how a Command and an event are written and read (each its own way), the
77
+ `EventQueue` and `Subscribes` ports, a `Publisher` a Feature holds, the `Subscriber` — the
78
+ queue's only entrypoint: events heard, Commands consumed only when declared —, the queue that
79
79
  delivers in the call, and the stored queue's rules over an `EventStore` the platform plugs.
80
80
  The guidelines, the rules and the contracts are here; where events are kept is the
81
81
  platform's.
package/README.md CHANGED
@@ -20,206 +20,222 @@ platform storage: what a platform must give, it gives through a port.
20
20
 
21
21
  ## A bounded context
22
22
 
23
+ Laid out as a backend's context (`sincpro_mcp_odoo/domains/helpdesk`): what its services count on
24
+ (`dependencies.ts`), its bases and its instance (`framework.ts`), and one file per use case.
25
+
23
26
  ```ts
24
- import {
25
- ApplicationService,
26
- BoundedContext,
27
- Command,
28
- Feature,
29
- Response,
30
- } from "@sincpro/client-framework";
31
-
32
- class ResponseTotal extends Response {
33
- constructor(readonly total: number) {
34
- super();
35
- }
27
+ // domains/sales/infrastructure/dependencies.ts — the backend's DependencyContextType
28
+ export interface SalesDependencies {
29
+ prices: PriceList;
30
+ taxRate: number;
36
31
  }
37
-
38
- class CommandTotal extends Command<ResponseTotal> {
39
- constructor(readonly quantity: number) {
40
- super();
41
- }
32
+ export function registerDependencies(boundedContext: BoundedContext<SalesDependencies>) {
33
+ boundedContext.addDependency("prices", new PriceList());
34
+ boundedContext.addDependency("taxRate", 0.13);
35
+ return boundedContext;
42
36
  }
43
37
 
44
- class CommandQuote extends Command<ResponseTotal> {
45
- constructor(readonly quantity: number) {
38
+ // domains/sales/infrastructure/framework.ts — the bases inherit every dependency, typed
39
+ export const { Feature, ApplicationService } = servicesWith<SalesDependencies>();
40
+ export const salesBoundedContext = registerDependencies(
41
+ new BoundedContext<SalesDependencies>("sales"),
42
+ );
43
+
44
+ // domains/sales/services/quote/total.feature.ts
45
+ export class CommandTotal extends Command<ResponseTotal> {
46
+ constructor(
47
+ readonly sku: string,
48
+ readonly quantity: number,
49
+ ) {
46
50
  super();
47
51
  }
48
52
  }
49
53
 
50
- class Total extends Feature<CommandTotal, ResponseTotal> {
51
- static readonly serviceName = "Total";
52
- declare readonly unitPrice: number; // a dependency, typed
53
-
54
+ @salesBoundedContext.feature(CommandTotal)
55
+ export class Total extends Feature<CommandTotal, ResponseTotal> {
54
56
  execute(command: CommandTotal): ResponseTotal {
55
57
  this.logger.info("Totalling", { quantity: command.quantity });
56
- return new ResponseTotal(command.quantity * this.unitPrice);
58
+ const unit = this.prices.of(command.sku) * (1 + this.taxRate); // declared nowhere else
59
+ return new ResponseTotal(unit * command.quantity);
57
60
  }
58
61
  }
59
62
 
60
- class Quote extends ApplicationService<CommandQuote, ResponseTotal> {
61
- static readonly serviceName = "Quote";
62
-
63
+ // domains/sales/services/quote/quote.app-service.ts
64
+ @salesBoundedContext.appService(CommandQuote)
65
+ export class Quote extends ApplicationService<CommandQuote, ResponseTotal> {
63
66
  execute(command: CommandQuote): Promise<ResponseTotal> {
64
- return this.featureBus.execute(new CommandTotal(command.quantity));
67
+ return this.featureBus.execute(new CommandTotal(command.sku, command.quantity));
65
68
  }
66
69
  }
67
70
 
68
- const salesBoundedContext = new BoundedContext<{ unitPrice: number }>("sales");
69
- salesBoundedContext.addDependency("unitPrice", 10);
70
- salesBoundedContext.feature(CommandTotal)(Total);
71
- salesBoundedContext.appService(CommandQuote)(Quote);
72
-
73
- const answer = await salesBoundedContext.execute(new CommandQuote(3)); // ResponseTotal — total 30
71
+ const answer = await salesBoundedContext.execute(new CommandQuote("a1", 3)); // ResponseTotal
74
72
  ```
75
73
 
76
74
  A Command names, by its type, the Response it answers: `execute` infers it, with no second
77
75
  argument (the backend's `bus(dto, ResponseType)` is accepted too, and checked in TypeScript
78
76
  only). A Response may be a class, a plain object, a page, a primitive or `void`.
79
77
 
80
- - **One Command, one service.** A Command class is registered once, across both layers, and
81
- dispatched by its exact constructor. `serviceName` names the service in spans and logs —
82
- stable, where a minifier renames classes.
83
- - **Dependencies are attributes.** `addDependency` supplies them; a service declares their types
84
- (`declare readonly client: …`), usually once on a base class per bounded context, as
85
- `sincpro-client scaffold` writes it. Declaring registers nothing; reading a missing one fails.
78
+ - **Dependencies are the context's, never a service's.** `servicesWith<SalesDependencies>()` gives
79
+ the bases every dependency typed on `this` — the backend's `class Feature(_Feature,
80
+ DependencyContextType)` —; `addDependency` supplies them, and reading one never supplied fails.
86
81
  A replacement names what it replaces: `addDependency(name, next, { replaces: previous })`.
87
- - **A service is a singleton of its generation.** What belongs to one request goes in the
88
- Command or the context, never on `this`. Use TypeScript `private`, not `#private`: a run sees
89
- the instance through a view of its own.
82
+ - **The framework names a service when it registers it**: its class, as the code wrote it — a
83
+ standard decorator hands the name over before any minifier runs —, else the class's `name`. A
84
+ production build keeps class names (`keep_classnames` in Metro's minifier, `keepNames` in
85
+ esbuild and Vite). Nothing on the class declares it.
86
+ - **One service, N DTOs.** `feature([CommandX, EventY])` registers one service for each, as the
87
+ backend's `DTORegistration`; a DTO still has one service, across both layers, dispatched by
88
+ its exact class — or, generated, by its identity.
89
+ - **A service is a singleton of its generation**, one instance whatever the number of DTOs it
90
+ takes. What belongs to one request goes in the Command or the context, never on `this`. Use
91
+ TypeScript `private`, not `#private`: a run sees the instance through a view of its own.
90
92
  - **Generations.** The first call (or `buildRootBus()`) builds one; what is registered later
91
93
  answers from the next call, and a running call keeps its own. `fresh()` copies the
92
94
  registrations; `scoped({ company_id: 2 })` runs with more context and the same instances.
93
95
  - **Composition.** An ApplicationService runs its context's Features through `this.featureBus`,
94
- as children of its own execution; never another ApplicationService.
95
-
96
- ### Decorators, when the project has them
96
+ as children of its own execution; never another ApplicationService. A bounded context injected
97
+ into another's services (the backend's `common_mcp`) is bound to the run: what it executes is
98
+ a child of it.
97
99
 
98
- ```ts
99
- @salesBoundedContext.feature(CommandTotal)
100
- class Total extends Feature<CommandTotal, ResponseTotal> { … }
101
- ```
100
+ ### Registering: a decorator, or a call
102
101
 
103
- The same functions work as standard decorators and as legacy ones (`experimentalDecorators`);
104
- without a decorator transform, call them: `salesBoundedContext.feature(CommandTotal)(Total)`. No DI library
105
- and no `reflect-metadata`. The tests compile both decorator forms with TypeScript; a bundler's
106
- transform (Vite, Metro/Babel) is each application's to configure and test.
102
+ The same functions work as standard decorators, as legacy ones (`experimentalDecorators`), and
103
+ called: `salesBoundedContext.feature(CommandTotal)(Total)`. No DI library and no
104
+ `reflect-metadata`. The tests compile both decorator forms with TypeScript; a bundler's transform
105
+ (Vite, Metro/Babel) is each application's to configure and test. A service registers itself
106
+ where it is written; `services/index.ts` imports each file, so all are registered before anyone
107
+ executes.
107
108
 
108
109
  ### Replacing a service
109
110
 
110
111
  An application takes the place of a service a module registered, as the backend's `replaces=`:
111
112
 
112
113
  ```ts
114
+ @printingBoundedContext.feature(CommandPrint, { replaces: Print })
113
115
  class PrintOnBixolon extends Print {
114
- static override readonly serviceName = "PrintOnBixolon";
115
116
  override execute(command: CommandPrint) { … }
116
117
  }
117
- printingBoundedContext.feature(CommandPrint, { replaces: Print })(PrintOnBixolon);
118
118
  printingBoundedContext.handlerOf(CommandPrint); // PrintOnBixolon
119
119
  ```
120
120
 
121
- `replaces` names the service registered now for that class, or the registration is refused. The
122
- next call answers with the new one; its spans say which it replaced (`sincpro.replaces`). A
123
- service meant to be replaced by a subclass widens its name — `static readonly serviceName:
124
- string = "Print"` —, or TypeScript keeps the literal and the subclass cannot rename itself. A
125
- dependency is replaced the same way: `addDependency(name, next, { replaces: previous })`.
126
-
127
- ## Domain events
128
-
129
- A fact that already happened — `OrderPaid` — is heard in one of two ways:
121
+ `replaces` names the service registered now for each DTO listed, or the registration is
122
+ refused — all of them or none. The next call answers with the new one; its spans say which it
123
+ replaced (`sincpro.replaces`). A dependency is replaced the same way.
124
+
125
+ ## Commands and events: two DTOs that travel differently
126
+
127
+ | | A Command | An event |
128
+ | -------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
129
+ | Is | a request to **one** bus | a fact **N** buses hear |
130
+ | Known on the wire by | its identity, `<context>.<Command>` — given by the bounded context that registers it (the backend's `registered_name`) | its wire name, `static eventName = "billing.invoice.v1.issued"` — required, dotted |
131
+ | Travels as | CloudEvents 1.0, `type` = its identity | CloudEvents 1.0, `type` = its name; `data` repeats `name` |
132
+ | Written / read with | `commandMessageOf(command, cause?)` / `commandFrom(type, data)` | `eventMessageOf(event, envelope)` / `eventFrom(type, data)` |
133
+
134
+ Both travel as the backend writes them on every queue — CloudEvents 1.0: `id`, `source`, `type`,
135
+ `time`, `correlationid`, `causationid`, `traceparent`, and the DTO's JSON as `data` —; what differs
136
+ is the route. `readMessage` reads one structured, or in a broker's binary mode (the attributes as
137
+ `ce_`, `ce-` or `cloudEvents:` headers, the type falling back to `sincpro-event`), as the backend's
138
+ `Envelope.of`. A delivered message continues its flow and its trace: the run's span is a child of
139
+ its `traceparent`. An event's name is declared — the contract other processes read, with its
140
+ version; a Command's identity is the framework's, the one a generated contract's `operations`
141
+ carry (`static commandName` fixes another). A value that is not JSON (`Money`, `Decimal`, a day)
142
+ comes back as such through the class's `static fromJSON`.
130
143
 
131
- | What hears it | When |
132
- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
133
- | **A use case of the event**: a Feature or ApplicationService whose input _is_ the event | the use case exists because of the event, and nothing else calls it |
134
- | **An `EventSubscriber`**: an entrypoint that reads the event and executes Commands on the bus | the event starts use cases that have their own Command — a screen or a cron calls them too |
144
+ ```ts
145
+ class InvoiceIssued extends DomainEvent {
146
+ static readonly eventName = "billing.invoice.v1.issued";
147
+ static fromJSON(values: {
148
+ invoice_id: string;
149
+ total: { amount: string; currency: string };
150
+ }) {
151
+ return new InvoiceIssued(
152
+ values.invoice_id,
153
+ new Money(values.total.amount, values.total.currency),
154
+ );
155
+ }
156
+ constructor(
157
+ readonly invoice_id: string,
158
+ readonly total: Money,
159
+ ) {
160
+ super();
161
+ }
162
+ }
163
+ ```
135
164
 
136
- A subscriber is not a use case — it is a door, as a cron or a screen is: it decides nothing. Work
137
- of several steps is an ApplicationService (the workflow) that the subscriber executes, never
138
- logic in the subscriber.
165
+ `event.name` reads `eventName`; `name` is reserved, and a subclass cannot make it a field.
139
166
 
140
- ### A use case of the event
167
+ ### What the generator writes is recognized on the bus
141
168
 
142
- The event is executed as a Command is: by the Feature or ApplicationService registered for its
143
- class in this bounded context, through the same pipeline (span, log lines, error handlers,
144
- report):
169
+ A contract's Commands and events are generated as types and data, never classes. The bus takes
170
+ their entries — `operations.X` (an identity), `events.X` (a wire name) — as what a service is
171
+ registered for, and executes them as data:
145
172
 
146
173
  ```ts
147
- class OrderPaid extends DomainEvent {
148
- static readonly eventName = "shop.order.v1.paid"; // its wire name, as the backend's `name`
149
- constructor(readonly order_id: string) {
150
- super();
151
- }
152
- }
174
+ import { events, operations } from "../generated/client";
175
+ import type * as remote from "../generated/domain";
153
176
 
154
- class ThankCustomer extends Feature<OrderPaid, void> {
155
- static readonly serviceName = "ThankCustomer";
156
- async execute(event: OrderPaid) { … }
177
+ @projectBoundedContext.feature([events.IssueClosed, operations.CommandArchiveIssue])
178
+ class Archive extends Feature<remote.IssueClosed | RemoteCommand<remote.CommandArchiveIssue>, void> {
179
+ execute(input: remote.IssueClosed | RemoteCommand<remote.CommandArchiveIssue>) { … }
157
180
  }
158
181
 
159
- shopBoundedContext.feature(OrderPaid)(ThankCustomer);
160
- await shopBoundedContext.execute(new OrderPaid("o-1")); // span shop/ThankCustomer, sincpro.event = its name
182
+ await projectBoundedContext.execute(issueClosed); // the event's data: its `name` says which
183
+ await projectBoundedContext.execute(commandOf(operations.CommandArchiveIssue, { issue_id }));
161
184
  ```
162
185
 
163
- - **`eventName` is declared**, as `serviceName` is: a minifier renames classes. `event.name`
164
- reads it; `name` is reserved, and a subclass cannot make it a field.
165
- - **One use case per event in a bounded context.** Another context that hears the event
166
- registers its own; the queue's `Subscriber` executes it in each.
167
- - An ApplicationService can take the event too, and compose Features — of Commands or of events
168
- — through `featureBus`. `execute(event)` answers whatever its use case returns (`unknown`).
186
+ `commandOf` tags the input with the operation's identity — never serialized with its data.
169
187
 
170
- ### An `EventSubscriber`: the entrypoint that hears an event
188
+ ## Domain events
171
189
 
172
- ```ts
173
- // entrypoints/queue/logged-successfully.subscriber.ts — reads the event, executes the Command
174
- export class LoggedSuccessfully extends EventSubscriber<OdooLoggedIn> {
175
- static readonly subscriberName = "LoggedSuccessfully";
176
- declare readonly ticketsBoundedContext: BoundedContext<TicketsDependencies>;
190
+ Registering a use case for an event **is** the subscription — the backend's
191
+ `@accounting.feature(InvoiceIssued)`. Several bounded contexts may register it; each hears it once.
177
192
 
178
- async handle(event: OdooLoggedIn) {
179
- await this.ticketsBoundedContext.execute(new CommandStartDay(event.uid)); // an ApplicationService
180
- }
181
- }
193
+ ```ts
194
+ @accountingBoundedContext.feature(InvoiceIssued)
195
+ class Book extends Feature<InvoiceIssued, void> { … }
182
196
 
183
- // entrypoints/queue/index.ts — who hears what, and what they call
184
- export const ticketsSubscriptions = new Subscriptions<TicketsEntrypoints>(
185
- "tickets-subscriptions",
186
- );
187
- ticketsSubscriptions.addDependency("ticketsBoundedContext", ticketsBoundedContext);
188
- ticketsSubscriptions.subscribe(OdooLoggedIn)(LoggedSuccessfully);
197
+ @billingBoundedContext.feature([CommandIssueInvoice, OrderPaid]) // a screen, or the event
198
+ class IssueInvoice extends Feature<CommandIssueInvoice | OrderPaid, ResponseInvoice> { … }
189
199
  ```
190
200
 
191
- - **Each delivery is a run of its own**, `tickets-subscriptions/LoggedSuccessfully` in the layer
192
- `entrypoint`: its span, its log lines, `this.logger`, `this.execution`. It continues the
193
- envelope's flow, and the use cases it executes are its children.
194
- - **A bounded context it was given is bound to it** (`BIND`), as a transport is: what it executes
195
- runs under the subscriber's span, in the same flow, caused by it, cancelled with it — and still
196
- with its own dependencies, context, interceptors and handlers. A Feature that calls another
197
- bounded context injected into it gets the same.
198
- - **One subscriber per event in a `Subscriptions`**; a second is refused, a replacement names the
199
- one it replaces (`subscribe(Event, { replaces: Old })`). Several reactions to one event are one
200
- ApplicationService, or subscribers of different registries.
201
- - **It is not a use case**: interceptors and listeners see the use cases it calls, not it. A
202
- failure is reported once along the flow, where it happened, with the outcome its bounded
203
- context gave it (`expectErrors` holds).
204
- - **Its name is its identity** in spans, logs and the stored queue's record of who already
205
- heard an event, so it differs from every bounded context's (`<context>-subscriptions`).
206
-
207
- ### Publishing and subscribing
201
+ A use case of an event runs through the same pipeline (span `<context>/<Service>` with
202
+ `sincpro.event`, log lines, error handlers, report). An ApplicationService may take the event and
203
+ compose Features; `execute(event)` answers whatever its use case returns (`unknown`).
204
+
205
+ ### The Subscriber: the queue's only entrypoint
206
+
207
+ One per queue — the backend's `Subscriber(*buses)` and `QueueGateway`. What arrives is
208
+ recognized (an event by its name, a Command by its identity), rebuilt and executed on the bus
209
+ that registered it. Nobody writes a subscriber per event.
208
210
 
209
211
  ```ts
210
- import { Publisher, Subscriber, syncQueue } from "@sincpro/client-framework";
212
+ new Subscriber(accountingBoundedContext, billingBoundedContext); // every event they registered
211
213
 
212
- // the queue's door: every bounded context with a use case of the event, every Subscriptions
213
- const subscriber = new Subscriber(
214
- mailBoundedContext,
215
- stockBoundedContext,
216
- ticketsSubscriptions,
217
- );
218
- const queue = syncQueue(subscriber); // in the call, in memory — or a platform's
214
+ new Subscriber({
215
+ boundedContexts: [accountingBoundedContext, billingBoundedContext],
216
+ events: [InvoiceIssued, events.IssueClosed], // only these
217
+ commands: [CommandIssueInvoice], // consumed from the queue: only when declared
218
+ });
219
+
220
+ await subscriber.receive(message); // CloudEvents, structured or { headers, body }: what each answered
221
+ ```
222
+
223
+ - **An event** is handed to every bounded context that registered it, in the order named; one
224
+ that fails does not stop the others, and each is said under its name — which a stored queue
225
+ keeps, so a redelivery never runs one again. Two bounded contexts never share a name.
226
+ - **A Command** is executed by the one bounded context that registered it, continuing the
227
+ message's flow — **only when declared** (`commands`). A bus never hands all its Commands to
228
+ whoever can publish on a queue: an undeclared one fails `CommandNotConsumed`
229
+ (`permission_denied`).
230
+
231
+ ### Publishing
232
+
233
+ ```ts
234
+ const queue = syncQueue(new Subscriber(mailBoundedContext, stockBoundedContext)); // or storedQueue
219
235
  shopBoundedContext.addDependency("publisher", new Publisher(queue));
220
236
 
237
+ @shopBoundedContext.feature(CommandPay)
221
238
  class Pay extends Feature<CommandPay, string> {
222
- declare readonly publisher: Publisher;
223
239
  async execute(command: CommandPay) {
224
240
  await this.publisher.publish(new OrderPaid(command.order_id)); // its Envelope
225
241
  return command.order_id;
@@ -228,21 +244,19 @@ class Pay extends Feature<CommandPay, string> {
228
244
  ```
229
245
 
230
246
  The `Publisher` is bound to the run that holds it, so the event joins that run's flow: its
231
- envelope carries the run's `correlationId` and names the run as its cause. The `Subscriber`
232
- executes it in `mail`, in `stock` and in `tickets-subscriptions` — `execute(event, envelope)`
233
- —, so their runs continue the same flow; one that fails does not stop the others. Two of them
234
- never share a name.
247
+ envelope carries the run's `correlationId` and names the run as its cause, and every use case
248
+ that hears it continues that flow.
235
249
 
236
250
  What is defined here, and what each platform plugs behind the ports:
237
251
 
238
252
  | Piece | Here | The platform's |
239
253
  | ----------------- | -------------------------------------------------------------- | -------------------------------------- |
240
- | `DomainEvent` | the class, its `eventName`, its execution | — |
241
- | `EventSubscriber` | the entrypoint, its run, `Subscriptions` | — |
254
+ | `DomainEvent` | the class, its `eventName`, its messages | — |
255
+ | `Command` | its identity (given at registration), its messages | — |
242
256
  | `Envelope` | `name`, `id`, `correlationId`, `causationId`, `publishedAt` | storing it beside the event |
243
257
  | `EventQueue` port | `syncQueue` (in the call); `storedQueue` (store, then deliver) | a broker's queue, `BroadcastChannel` |
244
258
  | `EventStore` port | `memoryEventStore()` | mobile: a SQLite table; web: IndexedDB |
245
- | `Subscribes` port | `Subscriber(...hearing)`, `eventTypeOf(name)` | — |
259
+ | `Subscriber` | recognize, rebuild, execute; events heard, Commands declared | where messages come from (a socket) |
246
260
 
247
261
  ### Stored events: one way to carry them, any store
248
262
 
@@ -280,9 +294,9 @@ memory carry events the same way, with the same rules.
280
294
  Three things a platform keeps in mind:
281
295
 
282
296
  - **At least once.** A process that stops after a context executed an event and before the store
283
- saved it runs it there again. What must not act twice keys what it does by the envelope's id —
284
- `this.execution.causationId` in a use case of the event, or in an `EventSubscriber`, which hands
285
- it to the Command it executes — or by what the event names (the entity's own id).
297
+ saved it runs it there again. What must not act twice keys what it does by the message's id —
298
+ `this.execution.causationId` in the use case that received it — or by what the event names
299
+ (the entity's own id).
286
300
  - **One drainer per store.** Two tabs over one IndexedDB claim it first (the Web Locks API).
287
301
  - **Values come back as JSON.** An event that carries a `Money`, a `Decimal` or a date declares
288
302
  `static fromJSON` to read them back as such.
@@ -445,7 +459,7 @@ configureProcess({
445
459
  });
446
460
  ```
447
461
 
448
- Every execution opens a span `<bounded context>/<serviceName>`; an ApplicationService's Features
462
+ Every execution opens a span `<bounded context>/<Service>`; an ApplicationService's Features
449
463
  are its children, on the same trace. A dependency that is a `Transport` or a generated client is
450
464
  bound to the run, so each request carries `traceparent` (and `tracestate`) and
451
465
  `sincpro-context` — the backend continues the trace. A tracer, reporter or logger that fails is
@@ -601,8 +615,9 @@ sincpro-client check --root src
601
615
  Each method takes the operation's input and answers its answer, as `domain.ts` types them — a
602
616
  search answers its `Response…` with its records and cursor, as the backend's callers get it, on
603
617
  every wire. `scaffold` writes, once, the application's own files: its dependencies (the client
604
- over the `operations` the application exports — `--operations <module>` —), its service bases
605
- and `registerServices`. `check` enforces the application's layers and bounded-context
618
+ over the `operations` the application exports — `--operations <module>` —), its `framework.ts`
619
+ (the service bases with every dependency typed, and the instance) and `services/index.ts`. `check`
620
+ enforces the application's layers and bounded-context
606
621
  boundaries.
607
622
 
608
623
  **Domain events, on demand.** A backend leaves its events out of the contract unless it is
@@ -699,21 +714,29 @@ src/
699
714
  <entity of the aggregate>/ payments/: a related entity with use cases of its own
700
715
  register-payment.feature.ts
701
716
  reconcile-payments.app-service.ts
702
- index.ts registerServices: each Command with its service
703
- infrastructure/ dependencies.ts, bounded_context.ts (service bases)
717
+ index.ts imports each service: it registers itself (a decorator)
718
+ infrastructure/
719
+ dependencies.ts <Context>Dependencies and registerDependencies
720
+ framework.ts servicesWith<…>() bases, and <context>BoundedContext
704
721
  entrypoints/ the doors: they translate, they decide nothing
705
- queue/ EventSubscribers: event → Command → bus; index.ts: Subscriptions
706
- cron/ the platform's scheduler: tick → Command → bus
707
- index.ts export const <context>BoundedContext — ready to execute
722
+ cron/ mobile only — its scheduler: tick → Command → bus
723
+ index.ts <context>BoundedContext, ready to execute
708
724
  ```
709
725
 
710
726
  - **Services by aggregate.** A simple entity is one folder with its Features (a CRUD). When an
711
727
  aggregate holds related entities with use cases of their own — the payments of a sale order —,
712
728
  they get a folder inside it, and its Features and ApplicationServices live there, grouped by
713
729
  what they are about.
714
- - **Entrypoints translate.** A subscriber, a cron and a screen build a Command and execute it;
715
- a workflow of several use cases is an ApplicationService they execute. `sincpro-client check`
716
- refuses a service that imports an entrypoint.
730
+ - **Entrypoints translate.** A screen and a cron build a Command and execute it; what a queue
731
+ carries goes through the one `Subscriber` (`entrypoints/main.ts`). A workflow of several use
732
+ cases is an ApplicationService. `sincpro-client check` refuses a service that imports an
733
+ entrypoint.
734
+ - **A cron is a platform's door, and only where the platform has a scheduler.** A phone wakes a
735
+ closed app on a schedule (mobile's `CronWorker`); a browser does not — Periodic Background Sync
736
+ is Chromium-only, for an installed PWA, and the browser decides when. On the web, refreshing
737
+ what a screen shows is the screen's (a query's refetch interval), not a cron, and work on a
738
+ schedule is the backend's (`Crons`). This package has no cron: the day web needs one, its
739
+ registry and a `Scheduler` port come here.
717
740
  - **A bounded context is named for what it is**: `salesBoundedContext`, never `sales` (an
718
741
  entity?) or `ctx` — `context` is already the run's (`this.context`).
719
742
 
@@ -749,9 +772,11 @@ src/
749
772
  entrypoint/ BoundedContext, screensTransport
750
773
  infrastructure/ configureProcess, configureLogger, processListeners
751
774
  event_driven/
752
- domain/ Envelope, the EventQueue, Subscribes and EventStore ports
775
+ domain/ Envelope, the messages (an event's, a Command's), the EventQueue,
776
+ Subscribes and EventStore ports
777
+ services/ writing and reading messages
753
778
  adapters/ syncQueue, storedQueue, memoryEventStore
754
- entrypoint/ Publisher, Subscriber (the queue's door), Subscriptions, EventSubscriber
779
+ entrypoint/ Publisher, Subscriber (the queue's only entrypoint)
755
780
  codegen/ the generator and its CLI — the only place Node is allowed
756
781
  testing/ memoryTracer, memoryReporter, memoryLogger
757
782
  ```
@@ -1,6 +1,7 @@
1
1
  import { plainCodec } from "../../context/adapters/plain-codec.js";
2
2
  import { CONTEXT_HEADER, travels } from "../../context/domain/codec.js";
3
3
  import { BIND } from "../../context/domain/execution.js";
4
+ import { traceparentOf } from "../../observability/services/trace-context.js";
4
5
  /** Whether a value is a `Transport`: what a run binds to itself even without `BIND`. */
5
6
  export function isTransport(value) {
6
7
  if (value === null || typeof value !== "object")
@@ -18,9 +19,9 @@ export function isTransport(value) {
18
19
  export function headersOf(execution) {
19
20
  const headers = {};
20
21
  const { span, context } = execution;
21
- if (span.traceId !== "" && span.spanId !== "") {
22
- headers["traceparent"] =
23
- `00-${span.traceId}-${span.spanId}-${span.sampled ? "01" : "00"}`;
22
+ const traceparent = traceparentOf(span);
23
+ if (traceparent !== undefined) {
24
+ headers["traceparent"] = traceparent;
24
25
  if (span.state)
25
26
  headers["tracestate"] = span.state;
26
27
  }