@smitejs/domain
Functional DDD toolkit for Smite: value objects, entities, ports, specifications and usecases.
yarn add @smitejs/domain50 documented symbols · version 2.0.0-SNAPSHOT.0 · source
Builders
functionaggregate
function aggregate<State, Event, Id>(config: {
readonly name: string;
readonly idKey?: keyof State & string;
readonly eventSchema?: z.ZodType<Event>;
readonly initial: (id: Id) => State;
readonly apply: (state: State, event: Event) => State;
}): Aggregate<State, Event, Id>;Builds an event-sourced aggregate from a reducer. apply(state, event) returns the next state, keeping the log append-only. create(id) starts an empty instance; load(id, events) replays a committed history. New instances receive every event via record (validated by eventSchema when given) and fold it into their state. commit produces the persistent projection of the committed events. In collect mode a domain.aggregate node is registered.
const Account = aggregate({
name: "Account",
initial: () => ({ balance: 0 }),
apply: (state, event: { readonly amount: number }) => ({
balance: state.balance + event.amount,
}),
});
const account = Account.create("account-1")
.record({ amount: 10 })
.unwrapOrElse(() => null);10
10
[]
{
projection: { balance: 10 },
version: 1,
events: [{ amount: 10 }],
}const restored = Account.load("account-1", [{ amount: 10 }]);10
[]
{
projection: { balance: 10 },
version: 1,
events: [{ amount: 10 }],
}const committed = account?.commit();{
projection: { balance: 10 },
version: 1,
events: [{ amount: 10 }],
}packages/domain/src/aggregate.ts:86
constcommand
const command: <Deps, Input, Output, ErrorValue = unknown>(config: CommandConfig<Deps, Input, Output, ErrorValue>) => Usecase<Deps, Input, Output, ErrorValue>;Builds a mutating usecase (CQRS command). Same kernel as usecase; only the recorded kind differs.
const greet = usecase({
name: "greet",
input: z.object({ name: z.string() }),
handle: (_deps, input) => Result.ok(`hello ${input.name}`),
});
const greeting = await greet.run({ name: "smite" }, {}).run();"hello smite"functionentity
function entity<Shape>(config: {
readonly name: string;
readonly id: keyof Shape & string;
readonly schema: z.ZodType<Shape>;
}): EntityFactory<Shape>;Declares an entity from a zod schema plus an id key. New entities are frozen and validated on creation; equality follows identity (two entities with the same id are the same entity). In collect mode a domain.entity node is registered.
const Order = entity({
name: "Order",
id: "id",
schema: z.object({ id: z.number().int().positive(), note: z.string() }),
});
const same = Order.create({ id: 1, note: "first" })
.map((a) =>
Order.create({ id: 1, note: "second" })
.map((b) => a.equals(b))
.unwrapOr(false),
)
.unwrapOr(false);truepackages/domain/src/entity.ts:49
functionhandler
function handler<Deps, Input, Output, ErrorValue>(usecase: Usecase<Deps, Input, Output, ErrorValue>, deps: Deps, options?: HandlerOptions<Input>): (ctx: HandlerContext) => Promise<HandlerOutput>;A transport handler that runs a usecase against injected deps and maps the Result to a response: ok becomes the configured success (200 by default), failures become a configurable error status (422 by default) with the reason in the body. Carries non-enumerable metadata the transport relates to the usecase IR node in collect mode.
const echo = usecase({
name: "echo",
handle: (_deps, input) => Result.ok({ echo: input }),
});
const httpHandler = handler(echo, {});
const response = await httpHandler({ body: "hi" });200packages/domain/src/handler.ts:60
functionmergeSpecifications
function mergeSpecifications<Value, Reason = SpecificationReason>(...specs: readonly Specification<Value, Reason>[]): Specification<Value, Reason>;Combines specifications so every one must pass. Short-circuits at the first failure and returns that reason. An empty checklist always passes.
const active = specification({
name: "active",
predicate: (user: { readonly active: boolean }) =>
user.active
? Result.ok(true)
: Result.err("inactive", { active: false }),
});
const verified = specification({
name: "verified",
predicate: (user: { readonly verified: boolean }) =>
user.verified
? Result.ok(true)
: Result.err("unverified", { verified: false }),
});
const allowed = active.and(verified);
const satisfied = allowed
.isSatisfiedBy({ active: true, verified: true })
.isOk();truepackages/domain/src/specification.ts:74
functionport
function port(config: {
readonly name: string;
readonly methods: readonly string[];
}): PortDescriptor;Records a port (a dependency contract) so the collect-mode CLI can graph what each usecase depends on. The contract itself is a plain TypeScript type the usecase declares; this builder only registers the IR node.
const orderRepo = port({
name: "OrderRepository",
methods: ["findById", "save"],
});
const loadOrder: ReadPort<{ id: number; total: number }, number> = {
findById: async () => Promise.resolve(null),
};
"domain.port"packages/domain/src/port.ts:41
functionprojection
function projection<State, Event, ReadModel>(config: {
readonly name: string;
readonly aggregate: ProjectionConfig<State, Event, ReadModel>["aggregate"];
readonly initial: () => ReadModel;
readonly reduce: (readModel: ReadModel, projection: Commit<State, Event>) => ReadModel;
}): Projection<State, Event, ReadModel>;Builds a read-side projection: a pure reducer over the committed events of an aggregate (domain.projection node). reduce(view, commit) returns the next read model; build(commits) folds a batch of commits into one. In collect mode the projection is related to its aggregate edge so the CLI can trace projection → aggregate → events.
const view = Balances.build([
account?.commit() ?? {
projection: { balance: 0 },
version: 0,
events: [],
},
]);{ total: 10 }
truepackages/domain/src/projection.ts:55
constquery
const query: <Deps, Input, Output, ErrorValue = unknown>(config: CommandConfig<Deps, Input, Output, ErrorValue>) => Usecase<Deps, Input, Output, ErrorValue>;Builds a read-only usecase (CQRS query). Same kernel as usecase; only the recorded kind differs.
const greet = usecase({
name: "greet",
input: z.object({ name: z.string() }),
handle: (_deps, input) => Result.ok(`hello ${input.name}`),
});
const greeting = await greet.run({ name: "smite" }, {}).run();"hello smite"packages/domain/src/cqrs.ts:21
functionspecification
function specification<Value, Reason = SpecificationReason>(config: {
readonly name: string;
readonly predicate: SpecificationPredicate<Value, Reason>;
}): Specification<Value, Reason>;Creates a named specification from a reason-returning predicate. The predicate returns Result.ok(true) when satisfied or Result.err(tag, data) otherwise. In collect mode a domain.specification node is registered.
const active = specification({
name: "active",
predicate: (user: { readonly active: boolean }) =>
user.active
? Result.ok(true)
: Result.err("inactive", { active: false }),
});
const verified = specification({
name: "verified",
predicate: (user: { readonly verified: boolean }) =>
user.verified
? Result.ok(true)
: Result.err("unverified", { verified: false }),
});
const allowed = active.and(verified);
const satisfied = allowed
.isSatisfiedBy({ active: true, verified: true })
.isOk();truepackages/domain/src/specification.ts:55
functionusecase
function usecase<Deps, Input, Output, ErrorValue = unknown>(config: UsecaseConfig<Deps, Input, Output, ErrorValue>): Usecase<Deps, Input, Output, ErrorValue>;Builds a pure usecase. handle(deps, input) is the functional core and returns a Result (sync or async); all I/O happens in the injected deps (ports). Invalid input returns a domain.validation failure instead of throwing. In collect mode a domain.usecase node is registered.
const greet = usecase({
name: "greet",
input: z.object({ name: z.string() }),
handle: (_deps, input) => Result.ok(`hello ${input.name}`),
});
const greeting = await greet.run({ name: "smite" }, {}).run();"hello smite"const notes = { save: async () => Result.ok(undefined) };
const saveNote = usecase({
name: "saveNote",
deps: ["notes"],
handle: (deps, input) => deps.notes.save(input),
});
const runner = saveNote.with({ notes });
const result = await runner({ text: "hi" }).run();truepackages/domain/src/usecase.ts:89
functionvalueObject
function valueObject<Shape>(config: {
readonly name: string;
readonly schema: z.ZodType<Shape>;
}): ValueObjectFactory<Shape>;Creates a value object factory from a zod schema. Values are frozen on creation and equal structurally (by parsed value, never by reference). In collect mode a domain.valueObject node is registered.
const Money = valueObject({
name: "Money",
schema: z.object({
amount: z.number().nonnegative(),
currency: z.string(),
}),
});
const eur = Money.create({ amount: 10, currency: "EUR" })
.map((a) =>
Money.create({ amount: 10, currency: "EUR" })
.map((b) => a.equals(b))
.unwrapOr(false),
)
.unwrapOr(false);truepackages/domain/src/value-object.ts:53
Internals
interfaceAggregateDescriptor
interface AggregateDescriptor<Event> extends Descriptor<"domain.aggregate", {
readonly name: string;
readonly idKey: string;
readonly eventSchema?: z.ZodType<Event>;
readonly reduceArity: number;
}> {
}A domain.aggregate IR node.
packages/domain/src/aggregate.ts:8
constaggregateDescriptorSymbol
const aggregateDescriptorSymbol: unique symbol;Non-enumerable symbol under which an aggregate factory stores its IR node, read by projection to relate a projection to its aggregate edge.
packages/domain/src/aggregate.ts:24
typeDomainHandlerMetadata
type DomainHandlerMetadata = {
readonly usecaseNode: unknown;
readonly deps: Readonly<Record<string, unknown>>;
};Metadata attached to a handler function referencing the usecase it runs.
packages/domain/src/handler.ts:16
constdomainHandlerSymbol
const domainHandlerSymbol: unique symbol;Non-enumerable symbol carried by functions produced by handler and by usecase runners. Transport builders read it (via Symbol.for with the same string) to relate an http.handler node to the underlying domain.usecase node in collect mode — without a package dependency between the two.
packages/domain/src/handler.ts:4
interfaceEntityDescriptor
interface EntityDescriptor<Shape> extends Descriptor<"domain.entity", {
readonly name: string;
readonly idKey: string;
readonly schema: z.ZodType<Shape>;
}> {
}A domain.entity IR node.
packages/domain/src/entity.ts:8
interfacePortDescriptor
interface PortDescriptor extends Descriptor<"domain.port", {
readonly name: string;
readonly methods: readonly string[];
}> {
}A domain.port IR node naming a dependency contract.
interfaceProjectionDescriptor
interface ProjectionDescriptor<_State, _Event, _ReadModel> extends Descriptor<"domain.projection", {
readonly name: string;
readonly aggregate: string;
readonly reduceArity: number;
}> {
}A domain.projection IR node.
packages/domain/src/projection.ts:6
interfaceSpecificationDescriptor
interface SpecificationDescriptor extends Descriptor<"domain.specification", {
readonly name: string;
readonly operators: readonly string[];
}> {
}A domain.specification IR node.
packages/domain/src/specification.ts:16
interfaceUsecaseDescriptor
interface UsecaseDescriptor<Input> extends Descriptor<"domain.usecase", {
readonly name: string;
readonly kind: UsecaseKind;
readonly inputSchema?: z.ZodType<Input>;
readonly deps: readonly string[];
}> {
}A domain.usecase IR node.
packages/domain/src/usecase.ts:26
constusecaseDescriptorSymbol
const usecaseDescriptorSymbol: unique symbol;Non-enumerable symbol under which a usecase stores its IR node, read by the handler glue to relate an http handler to the usecase edge.
packages/domain/src/usecase.ts:60
interfaceValueObjectDescriptor
interface ValueObjectDescriptor<Shape> extends Descriptor<"domain.valueObject", {
readonly name: string;
readonly schema: z.ZodType<Shape>;
}> {
}A domain.valueObject IR node.
packages/domain/src/value-object.ts:17
Reference
constdeepEqual
const deepEqual: (a: unknown, b: unknown) => boolean;Structural equality over plain values: primitives, arrays and objects.
packages/domain/src/value.ts:17
constfreezeDeep
const freezeDeep: <Value>(value: Value) => Readonly<Value>;Deep-freezes a parsed snapshot so a value object or entity value can never be mutated after construction.
packages/domain/src/value.ts:1
consthashOf
const hashOf: (value: unknown) => string;Stable canonical string for a value, usable as a Set/Map key.
packages/domain/src/value.ts:70
Surface
constdomain
const domain: {
command: <Deps, Input, Output, ErrorValue = unknown>(config: {
readonly handle: (deps: Deps, input: Input) => import("@smitejs/fp").Result<Output, ErrorValue> | PromiseLike<import("@smitejs/fp").Result<Output, ErrorValue>>;
readonly name: string;
readonly input?: import("zod").ZodType<Input, unknown, import("zod/v4/core").$ZodTypeInternals<Input, unknown>>;
readonly deps?: readonly (keyof Deps & string)[];
}) => import("./usecase.js").Usecase<Deps, Input, Output, ErrorValue>;
aggregate: typeof aggregate;
entity: typeof entity;
handler: typeof handler;
mergeSpecifications: typeof mergeSpecifications;
port: typeof port;
projection: typeof projection;
query: <Deps, Input, Output, ErrorValue = unknown>(config: {
readonly handle: (deps: Deps, input: Input) => import("@smitejs/fp").Result<Output, ErrorValue> | PromiseLike<import("@smitejs/fp").Result<Output, ErrorValue>>;
readonly name: string;
readonly input?: import("zod").ZodType<Input, unknown, import("zod/v4/core").$ZodTypeInternals<Input, unknown>>;
readonly deps?: readonly (keyof Deps & string)[];
}) => import("./usecase.js").Usecase<Deps, Input, Output, ErrorValue>;
specification: typeof specification;
usecase: typeof usecase;
valueObject: typeof valueObject;
};The @smitejs/domain namespace: a single import for the full DDD toolkit.
packages/domain/src/index.ts:72
Types
interfaceAggregate
interface Aggregate<State, Event, Id> {
readonly name: string;
readonly create: (id: Id) => AggregateInstance<State, Event, Id>;
readonly load: (id: Id, events: readonly Event[]) => AggregateInstance<State, Event, Id>;
readonly [aggregateDescriptorSymbol]?: AggregateDescriptor<Event>;
}An event-sourced aggregate: a named reducer over an immutable event log. Each instance receives and stores every event; commit folds the committed ones into a persistent Commit projection.
packages/domain/src/aggregate.ts:52
typeAggregateEvent
type AggregateEvent<Type extends string> = {
readonly type: Type;
};A single event in an aggregate's history, discriminated by type.
packages/domain/src/aggregate.ts:34
interfaceAggregateInstance
interface AggregateInstance<State, Event, Id> {
readonly id: Id;
readonly state: Readonly<State>;
readonly events: readonly Event[];
readonly uncommitted: readonly Event[];
readonly record: (event: Event) => Result<AggregateInstance<State, Event, Id>, DomainValidationError>;
readonly commit: () => Commit<State, Event>;
}A materialized aggregate: the folded state plus the full event log it was folded from. Immutable read-only; every operation returns a new instance.
packages/domain/src/aggregate.ts:69
interfaceCommit
interface Commit<State, Event> {
readonly projection: Readonly<State>;
readonly version: number;
readonly events: readonly Event[];
}The persistent representation folded from an aggregate's committed events.
packages/domain/src/aggregate.ts:41
typeDomainFailure
type DomainFailure = {
readonly tag: "domain.validation";
readonly data: readonly z.ZodIssue[];
} | {
readonly tag: "domain.deps";
readonly data: {
readonly missing: readonly string[];
};
};A built-in failure: invalid input, or a dependency the injected deps lacked.
packages/domain/src/usecase.ts:14
typeDomainValidationError
type DomainValidationError = {
readonly tag: "domain.validation";
readonly data: readonly z.ZodIssue[];
};The failure carried by a failed create/parse: the zod validation issues.
packages/domain/src/value-object.ts:7
interfaceEntity
interface Entity<Shape> {
readonly value: Readonly<Shape>;
readonly id: Shape[keyof Shape];
readonly equals: (other: Entity<Shape>) => boolean;
readonly hash: () => string;
}A frozen domain value with a stable identity, compared by id.
packages/domain/src/entity.ts:23
interfaceEntityFactory
interface EntityFactory<Shape> {
readonly name: string;
readonly idKey: keyof Shape & string;
readonly create: (input: unknown) => Result<Entity<Shape>, DomainValidationError>;
readonly parse: (input: unknown) => Entity<Shape>;
}Factory produced by entity.
packages/domain/src/entity.ts:35
interfaceHandlerContext
interface HandlerContext {
readonly body?: unknown;
readonly params?: Readonly<Record<string, string>>;
readonly query?: Readonly<Record<string, unknown>>;
}The structural context a domain handler reads. Compatible with the context a transport provides.
packages/domain/src/handler.ts:26
interfaceHandlerOptions
interface HandlerOptions<Input> {
readonly input?: (ctx: HandlerContext) => Input;
readonly status?: number;
readonly errorStatus?: number;
}Options for handler.
packages/domain/src/handler.ts:49
interfaceHandlerOutput
interface HandlerOutput {
readonly status: number;
readonly body?: unknown;
readonly headers?: Readonly<Record<string, string>>;
}The structural response a domain handler returns.
packages/domain/src/handler.ts:38
interfaceProjection
interface Projection<State, Event, ReadModel> {
readonly name: string;
readonly build: (commits: readonly Commit<State, Event>[]) => ReadModel;
}A named read model derived from the committed projections of an aggregate. build(commits) folds each Commit through reduce, producing a queryable persistent representation that stays in sync with the event log.
packages/domain/src/projection.ts:43
interfaceProjectionConfig
interface ProjectionConfig<State, Event, ReadModel> {
readonly name: string;
readonly aggregate: {
readonly name: string;
readonly [aggregateDescriptorSymbol]?: {
readonly __key: string;
} | undefined;
};
readonly initial: () => ReadModel;
readonly reduce: (readModel: ReadModel, projection: Commit<State, Event>) => ReadModel;
}Config for projection.
packages/domain/src/projection.ts:21
typeReadPort
type ReadPort<Value, Id> = Pick<Repository<Value, Id>, "findById">;The read half of a repository: depends only on reads.
packages/domain/src/port.ts:27
typeRepository
type Repository<Value, Id> = {
readonly findById: (id: Id) => PromiseLike<Result<Value | null, unknown>>;
readonly save: (value: Value) => PromiseLike<Result<void, unknown>>;
};A write/read repository contract. Any object with these members satisfies it structurally, so production stores swap in without touching the usecase.
packages/domain/src/port.ts:16
interfaceSpecification
interface Specification<Value, Reason = SpecificationReason> {
readonly name: string;
readonly isSatisfiedBy: SpecificationPredicate<Value, Reason>;
readonly and: (...others: readonly Specification<Value, Reason>[]) => Specification<Value, Reason>;
readonly or: (...others: readonly Specification<Value, Reason>[]) => Specification<Value, Reason>;
readonly not: () => Specification<Value, Reason>;
}A named, composable business rule. and/or/not return new specifications and never mutate the receiver (open/closed).
packages/domain/src/specification.ts:37
typeSpecificationPredicate
type SpecificationPredicate<Value, Reason> = (input: Value) => Result<boolean, Reason>;A rule that returns a Result instead of a bare boolean, so a failed check carries why.
packages/domain/src/specification.ts:27
typeSpecificationReason
type SpecificationReason = {
readonly tag: string;
readonly data?: unknown;
};The default reason carried by a failed specification. Predicates build it with Result.err(tag, data).
packages/domain/src/specification.ts:5
interfaceUsecase
interface Usecase<Deps, Input, Output, ErrorValue = unknown> {
readonly name: string;
readonly kind: UsecaseKind;
readonly id: string;
readonly run: (input: Input, deps: Deps) => TaskResult<Output, ErrorValue | DomainFailure>;
readonly with: (deps: Deps) => (input: Input) => TaskResult<Output, ErrorValue | DomainFailure>;
readonly [usecaseDescriptorSymbol]?: UsecaseDescriptor<Input>;
}A usecase: a named, pure command/query returning a TaskResult.
packages/domain/src/usecase.ts:70
interfaceUsecaseConfig
interface UsecaseConfig<Deps, Input, Output, ErrorValue = unknown> {
readonly name: string;
readonly kind?: UsecaseKind;
readonly input?: z.ZodType<Input>;
readonly deps?: readonly (keyof Deps & string)[];
readonly handle: (deps: Deps, input: Input) => MaybePromise<Result<Output, ErrorValue>>;
}Config for usecase.
packages/domain/src/usecase.ts:44
typeUsecaseKind
type UsecaseKind = "command" | "query";Whether a usecase mutates state (command) or only reads it (query).
packages/domain/src/usecase.ts:7
interfaceValueObject
interface ValueObject<Shape> {
readonly value: Readonly<Shape>;
readonly equals: (other: ValueObject<Shape>) => boolean;
readonly hash: () => string;
}A frozen, structurally-equal domain value.
packages/domain/src/value-object.ts:28
interfaceValueObjectFactory
interface ValueObjectFactory<Shape> {
readonly name: string;
readonly schema: z.ZodType<Shape>;
readonly create: (input: unknown) => Result<ValueObject<Shape>, DomainValidationError>;
readonly parse: (input: unknown) => ValueObject<Shape>;
}Factory produced by valueObject.
packages/domain/src/value-object.ts:39
typeWritePort
type WritePort<Value, Id> = Pick<Repository<Value, Id>, "save">;The write half of a repository: depends only on writes.