@sincpro/client-framework 1.2.0 → 1.4.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 (55) hide show
  1. package/AGENTS.md +57 -27
  2. package/MANIFESTO.md +5 -4
  3. package/README.md +225 -157
  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/consumers.d.ts +19 -0
  10. package/dist/core/domain/consumers.js +1 -0
  11. package/dist/core/domain/dto.d.ts +68 -6
  12. package/dist/core/domain/dto.js +22 -2
  13. package/dist/core/domain/pipeline.d.ts +7 -3
  14. package/dist/core/domain/services.d.ts +97 -14
  15. package/dist/core/domain/services.js +65 -6
  16. package/dist/core/entrypoint/bounded-context.d.ts +86 -35
  17. package/dist/core/entrypoint/bounded-context.js +224 -71
  18. package/dist/core/entrypoint/screens.js +0 -5
  19. package/dist/core/index.d.ts +6 -3
  20. package/dist/core/index.js +4 -3
  21. package/dist/core/infrastructure/listeners.d.ts +5 -4
  22. package/dist/core/infrastructure/listeners.js +1 -1
  23. package/dist/core/services/dto-keys.d.ts +44 -0
  24. package/dist/core/services/dto-keys.js +97 -0
  25. package/dist/core/services/event-handlers.d.ts +57 -0
  26. package/dist/core/services/event-handlers.js +114 -0
  27. package/dist/core/services/execution.d.ts +15 -21
  28. package/dist/core/services/execution.js +38 -32
  29. package/dist/core/services/interceptors.d.ts +2 -2
  30. package/dist/core/services/interceptors.js +5 -5
  31. package/dist/core/services/listening.d.ts +6 -8
  32. package/dist/core/services/listening.js +3 -2
  33. package/dist/event_driven/adapters/stored-queue.d.ts +5 -5
  34. package/dist/event_driven/adapters/stored-queue.js +5 -10
  35. package/dist/event_driven/domain/envelope.d.ts +2 -2
  36. package/dist/event_driven/domain/envelope.js +7 -1
  37. package/dist/event_driven/domain/messages.d.ts +34 -0
  38. package/dist/event_driven/domain/messages.js +1 -0
  39. package/dist/event_driven/domain/queue.d.ts +9 -5
  40. package/dist/event_driven/entrypoint/publisher.d.ts +2 -2
  41. package/dist/event_driven/entrypoint/publisher.js +4 -0
  42. package/dist/event_driven/entrypoint/subscriber.d.ts +122 -29
  43. package/dist/event_driven/entrypoint/subscriber.js +277 -33
  44. package/dist/event_driven/index.d.ts +11 -10
  45. package/dist/event_driven/index.js +9 -9
  46. package/dist/event_driven/services/messages.d.ts +41 -0
  47. package/dist/event_driven/services/messages.js +147 -0
  48. package/dist/observability/domain/logging.d.ts +4 -8
  49. package/dist/observability/services/logging.d.ts +3 -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
  54. package/dist/event_driven/entrypoint/subscriptions.d.ts +0 -110
  55. package/dist/event_driven/entrypoint/subscriptions.js +0 -184
package/README.md CHANGED
@@ -20,206 +20,263 @@ 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 })`.
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`.
126
143
 
127
- ## Domain events
128
-
129
- A fact that already happened — `OrderPaid` — is heard in one of two ways:
130
-
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
189
+
190
+ An event reaches a use case registered for it — the backend's `@accounting.feature(InvoiceIssued)`,
191
+ when the event is that use case's input — or an event handler, the entrypoint that translates it
192
+ into Commands (see the Subscriber below). Several bounded contexts may register it; each consumer
193
+ gets it once.
171
194
 
172
195
  ```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>;
196
+ @accountingBoundedContext.feature(InvoiceIssued)
197
+ class Book extends Feature<InvoiceIssued, void> { … }
198
+
199
+ @billingBoundedContext.feature([CommandIssueInvoice, OrderPaid]) // a screen, or the event
200
+ class IssueInvoice extends Feature<CommandIssueInvoice | OrderPaid, ResponseInvoice> { … }
201
+ ```
202
+
203
+ A use case of an event runs through the same pipeline (span `<context>/<Service>` with
204
+ `sincpro.event`, log lines, error handlers, report). An ApplicationService may take the event and
205
+ compose Features; `execute(event)` answers whatever its use case returns (`unknown`).
206
+
207
+ ### The Subscriber: the queue's entrypoint, composite
177
208
 
178
- async handle(event: OdooLoggedIn) {
179
- await this.ticketsBoundedContext.execute(new CommandStartDay(event.uid)); // an ApplicationService
209
+ One per queue — the backend's `Subscriber(*buses)` and `QueueGateway`, never one per handler.
210
+ It pulls what the queue delivers, rebuilds it (an event by its name, a Command by its identity)
211
+ and hands it to every consumer subscribed to it. An event has three kinds of consumers, all
212
+ registered the same way, with or without a decorator:
213
+
214
+ | Consumer | Registered with | It finds on `this` | Acknowledged as |
215
+ | -------------------------------- | -------------------------------------------- | ------------------------------------------------ | --------------------- |
216
+ | a use case of a bus | `@salesBoundedContext.feature([Cmd, Evt])` | the bus's dependencies | `sales` |
217
+ | an event handler of a bus | `@salesBoundedContext.handler([EvtA, EvtB])` | the bus's dependencies and `this.boundedContext` | `sales/OnSaleChanged` |
218
+ | an event handler of a subscriber | `@appSubscriber.handler([EvtA])` | the subscriber's dependencies | `app/NotifySalePaid` |
219
+
220
+ ```ts
221
+ // entrypoints/queue/framework.ts — once, like a bounded context's framework.ts
222
+ export const { EventHandler } = handlersWith<AppSubscriberDependencies>();
223
+ export const appSubscriber = new Subscriber<AppSubscriberDependencies>("app", {
224
+ commands: [CommandIssueInvoice], // consumed from the queue: only when declared
225
+ });
226
+ appSubscriber.addDependency("invoicingBoundedContext", invoicingBoundedContext); // to call it
227
+ appSubscriber.addDependency("notifier", notifier);
228
+ appSubscriber.addBus(salesBoundedContext); // to deliver to its use cases and handlers
229
+
230
+ // entrypoints/queue/sale_paid.handler.ts — events → handler; it decides nothing
231
+ @appSubscriber.handler([SalePaid, SaleCancelled])
232
+ export class NotifySaleChanged extends EventHandler<SalePaid | SaleCancelled> {
233
+ async handle(event: SalePaid | SaleCancelled) {
234
+ await this.invoicingBoundedContext.execute(new CommandIssueInvoice(event.saleId));
235
+ }
236
+ }
237
+ appSubscriber.handler([InvoiceVoided])(OnInvoiceVoided); // the same, without a decorator
238
+
239
+ // entrypoints/queue/sale_paid.handler.ts of the sales context — a handler of the bus, an entrypoint
240
+ export const { Feature, ApplicationService, EventHandler } =
241
+ servicesWith<SalesDependencies>();
242
+ @salesBoundedContext.handler([SalePaid])
243
+ export class OnSalePaid extends EventHandler<SalePaid> {
244
+ async handle(event: SalePaid) {
245
+ await this.boundedContext.execute(new CommandCloseSale(event.saleId)); // its own bus
180
246
  }
181
247
  }
182
248
 
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);
249
+ const queue = storedQueue({ store, subscriber: appSubscriber });
250
+ await appSubscriber.receive(message); // CloudEvents, structured or { headers, body }
189
251
  ```
190
252
 
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
253
+ - **Two levels, never mixed.** `addDependency("x", value)` is what its handlers find on `this` —
254
+ a bus they call is a dependency like any other —; `addBus(bus)`, with no name to write (the
255
+ bus's own namespace), is a bus it delivers to. The same bus added again changes nothing;
256
+ another bus of the same name is delivered to as well, under its own key (`sales#2`).
257
+ - **An event** reaches every consumer subscribed to it — the subscriber's handlers, then each bus
258
+ in the order added (its use case, then its handlers); one that fails does not stop the others,
259
+ and each is acknowledged under its key — which a stored queue keeps, so a redelivery runs only
260
+ the ones that do not have it yet.
261
+ - **A handler** runs in the pipeline of a use case, in its own layer (`event_handler`): its span
262
+ `<owner>/<Handler>`, `this.logger`, `this.execution.causationId` (the message's id), and what it
263
+ executes is its child. A handler takes N events: its type is their union, and TypeScript checks
264
+ it accepts every event listed.
265
+ - **A Command** is executed by the one bounded context that registered it, continuing the
266
+ message's flow — **only when declared** (`commands`). A bus never hands all its Commands to
267
+ whoever can publish on a queue: an undeclared one fails `CommandNotConsumed`
268
+ (`permission_denied`).
269
+ - `new Subscriber(...boundedContexts)` and `new Subscriber({ boundedContexts, events, commands })`
270
+ still build one that delivers to those buses only.
271
+
272
+ ### Publishing
208
273
 
209
274
  ```ts
210
- import { Publisher, Subscriber, syncQueue } from "@sincpro/client-framework";
211
-
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
275
+ const queue = syncQueue(new Subscriber(mailBoundedContext, stockBoundedContext)); // or storedQueue
219
276
  shopBoundedContext.addDependency("publisher", new Publisher(queue));
220
277
 
278
+ @shopBoundedContext.feature(CommandPay)
221
279
  class Pay extends Feature<CommandPay, string> {
222
- declare readonly publisher: Publisher;
223
280
  async execute(command: CommandPay) {
224
281
  await this.publisher.publish(new OrderPaid(command.order_id)); // its Envelope
225
282
  return command.order_id;
@@ -228,21 +285,19 @@ class Pay extends Feature<CommandPay, string> {
228
285
  ```
229
286
 
230
287
  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.
288
+ envelope carries the run's `correlationId` and names the run as its cause, and every use case
289
+ that hears it continues that flow.
235
290
 
236
291
  What is defined here, and what each platform plugs behind the ports:
237
292
 
238
293
  | Piece | Here | The platform's |
239
294
  | ----------------- | -------------------------------------------------------------- | -------------------------------------- |
240
- | `DomainEvent` | the class, its `eventName`, its execution | — |
241
- | `EventSubscriber` | the entrypoint, its run, `Subscriptions` | — |
295
+ | `DomainEvent` | the class, its `eventName`, its messages | — |
296
+ | `Command` | its identity (given at registration), its messages | — |
242
297
  | `Envelope` | `name`, `id`, `correlationId`, `causationId`, `publishedAt` | storing it beside the event |
243
298
  | `EventQueue` port | `syncQueue` (in the call); `storedQueue` (store, then deliver) | a broker's queue, `BroadcastChannel` |
244
299
  | `EventStore` port | `memoryEventStore()` | mobile: a SQLite table; web: IndexedDB |
245
- | `Subscribes` port | `Subscriber(...hearing)`, `eventTypeOf(name)` | — |
300
+ | `Subscriber` | pull, rebuild, deliver to every consumer; Commands declared | where messages come from (a socket) |
246
301
 
247
302
  ### Stored events: one way to carry them, any store
248
303
 
@@ -280,9 +335,9 @@ memory carry events the same way, with the same rules.
280
335
  Three things a platform keeps in mind:
281
336
 
282
337
  - **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).
338
+ saved it runs it there again. What must not act twice keys what it does by the message's id —
339
+ `this.execution.causationId` in the use case that received it — or by what the event names
340
+ (the entity's own id).
286
341
  - **One drainer per store.** Two tabs over one IndexedDB claim it first (the Web Locks API).
287
342
  - **Values come back as JSON.** An event that carries a `Money`, a `Decimal` or a date declares
288
343
  `static fromJSON` to read them back as such.
@@ -445,7 +500,7 @@ configureProcess({
445
500
  });
446
501
  ```
447
502
 
448
- Every execution opens a span `<bounded context>/<serviceName>`; an ApplicationService's Features
503
+ Every execution opens a span `<bounded context>/<Service>`; an ApplicationService's Features
449
504
  are its children, on the same trace. A dependency that is a `Transport` or a generated client is
450
505
  bound to the run, so each request carries `traceparent` (and `tracestate`) and
451
506
  `sincpro-context` — the backend continues the trace. A tracer, reporter or logger that fails is
@@ -601,8 +656,9 @@ sincpro-client check --root src
601
656
  Each method takes the operation's input and answers its answer, as `domain.ts` types them — a
602
657
  search answers its `Response…` with its records and cursor, as the backend's callers get it, on
603
658
  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
659
+ over the `operations` the application exports — `--operations <module>` —), its `framework.ts`
660
+ (the service bases with every dependency typed, and the instance) and `services/index.ts`. `check`
661
+ enforces the application's layers and bounded-context
606
662
  boundaries.
607
663
 
608
664
  **Domain events, on demand.** A backend leaves its events out of the contract unless it is
@@ -686,7 +742,8 @@ bus runs the use cases, the use cases use the adapters:
686
742
 
687
743
  ```text
688
744
  src/
689
- entrypoints/main.ts(x) configureProcess, the stored queue and its Subscriber
745
+ entrypoints/main.ts(x) configureProcess, the stored queue
746
+ entrypoints/queue/ the Subscriber (framework.ts) and its event handlers
690
747
  domains/
691
748
  common/infrastructure/operations.ts export const operations — the wire every client uses
692
749
  <bounded context>/
@@ -699,21 +756,30 @@ src/
699
756
  <entity of the aggregate>/ payments/: a related entity with use cases of its own
700
757
  register-payment.feature.ts
701
758
  reconcile-payments.app-service.ts
702
- index.ts registerServices: each Command with its service
703
- infrastructure/ dependencies.ts, bounded_context.ts (service bases)
759
+ index.ts imports each service: it registers itself (a decorator)
760
+ infrastructure/
761
+ dependencies.ts <Context>Dependencies and registerDependencies
762
+ framework.ts servicesWith<…>() bases, and <context>BoundedContext
704
763
  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
764
+ queue/ the bus's event handlers: event → Command → bus
765
+ cron/ mobile only — its scheduler: tick → Command → bus
766
+ index.ts <context>BoundedContext, ready to execute
708
767
  ```
709
768
 
710
769
  - **Services by aggregate.** A simple entity is one folder with its Features (a CRUD). When an
711
770
  aggregate holds related entities with use cases of their own — the payments of a sale order —,
712
771
  they get a folder inside it, and its Features and ApplicationServices live there, grouped by
713
772
  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.
773
+ - **Entrypoints translate.** A screen and a cron build a Command and execute it; what a queue
774
+ carries goes through the one `Subscriber` (`entrypoints/main.ts`). A workflow of several use
775
+ cases is an ApplicationService. `sincpro-client check` refuses a service that imports an
776
+ entrypoint.
777
+ - **A cron is a platform's door, and only where the platform has a scheduler.** A phone wakes a
778
+ closed app on a schedule (mobile's `CronWorker`); a browser does not — Periodic Background Sync
779
+ is Chromium-only, for an installed PWA, and the browser decides when. On the web, refreshing
780
+ what a screen shows is the screen's (a query's refetch interval), not a cron, and work on a
781
+ schedule is the backend's (`Crons`). This package has no cron: the day web needs one, its
782
+ registry and a `Scheduler` port come here.
717
783
  - **A bounded context is named for what it is**: `salesBoundedContext`, never `sales` (an
718
784
  entity?) or `ctx` — `context` is already the run's (`this.context`).
719
785
 
@@ -749,9 +815,11 @@ src/
749
815
  entrypoint/ BoundedContext, screensTransport
750
816
  infrastructure/ configureProcess, configureLogger, processListeners
751
817
  event_driven/
752
- domain/ Envelope, the EventQueue, Subscribes and EventStore ports
818
+ domain/ Envelope, the messages (an event's, a Command's), the EventQueue,
819
+ Subscribes and EventStore ports
820
+ services/ writing and reading messages
753
821
  adapters/ syncQueue, storedQueue, memoryEventStore
754
- entrypoint/ Publisher, Subscriber (the queue's door), Subscriptions, EventSubscriber
822
+ entrypoint/ Publisher, Subscriber (the queue's composite entrypoint)
755
823
  codegen/ the generator and its CLI — the only place Node is allowed
756
824
  testing/ memoryTracer, memoryReporter, memoryLogger
757
825
  ```
@@ -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
  }
@@ -1,20 +1,22 @@
1
1
  import type { Metamodel } from "../domain/metamodel.js";
2
2
  /**
3
3
  * A bounded context's skeleton, written ONCE beside what is generated — the files that are the
4
- * application's from then on:
4
+ * application's from then on, laid out as the backend's (`sincpro_mcp_odoo/domains/helpdesk`):
5
5
  *
6
6
  * domains/project/
7
7
  * generated/ `sincpro-client generate` — regenerated, never edited
8
- * infrastructure/dependencies.ts what the services can count on: the generated client
9
- * infrastructure/bounded_context.ts its Feature and ApplicationService, and how it is made
10
- * services/index.ts registers command classes and their services
11
- * index.ts `export const projectBoundedContext` — ready to use
8
+ * infrastructure/dependencies.ts what its services count on, and who supplies it
9
+ * infrastructure/framework.ts its Feature and ApplicationService — every dependency
10
+ * typed on `this` — and `projectBoundedContext`
11
+ * services/index.ts imports each service, which registers itself
12
+ * index.ts `projectBoundedContext`, ready to use
12
13
  *
13
- * Context: the layout sincpro_framework gives a service (`dependencies.py`, `framework.py`,
14
- * `services/`, `__init__.py`), so a bounded context starts the way every other does and nobody
15
- * copies it by hand from another. It is the application's to change: the CLI writes a file only
16
- * when it is not there, and never touches one that is — unlike `generated/`, which is written
17
- * whole every time.
14
+ * Context: `dependencies.py`, `framework.py`, `services/` and `__init__.py` — a bounded context
15
+ * starts the way every other does. The instance lives in `framework.ts`, not `index.ts`: a service
16
+ * imports it to register itself (`@projectBoundedContext.feature(Command)`), and ES modules run
17
+ * their imports first, so `index.ts` importing the services could not also define it. It is the
18
+ * application's to change: the CLI writes a file only when it is not there, and never touches one
19
+ * that is — unlike `generated/`, which is written whole every time.
18
20
  */
19
21
  export type ScaffoldOptions = {
20
22
  /**