Skip to main content
Version: Current

StateBuilder

@rotorsoft/act-root


@rotorsoft/act-root / act/src / StateBuilder

Type Alias: StateBuilder<TState, TName>

StateBuilder<TState, TName> = object

Defined in: libs/act/src/types/builders.ts:300

Builder interface for defining a state with event sourcing.

Provides a fluent API to configure the initial state, event types, and event handlers (reducers) before moving to action configuration.

See​

Type Parameters​

TState​

TState extends Schema

State schema type

TName​

TName extends string = string

State name literal type

Properties​

init​

init: (init) => object

Defined in: libs/act/src/types/builders.ts:318

Defines the initial state for new state instances.

The init function is called when a new stream is created (first event). It can accept initial data or return a default state.

Parameters​

init​

() => Readonly<TState>

Function returning the initial state

Returns​

A builder with .emits() to declare event types

emits​

emits: <TEvents>(events) => ActionBuilder<TState, TEvents, { }, TName> & object

Declares the event types that this state can emit.

Events represent facts that have happened - they should be named in past tense. Each event is defined with a Zod schema for type safety and runtime validation.

Type Parameters​
TEvents​

TEvents extends Schemas

Event schemas type

Parameters​
events​

ZodTypes<TEvents>

Object mapping event names to Zod schemas

Returns​

ActionBuilder<TState, TEvents, { }, TName> & object

An ActionBuilder (with optional .patch() to override specific reducers)

Example​
.emits({
Incremented: z.object({ amount: z.number() }),
Decremented: z.object({ amount: z.number() }),
Reset: z.object({})
})

Example​

.init(() => ({ count: 0, created: new Date() }))