@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
@@ -1,42 +1,81 @@
1
- import type { DomainEvent, EventClass } from "../../core/domain/dto.js";
2
- import type { Cause } from "../../core/domain/pipeline.js";
1
+ import type { AnyCommand, CommandClass, CommandDescriptor, DomainEvent, DtoKey, EventClass, EventDescriptor, Executable, RemoteEvent } from "../../core/domain/dto.js";
2
+ import type { Cause, ExecuteOptions } from "../../core/domain/pipeline.js";
3
3
  import type { Envelope } from "../domain/envelope.js";
4
- import type { Handled, Subscribes } from "../domain/queue.js";
5
- /**
6
- * What the subscriber needs of whoever hears events — a bounded context (a use case of the event)
7
- * or `Subscriptions` (an `EventSubscriber` of it): its name, whether it hears an event, and
8
- * running it.
9
- */
4
+ import type { BinaryMessage, Message } from "../domain/messages.js";
5
+ import type { CommandType, EventType, Handled, Subscribes } from "../domain/queue.js";
6
+ /** What the subscriber needs of a bounded context: what it registered, and running it. */
10
7
  export type HearingContext = {
11
8
  readonly name: string;
12
- handlerOf(dto: abstract new (...args: never[]) => DomainEvent): unknown;
13
- eventTypeOf(name: string): EventClass<DomainEvent> | undefined;
14
- execute(event: DomainEvent, cause?: Cause): Promise<unknown>;
9
+ handlerOf(dto: DtoKey): unknown;
10
+ eventTypeOf(name: string): EventType | undefined;
11
+ commandTypeOf(identity: string): CommandType | undefined;
12
+ execute(executable: Executable, options?: ExecuteOptions | Cause): Promise<unknown>;
13
+ };
14
+ /** Which bounded contexts it hands messages to, and what it takes from the queue. */
15
+ export type SubscriberOptions = {
16
+ readonly boundedContexts: readonly HearingContext[];
17
+ /** The events it hears; every event the bounded contexts registered when none is named. */
18
+ readonly events?: readonly (EventClass<DomainEvent> | EventDescriptor)[];
19
+ /**
20
+ * The Commands it consumes from the queue — none unless named, as the backend's
21
+ * `@queue.consumes`: a bus never hands all its Commands to whoever can publish on a queue.
22
+ */
23
+ readonly commands?: readonly (CommandClass<AnyCommand> | CommandDescriptor)[];
15
24
  };
25
+ /** A Command the queue carried that this subscriber was not told to consume. */
26
+ export declare class CommandNotConsumed extends Error {
27
+ readonly type: string;
28
+ static readonly failureKind = "permission_denied";
29
+ readonly reason = "COMMAND_NOT_CONSUMED";
30
+ constructor(type: string);
31
+ }
16
32
  /**
17
- * The door of a queue: hands an event to everyone who hears it — the backend's
18
- * `Subscriber(buses)`:
33
+ * The queue's entrypoint — the backend's `Subscriber(*buses)` and `QueueGateway`: what arrives is
34
+ * recognized, rebuilt and executed on the bus that registered it.
19
35
  *
20
- * const subscriber = new Subscriber(shopBoundedContext, mailBoundedContext, ticketsSubscriptions);
21
- * const queue = syncQueue(subscriber); // or a platform's durable queue
36
+ * new Subscriber(billingBoundedContext, accountingBoundedContext) // every event they registered
37
+ * new Subscriber({
38
+ * boundedContexts: [billingBoundedContext],
39
+ * events: [OrderPaid, events.IssueClosed], // only these
40
+ * commands: [CommandIssueInvoice], // consumed: declared
41
+ * })
42
+ * await subscriber.receive(message); // what each one answered
22
43
  *
23
- * Context: who hears an event is a bounded context with a use case of it (a Feature or an
24
- * ApplicationService registered for its class) or `Subscriptions` with an `EventSubscriber` of
25
- * it — the entrypoint that calls use cases. Several hearing one event is several executions, one
26
- * each, in the order named; one that fails does not stop the others: each answer, or failure, is
27
- * said under its name — which a stored queue keeps, so a redelivery never runs again one that
28
- * already heard it. Two of them never share a name.
44
+ * Context: one per queue, never one per event — registering a use case for an event is the
45
+ * subscription. An event is a fact N buses hear, by its wire name; a Command is a request to one
46
+ * bus, by its identity, and only when it was declared here. Several hearing one event is several
47
+ * executions, one each, in the order named; one that fails does not stop the others, and each is
48
+ * said under its bounded context's name — which a stored queue keeps, so a redelivery never runs
49
+ * one again. Two never share a name.
29
50
  */
30
51
  export declare class Subscriber implements Subscribes {
31
52
  private readonly contexts;
32
- constructor(...contexts: HearingContext[]);
33
- eventTypeOf(name: string): EventClass<DomainEvent> | undefined;
53
+ private readonly events;
54
+ private readonly commands;
55
+ constructor(options: SubscriberOptions);
56
+ constructor(...boundedContexts: HearingContext[]);
57
+ /** What an event of that wire name is rebuilt as, or `undefined` when nobody here hears it. */
58
+ eventTypeOf(name: string): EventType | undefined;
59
+ /** What a consumed Command of that identity is rebuilt as, or `undefined` when it is not consumed here. */
60
+ commandTypeOf(identity: string): CommandType | undefined;
34
61
  /**
35
- * 1. Every bounded context registered for the event's class, in the order named — but those
36
- * `skip` names, which already have it.
62
+ * 1. Every bounded context that registered the event — its class exactly, or its wire name for
63
+ * a generated one —, in the order named, but those `skip` names, which already have it.
37
64
  * 2. Each executes it — continuing the envelope's flow when there is one —, and its answer or
38
65
  * failure is kept; a failure does not stop the next.
39
- * Final: what each answered, or failed with.
66
+ * Final: what each answered, or failed with; nothing when this subscriber does not hear it.
67
+ */
68
+ handle(event: DomainEvent | RemoteEvent, envelope?: Envelope, skip?: readonly string[]): Promise<Handled[]>;
69
+ /**
70
+ * What a queue delivered — CloudEvents, structured or in a broker's binary mode —, executed:
71
+ *
72
+ * 1. An event this subscriber hears (by its `type`, the event's name): rebuilt as what it is
73
+ * known by here and handed to every bounded context that registered it (`handle`).
74
+ * 2. A Command (its `type`, its identity): only when declared — `CommandNotConsumed` when a bus
75
+ * registered it but this subscriber does not consume it —, rebuilt and executed by the one
76
+ * bounded context that registered it.
77
+ * 3. Either continues the message's flow and trace.
78
+ * Final: what each answered, or failed with; nothing when nobody here knows it.
40
79
  */
41
- handle(event: DomainEvent, envelope?: Envelope, skip?: readonly string[]): Promise<Handled[]>;
80
+ receive(arrived: Message | BinaryMessage, skip?: readonly string[]): Promise<Handled[]>;
42
81
  }
@@ -1,30 +1,75 @@
1
+ import { identityOf, keyIdentity } from "../../core/services/dto-keys.js";
2
+ import { causeOf, commandFrom, envelopeFrom, eventFrom, readMessage, } from "../services/messages.js";
3
+ /** A Command the queue carried that this subscriber was not told to consume. */
4
+ export class CommandNotConsumed extends Error {
5
+ type;
6
+ static failureKind = "permission_denied";
7
+ reason = "COMMAND_NOT_CONSUMED";
8
+ constructor(type) {
9
+ super(`${type} is not consumed from this queue: name it in the subscriber's commands`);
10
+ this.type = type;
11
+ this.name = "CommandNotConsumed";
12
+ }
13
+ }
14
+ function isOptions(value) {
15
+ return (value !== null &&
16
+ typeof value === "object" &&
17
+ Array.isArray(value.boundedContexts));
18
+ }
19
+ function wireNames(keys) {
20
+ if (keys === undefined)
21
+ return undefined;
22
+ const names = new Set();
23
+ for (const key of keys) {
24
+ const wire = keyIdentity(key).wire;
25
+ if (wire === undefined || wire.trim() === "")
26
+ throw new TypeError("A subscriber names an event by its eventName, a Command by its commandName");
27
+ names.add(wire);
28
+ }
29
+ return names;
30
+ }
1
31
  /**
2
- * The door of a queue: hands an event to everyone who hears it — the backend's
3
- * `Subscriber(buses)`:
32
+ * The queue's entrypoint — the backend's `Subscriber(*buses)` and `QueueGateway`: what arrives is
33
+ * recognized, rebuilt and executed on the bus that registered it.
4
34
  *
5
- * const subscriber = new Subscriber(shopBoundedContext, mailBoundedContext, ticketsSubscriptions);
6
- * const queue = syncQueue(subscriber); // or a platform's durable queue
35
+ * new Subscriber(billingBoundedContext, accountingBoundedContext) // every event they registered
36
+ * new Subscriber({
37
+ * boundedContexts: [billingBoundedContext],
38
+ * events: [OrderPaid, events.IssueClosed], // only these
39
+ * commands: [CommandIssueInvoice], // consumed: declared
40
+ * })
41
+ * await subscriber.receive(message); // what each one answered
7
42
  *
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.
43
+ * Context: one per queue, never one per event — registering a use case for an event is the
44
+ * subscription. An event is a fact N buses hear, by its wire name; a Command is a request to one
45
+ * bus, by its identity, and only when it was declared here. Several hearing one event is several
46
+ * executions, one each, in the order named; one that fails does not stop the others, and each is
47
+ * said under its bounded context's name — which a stored queue keeps, so a redelivery never runs
48
+ * one again. Two never share a name.
14
49
  */
15
50
  export class Subscriber {
16
51
  contexts;
17
- constructor(...contexts) {
52
+ events;
53
+ commands;
54
+ constructor(...given) {
55
+ const options = given.length === 1 && isOptions(given[0])
56
+ ? given[0]
57
+ : { boundedContexts: given };
18
58
  const names = new Set();
19
- for (const context of contexts) {
59
+ for (const context of options.boundedContexts) {
20
60
  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`);
61
+ throw new Error(`Two bounded contexts are named ${context.name}: the queue keeps who heard a message by its name`);
22
62
  }
23
63
  names.add(context.name);
24
64
  }
25
- this.contexts = contexts;
65
+ this.contexts = options.boundedContexts;
66
+ this.events = wireNames(options.events);
67
+ this.commands = wireNames(options.commands) ?? new Set();
26
68
  }
69
+ /** What an event of that wire name is rebuilt as, or `undefined` when nobody here hears it. */
27
70
  eventTypeOf(name) {
71
+ if (this.events !== undefined && !this.events.has(name))
72
+ return undefined;
28
73
  for (const context of this.contexts) {
29
74
  const found = context.eventTypeOf(name);
30
75
  if (found)
@@ -32,20 +77,36 @@ export class Subscriber {
32
77
  }
33
78
  return undefined;
34
79
  }
80
+ /** What a consumed Command of that identity is rebuilt as, or `undefined` when it is not consumed here. */
81
+ commandTypeOf(identity) {
82
+ if (!this.commands.has(identity))
83
+ return undefined;
84
+ for (const context of this.contexts) {
85
+ const found = context.commandTypeOf(identity);
86
+ if (found)
87
+ return found;
88
+ }
89
+ return undefined;
90
+ }
35
91
  /**
36
- * 1. Every bounded context registered for the event's class, in the order named — but those
37
- * `skip` names, which already have it.
92
+ * 1. Every bounded context that registered the event — its class exactly, or its wire name for
93
+ * a generated one —, in the order named, but those `skip` names, which already have it.
38
94
  * 2. Each executes it — continuing the envelope's flow when there is one —, and its answer or
39
95
  * failure is kept; a failure does not stop the next.
40
- * Final: what each answered, or failed with.
96
+ * Final: what each answered, or failed with; nothing when this subscriber does not hear it.
41
97
  */
42
98
  async handle(event, envelope, skip = []) {
43
- const type = Object.getPrototypeOf(event)?.constructor;
99
+ const known = identityOf(event);
100
+ if (known?.kind !== "event")
101
+ return [];
102
+ if (this.events !== undefined && !this.events.has(known.wire ?? ""))
103
+ return [];
44
104
  const handled = [];
45
105
  for (const context of this.contexts) {
46
- if (type === undefined || context.handlerOf(type) === undefined)
47
- continue;
48
- if (skip.includes(context.name))
106
+ const hears = known.type !== undefined
107
+ ? context.handlerOf(known.type) !== undefined
108
+ : context.eventTypeOf(known.wire ?? "") !== undefined;
109
+ if (!hears || skip.includes(context.name))
49
110
  continue;
50
111
  try {
51
112
  handled.push({
@@ -59,4 +120,39 @@ export class Subscriber {
59
120
  }
60
121
  return handled;
61
122
  }
123
+ /**
124
+ * What a queue delivered — CloudEvents, structured or in a broker's binary mode —, executed:
125
+ *
126
+ * 1. An event this subscriber hears (by its `type`, the event's name): rebuilt as what it is
127
+ * known by here and handed to every bounded context that registered it (`handle`).
128
+ * 2. A Command (its `type`, its identity): only when declared — `CommandNotConsumed` when a bus
129
+ * registered it but this subscriber does not consume it —, rebuilt and executed by the one
130
+ * bounded context that registered it.
131
+ * 3. Either continues the message's flow and trace.
132
+ * Final: what each answered, or failed with; nothing when nobody here knows it.
133
+ */
134
+ async receive(arrived, skip = []) {
135
+ const message = readMessage(arrived);
136
+ const eventType = this.eventTypeOf(message.type);
137
+ if (eventType !== undefined)
138
+ return this.handle(eventFrom(eventType, message.data), envelopeFrom(message), skip);
139
+ const commandType = this.commandTypeOf(message.type);
140
+ if (commandType === undefined) {
141
+ if (this.contexts.some((one) => one.commandTypeOf(message.type) !== undefined))
142
+ throw new CommandNotConsumed(message.type);
143
+ return [];
144
+ }
145
+ const context = this.contexts.find((one) => one.commandTypeOf(message.type) !== undefined);
146
+ if (context === undefined || skip.includes(context.name))
147
+ return [];
148
+ try {
149
+ const answer = await context.execute(commandFrom(commandType, message.data), {
150
+ cause: causeOf(message),
151
+ });
152
+ return [{ boundedContext: context.name, answer }];
153
+ }
154
+ catch (error) {
155
+ return [{ boundedContext: context.name, error }];
156
+ }
157
+ }
62
158
  }
@@ -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, 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" | "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 or an ApplicationService's. */
11
+ type RunLogLayer = Extract<LogLayer, "feature" | "application_service">;
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
  }
@@ -0,0 +1,10 @@
1
+ import type { Span } from "../domain/tracing.js";
2
+ /** A span as W3C trace context writes it (`traceparent`), or `undefined` when nothing traces. */
3
+ export declare function traceparentOf(span: Span): string | undefined;
4
+ /**
5
+ * The span another process opened, as its `traceparent` says — what a run continues when a
6
+ * message from it arrives. `undefined` for one that is not W3C's or names the all-zeros trace.
7
+ *
8
+ * remoteSpan("00-4bf9…4736-00f0…02b7-01") -> { traceId: "4bf9…4736", spanId: "00f0…02b7", sampled: true }
9
+ */
10
+ export declare function remoteSpan(traceparent: string, tracestate?: string): Span | undefined;
@@ -0,0 +1,29 @@
1
+ const TRACEPARENT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
2
+ /** A span as W3C trace context writes it (`traceparent`), or `undefined` when nothing traces. */
3
+ export function traceparentOf(span) {
4
+ if (span.traceId === "" || span.spanId === "")
5
+ return undefined;
6
+ return `00-${span.traceId}-${span.spanId}-${span.sampled ? "01" : "00"}`;
7
+ }
8
+ /**
9
+ * The span another process opened, as its `traceparent` says — what a run continues when a
10
+ * message from it arrives. `undefined` for one that is not W3C's or names the all-zeros trace.
11
+ *
12
+ * remoteSpan("00-4bf9…4736-00f0…02b7-01") -> { traceId: "4bf9…4736", spanId: "00f0…02b7", sampled: true }
13
+ */
14
+ export function remoteSpan(traceparent, tracestate) {
15
+ const found = TRACEPARENT.exec(traceparent.trim().toLowerCase());
16
+ if (found === null)
17
+ return undefined;
18
+ const [, traceId = "", spanId = "", flags = "00"] = found;
19
+ if (/^0+$/.test(traceId) || /^0+$/.test(spanId))
20
+ return undefined;
21
+ return {
22
+ traceId,
23
+ spanId,
24
+ sampled: (Number.parseInt(flags, 16) & 1) === 1,
25
+ ...(tracestate ? { state: tracestate } : {}),
26
+ set: () => undefined,
27
+ end: () => undefined,
28
+ };
29
+ }