Projections
Projections are shared Chronicle read-model behavior. Use the shared docs for projection styles, model-bound projections, declarative projections, and client-tabbed examples.
- Projections
- Choosing a read model style
- Model-bound projections
- Declarative projections
- Composite keys
- Graph projections
- TypeScript client setup
Register projections at runtime
Section titled “Register projections at runtime”Use store.projections.registerFor(ReadModel, define, id?) to define a fluent projection without a discovered projection class, or store.projections.registerModelBound(ReadModel) to register an undiscovered decorator-based model. These correspond to the two explicit Register<TReadModel> forms in the .NET client. The existing parameterless register() still registers discovered projections, and now also sends retained runtime definitions.
For example, with a connected client:
import { field } from '@cratis/fundamentals';import { eventType, fromEvent, setFrom } from '@cratis/chronicle';
@eventType('runtime-name-changed')class NameChanged { @field(String) name = '';}
class NameSummary { static readonly readModelId = 'name-summary'; @field(String) name = '';}
const store = await client.getEventStore('Library');await store.projections.registerFor(NameSummary, builder => { builder.from(NameChanged, from => from.set(model => model.name).to(event => event.name));});
@fromEvent(NameChanged)class NameDetails { @setFrom(NameChanged) @field(String) name = '';}
await store.projections.registerModelBound(NameDetails);const state = await store.projections.getStateForModel(NameSummary);The fluent identifier defaults to the read model identifier (static readModelId, the legacy @readModel identifier, or the class name); pass the optional third argument to use another projection identifier. The model-bound form uses the read model identifier. Read-model schemas, naming policies, validation and builder options use the same paths as discovered projections. Calling .passive() in the fluent callback registers an on-demand projection rather than a materialized sink.
Both methods return Promise<void> and resolve only after the kernel acknowledges the read model and projection. Validation and kernel failures reject the promise and leave no runtime definition retained locally; a later retry can use the same identifier. A runtime identifier already discovered, retained or in flight is rejected, never replaced, except that registerModelBound() accepts an already-discovered model with the same constructor and identifier. It registers and retains that model at runtime; repeating the call after an acknowledged model-bound registration is a no-op. Switching between fluent and model-bound registrations for the same constructor and identifier is rejected as a collision. Later discovery skips the same retained model rather than registering it twice. A different declaration using that identifier is still rejected. Each read model can have only one projection. Explicit variant registration is not supported; register variants together through discovery.
Acknowledged definitions survive discover() and are sent again when a cached event store reconnects. hasForModel(), getProjectionIdFor(), getStateForModel(), failed-partition lookup and replay work with their read model constructors. Keep event types discoverable for event-log operations; explicitly registering a projection does not register its event types.
TypeScript client notes
Section titled “TypeScript client notes”Choose a projection style in the shared guides, then use its TypeScript example. Check the feature-specific limits below before adapting a C# recipe.
The TypeScript client supports these projection capabilities, in addition to @fromEvent, @setFrom, and the declarative .from(...) builder:
Earlier client versions rejected these with a not implemented yet. error at registration. Upgrade the client if you still see it.
Map values and keys
Section titled “Map values and keys”- The model-bound arithmetic decorators —
@addFrom,@subtractFrom,@increment,@decrement,@count— and their fluent equivalents (.add()/.subtract()/.count()onIFromBuilder/IJoinBuilder). - Constant values with
@setValue(Event, value)and.set(...).toValue(value), and constant keys. Earlier client versions sent these in a form the kernel did not apply, so the read model kept its previous value. - Event-context mappings with
@setFromContext(Event, 'occurred'),.set(...).toEventContextProperty('occurred'), and context-derived keys with.usingKeyFromContext('eventSourceId')or.usingParentKeyFromContext('eventSourceId'), including inside.addChild(model => model.children, child => child.identifiedBy(item => item.id).usingKeyFromContext('sequenceNumber').usingParentKeyFromContext('eventSourceId')). In the accessor form of.addChild(model => model.children, event => event.property), the builder namesidentifiedBy,usingKey,usingKeyFromContextandusingParentKeyFromContextare reserved and can’t be selected as event properties. These names use the TypeScriptEventContextspelling; the client sends$eventContext(Occurred)and$eventContext(EventSourceId)to the kernel. Registration accepts only paths the kernel can resolve: any rootEventContextproperty; an identity member ofcausedBy(subject,name,userName), orcausedBy.onBehalfOfas a whole identity; andoccurred.week(), the kernel’s only derived function, emitted asOccurred.Week().causationandtagsare collections, so they can be mapped only as a whole. Anything else fails during projection registration, naming the projection, read model and invalid path. The error’s cause isInvalidEventContextPropertyError, exported from@cratis/chronicleand@cratis/chronicle/projections. Earlier client versions sent expressions the kernel did not recognize, or treated model-bound context names as event-content properties. .usingCompositeKey()/.usingParentCompositeKey()on the fluentIFromBuilder/IJoinBuilder. Each part accepts an event property, event context property, event source id or constant through.set(target).to(...),.toEventContextProperty(...),.toEventSourceId()or.toValue(...). The existing.set(target, eventAccessor)form remains supported. See TypeScript composite keys and the shared composite keys guide.
Configure children and nested objects
Section titled “Configure children and nested objects”When upgrading existing apps with model-bound children, check these two changed behaviors: an automatically mapped identifier now comes from the event source id rather than an AutoMapped same-named event property when the child key is implicit, and a child without id whose property matches an explicit event key now uses that property as IdentifiedBy. When @count, @increment or @decrement give an aggregate-only creating event a constant key, the kernel initializes the identifier from that constant ($value(...)), the key it uses to find the child. The .NET model-bound builder instead adds an explicit identifier mapping from the event source id for the default child key, even for aggregate-only events. Replaying affected events with the new definitions can produce different persisted child data; check those read models when upgrading.
- The model-bound
@childrenFrom,@nested, and class- or property-level@clearWithdecorators, and the matching fluent.children()/.nested()builders (plus.addChild()/.setThisValue()onIFromBuilder/IJoinBuilder). On a scalar member of a root, child, or nested type,@clearWith(Event)maps that member to$nullin the event’sFromentry. On a nested type or the member carrying@nested, it clears the whole nested object instead. - Apply
@noAutoMapto a child or nested class to disable automatic property mapping for that definition; a decorated declaring class also disables it for its direct child and nested definitions (the policy does not cascade further). Apply@noAutoMapto individual properties on child or nested types to exclude just those members from automatic mapping. Explicit@setFrommappings still apply. Fluent child and nested builders support.noAutoMap()and.autoMap().
For model-bound @childrenFrom, an automatically mapped child whose identifier is a discoverable id/Id, or supplied as identifiedBy, gets its identifier from $eventContext(EventSourceId) when the child key defaults to the event source id. An explicit single-property event key instead maps to that event property unless it already matches the identifier name; if no id is found, a child property matching the event key becomes IdentifiedBy. TypeScript has no [Key] decorator: pass identifiedBy for a differently named identifier, and use an initialized property or @field so convention-based id/Id is discoverable at runtime. Explicit identifier mappings and class-level @noAutoMap on the child or its declaring class take precedence; property-level @noAutoMap on the identifier does not suppress this default identifier mapping. A composite child key ($composite(...), built with CompositeKeyBuilder) retains Key and IdentifiedBy without synthesizing an identifier property mapper: the kernel initializes the child identifier from the resolved composite key, and composite-key expressions are not read-model property expressions. Explicit property mappings remain unchanged. This fixes composite-keyed child creation/update registration, not composite-key removal; see the composite child removal limitation. Creating events with non-empty mappings consisting only of aggregate expressions (@count, @increment, @decrement, @addFrom, @subtractFrom) do not get the identifier mapping: the kernel initializes the child identifier from the resolved key, and leaving those mappings aggregate-only prevents unrelated same-named event properties from being AutoMapped onto the child.
Supply child types at runtime
Section titled “Supply child types at runtime”Under runtimes that emit no type metadata, such as tsx, name the child type of a children collection in @childrenFrom(ItemAdded, Item, 'itemId'): the second argument can be the child class instead of the key. The client then excludes Item from the root read models and restores the collection as Item instances. In this form the child type takes the key’s place, so 'itemId' is the identifiedBy property and the child key is always the event source id, which also becomes the identifier. To name the child type and key children by an event property, use the options form, which accepts the same key, identifiedBy and parentKey as the .NET [ChildrenFrom<TEvent>] attribute:
@childrenFrom(ItemAdded, { childType: Item, key: 'itemId', identifiedBy: 'id', parentKey: 'orderId' })items: Item[] = [];Every option is optional; an omitted key or parentKey defaults to the event source id, and identifiedBy is discovered as described above. In both decorator modes, a child type with resolvable runtime members registers a typed item schema so AutoMap maps the child’s properties, not just its identifier. With legacy decorators, the item schema falls back to { type: 'object' } if no child properties resolve or the resolved properties do not include the child identifier. Members declared only with ! have no runtime type under tsx/esbuild; initialize them or use @field to make them discoverable. Partially resolved children remain typed when their identifier resolves. TypeScript’s emitted design:type only identifies the collection as an array, not its element type. With legacy decorators and no element-type metadata, pass childType; without it, the item schema remains untyped and AutoMap stores only the identifier. Declaring the element type with @field(Array, { genericArguments: [Item] }) and using @childrenFrom(ItemAdded, 'itemId') still works and produces the same definition. The projections/model-bound/children/child-type-with-key client snippet shows a complete, compiled example.
With standard decorators, a model-bound read model whose mappings are all on properties registers only once an instance of it exists. Give it a class-level @fromEvent(...) decorator so it registers when its module loads.
Dictionaries, set once and children ordering
Section titled “Dictionaries, set once and children ordering”These need Chronicle 19.150.0 or later. An older kernel rejects the projection when it registers.
Map into a dictionary-typed property (Record<string, T>) by passing a key as the second argument of .set(), .setOnce(), .add(), .subtract(), .increment(), .decrement() and .count() on IFromBuilder/IJoinBuilder. Remove an entry with .removeKey(property, key). The key is an accessor on the event, such as e => e.category or e => e.slot.name. You can also use a DictionaryKey:
DictionaryKey.fromEventContent(e => e.category)reads a property of the event. A plain accessor does the same. The property has to exist on the event; the kernel matches the name case-sensitively when the projection registers. If an event has no value for the key, the dictionary stays as it is.DictionaryKey.fromEventContext('eventSourceId')orDictionaryKey.fromEventContext('causedBy.userName')reads the event context.DictionaryKey.causedBy('subject' | 'name' | 'userName')reads the identity that caused the event.
builder.from(ItemSold, _ => _ .add(m => m.unitsByCategory, e => e.category).with(e => e.quantity) .count(m => m.salesByUser, DictionaryKey.causedBy('subject')) .setOnce(m => m.firstSaleByCategory, e => e.category).toEventContextProperty('occurred')).from(CategoryRetired, _ => _ .removeKey(m => m.unitsByCategory, e => e.category));.setOnce(property) assigns the property only while it has no value yet. The first event that carries a value wins, and later events leave it unchanged. It works on plain properties and dictionary entries, and on fromEvery/fromAll. Use it to record when something was first seen without adding a creation event. In model-bound projections, use @setFrom(Event, { setOnce: true }) or @setFromContext(Event, { contextProperty: 'occurred', setOnce: true }).
Set once is not supported on graph projections. Graph projections do not read the current value of a node or an edge, so a set once mapping would overwrite it. Using setOnce on a node or edge member fails registration with SetOnceNotSupportedInGraph.
.toCausedBy() maps a property from the identity that caused the event: .set(m => m.lastChangedBy).toCausedBy('userName'). Leave out the member to map the whole identity.
Children are appended by default. Call .prepend(), .orderBy(child => child.position) or .orderByDescending(child => child.position) on a .children() builder to place new children differently. For @childrenFrom, use the prepend, orderBy or orderByDescending option. All @childrenFrom decorators on a property must declare the same ordering, or leave it unset. Otherwise registration fails with ConflictingChildrenOrdering. An ascending sort puts children without a value first, and a descending sort puts them last. Updating a child never moves it.
ReadModelScenario runs projections in memory. It does not support set once, dictionary entries or ordered children. Test projections that use them against a kernel (ChronicleKernelScenario).
Remove a child via a join
Section titled “Remove a child via a join”Chronicle supports removedWithJoin inside a children collection, not at the projection root. A root declaration logs a warning at registration and will not remove the read model. Use removedWith (or @removedWith for a model-bound projection) to remove the root read model.
The fluent removedWithJoin(...).on(...) method is deprecated. Its value is never sent to Chronicle, and the method will be removed in a future major release.
When to use a projection instead of a reducer
Section titled “When to use a projection instead of a reducer”Choose a projection when the read model is a direct mapping of events. That includes values set from events, counters, dictionaries keyed by event data, first-seen values with set once, and child collections in a fixed order. The kernel then handles keys, replays and every sink for you. Choose a reducer when the next state depends on logic that a mapping cannot express, such as conditional rules, calculations across several properties, or validating against the current state.
All-event mappings on children and nested objects
Section titled “All-event mappings on children and nested objects”@fromAllEvents maps a property on the object where you declare it. On a child or nested type, it populates that object’s property, including on the event that creates it. Root and child properties with the same name can map from different event properties without overwriting each other’s mappings. @fromEvery on a child or nested property also stays on that object and applies to its handled events.
Only a root @fromAllEvents enables sequence-wide subscription for the root projection. A child annotation does not subscribe the root to unrelated events. Root mappings still run on child events when the root mapping includes them, but root values are never copied into child objects.
Earlier TypeScript clients sent child and nested @fromAllEvents mappings as bare root property names. Chronicle 19.78.1 can recover those mappings when the root schema does not declare the same property. Upgrade the client when both levels declare it, then replay affected projections to rebuild previously materialized child values. Child-local mappings use the existing child definition contract; no new contract package is required.
Projection tags
Section titled “Projection tags”The client sends the tags with the projection definition. Chronicle maps them in both directions when it registers a projection and stores them with the definition. Tags do not filter received events or change in-process ReadModelScenario evaluation. See Tagging projections for client examples.
Projection registration computes LastUpdated from the full definition, including tags and nested mappings. After upgrading, this value changes once for every projection. The Chronicle kernel’s ProjectionDefinitionComparer excludes LastUpdated, ReadModel, and InitialModelState before comparing definitions (and normalizes optional collections). A changed LastUpdated alone therefore does not trigger a replay; changed child mappings or IdentifiedBy are part of the comparison.
Tags are not part of the kernel’s definition comparison: Chronicle removes them before comparing definitions, so adding, removing, reordering, or changing a tag does not replay the projection or create a replay recommendation.
Apply @tag('Analytics') or @tags('Analytics', 'Reporting') to a declarative projection class, or to the read model class for a model-bound projection. Import either decorator from @cratis/chronicle. Both decorator modes support repeated declarations; duplicate values are emitted once, sorted for deterministic definition hashing. For declarative projections, only tags on the projection class are sent, not tags on its read model.