@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
@@ -1,62 +1,306 @@
1
+ import { processContext } from "../../context/infrastructure/process.js";
2
+ import { RESERVED_MEMBERS, } from "../../core/domain/services.js";
3
+ import { processHearing } from "../../core/infrastructure/listeners.js";
4
+ import { identityOf, keyIdentity } from "../../core/services/dto-keys.js";
5
+ import { eventKeysOf, handlerRegistrar, handles, runHandler, } from "../../core/services/event-handlers.js";
6
+ import { announceTo } from "../../core/services/listening.js";
7
+ import { causeOf, commandFrom, envelopeFrom, eventFrom, readMessage, } from "../services/messages.js";
8
+ /** A Command the queue carried that this subscriber was not told to consume. */
9
+ export class CommandNotConsumed extends Error {
10
+ type;
11
+ static failureKind = "permission_denied";
12
+ reason = "COMMAND_NOT_CONSUMED";
13
+ constructor(type) {
14
+ super(`${type} is not consumed from this queue: name it in the subscriber's commands`);
15
+ this.type = type;
16
+ this.name = "CommandNotConsumed";
17
+ }
18
+ }
19
+ function isOptions(value) {
20
+ return (value !== null &&
21
+ typeof value === "object" &&
22
+ Array.isArray(value.boundedContexts));
23
+ }
24
+ function wireNames(keys) {
25
+ if (keys === undefined)
26
+ return undefined;
27
+ const names = new Set();
28
+ for (const key of keys) {
29
+ const wire = keyIdentity(key).wire;
30
+ if (wire === undefined || wire.trim() === "")
31
+ throw new TypeError("A subscriber names an event by its eventName, a Command by its commandName");
32
+ names.add(wire);
33
+ }
34
+ return names;
35
+ }
36
+ /** The consumers of a bus: what it says, or — a bus that says nothing — its one use case. */
37
+ function consumersIn(bus, event) {
38
+ const { context, key } = bus;
39
+ let consumers;
40
+ if (context.consumersOf)
41
+ consumers = context.consumersOf(event);
42
+ else {
43
+ const known = identityOf(event);
44
+ const hears = known?.type !== undefined
45
+ ? context.handlerOf(known.type) !== undefined
46
+ : context.eventTypeOf(known?.wire ?? "") !== undefined;
47
+ consumers = hears
48
+ ? [{ key: context.name, consume: (heard, cause) => context.execute(heard, cause) }]
49
+ : [];
50
+ }
51
+ if (key === context.name)
52
+ return consumers;
53
+ // Another bus of the same name: its consumers are acknowledged under its own key.
54
+ return consumers.map((one) => ({
55
+ key: one.key === context.name ? key : `${key}${one.key.slice(context.name.length)}`,
56
+ consume: one.consume,
57
+ }));
58
+ }
1
59
  /**
2
- * The door of a queue: hands an event to everyone who hears it — the backend's
3
- * `Subscriber(buses)`:
60
+ * The queue's entrypoint — the backend's `Subscriber(*buses)` and `QueueGateway`, composed: it
61
+ * pulls what the queue delivers, rebuilds it and hands it to every consumer subscribed to it —
62
+ * its own event handlers, and the buses added to it, each with its use case and its handlers.
63
+ *
64
+ * // entrypoints/queue/framework.ts — once, like a bounded context's framework.ts
65
+ * export const { EventHandler } = handlersWith<AppSubscriberDependencies>();
66
+ * export const appSubscriber = new Subscriber<AppSubscriberDependencies>("app");
67
+ * appSubscriber.addDependency("invoicingBoundedContext", invoicingBoundedContext); // to call it
68
+ * appSubscriber.addDependency("notifier", deviceNotifier);
69
+ * appSubscriber.addBus(salesBoundedContext); // to deliver to its use cases and handlers
4
70
  *
5
- * const subscriber = new Subscriber(shopBoundedContext, mailBoundedContext, ticketsSubscriptions);
6
- * const queue = syncQueue(subscriber); // or a platform's durable queue
71
+ * // entrypoints/queue/sale_paid.handler.ts — events → handler
72
+ * @appSubscriber.handler([SalePaid])
73
+ * export class NotifySalePaid extends EventHandler<SalePaid> { async handle(event) { … } }
7
74
  *
8
- * Context: who hears an event is a bounded context with a use case of it (a Feature or an
9
- * ApplicationService registered for its class) or `Subscriptions` with an `EventSubscriber` of
10
- * it — the entrypoint that calls use cases. Several hearing one event is several executions, one
11
- * each, in the order named; one that fails does not stop the others: each answer, or failure, is
12
- * said under its name — which a stored queue keeps, so a redelivery never runs again one that
13
- * already heard it. Two of them never share a name.
75
+ * storedQueue({ store, subscriber: appSubscriber });
76
+ *
77
+ * Context: one per queue, never one per handler. Two levels, never mixed: a dependency — a bus
78
+ * to call included — is what its handlers find on `this` (`addDependency`, by name); a bus added
79
+ * (`addBus`, by its own namespace) is one it delivers to. Adding the same bus again changes
80
+ * nothing; another bus of the same name is delivered to as well (`sales#2`). Every consumer is
81
+ * acknowledged apart — `app/NotifySalePaid`, `sales`, `sales/OnSalePaid` —, which a stored queue
82
+ * keeps, so a redelivery runs only who does not have it yet. A Command is a request to one bus,
83
+ * by its identity, and only when it was declared here.
14
84
  */
15
85
  export class Subscriber {
16
- contexts;
17
- constructor(...contexts) {
18
- const names = new Set();
19
- for (const context of contexts) {
20
- if (names.has(context.name)) {
21
- throw new Error(`Two of those who hear events are named ${context.name}: the queue keeps who heard an event by its name`);
86
+ /** Its namespace: its own handlers are said `<name>/<Handler>`. */
87
+ name;
88
+ buses = [];
89
+ dependencyValues = new Map();
90
+ handlers = [];
91
+ instances = new Map();
92
+ events;
93
+ commands;
94
+ constructor(...given) {
95
+ let options;
96
+ let boundedContexts = [];
97
+ if (typeof given[0] === "string") {
98
+ const name = given[0];
99
+ if (name.trim() === "" || name.includes("/")) {
100
+ throw new TypeError("A subscriber needs a nonempty name without '/'");
22
101
  }
23
- names.add(context.name);
102
+ this.name = name;
103
+ options = given[1] ?? {};
104
+ }
105
+ else {
106
+ this.name = "";
107
+ const all = given.length === 1 && isOptions(given[0])
108
+ ? given[0]
109
+ : { boundedContexts: given };
110
+ options = all;
111
+ boundedContexts = all.boundedContexts;
24
112
  }
25
- this.contexts = contexts;
113
+ this.events = wireNames(options.events);
114
+ this.commands = wireNames(options.commands) ?? new Set();
115
+ for (const boundedContext of boundedContexts)
116
+ this.addBus(boundedContext);
117
+ }
118
+ /**
119
+ * What its handlers find on `this` — a bus they call, a notifier, a repository —, by name; a
120
+ * dependency carrying `BIND` (a bounded context, a publisher) is bound to the handler's run.
121
+ */
122
+ addDependency(name, dependency, options) {
123
+ if (RESERVED_MEMBERS.has(name))
124
+ throw new Error(`Reserved dependency name: ${name}`);
125
+ const registered = this.dependencyValues.has(name);
126
+ if (registered && options === undefined) {
127
+ throw new Error(`Dependency already registered: ${name}`);
128
+ }
129
+ if (options && (!registered || this.dependencyValues.get(name) !== options.replaces)) {
130
+ throw new Error(`Replacement does not match the dependency: ${name}`);
131
+ }
132
+ this.dependencyValues.set(name, dependency);
133
+ return this;
134
+ }
135
+ /**
136
+ * A bus it delivers to: the events its use cases and handlers are registered for reach them
137
+ * through this subscriber. By its namespace — no name to write —; the same bus again changes
138
+ * nothing, another of the same name is delivered to as well. It is not a dependency: a
139
+ * handler that calls a bus has it as one (`addDependency`).
140
+ */
141
+ addBus(boundedContext) {
142
+ if (this.buses.some((one) => one.context === boundedContext))
143
+ return this;
144
+ const sameName = this.buses.filter((one) => one.context.name === boundedContext.name);
145
+ const key = sameName.length === 0
146
+ ? boundedContext.name
147
+ : `${boundedContext.name}#${sameName.length + 1}`;
148
+ this.buses.push({ context: boundedContext, key });
149
+ return this;
150
+ }
151
+ handler(events) {
152
+ const keys = eventKeysOf(events);
153
+ return handlerRegistrar((Handler, name) => {
154
+ if (this.name === "") {
155
+ throw new Error("A subscriber with event handlers has a name: new Subscriber(name)");
156
+ }
157
+ if (this.handlers.some((one) => one.Handler === Handler)) {
158
+ throw new Error(`Event handler already registered: ${name} — list all its events once`);
159
+ }
160
+ if (this.handlers.some((one) => one.name === name)) {
161
+ throw new Error(`Event handler name already registered: ${name}`);
162
+ }
163
+ this.handlers.push({ name, Handler, events: keys });
164
+ });
26
165
  }
166
+ /** What an event of that wire name is rebuilt as, or `undefined` when nobody here hears it. */
27
167
  eventTypeOf(name) {
28
- for (const context of this.contexts) {
29
- const found = context.eventTypeOf(name);
168
+ if (this.events !== undefined && !this.events.has(name))
169
+ return undefined;
170
+ for (const registration of this.handlers) {
171
+ for (const key of registration.events) {
172
+ if (keyIdentity(key).wire === name)
173
+ return key;
174
+ }
175
+ }
176
+ for (const bus of this.buses) {
177
+ const found = bus.context.eventTypeOf(name);
178
+ if (found)
179
+ return found;
180
+ }
181
+ return undefined;
182
+ }
183
+ /** What a consumed Command of that identity is rebuilt as, or `undefined` when it is not consumed here. */
184
+ commandTypeOf(identity) {
185
+ if (!this.commands.has(identity))
186
+ return undefined;
187
+ for (const bus of this.buses) {
188
+ const found = bus.context.commandTypeOf(identity);
30
189
  if (found)
31
190
  return found;
32
191
  }
33
192
  return undefined;
34
193
  }
35
194
  /**
36
- * 1. Every bounded context registered for the event's class, in the order named — but those
37
- * `skip` names, which already have it.
38
- * 2. Each executes it — continuing the envelope's flow when there is one —, and its answer or
39
- * failure is kept; a failure does not stop the next.
40
- * Final: what each answered, or failed with.
195
+ * 1. Who consumes the event here: its own handlers, then each bus added, in the order added —
196
+ * the bus's use case, then its handlers —; none when this subscriber does not hear it.
197
+ * 2. Those `skip` names already have it; each other one consumes it — continuing the
198
+ * envelope's flow and trace when there is one —, and its answer or failure is kept: a
199
+ * failure does not stop the next.
200
+ * Final: what each consumer answered, or failed with, under its key.
41
201
  */
42
202
  async handle(event, envelope, skip = []) {
43
- const type = Object.getPrototypeOf(event)?.constructor;
44
203
  const handled = [];
45
- for (const context of this.contexts) {
46
- if (type === undefined || context.handlerOf(type) === undefined)
47
- continue;
48
- if (skip.includes(context.name))
204
+ for (const consumer of this.consumersOf(event)) {
205
+ if (skip.includes(consumer.key))
49
206
  continue;
50
207
  try {
51
208
  handled.push({
52
- boundedContext: context.name,
53
- answer: await context.execute(event, envelope),
209
+ boundedContext: consumer.key,
210
+ answer: await consumer.consume(event, envelope),
54
211
  });
55
212
  }
56
213
  catch (error) {
57
- handled.push({ boundedContext: context.name, error });
214
+ handled.push({ boundedContext: consumer.key, error });
58
215
  }
59
216
  }
60
217
  return handled;
61
218
  }
219
+ /**
220
+ * What a queue delivered — CloudEvents, structured or in a broker's binary mode —, executed:
221
+ *
222
+ * 1. An event this subscriber hears (by its `type`, the event's name): rebuilt as what it is
223
+ * known by here and handed to every consumer subscribed to it (`handle`).
224
+ * 2. A Command (its `type`, its identity): only when declared — `CommandNotConsumed` when a bus
225
+ * registered it but this subscriber does not consume it —, rebuilt and executed by the one
226
+ * bus that registered it.
227
+ * 3. Either continues the message's flow and trace.
228
+ * Final: what each answered, or failed with; nothing when nobody here knows it.
229
+ */
230
+ async receive(arrived, skip = []) {
231
+ const message = readMessage(arrived);
232
+ const eventType = this.eventTypeOf(message.type);
233
+ if (eventType !== undefined)
234
+ return this.handle(eventFrom(eventType, message.data), envelopeFrom(message), skip);
235
+ const commandType = this.commandTypeOf(message.type);
236
+ if (commandType === undefined) {
237
+ if (this.buses.some((one) => one.context.commandTypeOf(message.type) !== undefined))
238
+ throw new CommandNotConsumed(message.type);
239
+ return [];
240
+ }
241
+ const bus = this.buses.find((one) => one.context.commandTypeOf(message.type) !== undefined);
242
+ if (bus === undefined || skip.includes(bus.key))
243
+ return [];
244
+ try {
245
+ const answer = await bus.context.execute(commandFrom(commandType, message.data), {
246
+ cause: causeOf(message),
247
+ });
248
+ return [{ boundedContext: bus.key, answer }];
249
+ }
250
+ catch (error) {
251
+ return [{ boundedContext: bus.key, error }];
252
+ }
253
+ }
254
+ /** Every consumer of `event`, each under a key no other one has. */
255
+ consumersOf(event) {
256
+ const known = identityOf(event);
257
+ if (known?.kind !== "event")
258
+ return [];
259
+ if (this.events !== undefined && !this.events.has(known.wire ?? ""))
260
+ return [];
261
+ const consumers = [];
262
+ for (const registration of this.handlers) {
263
+ if (!registration.events.some((key) => handles(key, known)))
264
+ continue;
265
+ consumers.push(this.consumerOf(registration));
266
+ }
267
+ for (const bus of this.buses)
268
+ consumers.push(...consumersIn(bus, event));
269
+ const keys = new Set();
270
+ for (const consumer of consumers) {
271
+ if (keys.has(consumer.key)) {
272
+ throw new Error(`Two consumers are ${consumer.key}: the queue keeps who has a message by it`);
273
+ }
274
+ keys.add(consumer.key);
275
+ }
276
+ return consumers;
277
+ }
278
+ /** One of its own handlers, as a consumer: its run, with this subscriber's dependencies. */
279
+ consumerOf(registration) {
280
+ const everyContext = processHearing();
281
+ return {
282
+ key: `${this.name}/${registration.name}`,
283
+ consume: (event, cause) => {
284
+ let instance = this.instances.get(registration.Handler);
285
+ if (instance === undefined) {
286
+ instance = new registration.Handler();
287
+ this.instances.set(registration.Handler, instance);
288
+ }
289
+ return runHandler(instance, event, {
290
+ owner: this.name,
291
+ name: registration.name,
292
+ dependencies: this.dependencyValues,
293
+ context: () => ({ ...processContext.values }),
294
+ ...(cause ? { cause } : {}),
295
+ expected: () => false,
296
+ interceptors: [],
297
+ announce: {
298
+ started: (heard) => announceTo(everyContext.started, heard),
299
+ completed: (heard) => announceTo(everyContext.completed, heard),
300
+ },
301
+ failed: (heard) => announceTo(everyContext.failed, heard),
302
+ });
303
+ },
304
+ };
305
+ }
62
306
  }
@@ -1,22 +1,23 @@
1
1
  /**
2
2
  * Event-driven: the ports and the in-memory pieces that let every platform publish domain events
3
- * and subscribe to them the same way — as sincpro_framework's `event_driven`. Delivering them
4
- * durably (SQLite on a phone, IndexedDB in a browser, a broker) is each platform's, behind
5
- * `EventQueue`.
3
+ * and hand what a queue carries to the bus the same way — as sincpro_framework's `event_driven`.
4
+ * Delivering them durably (SQLite on a phone, IndexedDB in a browser, a broker) is each
5
+ * platform's, behind `EventQueue`.
6
6
  *
7
- * domain/ the envelope and the ports: EventQueue, Subscribes, EventStore
7
+ * domain/ the envelope, the messages (an event, a Command) and the ports: EventQueue,
8
+ * Subscribes, EventStore
9
+ * services/ writing and reading messages: a Command by its identity, an event by its name
8
10
  * adapters/ syncQueue (in the call), storedQueue (store, then deliver, retry, set aside),
9
11
  * memoryEventStore
10
- * entrypoint/ Publisher (what a Feature holds), Subscriber (the queue's door: everyone who
11
- * hears), Subscriptions and EventSubscriber (the entrypoint that hears an event and
12
- * calls use cases)
12
+ * entrypoint/ Publisher (what a Feature holds), Subscriber (the queue's only entrypoint)
13
13
  */
14
14
  export { type MemoryEventStore, memoryEventStore, } from "./adapters/memory-event-store.js";
15
15
  export { type StoredQueue, storedQueue, type StoredQueueOptions, } from "./adapters/stored-queue.js";
16
16
  export { syncQueue } from "./adapters/sync-queue.js";
17
17
  export { type Envelope, envelopeOf, } from "./domain/envelope.js";
18
- export type { EventQueue, Handled, Subscribes, } from "./domain/queue.js";
18
+ export type { BinaryMessage, Message, } from "./domain/messages.js";
19
+ export type { CommandType, EventQueue, EventType, Handled, Subscribes, } from "./domain/queue.js";
19
20
  export type { DeliveryFailure, EventStore, StoredEvent, StoredState, } from "./domain/store.js";
20
21
  export { Publisher } from "./entrypoint/publisher.js";
21
- export { type HearingContext, Subscriber, } from "./entrypoint/subscriber.js";
22
- export { EventSubscriber, type Subscribing, type SubscriptionOptions, Subscriptions, } from "./entrypoint/subscriptions.js";
22
+ export { CommandNotConsumed, type HearingContext, type NamedSubscriberOptions, Subscriber, type SubscriberOptions, } from "./entrypoint/subscriber.js";
23
+ export { causeOf, commandFrom, commandMessageOf, envelopeFrom, eventFrom, eventMessageOf, type MessageOptions, readMessage, } from "./services/messages.js";
@@ -1,20 +1,20 @@
1
1
  /**
2
2
  * Event-driven: the ports and the in-memory pieces that let every platform publish domain events
3
- * and subscribe to them the same way — as sincpro_framework's `event_driven`. Delivering them
4
- * durably (SQLite on a phone, IndexedDB in a browser, a broker) is each platform's, behind
5
- * `EventQueue`.
3
+ * and hand what a queue carries to the bus the same way — as sincpro_framework's `event_driven`.
4
+ * Delivering them durably (SQLite on a phone, IndexedDB in a browser, a broker) is each
5
+ * platform's, behind `EventQueue`.
6
6
  *
7
- * domain/ the envelope and the ports: EventQueue, Subscribes, EventStore
7
+ * domain/ the envelope, the messages (an event, a Command) and the ports: EventQueue,
8
+ * Subscribes, EventStore
9
+ * services/ writing and reading messages: a Command by its identity, an event by its name
8
10
  * adapters/ syncQueue (in the call), storedQueue (store, then deliver, retry, set aside),
9
11
  * memoryEventStore
10
- * entrypoint/ Publisher (what a Feature holds), Subscriber (the queue's door: everyone who
11
- * hears), Subscriptions and EventSubscriber (the entrypoint that hears an event and
12
- * calls use cases)
12
+ * entrypoint/ Publisher (what a Feature holds), Subscriber (the queue's only entrypoint)
13
13
  */
14
14
  export { memoryEventStore, } from "./adapters/memory-event-store.js";
15
15
  export { storedQueue, } from "./adapters/stored-queue.js";
16
16
  export { syncQueue } from "./adapters/sync-queue.js";
17
17
  export { envelopeOf, } from "./domain/envelope.js";
18
18
  export { Publisher } from "./entrypoint/publisher.js";
19
- export { Subscriber, } from "./entrypoint/subscriber.js";
20
- export { EventSubscriber, Subscriptions, } from "./entrypoint/subscriptions.js";
19
+ export { CommandNotConsumed, Subscriber, } from "./entrypoint/subscriber.js";
20
+ export { causeOf, commandFrom, commandMessageOf, envelopeFrom, eventFrom, eventMessageOf, readMessage, } from "./services/messages.js";
@@ -0,0 +1,41 @@
1
+ import { type JsonValue } from "../../common/serialization.js";
2
+ import { type AnyCommand, type DomainEvent, type RemoteCommand, type RemoteEvent } from "../../core/domain/dto.js";
3
+ import type { Cause } from "../../core/domain/pipeline.js";
4
+ import type { Envelope } from "../domain/envelope.js";
5
+ import type { BinaryMessage, Message } from "../domain/messages.js";
6
+ import type { CommandType, EventType } from "../domain/queue.js";
7
+ /** The attributes a message carries besides its data: who produced it, about which entity. */
8
+ export type MessageOptions = {
9
+ readonly source?: string;
10
+ readonly subject?: string;
11
+ };
12
+ /**
13
+ * `event` as it travels, with its envelope — its `name` in the data too, as the backend's
14
+ * `as_json`, so a body read alone says which event it is.
15
+ */
16
+ export declare function eventMessageOf(event: DomainEvent | RemoteEvent, envelope: Envelope, options?: MessageOptions): Message;
17
+ /**
18
+ * `command` as it travels — sent by the run `cause` names, or the head of its own flow; its
19
+ * `type` is its identity, which a bounded context gave it when it registered it.
20
+ *
21
+ * commandMessageOf(new CommandIssueInvoice("o-1")) -> { type: "billing.CommandIssueInvoice", … }
22
+ * commandMessageOf(new CommandNobodyRegistered()) -> TypeError: it has no identity
23
+ */
24
+ export declare function commandMessageOf(command: AnyCommand | RemoteCommand, cause?: Cause, options?: MessageOptions): Message;
25
+ /**
26
+ * What arrived, as one message — structured already, or a broker's binary mode: the attributes
27
+ * under any CloudEvents binding's prefix (`ce_`, `ce-`, `cloudEvents:`), the type falling back to
28
+ * the `sincpro-event` header, as the backend's `Envelope.of` reads them.
29
+ */
30
+ export declare function readMessage(arrived: Message | BinaryMessage): Message;
31
+ /** The cause a delivered message continues: its id, its chain and its trace. */
32
+ export declare function causeOf(message: Message): Cause;
33
+ /** A delivered event's envelope, as the queue and the run read it. */
34
+ export declare function envelopeFrom(message: Message): Envelope;
35
+ /**
36
+ * An event's values as what they are here: an instance of its class — `static fromJSON` when it
37
+ * has one —, or the generated event's data, its wire name in it.
38
+ */
39
+ export declare function eventFrom(type: EventType, data: JsonValue): DomainEvent | RemoteEvent;
40
+ /** A Command's values as what they are here: an instance of its class, or the generated Command. */
41
+ export declare function commandFrom(type: CommandType, data: JsonValue): AnyCommand | RemoteCommand;
@@ -0,0 +1,147 @@
1
+ import { newEntityId } from "../../common/ids.js";
2
+ import { readValues, rebuilt, valuesOf, } from "../../common/serialization.js";
3
+ import { commandOf, } from "../../core/domain/dto.js";
4
+ import { identityOf, isCommandDescriptor, isEventDescriptor, } from "../../core/services/dto-keys.js";
5
+ /** The values of a DTO as they travel: what it carries, never how it is routed. */
6
+ function dataOf(dto) {
7
+ return valuesOf(dto);
8
+ }
9
+ /** `values` as an instance of `type`: its `static fromJSON` when it has one, else set on one. */
10
+ function instanceOf(type, values) {
11
+ if (typeof type.fromJSON === "function")
12
+ return rebuilt(values, type);
13
+ return Object.assign(Object.create(type.prototype), values);
14
+ }
15
+ /**
16
+ * `event` as it travels, with its envelope — its `name` in the data too, as the backend's
17
+ * `as_json`, so a body read alone says which event it is.
18
+ */
19
+ export function eventMessageOf(event, envelope, options = {}) {
20
+ return {
21
+ specversion: "1.0",
22
+ id: envelope.id,
23
+ source: options.source ?? "",
24
+ type: envelope.name,
25
+ ...(options.subject ? { subject: options.subject } : {}),
26
+ time: envelope.publishedAt,
27
+ correlationid: envelope.correlationId,
28
+ ...(envelope.causationId ? { causationid: envelope.causationId } : {}),
29
+ ...(envelope.traceparent ? { traceparent: envelope.traceparent } : {}),
30
+ ...(envelope.tracestate ? { tracestate: envelope.tracestate } : {}),
31
+ datacontenttype: "application/json",
32
+ data: { name: envelope.name, ...dataOf(event) },
33
+ };
34
+ }
35
+ /**
36
+ * `command` as it travels — sent by the run `cause` names, or the head of its own flow; its
37
+ * `type` is its identity, which a bounded context gave it when it registered it.
38
+ *
39
+ * commandMessageOf(new CommandIssueInvoice("o-1")) -> { type: "billing.CommandIssueInvoice", … }
40
+ * commandMessageOf(new CommandNobodyRegistered()) -> TypeError: it has no identity
41
+ */
42
+ export function commandMessageOf(command, cause, options = {}) {
43
+ const known = identityOf(command);
44
+ if (known?.kind !== "command" || known.wire === undefined || known.wire.trim() === "") {
45
+ throw new TypeError(`${known?.type?.name ?? "This Command"} has no identity: a bounded context gives it one when it registers it`);
46
+ }
47
+ const id = newEntityId();
48
+ return {
49
+ specversion: "1.0",
50
+ id,
51
+ source: options.source ?? "",
52
+ type: known.wire,
53
+ ...(options.subject ? { subject: options.subject } : {}),
54
+ time: new Date().toISOString(),
55
+ correlationid: cause?.correlationId ?? id,
56
+ ...(cause?.id ? { causationid: cause.id } : {}),
57
+ ...(cause?.traceparent ? { traceparent: cause.traceparent } : {}),
58
+ ...(cause?.tracestate ? { tracestate: cause.tracestate } : {}),
59
+ datacontenttype: "application/json",
60
+ data: dataOf(command),
61
+ };
62
+ }
63
+ const PREFIXES = ["ce_", "ce-", "cloudEvents:", "cloudEvents_"];
64
+ /** A header as text: a broker may hand bytes. */
65
+ function text(value) {
66
+ if (value === null || value === undefined)
67
+ return undefined;
68
+ return typeof value === "string" ? value : new TextDecoder().decode(value);
69
+ }
70
+ /**
71
+ * What arrived, as one message — structured already, or a broker's binary mode: the attributes
72
+ * under any CloudEvents binding's prefix (`ce_`, `ce-`, `cloudEvents:`), the type falling back to
73
+ * the `sincpro-event` header, as the backend's `Envelope.of` reads them.
74
+ */
75
+ export function readMessage(arrived) {
76
+ if (!("headers" in arrived))
77
+ return arrived;
78
+ const headers = arrived.headers;
79
+ const attribute = (name) => {
80
+ for (const prefix of PREFIXES) {
81
+ const found = text(headers[`${prefix}${name}`]);
82
+ if (found)
83
+ return found;
84
+ }
85
+ return undefined;
86
+ };
87
+ const data = typeof arrived.body === "string" ? JSON.parse(arrived.body) : arrived.body;
88
+ const id = attribute("id") ?? newEntityId();
89
+ const type = attribute("type") ??
90
+ text(headers["sincpro-event"]) ??
91
+ String(data?.name ?? "");
92
+ const causationid = attribute("causationid");
93
+ const subject = attribute("subject");
94
+ const traceparent = text(headers["traceparent"]) ?? attribute("traceparent");
95
+ const tracestate = text(headers["tracestate"]) ?? attribute("tracestate");
96
+ return {
97
+ specversion: "1.0",
98
+ id,
99
+ source: attribute("source") ?? "",
100
+ type,
101
+ ...(subject ? { subject } : {}),
102
+ time: attribute("time") ?? new Date().toISOString(),
103
+ correlationid: attribute("correlationid") ?? id,
104
+ ...(causationid ? { causationid } : {}),
105
+ ...(traceparent ? { traceparent } : {}),
106
+ ...(tracestate ? { tracestate } : {}),
107
+ datacontenttype: "application/json",
108
+ data,
109
+ };
110
+ }
111
+ /** The cause a delivered message continues: its id, its chain and its trace. */
112
+ export function causeOf(message) {
113
+ return {
114
+ id: message.id,
115
+ correlationId: message.correlationid,
116
+ ...(message.traceparent ? { traceparent: message.traceparent } : {}),
117
+ ...(message.tracestate ? { tracestate: message.tracestate } : {}),
118
+ };
119
+ }
120
+ /** A delivered event's envelope, as the queue and the run read it. */
121
+ export function envelopeFrom(message) {
122
+ return {
123
+ ...causeOf(message),
124
+ name: message.type,
125
+ causationId: message.causationid ?? null,
126
+ publishedAt: message.time,
127
+ };
128
+ }
129
+ /**
130
+ * An event's values as what they are here: an instance of its class — `static fromJSON` when it
131
+ * has one —, or the generated event's data, its wire name in it.
132
+ */
133
+ export function eventFrom(type, data) {
134
+ const values = readValues(data);
135
+ if (isEventDescriptor(type))
136
+ return { ...values, name: type.name };
137
+ // `name` is the class's (its `eventName`): what the data repeats is not set on the instance.
138
+ const { name: _name, ...fields } = (values ?? {});
139
+ return instanceOf(type, fields);
140
+ }
141
+ /** A Command's values as what they are here: an instance of its class, or the generated Command. */
142
+ export function commandFrom(type, data) {
143
+ const values = readValues(data);
144
+ if (isCommandDescriptor(type))
145
+ return commandOf(type, values);
146
+ return instanceOf(type, values);
147
+ }
@@ -5,18 +5,14 @@ import type { Attributes, Outcome } from "./tracing.js";
5
5
  *
6
6
  * Context: a line says which layer wrote it, the way sincpro_framework's architecture names
7
7
  * them: the application layer (a bounded context and its ApplicationServices and Features,
8
- * through `projectBoundedContext.logger` and `this.logger`), the entrypoints that call it (an
9
- * `EventSubscriber`'s `this.logger`), its adapters (`loggerAdapter`) and the infrastructure
10
- * around them (`logger`). A line written inside a use case carries that
8
+ * through `projectBoundedContext.logger` and `this.logger`), its adapters (`loggerAdapter`) and
9
+ * the infrastructure around them (`logger`). A line written inside a use case carries that
11
10
  * execution's identity; nothing writes a DTO, a response, an error body or the session's
12
11
  * context on its own.
13
12
  */
14
13
  export type LogLevel = "debug" | "info" | "warn" | "error";
15
- /**
16
- * The layer a line comes from: the infrastructure, an adapter, an entrypoint that calls use cases
17
- * (an `EventSubscriber`), a bounded context, an ApplicationService, a Feature.
18
- */
19
- export type LogLayer = "infrastructure" | "adapter" | "entrypoint" | "bounded_context" | "application_service" | "feature";
14
+ /** The layer a line comes from. */
15
+ export type LogLayer = "infrastructure" | "adapter" | "bounded_context" | "event_handler" | "application_service" | "feature";
20
16
  /** Structured logging never implicitly includes a DTO, response, error body or session context. */
21
17
  export type LogRecord = {
22
18
  readonly timestamp: string;
@@ -7,9 +7,9 @@ export declare const logger: LayerLogger;
7
7
  export declare const loggerAdapter: LayerLogger;
8
8
  /** @internal — a bounded context's own logger (`projectBoundedContext.logger`). */
9
9
  export declare function boundedContextLogger(name: string): LayerLogger;
10
- /** A run's layer: an entrypoint's (an `EventSubscriber`), a Feature's or an ApplicationService's. */
11
- type RunLogLayer = Extract<LogLayer, "entrypoint" | "feature" | "application_service">;
12
- /** @internal — what a run (a use case, an entrypoint) finds as `this.logger` while it runs. */
10
+ /** A run's layer: a Feature's, an ApplicationService's or an event handler's. */
11
+ type RunLogLayer = Extract<LogLayer, "feature" | "application_service" | "event_handler">;
12
+ /** @internal — what a Feature or ApplicationService finds as `this.logger` while it runs. */
13
13
  export declare function executionLogger(layer: RunLogLayer, execution: Execution): LayerLogger;
14
14
  /** Each destination keeps its own policy; one failing sink does not hold back the others. */
15
15
  export declare function combineLoggers(...loggers: readonly Logger[]): Logger;
@@ -55,7 +55,7 @@ export const loggerAdapter = layerLogger("adapter", processSink);
55
55
  export function boundedContextLogger(name) {
56
56
  return layerLogger("bounded_context", processSink, { boundedContext: name });
57
57
  }
58
- /** @internal — what a run (a use case, an entrypoint) finds as `this.logger` while it runs. */
58
+ /** @internal — what a Feature or ApplicationService finds as `this.logger` while it runs. */
59
59
  export function executionLogger(layer, execution) {
60
60
  return layerLogger(layer, processSink, correlationOf(execution));
61
61
  }