@arki/event-sourcing 0.1.1 → 0.1.2
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.
- package/package.json +10 -4
- package/src/builders/command-handler.ts +77 -0
- package/src/builders/command.ts +72 -0
- package/src/builders/decider.ts +288 -0
- package/src/builders/event.ts +68 -0
- package/src/builders/index.ts +40 -0
- package/src/builders/process-manager.ts +153 -0
- package/src/builders/projection.ts +151 -0
- package/src/builders/stateful-process-manager.ts +338 -0
- package/src/bus.ts +3 -0
- package/src/command-flow.ts +491 -0
- package/src/command.ts +52 -0
- package/src/debug.ts +36 -0
- package/src/decide.ts +10 -0
- package/src/dot.ts +161 -0
- package/src/error.ts +1 -0
- package/src/event-sourcing-features.ts +215 -0
- package/src/event.ts +46 -0
- package/src/index.ts +10 -0
- package/src/process-manager.ts +335 -0
- package/src/simple-process-manager.ts +70 -0
- package/src/store.ts +367 -0
- package/src/types.ts +9 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arki/event-sourcing",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Event sourcing primitives — event store, message bus, projections, process managers — built on Emmett for ARKI.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -74,20 +74,26 @@
|
|
|
74
74
|
},
|
|
75
75
|
"files": [
|
|
76
76
|
"dist/**",
|
|
77
|
+
"src/**",
|
|
78
|
+
"!src/**/*.test.*",
|
|
79
|
+
"!src/**/*.spec.*",
|
|
80
|
+
"!src/**/tests/**",
|
|
81
|
+
"!src/**/test/**",
|
|
82
|
+
"!src/**/__tests__/**",
|
|
77
83
|
"README.md",
|
|
78
84
|
"LICENSE",
|
|
79
85
|
"package.json"
|
|
80
86
|
],
|
|
81
87
|
"dependencies": {
|
|
82
|
-
"@arki/contracts": "0.0.
|
|
83
|
-
"@arki/log": "0.0.
|
|
88
|
+
"@arki/contracts": "0.0.2",
|
|
89
|
+
"@arki/log": "0.0.2",
|
|
84
90
|
"@event-driven-io/emmett": "^0.41.0",
|
|
85
91
|
"@event-driven-io/emmett-postgresql": "^0.41.0",
|
|
86
92
|
"ansis": "^3.3.2",
|
|
87
93
|
"drizzle-orm": "1.0.0-rc.1"
|
|
88
94
|
},
|
|
89
95
|
"peerDependencies": {
|
|
90
|
-
"@arki/dot": "^0.1.
|
|
96
|
+
"@arki/dot": "^0.1.2"
|
|
91
97
|
},
|
|
92
98
|
"peerDependenciesMeta": {
|
|
93
99
|
"@arki/dot": {
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DeciderCommandHandler
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
} from '@event-driven-io/emmett';
|
|
9
|
+
import type {Command, CommandHandlerResult, Event, EventStore, HandleOptions} from '@event-driven-io/emmett';
|
|
10
|
+
|
|
11
|
+
import { debugBuilder } from '../debug.js';
|
|
12
|
+
|
|
13
|
+
type DeciderConfig<State, CommandType, StreamEvent> = {
|
|
14
|
+
initialState: () => State;
|
|
15
|
+
evolve: (state: State, event: StreamEvent) => State;
|
|
16
|
+
decide: (command: CommandType, state: State) => StreamEvent | StreamEvent[];
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Store-connected command handler function type.
|
|
21
|
+
*
|
|
22
|
+
* Given an event store, stream id, and one or more commands, it loads the
|
|
23
|
+
* current aggregate state from the stream, applies the decider's `decide`
|
|
24
|
+
* function, and appends the resulting events.
|
|
25
|
+
*/
|
|
26
|
+
export type CommandHandler<State, CommandType, StreamEvent extends Event> = <Store extends EventStore>(
|
|
27
|
+
eventStore: Store,
|
|
28
|
+
id: string,
|
|
29
|
+
commands: CommandType | CommandType[],
|
|
30
|
+
handleOptions?: HandleOptions<Store>,
|
|
31
|
+
) => Promise<CommandHandlerResult<State, StreamEvent, Store>>;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Creates a store-connected command handler from a decider configuration.
|
|
35
|
+
*
|
|
36
|
+
* This is the recommended way to create command handlers. It wraps Emmett's
|
|
37
|
+
* `DeciderCommandHandler` while lifting the `CommandType extends Command`
|
|
38
|
+
* constraint that prevents commands with custom metadata from type-checking.
|
|
39
|
+
*
|
|
40
|
+
* Emmett's `Command` type uses a conditional type for metadata:
|
|
41
|
+
* - When metadata is `undefined`, the `metadata` property is optional.
|
|
42
|
+
* - When metadata is defined, it becomes required.
|
|
43
|
+
*
|
|
44
|
+
* TypeScript cannot prove that a concrete command (with custom metadata)
|
|
45
|
+
* satisfies `extends Command` across these conditional branches. This wrapper
|
|
46
|
+
* bridges that gap with a single, localised type assertion — keeping all
|
|
47
|
+
* call sites fully type-safe.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```typescript
|
|
51
|
+
* const handler = defineCommandHandler({
|
|
52
|
+
* initialState,
|
|
53
|
+
* evolve,
|
|
54
|
+
* decide,
|
|
55
|
+
* });
|
|
56
|
+
*
|
|
57
|
+
* export const bookCommandHandlers = BookCommands.map(commandType => ({
|
|
58
|
+
* commandType,
|
|
59
|
+
* handler,
|
|
60
|
+
* getStreamName,
|
|
61
|
+
* }));
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
export function defineCommandHandler<State, CommandType, StreamEvent extends Event>(
|
|
65
|
+
config: DeciderConfig<State, CommandType, StreamEvent>,
|
|
66
|
+
): CommandHandler<State, CommandType, StreamEvent> {
|
|
67
|
+
debugBuilder('[command-handler] Creating command handler');
|
|
68
|
+
|
|
69
|
+
// DeciderCommandHandler constrains CommandType extends Command. At runtime
|
|
70
|
+
// the decide/evolve functions are called with the concrete command values —
|
|
71
|
+
// no metadata shape is enforced. We bridge the compile-time gap here.
|
|
72
|
+
type EmmettConfig = Parameters<typeof DeciderCommandHandler<State, Command, StreamEvent>>[0];
|
|
73
|
+
const emmettHandler = DeciderCommandHandler(config as EmmettConfig);
|
|
74
|
+
|
|
75
|
+
debugBuilder('[command-handler] Command handler created successfully');
|
|
76
|
+
return emmettHandler as CommandHandler<State, CommandType, StreamEvent>;
|
|
77
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { z } from '@arki/contracts';
|
|
2
|
+
|
|
3
|
+
import type { Command, DefaultCommandMetadata } from '../command.js';
|
|
4
|
+
import type { DefaultRecord } from '../types.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Configuration for defining a domain command factory.
|
|
8
|
+
*/
|
|
9
|
+
export type CommandConfig<
|
|
10
|
+
TType extends string,
|
|
11
|
+
TInput extends DefaultRecord,
|
|
12
|
+
TMetadata extends DefaultCommandMetadata | undefined = undefined,
|
|
13
|
+
> = {
|
|
14
|
+
/** The command type string (e.g., 'CreateUser') */
|
|
15
|
+
type: TType;
|
|
16
|
+
/** Zod schema for validating command input */
|
|
17
|
+
inputSchema: z.ZodType<TInput>;
|
|
18
|
+
/** Optional Zod schema for validating command metadata */
|
|
19
|
+
metadataSchema?: z.ZodType<TMetadata>;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Creates a strongly-typed command factory function.
|
|
24
|
+
*
|
|
25
|
+
* This factory validates input and metadata using Zod schemas before
|
|
26
|
+
* creating commands that can be dispatched through a command flow or aggregate.
|
|
27
|
+
*
|
|
28
|
+
* @param config - Configuration object containing type, input schema, and optional metadata schema
|
|
29
|
+
* @returns A factory function that validates and creates commands
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* const createUserCommand = defineCommand({
|
|
34
|
+
* type: 'CreateUser',
|
|
35
|
+
* inputSchema: z.object({ name: z.string(), email: z.email() }),
|
|
36
|
+
* metadataSchema: z.object({ now: z.date(), issuedBy: z.string().uuid() }),
|
|
37
|
+
* });
|
|
38
|
+
*
|
|
39
|
+
* const command = createUserCommand(
|
|
40
|
+
* { name: 'Ada', email: 'ada@example.org' },
|
|
41
|
+
* { now: new Date(), issuedBy: 'usr_123' },
|
|
42
|
+
* );
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
export function defineCommand<
|
|
46
|
+
TType extends string,
|
|
47
|
+
TInput extends DefaultRecord,
|
|
48
|
+
TMetadata extends DefaultCommandMetadata | undefined = undefined,
|
|
49
|
+
>(
|
|
50
|
+
config: CommandConfig<TType, TInput, TMetadata>,
|
|
51
|
+
): (input: TInput, metadata?: TMetadata) => Command<TType, TInput, TMetadata> {
|
|
52
|
+
const { type, inputSchema, metadataSchema } = config;
|
|
53
|
+
|
|
54
|
+
return (input: TInput, metadata?: TMetadata) => {
|
|
55
|
+
const validatedInput = inputSchema.parse(input);
|
|
56
|
+
const validatedMetadata = metadataSchema ? metadataSchema.parse(metadata) : metadata;
|
|
57
|
+
|
|
58
|
+
// Conditionally construct the command object based on whether metadata is provided
|
|
59
|
+
return (validatedMetadata === undefined
|
|
60
|
+
? {
|
|
61
|
+
type,
|
|
62
|
+
data: validatedInput,
|
|
63
|
+
kind: 'Command' as const,
|
|
64
|
+
}
|
|
65
|
+
: {
|
|
66
|
+
type,
|
|
67
|
+
data: validatedInput,
|
|
68
|
+
metadata: validatedMetadata,
|
|
69
|
+
kind: 'Command' as const,
|
|
70
|
+
}) as unknown as Command<TType, TInput, TMetadata>;
|
|
71
|
+
};
|
|
72
|
+
}
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import type { Event as EmmettEvent } from '@event-driven-io/emmett';
|
|
2
|
+
import type { z } from '@arki/contracts';
|
|
3
|
+
|
|
4
|
+
import type { AnyEvent, Event } from '../event.js';
|
|
5
|
+
import { debugBuilder } from '../debug.js';
|
|
6
|
+
import { defineCommandHandler } from './command-handler.js';
|
|
7
|
+
import type {CommandHandler} from './command-handler.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Applies a domain event to the current aggregate state and produces the next state.
|
|
11
|
+
*/
|
|
12
|
+
type Evolve<State, StreamEvent extends AnyEvent> = (state: State, event: StreamEvent) => State;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Computes the domain events that should be emitted for an incoming command,
|
|
16
|
+
* based on the aggregate's current state.
|
|
17
|
+
*/
|
|
18
|
+
type Decide<State, Command, StreamEvent extends AnyEvent> = (command: Command, state: State) => StreamEvent[];
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Fluent builder for aggregate behaviour (aka "decider") definitions.
|
|
22
|
+
*
|
|
23
|
+
* In many event-sourcing texts this role is called an *aggregate*: an object that owns
|
|
24
|
+
* the authoritative state, knows how to rebuild itself from events (`evolve`), and
|
|
25
|
+
* decides which new events should be recorded when commands arrive (`decide`).
|
|
26
|
+
*
|
|
27
|
+
* We keep the historical Emmett name `Decider` to match upstream types, but the builder
|
|
28
|
+
* intentionally documents the aggregate semantics so domain code can align on that
|
|
29
|
+
* mental model.
|
|
30
|
+
*
|
|
31
|
+
* Capabilities:
|
|
32
|
+
* - Type safety through TypeScript generics
|
|
33
|
+
* - Optional Zod schemas to validate state evolution at runtime
|
|
34
|
+
* - Chainable configuration that terminates with `.handler()`, returning the executed aggregate contract
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* const cartAggregate = defineDecider()
|
|
39
|
+
* .stateSchema(z.object({ items: z.array(z.string()), total: z.number() }))
|
|
40
|
+
* .initialState(() => ({ items: [], total: 0 }))
|
|
41
|
+
* .evolve((state, event) => {
|
|
42
|
+
* if (event.type === 'ItemAdded') {
|
|
43
|
+
* return {
|
|
44
|
+
* items: [...state.items, event.data.item],
|
|
45
|
+
* total: state.total + event.data.price,
|
|
46
|
+
* };
|
|
47
|
+
* }
|
|
48
|
+
* return state;
|
|
49
|
+
* })
|
|
50
|
+
* .decide((command, state) => {
|
|
51
|
+
* if (command.type === 'AddItem') {
|
|
52
|
+
* return [
|
|
53
|
+
* {
|
|
54
|
+
* type: 'ItemAdded',
|
|
55
|
+
* data: { item: command.data.item, price: command.data.price },
|
|
56
|
+
* },
|
|
57
|
+
* ];
|
|
58
|
+
* }
|
|
59
|
+
* return [];
|
|
60
|
+
* })
|
|
61
|
+
* .handler();
|
|
62
|
+
*
|
|
63
|
+
* const initial = cartAggregate.initialState();
|
|
64
|
+
* const events = cartAggregate.decide(addItemCommand, initial);
|
|
65
|
+
* const next = cartAggregate.evolve(initial, events[0]);
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
class DeciderBuilder<State = never, Command = never, StreamEvent extends AnyEvent = never> {
|
|
69
|
+
private _stateSchema?: z.ZodType<State>;
|
|
70
|
+
private _initialStateFn?: () => State;
|
|
71
|
+
private _evolveFn?: Evolve<State, StreamEvent>;
|
|
72
|
+
private _decideFn?: Decide<State, Command, StreamEvent>;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Creates a deep copy of the builder to ensure immutability
|
|
76
|
+
* @private
|
|
77
|
+
*/
|
|
78
|
+
private clone(): DeciderBuilder<State, Command, StreamEvent> {
|
|
79
|
+
const builder = new DeciderBuilder<State, Command, StreamEvent>();
|
|
80
|
+
builder._stateSchema = this._stateSchema;
|
|
81
|
+
builder._initialStateFn = this._initialStateFn;
|
|
82
|
+
builder._evolveFn = this._evolveFn;
|
|
83
|
+
builder._decideFn = this._decideFn;
|
|
84
|
+
return builder;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Sets the state schema for state validation
|
|
89
|
+
* @param schema - Zod schema for validating state
|
|
90
|
+
* @returns A new DeciderBuilder instance with the state schema set
|
|
91
|
+
*/
|
|
92
|
+
stateSchema<TNewState>(schema: z.ZodType<TNewState>): DeciderBuilder<TNewState, Command, StreamEvent> {
|
|
93
|
+
const builder = new DeciderBuilder<TNewState, Command, StreamEvent>();
|
|
94
|
+
builder._stateSchema = schema;
|
|
95
|
+
builder._initialStateFn = this._initialStateFn as (() => TNewState) | undefined;
|
|
96
|
+
builder._evolveFn = this._evolveFn as Evolve<TNewState, StreamEvent> | undefined;
|
|
97
|
+
builder._decideFn = this._decideFn as Decide<TNewState, Command, StreamEvent> | undefined;
|
|
98
|
+
debugBuilder('[decider] Set state schema');
|
|
99
|
+
return builder;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Sets the initial state function
|
|
104
|
+
* @param fn - Function that returns the initial state for a new aggregate
|
|
105
|
+
* @returns A new DeciderBuilder instance with the initial state function set
|
|
106
|
+
*/
|
|
107
|
+
initialState(fn: () => State): DeciderBuilder<State, Command, StreamEvent> {
|
|
108
|
+
const builder = this.clone();
|
|
109
|
+
builder._initialStateFn = fn;
|
|
110
|
+
debugBuilder('[decider] Set initial state function');
|
|
111
|
+
return builder;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Sets the evolve function
|
|
116
|
+
*
|
|
117
|
+
* This method is generic and will infer the StreamEvent type from the function parameter,
|
|
118
|
+
* allowing TypeScript to properly infer complex discriminated union types.
|
|
119
|
+
*
|
|
120
|
+
* @template TStreamEvent - The union type of all events (inferred from fn parameter)
|
|
121
|
+
* @param fn - Function that applies an event to state to compute the next state
|
|
122
|
+
* @returns A new DeciderBuilder instance with the evolve function and inferred event types set
|
|
123
|
+
*/
|
|
124
|
+
evolve<TStreamEvent extends AnyEvent>(fn: Evolve<State, TStreamEvent>): DeciderBuilder<State, Command, TStreamEvent> {
|
|
125
|
+
const builder = new DeciderBuilder<State, Command, TStreamEvent>();
|
|
126
|
+
builder._stateSchema = this._stateSchema;
|
|
127
|
+
builder._initialStateFn = this._initialStateFn;
|
|
128
|
+
builder._evolveFn = fn;
|
|
129
|
+
builder._decideFn = this._decideFn as Decide<State, Command, TStreamEvent> | undefined;
|
|
130
|
+
debugBuilder('[decider] Set evolve function');
|
|
131
|
+
return builder;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Sets the decide function
|
|
136
|
+
*
|
|
137
|
+
* This method is generic and will infer the Command type from the function parameter,
|
|
138
|
+
* allowing TypeScript to properly infer complex discriminated union types.
|
|
139
|
+
*
|
|
140
|
+
* @template TCommand - The union type of all commands (inferred from fn parameter)
|
|
141
|
+
* @param fn - Function that determines which events to emit for a given command and state
|
|
142
|
+
* @returns A new DeciderBuilder instance with the decide function and inferred command types set
|
|
143
|
+
*/
|
|
144
|
+
decide<TCommand>(fn: Decide<State, TCommand, StreamEvent>): DeciderBuilder<State, TCommand, StreamEvent> {
|
|
145
|
+
const builder = new DeciderBuilder<State, TCommand, StreamEvent>();
|
|
146
|
+
builder._stateSchema = this._stateSchema;
|
|
147
|
+
builder._initialStateFn = this._initialStateFn;
|
|
148
|
+
builder._evolveFn = this._evolveFn;
|
|
149
|
+
builder._decideFn = fn;
|
|
150
|
+
debugBuilder('[decider] Set decide function');
|
|
151
|
+
return builder;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Terminal method that creates the decider
|
|
156
|
+
*
|
|
157
|
+
* Validates that all required functions are set and returns an object
|
|
158
|
+
* with three validated functions:
|
|
159
|
+
* - initialState: Returns the validated initial state
|
|
160
|
+
* - evolve: Applies an event to state with validation
|
|
161
|
+
* - decide: Determines events to emit with validation
|
|
162
|
+
*
|
|
163
|
+
* @returns An object containing the three core decider functions
|
|
164
|
+
* @throws Error if state schema, initial state function, evolve function, or decide function are not defined
|
|
165
|
+
*/
|
|
166
|
+
handler(): {
|
|
167
|
+
initialState: () => State;
|
|
168
|
+
evolve: Evolve<State, StreamEvent>;
|
|
169
|
+
decide: Decide<State, Command, StreamEvent>;
|
|
170
|
+
} {
|
|
171
|
+
if (!this._stateSchema || !this._initialStateFn || !this._evolveFn || !this._decideFn) {
|
|
172
|
+
debugBuilder('[decider] ERROR: Missing required properties');
|
|
173
|
+
throw new Error(
|
|
174
|
+
'Decider must have state schema, initial state function, evolve function, and decide function defined',
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const stateSchema = this._stateSchema;
|
|
179
|
+
const initialStateFn = this._initialStateFn;
|
|
180
|
+
const evolveFn = this._evolveFn;
|
|
181
|
+
const decideFn = this._decideFn;
|
|
182
|
+
|
|
183
|
+
debugBuilder('[decider] Building decider handler');
|
|
184
|
+
|
|
185
|
+
return {
|
|
186
|
+
initialState: () => {
|
|
187
|
+
debugBuilder('[decider] Getting initial state');
|
|
188
|
+
const state = initialStateFn();
|
|
189
|
+
return stateSchema.parse(state);
|
|
190
|
+
},
|
|
191
|
+
evolve: (state: State, event: StreamEvent) => {
|
|
192
|
+
debugBuilder('[decider] Evolving state with event: %s', (event as Event).type);
|
|
193
|
+
const validatedState = stateSchema.parse(state);
|
|
194
|
+
const nextState = evolveFn(validatedState, event);
|
|
195
|
+
return stateSchema.parse(nextState);
|
|
196
|
+
},
|
|
197
|
+
decide: (command: Command, state: State) => {
|
|
198
|
+
debugBuilder('[decider] Deciding events for command: %s', (command as { type: string }).type);
|
|
199
|
+
const validatedState = stateSchema.parse(state);
|
|
200
|
+
const events = decideFn(command, validatedState);
|
|
201
|
+
debugBuilder('[decider] Generated %d event(s)', events.length);
|
|
202
|
+
return events;
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Terminal method that creates a store-connected command handler.
|
|
209
|
+
*
|
|
210
|
+
* Unlike `.handler()`, this does **not** require a state schema — it creates
|
|
211
|
+
* a handler that can be registered directly with an event store. Internally
|
|
212
|
+
* it delegates to `defineCommandHandler`, which bridges the Emmett type
|
|
213
|
+
* constraint on command metadata.
|
|
214
|
+
*
|
|
215
|
+
* Use this when you need a handler that reads/writes events from a store
|
|
216
|
+
* (the common case for aggregates), rather than the raw decider functions.
|
|
217
|
+
*
|
|
218
|
+
* @returns A store-connected command handler function
|
|
219
|
+
* @throws Error if initial state, evolve, or decide functions are not defined
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```typescript
|
|
223
|
+
* const handler = defineDecider()
|
|
224
|
+
* .initialState(() => null as BookState)
|
|
225
|
+
* .evolve(evolve)
|
|
226
|
+
* .decide(decide)
|
|
227
|
+
* .commandHandler();
|
|
228
|
+
* ```
|
|
229
|
+
*/
|
|
230
|
+
commandHandler(): StreamEvent extends EmmettEvent ? CommandHandler<State, Command, StreamEvent> : never {
|
|
231
|
+
if (!this._initialStateFn || !this._evolveFn || !this._decideFn) {
|
|
232
|
+
debugBuilder('[decider] ERROR: Missing required properties for command handler');
|
|
233
|
+
throw new Error(
|
|
234
|
+
'Decider must have initial state function, evolve function, and decide function defined to create a command handler',
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
debugBuilder('[decider] Building store-connected command handler');
|
|
239
|
+
return defineCommandHandler({
|
|
240
|
+
initialState: this._initialStateFn,
|
|
241
|
+
evolve: this._evolveFn,
|
|
242
|
+
decide: this._decideFn,
|
|
243
|
+
}) as StreamEvent extends EmmettEvent ? CommandHandler<State, Command, StreamEvent> : never;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Factory function to create a new DeciderBuilder
|
|
249
|
+
*
|
|
250
|
+
* **Recommended API**: This builder API supports complex discriminated unions
|
|
251
|
+
* through parameter-based type inference. The `.evolve()` and `.decide()` methods
|
|
252
|
+
* are generic and will automatically infer types from your function parameters.
|
|
253
|
+
*
|
|
254
|
+
* **Use cases:**
|
|
255
|
+
* - ✅ All cases (simple and complex)
|
|
256
|
+
* - ✅ Complex discriminated unions (10+ command/event types)
|
|
257
|
+
* - ✅ Fluent, chainable API preference
|
|
258
|
+
* - ✅ Automatic type inference from function parameters
|
|
259
|
+
*
|
|
260
|
+
* @example
|
|
261
|
+
* ```typescript
|
|
262
|
+
* // Works for both simple and complex union types
|
|
263
|
+
* const decider = defineDecider()
|
|
264
|
+
* .stateSchema(myStateSchema)
|
|
265
|
+
* .initialState(() => ({ ... }))
|
|
266
|
+
* .evolve((state, event) => {
|
|
267
|
+
* // TypeScript infers event type from this function
|
|
268
|
+
* switch (event.type) {
|
|
269
|
+
* case 'EventA': return { ... };
|
|
270
|
+
* case 'EventB': return { ... };
|
|
271
|
+
* // ... handles 10+ event types correctly
|
|
272
|
+
* }
|
|
273
|
+
* })
|
|
274
|
+
* .decide((command, state) => {
|
|
275
|
+
* // TypeScript infers command type from this function
|
|
276
|
+
* switch (command.type) {
|
|
277
|
+
* case 'CommandA': return [{ type: 'EventA', ... }];
|
|
278
|
+
* case 'CommandB': return [{ type: 'EventB', ... }];
|
|
279
|
+
* // ... handles 10+ command types correctly
|
|
280
|
+
* }
|
|
281
|
+
* })
|
|
282
|
+
* .handler();
|
|
283
|
+
* ```
|
|
284
|
+
*/
|
|
285
|
+
export function defineDecider(): DeciderBuilder {
|
|
286
|
+
debugBuilder('[decider] Creating new decider builder');
|
|
287
|
+
return new DeciderBuilder();
|
|
288
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { z } from '@arki/contracts';
|
|
2
|
+
|
|
3
|
+
import type { Event } from '../event.js';
|
|
4
|
+
import type { DefaultRecord } from '../types.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Configuration for defining a domain event factory.
|
|
8
|
+
*/
|
|
9
|
+
export type EventConfig<
|
|
10
|
+
TType extends string,
|
|
11
|
+
TData extends DefaultRecord,
|
|
12
|
+
TMetadata extends DefaultRecord | undefined = undefined,
|
|
13
|
+
> = {
|
|
14
|
+
/** The event type string (e.g., 'UserCreated') */
|
|
15
|
+
type: TType;
|
|
16
|
+
/** Zod schema for validating event data */
|
|
17
|
+
dataSchema: z.ZodType<TData>;
|
|
18
|
+
/** Optional Zod schema for validating event metadata */
|
|
19
|
+
metadataSchema?: z.ZodType<TMetadata>;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Creates a strongly-typed event factory function.
|
|
24
|
+
*
|
|
25
|
+
* This factory validates data and metadata using Zod schemas before
|
|
26
|
+
* creating events that can be appended to Emmett's event store.
|
|
27
|
+
*
|
|
28
|
+
* @param config - Configuration object containing type, data schema, and optional metadata schema
|
|
29
|
+
* @returns A factory function that validates and creates events
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* const userCreatedEvent = defineEvent({
|
|
34
|
+
* type: 'UserCreated',
|
|
35
|
+
* dataSchema: z.object({ userId: z.string().uuid(), name: z.string() }),
|
|
36
|
+
* metadataSchema: z.object({ now: z.date(), correlationId: z.string().uuid() }),
|
|
37
|
+
* });
|
|
38
|
+
*
|
|
39
|
+
* const event = userCreatedEvent(
|
|
40
|
+
* { userId: 'usr_123', name: 'Ada' },
|
|
41
|
+
* { now: new Date(), correlationId: 'corr_456' },
|
|
42
|
+
* );
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
export function defineEvent<
|
|
46
|
+
TType extends string,
|
|
47
|
+
TData extends DefaultRecord,
|
|
48
|
+
TMetadata extends DefaultRecord | undefined = undefined,
|
|
49
|
+
>(config: EventConfig<TType, TData, TMetadata>): (data: TData, metadata?: TMetadata) => Event<TType, TData, TMetadata> {
|
|
50
|
+
const { type, dataSchema, metadataSchema } = config;
|
|
51
|
+
|
|
52
|
+
return (data: TData, metadata?: TMetadata) => {
|
|
53
|
+
const validatedData = dataSchema.parse(data);
|
|
54
|
+
const validatedMetadata = metadataSchema ? metadataSchema.parse(metadata) : metadata;
|
|
55
|
+
|
|
56
|
+
// Conditionally construct the event object based on whether metadata is provided
|
|
57
|
+
return (validatedMetadata === undefined
|
|
58
|
+
? {
|
|
59
|
+
type,
|
|
60
|
+
data: validatedData,
|
|
61
|
+
}
|
|
62
|
+
: {
|
|
63
|
+
type,
|
|
64
|
+
data: validatedData,
|
|
65
|
+
metadata: validatedMetadata,
|
|
66
|
+
}) as unknown as Event<TType, TData, TMetadata>;
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -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
|
+
|
|
34
|
+
export { defineCommand } from './command.js';
|
|
35
|
+
export { defineCommandHandler, type CommandHandler } from './command-handler.js';
|
|
36
|
+
export { defineEvent } from './event.js';
|
|
37
|
+
export { defineDecider } from './decider.js';
|
|
38
|
+
export { defineProjection } from './projection.js';
|
|
39
|
+
export { defineProcessManager } from './process-manager.js';
|
|
40
|
+
export { defineStatefulProcessManager } from './stateful-process-manager.js';
|