@arki/event-sourcing 0.1.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 (130) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +124 -0
  3. package/dist/builders/command-handler.d.ts +48 -0
  4. package/dist/builders/command-handler.d.ts.map +1 -0
  5. package/dist/builders/command-handler.js +40 -0
  6. package/dist/builders/command-handler.js.map +1 -0
  7. package/dist/builders/command.d.ts +39 -0
  8. package/dist/builders/command.d.ts.map +1 -0
  9. package/dist/builders/command.js +44 -0
  10. package/dist/builders/command.js.map +1 -0
  11. package/dist/builders/decider.d.ts +188 -0
  12. package/dist/builders/decider.d.ts.map +1 -0
  13. package/dist/builders/decider.js +252 -0
  14. package/dist/builders/decider.js.map +1 -0
  15. package/dist/builders/event.d.ts +39 -0
  16. package/dist/builders/event.d.ts.map +1 -0
  17. package/dist/builders/event.js +42 -0
  18. package/dist/builders/event.js.map +1 -0
  19. package/dist/builders/index.d.ts +40 -0
  20. package/dist/builders/index.d.ts.map +1 -0
  21. package/dist/builders/index.js +40 -0
  22. package/dist/builders/index.js.map +1 -0
  23. package/dist/builders/process-manager.d.ts +94 -0
  24. package/dist/builders/process-manager.d.ts.map +1 -0
  25. package/dist/builders/process-manager.js +131 -0
  26. package/dist/builders/process-manager.js.map +1 -0
  27. package/dist/builders/projection.d.ts +92 -0
  28. package/dist/builders/projection.d.ts.map +1 -0
  29. package/dist/builders/projection.js +129 -0
  30. package/dist/builders/projection.js.map +1 -0
  31. package/dist/builders/stateful-process-manager.d.ts +181 -0
  32. package/dist/builders/stateful-process-manager.d.ts.map +1 -0
  33. package/dist/builders/stateful-process-manager.js +280 -0
  34. package/dist/builders/stateful-process-manager.js.map +1 -0
  35. package/dist/bus.d.ts +3 -0
  36. package/dist/bus.d.ts.map +1 -0
  37. package/dist/bus.js +2 -0
  38. package/dist/bus.js.map +1 -0
  39. package/dist/command-flow.d.ts +87 -0
  40. package/dist/command-flow.d.ts.map +1 -0
  41. package/dist/command-flow.js +233 -0
  42. package/dist/command-flow.js.map +1 -0
  43. package/dist/command.d.ts +38 -0
  44. package/dist/command.d.ts.map +1 -0
  45. package/dist/command.js +2 -0
  46. package/dist/command.js.map +1 -0
  47. package/dist/debug.d.ts +31 -0
  48. package/dist/debug.d.ts.map +1 -0
  49. package/dist/debug.js +31 -0
  50. package/dist/debug.js.map +1 -0
  51. package/dist/decide.d.ts +11 -0
  52. package/dist/decide.d.ts.map +1 -0
  53. package/dist/decide.js +2 -0
  54. package/dist/decide.js.map +1 -0
  55. package/dist/dot.d.ts +90 -0
  56. package/dist/dot.d.ts.map +1 -0
  57. package/dist/dot.js +91 -0
  58. package/dist/dot.js.map +1 -0
  59. package/dist/error.d.ts +2 -0
  60. package/dist/error.d.ts.map +1 -0
  61. package/dist/error.js +2 -0
  62. package/dist/error.js.map +1 -0
  63. package/dist/event-sourcing-features.d.ts +81 -0
  64. package/dist/event-sourcing-features.d.ts.map +1 -0
  65. package/dist/event-sourcing-features.js +139 -0
  66. package/dist/event-sourcing-features.js.map +1 -0
  67. package/dist/event.d.ts +25 -0
  68. package/dist/event.d.ts.map +1 -0
  69. package/dist/event.js +2 -0
  70. package/dist/event.js.map +1 -0
  71. package/dist/index.d.ts +7 -0
  72. package/dist/index.d.ts.map +1 -0
  73. package/dist/index.js +6 -0
  74. package/dist/index.js.map +1 -0
  75. package/dist/package.json +5 -0
  76. package/dist/process-manager.d.ts +113 -0
  77. package/dist/process-manager.d.ts.map +1 -0
  78. package/dist/process-manager.js +155 -0
  79. package/dist/process-manager.js.map +1 -0
  80. package/dist/simple-process-manager.d.ts +37 -0
  81. package/dist/simple-process-manager.d.ts.map +1 -0
  82. package/dist/simple-process-manager.js +55 -0
  83. package/dist/simple-process-manager.js.map +1 -0
  84. package/dist/src/builders/command-handler.d.ts +48 -0
  85. package/dist/src/builders/command-handler.d.ts.map +1 -0
  86. package/dist/src/builders/command.d.ts +39 -0
  87. package/dist/src/builders/command.d.ts.map +1 -0
  88. package/dist/src/builders/decider.d.ts +188 -0
  89. package/dist/src/builders/decider.d.ts.map +1 -0
  90. package/dist/src/builders/event.d.ts +39 -0
  91. package/dist/src/builders/event.d.ts.map +1 -0
  92. package/dist/src/builders/index.d.ts +40 -0
  93. package/dist/src/builders/index.d.ts.map +1 -0
  94. package/dist/src/builders/process-manager.d.ts +94 -0
  95. package/dist/src/builders/process-manager.d.ts.map +1 -0
  96. package/dist/src/builders/projection.d.ts +92 -0
  97. package/dist/src/builders/projection.d.ts.map +1 -0
  98. package/dist/src/builders/stateful-process-manager.d.ts +181 -0
  99. package/dist/src/builders/stateful-process-manager.d.ts.map +1 -0
  100. package/dist/src/bus.d.ts +3 -0
  101. package/dist/src/bus.d.ts.map +1 -0
  102. package/dist/src/command-flow.d.ts +87 -0
  103. package/dist/src/command-flow.d.ts.map +1 -0
  104. package/dist/src/command.d.ts +16 -0
  105. package/dist/src/command.d.ts.map +1 -0
  106. package/dist/src/debug.d.ts +31 -0
  107. package/dist/src/debug.d.ts.map +1 -0
  108. package/dist/src/decide.d.ts +11 -0
  109. package/dist/src/decide.d.ts.map +1 -0
  110. package/dist/src/error.d.ts +2 -0
  111. package/dist/src/error.d.ts.map +1 -0
  112. package/dist/src/event.d.ts +25 -0
  113. package/dist/src/event.d.ts.map +1 -0
  114. package/dist/src/index.d.ts +5 -0
  115. package/dist/src/index.d.ts.map +1 -0
  116. package/dist/src/process-manager.d.ts +113 -0
  117. package/dist/src/process-manager.d.ts.map +1 -0
  118. package/dist/src/store.d.ts +44 -0
  119. package/dist/src/store.d.ts.map +1 -0
  120. package/dist/src/types.d.ts +10 -0
  121. package/dist/src/types.d.ts.map +1 -0
  122. package/dist/store.d.ts +44 -0
  123. package/dist/store.d.ts.map +1 -0
  124. package/dist/store.js +94 -0
  125. package/dist/store.js.map +1 -0
  126. package/dist/types.d.ts +10 -0
  127. package/dist/types.d.ts.map +1 -0
  128. package/dist/types.js +2 -0
  129. package/dist/types.js.map +1 -0
  130. package/package.json +100 -0
@@ -0,0 +1,252 @@
1
+ import { debugBuilder } from '../debug.js';
2
+ import { defineCommandHandler } from './command-handler.js';
3
+ /**
4
+ * Fluent builder for aggregate behaviour (aka "decider") definitions.
5
+ *
6
+ * In many event-sourcing texts this role is called an *aggregate*: an object that owns
7
+ * the authoritative state, knows how to rebuild itself from events (`evolve`), and
8
+ * decides which new events should be recorded when commands arrive (`decide`).
9
+ *
10
+ * We keep the historical Emmett name `Decider` to match upstream types, but the builder
11
+ * intentionally documents the aggregate semantics so domain code can align on that
12
+ * mental model.
13
+ *
14
+ * Capabilities:
15
+ * - Type safety through TypeScript generics
16
+ * - Optional Zod schemas to validate state evolution at runtime
17
+ * - Chainable configuration that terminates with `.handler()`, returning the executed aggregate contract
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * const cartAggregate = defineDecider()
22
+ * .stateSchema(z.object({ items: z.array(z.string()), total: z.number() }))
23
+ * .initialState(() => ({ items: [], total: 0 }))
24
+ * .evolve((state, event) => {
25
+ * if (event.type === 'ItemAdded') {
26
+ * return {
27
+ * items: [...state.items, event.data.item],
28
+ * total: state.total + event.data.price,
29
+ * };
30
+ * }
31
+ * return state;
32
+ * })
33
+ * .decide((command, state) => {
34
+ * if (command.type === 'AddItem') {
35
+ * return [
36
+ * {
37
+ * type: 'ItemAdded',
38
+ * data: { item: command.data.item, price: command.data.price },
39
+ * },
40
+ * ];
41
+ * }
42
+ * return [];
43
+ * })
44
+ * .handler();
45
+ *
46
+ * const initial = cartAggregate.initialState();
47
+ * const events = cartAggregate.decide(addItemCommand, initial);
48
+ * const next = cartAggregate.evolve(initial, events[0]);
49
+ * ```
50
+ */
51
+ class DeciderBuilder {
52
+ _stateSchema;
53
+ _initialStateFn;
54
+ _evolveFn;
55
+ _decideFn;
56
+ /**
57
+ * Creates a deep copy of the builder to ensure immutability
58
+ * @private
59
+ */
60
+ clone() {
61
+ const builder = new DeciderBuilder();
62
+ builder._stateSchema = this._stateSchema;
63
+ builder._initialStateFn = this._initialStateFn;
64
+ builder._evolveFn = this._evolveFn;
65
+ builder._decideFn = this._decideFn;
66
+ return builder;
67
+ }
68
+ /**
69
+ * Sets the state schema for state validation
70
+ * @param schema - Zod schema for validating state
71
+ * @returns A new DeciderBuilder instance with the state schema set
72
+ */
73
+ stateSchema(schema) {
74
+ const builder = new DeciderBuilder();
75
+ builder._stateSchema = schema;
76
+ builder._initialStateFn = this._initialStateFn;
77
+ builder._evolveFn = this._evolveFn;
78
+ builder._decideFn = this._decideFn;
79
+ debugBuilder('[decider] Set state schema');
80
+ return builder;
81
+ }
82
+ /**
83
+ * Sets the initial state function
84
+ * @param fn - Function that returns the initial state for a new aggregate
85
+ * @returns A new DeciderBuilder instance with the initial state function set
86
+ */
87
+ initialState(fn) {
88
+ const builder = this.clone();
89
+ builder._initialStateFn = fn;
90
+ debugBuilder('[decider] Set initial state function');
91
+ return builder;
92
+ }
93
+ /**
94
+ * Sets the evolve function
95
+ *
96
+ * This method is generic and will infer the StreamEvent type from the function parameter,
97
+ * allowing TypeScript to properly infer complex discriminated union types.
98
+ *
99
+ * @template TStreamEvent - The union type of all events (inferred from fn parameter)
100
+ * @param fn - Function that applies an event to state to compute the next state
101
+ * @returns A new DeciderBuilder instance with the evolve function and inferred event types set
102
+ */
103
+ evolve(fn) {
104
+ const builder = new DeciderBuilder();
105
+ builder._stateSchema = this._stateSchema;
106
+ builder._initialStateFn = this._initialStateFn;
107
+ builder._evolveFn = fn;
108
+ builder._decideFn = this._decideFn;
109
+ debugBuilder('[decider] Set evolve function');
110
+ return builder;
111
+ }
112
+ /**
113
+ * Sets the decide function
114
+ *
115
+ * This method is generic and will infer the Command type from the function parameter,
116
+ * allowing TypeScript to properly infer complex discriminated union types.
117
+ *
118
+ * @template TCommand - The union type of all commands (inferred from fn parameter)
119
+ * @param fn - Function that determines which events to emit for a given command and state
120
+ * @returns A new DeciderBuilder instance with the decide function and inferred command types set
121
+ */
122
+ decide(fn) {
123
+ const builder = new DeciderBuilder();
124
+ builder._stateSchema = this._stateSchema;
125
+ builder._initialStateFn = this._initialStateFn;
126
+ builder._evolveFn = this._evolveFn;
127
+ builder._decideFn = fn;
128
+ debugBuilder('[decider] Set decide function');
129
+ return builder;
130
+ }
131
+ /**
132
+ * Terminal method that creates the decider
133
+ *
134
+ * Validates that all required functions are set and returns an object
135
+ * with three validated functions:
136
+ * - initialState: Returns the validated initial state
137
+ * - evolve: Applies an event to state with validation
138
+ * - decide: Determines events to emit with validation
139
+ *
140
+ * @returns An object containing the three core decider functions
141
+ * @throws Error if state schema, initial state function, evolve function, or decide function are not defined
142
+ */
143
+ handler() {
144
+ if (!this._stateSchema || !this._initialStateFn || !this._evolveFn || !this._decideFn) {
145
+ debugBuilder('[decider] ERROR: Missing required properties');
146
+ throw new Error('Decider must have state schema, initial state function, evolve function, and decide function defined');
147
+ }
148
+ const stateSchema = this._stateSchema;
149
+ const initialStateFn = this._initialStateFn;
150
+ const evolveFn = this._evolveFn;
151
+ const decideFn = this._decideFn;
152
+ debugBuilder('[decider] Building decider handler');
153
+ return {
154
+ initialState: () => {
155
+ debugBuilder('[decider] Getting initial state');
156
+ const state = initialStateFn();
157
+ return stateSchema.parse(state);
158
+ },
159
+ evolve: (state, event) => {
160
+ debugBuilder('[decider] Evolving state with event: %s', event.type);
161
+ const validatedState = stateSchema.parse(state);
162
+ const nextState = evolveFn(validatedState, event);
163
+ return stateSchema.parse(nextState);
164
+ },
165
+ decide: (command, state) => {
166
+ debugBuilder('[decider] Deciding events for command: %s', command.type);
167
+ const validatedState = stateSchema.parse(state);
168
+ const events = decideFn(command, validatedState);
169
+ debugBuilder('[decider] Generated %d event(s)', events.length);
170
+ return events;
171
+ },
172
+ };
173
+ }
174
+ /**
175
+ * Terminal method that creates a store-connected command handler.
176
+ *
177
+ * Unlike `.handler()`, this does **not** require a state schema — it creates
178
+ * a handler that can be registered directly with an event store. Internally
179
+ * it delegates to `defineCommandHandler`, which bridges the Emmett type
180
+ * constraint on command metadata.
181
+ *
182
+ * Use this when you need a handler that reads/writes events from a store
183
+ * (the common case for aggregates), rather than the raw decider functions.
184
+ *
185
+ * @returns A store-connected command handler function
186
+ * @throws Error if initial state, evolve, or decide functions are not defined
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ * const handler = defineDecider()
191
+ * .initialState(() => null as BookState)
192
+ * .evolve(evolve)
193
+ * .decide(decide)
194
+ * .commandHandler();
195
+ * ```
196
+ */
197
+ commandHandler() {
198
+ if (!this._initialStateFn || !this._evolveFn || !this._decideFn) {
199
+ debugBuilder('[decider] ERROR: Missing required properties for command handler');
200
+ throw new Error('Decider must have initial state function, evolve function, and decide function defined to create a command handler');
201
+ }
202
+ debugBuilder('[decider] Building store-connected command handler');
203
+ return defineCommandHandler({
204
+ initialState: this._initialStateFn,
205
+ evolve: this._evolveFn,
206
+ decide: this._decideFn,
207
+ });
208
+ }
209
+ }
210
+ /**
211
+ * Factory function to create a new DeciderBuilder
212
+ *
213
+ * **Recommended API**: This builder API supports complex discriminated unions
214
+ * through parameter-based type inference. The `.evolve()` and `.decide()` methods
215
+ * are generic and will automatically infer types from your function parameters.
216
+ *
217
+ * **Use cases:**
218
+ * - ✅ All cases (simple and complex)
219
+ * - ✅ Complex discriminated unions (10+ command/event types)
220
+ * - ✅ Fluent, chainable API preference
221
+ * - ✅ Automatic type inference from function parameters
222
+ *
223
+ * @example
224
+ * ```typescript
225
+ * // Works for both simple and complex union types
226
+ * const decider = defineDecider()
227
+ * .stateSchema(myStateSchema)
228
+ * .initialState(() => ({ ... }))
229
+ * .evolve((state, event) => {
230
+ * // TypeScript infers event type from this function
231
+ * switch (event.type) {
232
+ * case 'EventA': return { ... };
233
+ * case 'EventB': return { ... };
234
+ * // ... handles 10+ event types correctly
235
+ * }
236
+ * })
237
+ * .decide((command, state) => {
238
+ * // TypeScript infers command type from this function
239
+ * switch (command.type) {
240
+ * case 'CommandA': return [{ type: 'EventA', ... }];
241
+ * case 'CommandB': return [{ type: 'EventB', ... }];
242
+ * // ... handles 10+ command types correctly
243
+ * }
244
+ * })
245
+ * .handler();
246
+ * ```
247
+ */
248
+ export function defineDecider() {
249
+ debugBuilder('[decider] Creating new decider builder');
250
+ return new DeciderBuilder();
251
+ }
252
+ //# sourceMappingURL=decider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decider.js","sourceRoot":"","sources":["../../src/builders/decider.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,oBAAoB,EAAG,MAAM,sBAAsB,CAAC;AAc7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,MAAM,cAAc;IACV,YAAY,CAAoB;IAChC,eAAe,CAAe;IAC9B,SAAS,CAA8B;IACvC,SAAS,CAAuC;IAExD;;;OAGG;IACK,KAAK;QACX,MAAM,OAAO,GAAG,IAAI,cAAc,EAA+B,CAAC;QAClE,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY,CAAC;QACzC,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,eAAe,CAAC;QAC/C,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;QACnC,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;QACnC,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;;;OAIG;IACH,WAAW,CAAY,MAA4B;QACjD,MAAM,OAAO,GAAG,IAAI,cAAc,EAAmC,CAAC;QACtE,OAAO,CAAC,YAAY,GAAG,MAAM,CAAC;QAC9B,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,eAAgD,CAAC;QAChF,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,SAAuD,CAAC;QACjF,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,SAAgE,CAAC;QAC1F,YAAY,CAAC,4BAA4B,CAAC,CAAC;QAC3C,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;;;OAIG;IACH,YAAY,CAAC,EAAe;QAC1B,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC;QAC7B,OAAO,CAAC,eAAe,GAAG,EAAE,CAAC;QAC7B,YAAY,CAAC,sCAAsC,CAAC,CAAC;QACrD,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;;;;;;;;OASG;IACH,MAAM,CAAgC,EAA+B;QACnE,MAAM,OAAO,GAAG,IAAI,cAAc,EAAgC,CAAC;QACnE,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY,CAAC;QACzC,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,eAAe,CAAC;QAC/C,OAAO,CAAC,SAAS,GAAG,EAAE,CAAC;QACvB,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,SAA6D,CAAC;QACvF,YAAY,CAAC,+BAA+B,CAAC,CAAC;QAC9C,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;;;;;;;;OASG;IACH,MAAM,CAAW,EAAwC;QACvD,MAAM,OAAO,GAAG,IAAI,cAAc,EAAgC,CAAC;QACnE,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY,CAAC;QACzC,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,eAAe,CAAC;QAC/C,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;QACnC,OAAO,CAAC,SAAS,GAAG,EAAE,CAAC;QACvB,YAAY,CAAC,+BAA+B,CAAC,CAAC;QAC9C,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;;;;;;;;;;OAWG;IACH,OAAO;QAKL,IAAI,CAAC,IAAI,CAAC,YAAY,IAAI,CAAC,IAAI,CAAC,eAAe,IAAI,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACtF,YAAY,CAAC,8CAA8C,CAAC,CAAC;YAC7D,MAAM,IAAI,KAAK,CACb,sGAAsG,CACvG,CAAC;QACJ,CAAC;QAED,MAAM,WAAW,GAAG,IAAI,CAAC,YAAY,CAAC;QACtC,MAAM,cAAc,GAAG,IAAI,CAAC,eAAe,CAAC;QAC5C,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC;QAChC,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC;QAEhC,YAAY,CAAC,oCAAoC,CAAC,CAAC;QAEnD,OAAO;YACL,YAAY,EAAE,GAAG,EAAE;gBACjB,YAAY,CAAC,iCAAiC,CAAC,CAAC;gBAChD,MAAM,KAAK,GAAG,cAAc,EAAE,CAAC;gBAC/B,OAAO,WAAW,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAClC,CAAC;YACD,MAAM,EAAE,CAAC,KAAY,EAAE,KAAkB,EAAE,EAAE;gBAC3C,YAAY,CAAC,yCAAyC,EAAG,KAAe,CAAC,IAAI,CAAC,CAAC;gBAC/E,MAAM,cAAc,GAAG,WAAW,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBAChD,MAAM,SAAS,GAAG,QAAQ,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;gBAClD,OAAO,WAAW,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;YACtC,CAAC;YACD,MAAM,EAAE,CAAC,OAAgB,EAAE,KAAY,EAAE,EAAE;gBACzC,YAAY,CAAC,2CAA2C,EAAG,OAA4B,CAAC,IAAI,CAAC,CAAC;gBAC9F,MAAM,cAAc,GAAG,WAAW,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBAChD,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC;gBACjD,YAAY,CAAC,iCAAiC,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;gBAC/D,OAAO,MAAM,CAAC;YAChB,CAAC;SACF,CAAC;IACJ,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,cAAc;QACZ,IAAI,CAAC,IAAI,CAAC,eAAe,IAAI,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YAChE,YAAY,CAAC,kEAAkE,CAAC,CAAC;YACjF,MAAM,IAAI,KAAK,CACb,oHAAoH,CACrH,CAAC;QACJ,CAAC;QAED,YAAY,CAAC,oDAAoD,CAAC,CAAC;QACnE,OAAO,oBAAoB,CAAC;YAC1B,YAAY,EAAE,IAAI,CAAC,eAAe;YAClC,MAAM,EAAE,IAAI,CAAC,SAAS;YACtB,MAAM,EAAE,IAAI,CAAC,SAAS;SACvB,CAA0F,CAAC;IAC9F,CAAC;CACF;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,MAAM,UAAU,aAAa;IAC3B,YAAY,CAAC,wCAAwC,CAAC,CAAC;IACvD,OAAO,IAAI,cAAc,EAAE,CAAC;AAC9B,CAAC"}
@@ -0,0 +1,39 @@
1
+ import type { z } from '@arki/contracts';
2
+ import type { Event } from '../event.js';
3
+ import type { DefaultRecord } from '../types.js';
4
+ /**
5
+ * Configuration for defining a domain event factory.
6
+ */
7
+ export type EventConfig<TType extends string, TData extends DefaultRecord, TMetadata extends DefaultRecord | undefined = undefined> = {
8
+ /** The event type string (e.g., 'UserCreated') */
9
+ type: TType;
10
+ /** Zod schema for validating event data */
11
+ dataSchema: z.ZodType<TData>;
12
+ /** Optional Zod schema for validating event metadata */
13
+ metadataSchema?: z.ZodType<TMetadata>;
14
+ };
15
+ /**
16
+ * Creates a strongly-typed event factory function.
17
+ *
18
+ * This factory validates data and metadata using Zod schemas before
19
+ * creating events that can be appended to Emmett's event store.
20
+ *
21
+ * @param config - Configuration object containing type, data schema, and optional metadata schema
22
+ * @returns A factory function that validates and creates events
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const userCreatedEvent = defineEvent({
27
+ * type: 'UserCreated',
28
+ * dataSchema: z.object({ userId: z.string().uuid(), name: z.string() }),
29
+ * metadataSchema: z.object({ now: z.date(), correlationId: z.string().uuid() }),
30
+ * });
31
+ *
32
+ * const event = userCreatedEvent(
33
+ * { userId: 'usr_123', name: 'Ada' },
34
+ * { now: new Date(), correlationId: 'corr_456' },
35
+ * );
36
+ * ```
37
+ */
38
+ export declare function defineEvent<TType extends string, TData extends DefaultRecord, TMetadata extends DefaultRecord | undefined = undefined>(config: EventConfig<TType, TData, TMetadata>): (data: TData, metadata?: TMetadata) => Event<TType, TData, TMetadata>;
39
+ //# sourceMappingURL=event.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event.d.ts","sourceRoot":"","sources":["../../src/builders/event.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,iBAAiB,CAAC;AAEzC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD;;GAEG;AACH,MAAM,MAAM,WAAW,CACrB,KAAK,SAAS,MAAM,EACpB,KAAK,SAAS,aAAa,EAC3B,SAAS,SAAS,aAAa,GAAG,SAAS,GAAG,SAAS,IACrD;IACF,kDAAkD;IAClD,IAAI,EAAE,KAAK,CAAC;IACZ,2CAA2C;IAC3C,UAAU,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IAC7B,wDAAwD;IACxD,cAAc,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;CACvC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,WAAW,CACzB,KAAK,SAAS,MAAM,EACpB,KAAK,SAAS,aAAa,EAC3B,SAAS,SAAS,aAAa,GAAG,SAAS,GAAG,SAAS,EACvD,MAAM,EAAE,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,SAAS,KAAK,KAAK,CAAC,KAAK,EAAE,KAAK,EAAE,SAAS,CAAC,CAmBrH"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Creates a strongly-typed event factory function.
3
+ *
4
+ * This factory validates data and metadata using Zod schemas before
5
+ * creating events that can be appended to Emmett's event store.
6
+ *
7
+ * @param config - Configuration object containing type, data schema, and optional metadata schema
8
+ * @returns A factory function that validates and creates events
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const userCreatedEvent = defineEvent({
13
+ * type: 'UserCreated',
14
+ * dataSchema: z.object({ userId: z.string().uuid(), name: z.string() }),
15
+ * metadataSchema: z.object({ now: z.date(), correlationId: z.string().uuid() }),
16
+ * });
17
+ *
18
+ * const event = userCreatedEvent(
19
+ * { userId: 'usr_123', name: 'Ada' },
20
+ * { now: new Date(), correlationId: 'corr_456' },
21
+ * );
22
+ * ```
23
+ */
24
+ export function defineEvent(config) {
25
+ const { type, dataSchema, metadataSchema } = config;
26
+ return (data, metadata) => {
27
+ const validatedData = dataSchema.parse(data);
28
+ const validatedMetadata = metadataSchema ? metadataSchema.parse(metadata) : metadata;
29
+ // Conditionally construct the event object based on whether metadata is provided
30
+ return (validatedMetadata === undefined
31
+ ? {
32
+ type,
33
+ data: validatedData,
34
+ }
35
+ : {
36
+ type,
37
+ data: validatedData,
38
+ metadata: validatedMetadata,
39
+ });
40
+ };
41
+ }
42
+ //# sourceMappingURL=event.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event.js","sourceRoot":"","sources":["../../src/builders/event.ts"],"names":[],"mappings":"AAqBA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,WAAW,CAIzB,MAA4C;IAC5C,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,cAAc,EAAE,GAAG,MAAM,CAAC;IAEpD,OAAO,CAAC,IAAW,EAAE,QAAoB,EAAE,EAAE;QAC3C,MAAM,aAAa,GAAG,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC7C,MAAM,iBAAiB,GAAG,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;QAErF,iFAAiF;QACjF,OAAO,CAAC,iBAAiB,KAAK,SAAS;YACrC,CAAC,CAAC;gBACE,IAAI;gBACJ,IAAI,EAAE,aAAa;aACpB;YACH,CAAC,CAAC;gBACE,IAAI;gBACJ,IAAI,EAAE,aAAa;gBACnB,QAAQ,EAAE,iBAAiB;aAC5B,CAA8C,CAAC;IACtD,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Event Sourcing Builders
3
+ *
4
+ * Fluent API builders for constructing event sourcing components with type safety.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * import { defineEvent, defineDecider, defineProjection } from '@arki/event-sourcing/builders';
9
+ *
10
+ * // Define an event
11
+ * const userCreated = defineEvent()
12
+ * .type('UserCreated')
13
+ * .data(z.object({ userId: z.string(), email: z.string() }))
14
+ * .metadata(z.object({ timestamp: z.string() }))
15
+ * .handler(({ data, metadata }) => ({ type: 'UserCreated', data, metadata }));
16
+ *
17
+ * // Define a decider
18
+ * const userDecider = defineDecider()
19
+ * .stateSchema(userStateSchema)
20
+ * .initialState(() => ({ users: [] }))
21
+ * .evolve((state, event) => { ... })
22
+ * .decide((command, state) => { ... })
23
+ * .handler();
24
+ *
25
+ * // Define a projection
26
+ * const userProjection = defineProjection()
27
+ * .name('user-projection')
28
+ * .eventTypes(['UserCreated', 'UserUpdated'])
29
+ * .contextSchema(z.object({ repo: z.any() }))
30
+ * .handler(async (events, context) => { ... });
31
+ * ```
32
+ */
33
+ export { defineCommand } from './command.js';
34
+ export { defineCommandHandler, type CommandHandler } from './command-handler.js';
35
+ export { defineEvent } from './event.js';
36
+ export { defineDecider } from './decider.js';
37
+ export { defineProjection } from './projection.js';
38
+ export { defineProcessManager } from './process-manager.js';
39
+ export { defineStatefulProcessManager } from './stateful-process-manager.js';
40
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/builders/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,KAAK,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACjF,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,4BAA4B,EAAE,MAAM,+BAA+B,CAAC"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Event Sourcing Builders
3
+ *
4
+ * Fluent API builders for constructing event sourcing components with type safety.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * import { defineEvent, defineDecider, defineProjection } from '@arki/event-sourcing/builders';
9
+ *
10
+ * // Define an event
11
+ * const userCreated = defineEvent()
12
+ * .type('UserCreated')
13
+ * .data(z.object({ userId: z.string(), email: z.string() }))
14
+ * .metadata(z.object({ timestamp: z.string() }))
15
+ * .handler(({ data, metadata }) => ({ type: 'UserCreated', data, metadata }));
16
+ *
17
+ * // Define a decider
18
+ * const userDecider = defineDecider()
19
+ * .stateSchema(userStateSchema)
20
+ * .initialState(() => ({ users: [] }))
21
+ * .evolve((state, event) => { ... })
22
+ * .decide((command, state) => { ... })
23
+ * .handler();
24
+ *
25
+ * // Define a projection
26
+ * const userProjection = defineProjection()
27
+ * .name('user-projection')
28
+ * .eventTypes(['UserCreated', 'UserUpdated'])
29
+ * .contextSchema(z.object({ repo: z.any() }))
30
+ * .handler(async (events, context) => { ... });
31
+ * ```
32
+ */
33
+ export { defineCommand } from './command.js';
34
+ export { defineCommandHandler } from './command-handler.js';
35
+ export { defineEvent } from './event.js';
36
+ export { defineDecider } from './decider.js';
37
+ export { defineProjection } from './projection.js';
38
+ export { defineProcessManager } from './process-manager.js';
39
+ export { defineStatefulProcessManager } from './stateful-process-manager.js';
40
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/builders/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAuB,MAAM,sBAAsB,CAAC;AACjF,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,4BAA4B,EAAE,MAAM,+BAA+B,CAAC"}
@@ -0,0 +1,94 @@
1
+ import type { z } from '@arki/contracts';
2
+ import type { Event } from '../event.js';
3
+ /**
4
+ * Type definition for CanHandle predicate
5
+ * Used to filter events that a process manager can handle
6
+ */
7
+ type CanHandle<EventType extends Event> = EventType['type'][];
8
+ /**
9
+ * Fluent builder for Emmett process managers (sagas).
10
+ *
11
+ * Process managers sit outside an aggregate and react to streams of events in order to
12
+ * coordinate long-running workflows. This builder helps you describe that behaviour with
13
+ * explicit event filters, a validated execution context, and a terminal `.handler(...)`
14
+ * that produces the configuration object Emmett expects.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const orderSaga = defineProcessManager<OrderEvent>()
19
+ * .name('order-fulfillment')
20
+ * .eventTypes(['OrderPlaced', 'PaymentProcessed', 'OrderShipped'])
21
+ * .contextSchema(z.object({ messageBus: z.any(), repo: z.any() }))
22
+ * .handler(async (events, context) => {
23
+ * for (const event of events) {
24
+ * if (event.type === 'OrderPlaced') {
25
+ * await context.messageBus.send({ type: 'ProcessPayment', data: event.data });
26
+ * } else if (event.type === 'PaymentProcessed') {
27
+ * await context.messageBus.send({ type: 'ShipOrder', data: event.data });
28
+ * }
29
+ * }
30
+ * });
31
+ * ```
32
+ */
33
+ declare class ProcessManagerBuilder<EventType extends Event = never, Context = never> {
34
+ private _name?;
35
+ private _eventTypes?;
36
+ private _contextSchema?;
37
+ private _handlerFn?;
38
+ /**
39
+ * Creates a deep copy of the builder to ensure immutability
40
+ * @private
41
+ */
42
+ private clone;
43
+ /**
44
+ * Sets the process manager name
45
+ * @param name - Unique identifier for the process manager
46
+ * @returns A new ProcessManagerBuilder instance with the name set
47
+ */
48
+ name(name: string): ProcessManagerBuilder<EventType, Context>;
49
+ /**
50
+ * Sets the event types this process manager can handle
51
+ * @param types - Array of event type strings
52
+ * @returns A new ProcessManagerBuilder instance with the event types set
53
+ */
54
+ eventTypes(types: EventType['type'][]): ProcessManagerBuilder<EventType, Context>;
55
+ /**
56
+ * Sets the context schema for validation
57
+ * @param schema - Zod schema for validating the context
58
+ * @returns A new ProcessManagerBuilder instance with the context schema set
59
+ */
60
+ contextSchema<TNewContext>(schema: z.ZodType<TNewContext>): ProcessManagerBuilder<EventType, TNewContext>;
61
+ /**
62
+ * Terminal method that creates the process manager
63
+ *
64
+ * Validates that all required properties are set and returns an object
65
+ * with three properties:
66
+ * - processorId: The process manager identifier
67
+ * - canHandle: Array of event types to filter events
68
+ * - eachBatch: Function that validates context and processes event batches
69
+ *
70
+ * @param fn - Function that processes event batches to coordinate workflows
71
+ * @returns An object containing the process manager configuration
72
+ * @throws Error if name, eventTypes, or contextSchema are not defined
73
+ */
74
+ handler(fn: (events: EventType[], context: Context) => Promise<void>): {
75
+ processorId: string;
76
+ canHandle: CanHandle<EventType>;
77
+ eachBatch: (events: EventType[], context: unknown) => Promise<void>;
78
+ };
79
+ }
80
+ /**
81
+ * Factory function to create a new ProcessManagerBuilder
82
+ *
83
+ * @example
84
+ * ```typescript
85
+ * const builder = defineProcessManager<MyEvent>()
86
+ * .name('my-process-manager')
87
+ * .eventTypes(['EventTypeA', 'EventTypeB'])
88
+ * .contextSchema(myContextSchema)
89
+ * .handler(async (events, context) => { ... });
90
+ * ```
91
+ */
92
+ export declare function defineProcessManager<EventType extends Event = never>(): ProcessManagerBuilder<EventType, never>;
93
+ export {};
94
+ //# sourceMappingURL=process-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-manager.d.ts","sourceRoot":"","sources":["../../src/builders/process-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,iBAAiB,CAAC;AAEzC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAGzC;;;GAGG;AACH,KAAK,SAAS,CAAC,SAAS,SAAS,KAAK,IAAI,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC;AAE9D;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,cAAM,qBAAqB,CAAC,SAAS,SAAS,KAAK,GAAG,KAAK,EAAE,OAAO,GAAG,KAAK;IAC1E,OAAO,CAAC,KAAK,CAAC,CAAS;IACvB,OAAO,CAAC,WAAW,CAAC,CAAsB;IAC1C,OAAO,CAAC,cAAc,CAAC,CAAqB;IAC5C,OAAO,CAAC,UAAU,CAAC,CAA2D;IAE9E;;;OAGG;IACH,OAAO,CAAC,KAAK;IASb;;;;OAIG;IACH,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,qBAAqB,CAAC,SAAS,EAAE,OAAO,CAAC;IAO7D;;;;OAIG;IACH,UAAU,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,EAAE,GAAG,qBAAqB,CAAC,SAAS,EAAE,OAAO,CAAC;IAOjF;;;;OAIG;IACH,aAAa,CAAC,WAAW,EAAE,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,WAAW,CAAC,GAAG,qBAAqB,CAAC,SAAS,EAAE,WAAW,CAAC;IAUzG;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,EAAE,EAAE,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG;QACrE,WAAW,EAAE,MAAM,CAAC;QACpB,SAAS,EAAE,SAAS,CAAC,SAAS,CAAC,CAAC;QAChC,SAAS,EAAE,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KACrE;CAwBF;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,SAAS,KAAK,GAAG,KAAK,KAAK,qBAAqB,CAAC,SAAS,EAAE,KAAK,CAAC,CAG/G"}
@@ -0,0 +1,131 @@
1
+ import { debugBuilder } from '../debug.js';
2
+ /**
3
+ * Fluent builder for Emmett process managers (sagas).
4
+ *
5
+ * Process managers sit outside an aggregate and react to streams of events in order to
6
+ * coordinate long-running workflows. This builder helps you describe that behaviour with
7
+ * explicit event filters, a validated execution context, and a terminal `.handler(...)`
8
+ * that produces the configuration object Emmett expects.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const orderSaga = defineProcessManager<OrderEvent>()
13
+ * .name('order-fulfillment')
14
+ * .eventTypes(['OrderPlaced', 'PaymentProcessed', 'OrderShipped'])
15
+ * .contextSchema(z.object({ messageBus: z.any(), repo: z.any() }))
16
+ * .handler(async (events, context) => {
17
+ * for (const event of events) {
18
+ * if (event.type === 'OrderPlaced') {
19
+ * await context.messageBus.send({ type: 'ProcessPayment', data: event.data });
20
+ * } else if (event.type === 'PaymentProcessed') {
21
+ * await context.messageBus.send({ type: 'ShipOrder', data: event.data });
22
+ * }
23
+ * }
24
+ * });
25
+ * ```
26
+ */
27
+ class ProcessManagerBuilder {
28
+ _name;
29
+ _eventTypes;
30
+ _contextSchema;
31
+ _handlerFn;
32
+ /**
33
+ * Creates a deep copy of the builder to ensure immutability
34
+ * @private
35
+ */
36
+ clone() {
37
+ const builder = new ProcessManagerBuilder();
38
+ builder._name = this._name;
39
+ builder._eventTypes = this._eventTypes;
40
+ builder._contextSchema = this._contextSchema;
41
+ builder._handlerFn = this._handlerFn;
42
+ return builder;
43
+ }
44
+ /**
45
+ * Sets the process manager name
46
+ * @param name - Unique identifier for the process manager
47
+ * @returns A new ProcessManagerBuilder instance with the name set
48
+ */
49
+ name(name) {
50
+ const builder = this.clone();
51
+ builder._name = name;
52
+ debugBuilder('[process-manager] Set name: %s', name);
53
+ return builder;
54
+ }
55
+ /**
56
+ * Sets the event types this process manager can handle
57
+ * @param types - Array of event type strings
58
+ * @returns A new ProcessManagerBuilder instance with the event types set
59
+ */
60
+ eventTypes(types) {
61
+ const builder = this.clone();
62
+ builder._eventTypes = types;
63
+ debugBuilder('[process-manager:%s] Set event types: %o', this._name ?? 'unnamed', types);
64
+ return builder;
65
+ }
66
+ /**
67
+ * Sets the context schema for validation
68
+ * @param schema - Zod schema for validating the context
69
+ * @returns A new ProcessManagerBuilder instance with the context schema set
70
+ */
71
+ contextSchema(schema) {
72
+ const builder = new ProcessManagerBuilder();
73
+ builder._name = this._name;
74
+ builder._eventTypes = this._eventTypes;
75
+ builder._contextSchema = schema;
76
+ builder._handlerFn = this._handlerFn;
77
+ debugBuilder('[process-manager:%s] Set context schema', this._name ?? 'unnamed');
78
+ return builder;
79
+ }
80
+ /**
81
+ * Terminal method that creates the process manager
82
+ *
83
+ * Validates that all required properties are set and returns an object
84
+ * with three properties:
85
+ * - processorId: The process manager identifier
86
+ * - canHandle: Array of event types to filter events
87
+ * - eachBatch: Function that validates context and processes event batches
88
+ *
89
+ * @param fn - Function that processes event batches to coordinate workflows
90
+ * @returns An object containing the process manager configuration
91
+ * @throws Error if name, eventTypes, or contextSchema are not defined
92
+ */
93
+ handler(fn) {
94
+ if (!this._name || !this._eventTypes || !this._contextSchema) {
95
+ debugBuilder('[process-manager] ERROR: Missing required properties');
96
+ throw new Error('Process manager must have name, eventTypes, and contextSchema defined');
97
+ }
98
+ const name = this._name;
99
+ const eventTypes = this._eventTypes;
100
+ const contextSchema = this._contextSchema;
101
+ debugBuilder('[process-manager:%s] Building handler for event types: %o', name, eventTypes);
102
+ return {
103
+ processorId: name,
104
+ canHandle: eventTypes,
105
+ eachBatch: async (events, context) => {
106
+ debugBuilder('[process-manager:%s] Validating context', name);
107
+ const validatedContext = contextSchema.parse(context);
108
+ debugBuilder('[process-manager:%s] Processing batch of %d events', name, events.length);
109
+ await fn(events, validatedContext);
110
+ debugBuilder('[process-manager:%s] Batch processed successfully', name);
111
+ },
112
+ };
113
+ }
114
+ }
115
+ /**
116
+ * Factory function to create a new ProcessManagerBuilder
117
+ *
118
+ * @example
119
+ * ```typescript
120
+ * const builder = defineProcessManager<MyEvent>()
121
+ * .name('my-process-manager')
122
+ * .eventTypes(['EventTypeA', 'EventTypeB'])
123
+ * .contextSchema(myContextSchema)
124
+ * .handler(async (events, context) => { ... });
125
+ * ```
126
+ */
127
+ export function defineProcessManager() {
128
+ debugBuilder('[process-manager] Creating new process manager builder');
129
+ return new ProcessManagerBuilder();
130
+ }
131
+ //# sourceMappingURL=process-manager.js.map