AGENT SKILL

ddd-ts-fp

ACTIVATE when modeling DDD aggregates, value objects and domain logic in TypeScript using functional patterns. ACTIVATE for 'aggregate', 'smart constructor', 'make*', 'validation pipeline', 'enrichment', 'domain handler' in TypeScript. Provides TypeScript-specific examples for cross-language functional DDD principles defined in craft:ddd-fp-principles. DO NOT use for: infrastructure code, general FP patterns (see ts-functional), OOP modeling (see ts-oop).

License 许可
MIT
最近更新
2026-10-13
Stars
★ 9
Forks
2

01 前言 Front Matter

name
ddd-ts-fp
description
ACTIVATE when modeling DDD aggregates, value objects and domain logic in TypeScript using functional patterns. ACTIVATE for 'aggregate', 'smart constructor', 'make*', 'validation pipeline', 'enrichment', 'domain handler' in TypeScript. Provides TypeScript-specific examples for cross-language functional DDD principles defined in craft:ddd-fp-principles. DO NOT use for: infrastructure code, general FP patterns (see ts-functional), OOP modeling (see ts-oop).

02 资源文件 1

03 SKILL.md 正文

DDD Functional Patterns — TypeScript

The cross-language functional DDD principles (immutable aggregates, curried operations, smart constructors, validation/enrichment pipelines, handler orchestration) are defined in craft:ddd-fp-principles. This skill keeps TypeScript-specific syntax and patterns.

TS-specific: Immutable Aggregate as readonly Type

type Receipt = {
  readonly id: ReceiptId;
  readonly tenantId: TenantId;
  readonly addresses: readonly Address[];
  readonly period: Period;
  readonly amount: number;
  readonly createdAt: Date;
};

const addAddress =
  (address: Address) =>
  (receipt: Receipt): Receipt => ({
    ...receipt,
    addresses: [...receipt.addresses, address],
  });

Each operation is a curried function returning a new aggregate (or a Result). Compose with pipe and chain. Measure: no domain operation in this file's own examples takes its data and the aggregate in one non-curried argument list; every operation curries at least once before receiving the aggregate.

When implementing aggregate operations, pipe composition, or nested immutable updates, read references/ddd-functional-examples.md for complete patterns.

TS-specific: Validation Pipeline

A single check keeps the type; the composition is what mints the branded one. That is where the proof enters the type system, so nothing downstream has to trust a call order.

type Check<T> = (input: T) => Result<T, DomainError>;
type Validator<Raw, Valid extends Raw> = (input: Raw) => Result<Valid, DomainError>;

// Each check keeps the type; the last step BUILDS the narrower shape out of the
// primitives it just proved, so the pipeline narrows by construction, never by assertion.
const validateCreateReceipt: Validator<CreateReceiptCommand, ValidCreateReceiptCommand> = (cmd) =>
  pipe(
    cmd,
    validatePeriod,
    chain(validateAmount),
    chain(validateLease),
    chain(buildValidCreateReceipt),
  );

When building validation or enrichment pipelines, read references/ddd-functional-examples.md for complete pipeline implementations.

TS-specific: Enrichment Pipeline

Same pipe/chain machinery, applied at the system boundary to transform external data into domain objects.

When building enrichment pipelines, read references/ddd-functional-examples.md for examples with enrichers.

TS-specific: Handler Pattern

The handler orchestrates: retrieval, validation, transformation, persistence.

validate(command)
  → load(aggregate)
  → pure domain operations
  → persist

When writing domain handlers, read references/ddd-functional-examples.md for the complete handler pattern with error handling.

TS-specific: Handler Parameter Order

export type AddAddressHandler = (command: AddAddressCommand) => Promise<Result<Receipt, DomainError>>;

const addAddressHandler =
  (clock: Clock) =>
  async (command: AddAddressCommand): Promise<Result<Receipt, DomainError>> => {
    const validated = validateAddAddress(command);
    if (isFailure(validated)) return validated;

    return buildReceipt(clock.now())(validated.value);
  };

Dependencies (clock) come first as separate arguments, never as one destructured object. Measure: no handler example in this skill destructures its dependencies into a single options object; each dependency is its own curried argument.

The command comes last. A model-level operation instead takes its data first and the aggregate last: addAddress(address)(receipt).

TS-specific: Result vs Bare Model

An operation returns a Result only when it can fail; a total transition returns the bare model. Measure: no total operation in this skill's examples wraps its return type in Result, and no fallible operation returns the bare model.

// Fallible — the amount could be negative
const withAmount = (amount: number) => (receipt: Receipt): Result<Receipt, DomainError> => ...;

// Total — appending never fails
const addAddress = (address: Address) => (receipt: Receipt): Receipt => ...;

TS-specific: Entity Folder and Aggregate-Only Operations

An entity carrying identity has its own Models/Entities/<Name>/ folder, and its operations take and return the aggregate, never the entity. Measure: no entity operation in this skill's examples takes or returns the bare entity; updateAddress both receives and returns Customer, never Address.

// plugins/../Models/Entities/Address/updateAddress.ts
const updateAddress =
  (addressId: AddressId, patch: AddressPatch) =>
  (customer: Customer): Customer => ({
    ...customer,
    addresses: customer.addresses.map((a) => (a.id === addressId ? { ...a, ...patch } : a)),
  });

TS-specific: Validator and Maker

Validator files carry the invariants and return a branded command; the maker maps and normalizes a value the type system already proves valid, so it never fails. Measure: no maker in this skill's examples returns a Result; makeAddress's signature is total because ValidAddAddressCommand is the proof, not a runtime check.

// ValidAddAddressCommand.ts — a real shape, not a tag on the raw one
type ValidAddAddressCommand = {
  readonly street: NonEmptyString;
  readonly city: NonEmptyString;
};

// AddressValidator.ts — fallible, and it builds the narrower value rather than asserting it
const validateAddress = (command: AddAddressCommand): Result<ValidAddAddressCommand, DomainError> =>
  pipe(
    nonEmpty(command.street),
    chain((street) => map(nonEmpty(command.city), (city) => ({ street, city }))),
  );

// makeAddress.ts — curried on its context, total because its input is the proof
const makeAddress =
  (addressId: AddressId, createdAt: Date) =>
  (command: ValidAddAddressCommand): Address => ({
    id: addressId,
    street: command.street,
    city: command.city,
    createdAt,
  });

makeAddress(addressId, createdAt)(rawCommand) does not compile, and that is the entire point of the split. A maker that accepted AddAddressCommand would be total in its signature only — the invariant would live in a call-order convention nothing enforces. See craft:ddd-fp-principles §3 for why a single fallible constructor is the default, and what justifies splitting it.

The object literal is constructed, so the compiler checks it and the validator asserts nothing. Every remaining assertion sits in the primitive's own constructor — nonEmpty returns Brand<string, 'NonEmptyString'>, minted once in the kernel (ts-conventions — Branded Types). That is what keeps as out of the domain, per C138, instead of widening the rule to admit it.

TS-specific: CQRS Model Copies

Each CQRS side owns its own copy of the model; the read copy is deliberately narrowed. Measure: the Query-side Address type in this file's example carries fewer fields than the Command-side one, never the same shape imported from one file.

// Command/Models/Address.ts — full write shape
type Address = { readonly street: string; readonly city: string; readonly geo: GeoPoint /* … */ };

// Query/Models/Address.ts — narrowed read shape
type Address = { readonly street: string; readonly city: string };

TS-specific: Command DTO Duplication Across Features

The command DTO repeats per feature; two features are never factored together just because their types are identical. Measure: onboard-customer's AddAddressCommand and relocate-customer's AddAddressCommand stay two files in this skill's example, never one shared import.

// features/onboard-customer/AddAddressCommand.ts
type AddAddressCommand = { readonly street: string; readonly city: string };

// features/relocate-customer/AddAddressCommand.ts — same shape, its own file
type AddAddressCommand = { readonly street: string; readonly city: string };

TS-specific: Repository Receives the Whole Aggregate

The repository receives the whole aggregate, never a patch nor a list of fields. Cost: a repository interface that declares an update method accepting a patch or list of fields forces every caller to reconstruct the invariant the aggregate already proved, one call site at a time.

export type CustomerRepository = {
  save: (customer: Customer) => Promise<void>;
};

// ❌ AVOID — no partial-update method
// update: (id: CustomerId, patch: Partial<Customer>) => Promise<void>;

Quick Reference (TS-specific FP)

Element Convention
Aggregate Immutable readonly type, no class
Operations Pure curried functions
Validator Fallible; owns the invariants and returns a branded type
Maker Total; takes the branded type, which is what earns the totality
Updates Spread operator, never mutate
Composition pipe(aggregate, op1, op2, op3)
Fallible composition pipe(aggregate, op1, chain(op2))
Validation Composable Validator<Raw, Valid> pipeline; narrows the type
Enrichment Pipeline at system boundary
Handler Orchestrator: validate → load → domain → persist
Handler args Dependencies positional, then the Command/Query last
Model args Data first, aggregate last (op(data)(aggregate))
Command handler type export type XHandler = (command: XCommand) => Promise<Result<T, E>>

04 同仓库更多 Skills

FabienSalles
FabienSalles/claude-marketplace

vitest-test-conventions

ACTIVATE when writing Vitest tests, creating test files, using vi.fn()/vi.mock()/vi.spyOn(), or test factories. ACTIVATE for 'Vitest', 'it.each', 'NestJS testing module', 'supertest', 'vi.fn', 'vi.mock', 'spyOn'. Provides Vitest/NestJS-specific testing patterns; cross-language testing principles (DAMP, AAA, spy over mock, what NOT to test) live in craft:testing-principles. DO NOT use for: node:test files (a file importing node:test) or a project whose tests run under node --test (see node-test:node-test-conventions), TDD workflow/iterations (see vitest:vitest-tdd-workflow), PHP/PHPUnit tests (see phpunit:php-test-conventions).

★ 9
FabienSalles
FabienSalles/claude-marketplace

vitest-tdd-workflow

ACTIVATE when building new features, endpoints, or user stories using TDD with Vitest in a TypeScript/NestJS context. ACTIVATE for '/feature-tdd-dev', 'TDD', 'red-green-refactor' in TS context. Provides Vitest/NestJS-specific TDD examples and commands; cross-language TDD workflow (cross-layer iterations, RED-GREEN-REFACTOR, working app, bug-fix-first-test, mocks-hiding-bugs) lives in craft:tdd-workflow-principles. DO NOT use for: node:test files (a file importing node:test) or a project whose tests run under node --test (see node-test:node-test-conventions), test writing conventions (see vitest:vitest-test-conventions), PHP TDD (see phpunit:php-tdd-workflow).

★ 9
FabienSalles
FabienSalles/claude-marketplace

ts-refactoring

ACTIVATE when refactoring TypeScript code. ACTIVATE for 'refactor', 'extract', 'redesign', 'simplify', or 'clean up' in a TypeScript / Node / NestJS context. This skill provides TS-specific examples for the cross-language refactoring rules defined in craft:refactoring-principles. DO NOT use for: writing new features from scratch, general OOP patterns (see ts-oop).

★ 9
FabienSalles
FabienSalles/claude-marketplace

ts-ports-adapters

ACTIVATE when a TypeScript codebase with no dependency-injection container has to declare a port and wire its adapter — a repository, a clock, an id generator, an event dispatcher the domain depends on. ACTIVATE for 'port', 'adapter', 'SPI', 'dependency inversion' or 'composition root' in a codebase that wires its dependencies by hand. Covers: the port as a type of functions in the domain layer, the adapter as an object literal annotated with it, the handler that takes its dependencies first and its data second, the composition root in the infrastructure layer, and the in-memory stub that substitutes for the adapter in a unit test. DO NOT use for: NestJS, or any container-based DI with decorators and tokens (see nest-ddd-conventions), aggregate operations and smart constructors (see ddd-ts-fp), the Result type itself (see ts-functional).

★ 9
FabienSalles
FabienSalles/claude-marketplace

ts-oop

ACTIVATE when designing TypeScript classes, and the value objects or collections modelled as classes, or when the user asks about object design, encapsulation, Tell Don't Ask, or Symbol.iterator. Provides TS-specific examples for the cross-language OOP rules defined in craft:oop-principles, plus TS-specific patterns (Symbol.iterator, branded types for primitive identifiers). DO NOT use for: a value object or an aggregate modelled as an immutable record rather than a class (see ddd-ts-fp), refactoring methodology (see ts-refactoring).

★ 9
FabienSalles
FabienSalles/claude-marketplace

ts-layer-boundaries

ACTIVATE when wiring a Worker entry point, a Router, a controller, or a domain event consumer in a TypeScript CQRS codebase, or when deciding where a port belongs. ACTIVATE for 'composition root', 'layer boundary', 'ESLint zones', 'domain must not import infrastructure'. Covers: the *Worker.ts composition root, the curried consumer, Router wiring of command endpoints, the five-gesture controller, the domain-to-infrastructure import boundary enforced by ESLint, infrastructure-only ports, in-memory doubles for every port, the read-can-reach-write asymmetry, and read endpoints going through a domain handler. DO NOT use for: the port's own shape and adapter binding (see ts-ports-adapters), the Result type (see ts-functional), domain event structure (see ts-ddd-events).

★ 9