Skip to content

entityDomain entities, declared once

One declaration yields a type, four derived schemas, behaviour, and a class that is itself a zod schema — with branded fields, immutable data, sealed construction, and Result instead of throws.

entity identity card with a smiling beetroot portraitentity identity card with a smiling beetroot portrait

At a glance ​

ts
import { z } from "zod";
import { Entity } from "@btravstack/entity";

import { Instant, OrgId, Slug } from "./vocabulary.js"; // each brand declared once

class Organization extends Entity("Organization")(
  {
    id: Entity.field(OrgId, { generated: true, immutable: true }),
    slug: Entity.field(Slug, { immutable: true }),
    name: Entity.field(z.string().min(1), { unbranded: true }), // free text
    createdAt: Entity.field(Instant, { generated: true, immutable: true }),
  },
  {
    invariants: [
      Entity.invariant({
        code: "NAME_TOO_LONG",
        ensure: (d) => d.name.length <= 80,
        message: "name must be at most 80 characters",
      }),
    ],
  },
) {
  get greeting(): string {
    return `Welcome, ${this.name}`;
  }
}

// The package reads no clock and generates no id: bind the sources once,
// where your ports already live.
const createOrganization = Organization.factory({
  id: () => ids.next(),
  createdAt: () => clock.now(),
});

const org = createOrganization({ slug, name }).getOrThrow();
await db.insert(org.toJSON()); // exactly the stored shape — never `_tag`
const loaded = Organization.make(row).getOrThrow(); // rows, imports, event folds
const renamed = loaded.update({ name: next }).getOrThrow(); // a NEW entity

For a new id, a version-7 UUID (RFC 9562) sorts by creation time, so a primary-key index stays append-friendly; it is not an access control, and a tenant's rows stay guarded by its policy rather than by its ids. The uuidv7 package is monotonic within a millisecond; Node's own crypto.randomUUIDv7() is not, and recent Node releases alone have it.

ts
import { uuidv7 } from "uuidv7";

const OrgId = z.uuidv7().brand("OrgId"); // a v7 UUID, and nothing else

class Organization extends Entity("Organization")({
  id: Entity.field(OrgId, { generated: true, immutable: true }),
}) {}

const createOrganization = Organization.factory({ id: () => uuidv7() });

Failures are values, not exceptions:

ts
import { P } from "unthrown";

Organization.make({ ...row, name: "" }).match({
  ok: (o) => o,
  errCases: (m) => m.with(P.tag("InvalidEntity"), (e) => e.issues), // [{ path: ["name"], … }]
  defect: (cause) => report(cause), // a bug in domain code, kept separate
});

The design rule the whole package turns on: contracts compose the four plain ZodObjects; domain code composes the class itself. Why.

Released under the MIT License.