UNPKG

domain-objects

Version:

A simple, convenient way to represent domain objects, leverage domain knowledge, and add runtime validation in your code base.

32 lines (31 loc) 2.13 kB
import type { ZodSchema } from 'zod'; import type { DomainObjectClass } from './DomainObjectClass'; import type { DomainObjectRefBy } from './DomainObjectPragma'; /** * .what = the type of a domain object's `.contract`: its stamped zod schema, plus a `.ref(by)` * method that returns the schema-level reference to this dobj by key * .why = * - `.contract` embeds the WHOLE dobj (`x-domain-object`); `.contract.ref(by)` returns a key-only * reference (`x-domain-object-ref`) — the two live together because a ref *is* a smaller contract * - the `.ref` method is a function property on the schema; it does not appear in `z.toJSONSchema()` * output (proven), so an embedded `X.contract` still round-trips unchanged * .note = call `.ref(by)` on the RAW `.contract`, before any other zod chain op. zod ops like * `.optional()` / `.nullable()` / `.describe()` return a fresh schema WITHOUT `.ref`, so * `X.contract.optional().ref('primary')` fails (a `TypeError` in js, a compile error in ts). * embed the ref first, then chain: `z.object({ x: X.contract.ref('primary') }).optional()`. */ export type DomainObjectContract = ZodSchema<any> & { ref: (by: DomainObjectRefBy) => ZodSchema<any>; }; /** * .what = returns a domain object's `.contract`: its zod `schema` stamped with identity + key metadata * .why = * - lets a domain object's identity survive `z.toJSONSchema()` as an `x-domain-object` pragma * - so a cross-service consumer can name, de-dupe, and reconstruct the dobj from the wire * - mirrors how `serialize` stamps `_dobj` onto its string output * .note = `schema` validates; `contract` identifies. the contract is the schema that knows its own name + keys. * the result is memoized per-class, so repeated access returns the same stamped instance (idempotent). * .note = the returned contract also carries a `.ref(by)` method — `.contract.ref('primary')` returns * the schema-level *reference* to this dobj by key (an `x-domain-object-ref` pragma; see getContractRef). */ export declare const getContract: (dobj: DomainObjectClass) => DomainObjectContract;