Contract

Contract

The contract declares the events journeys react to, the profile fields they read and the subscription topics users can opt out of, as Zod schemas shared by your api and the journey host.

The contract is the agreement between the service that knows what users do (your api) and the engine that acts on it. It lists every event, the shape of each event's payload, the profile fields a journey may read, and the subscription topics. It is written once, with defineContract, in a module both sides import. From that one object the DSL gets its types, the producer gets a typed client that checks payloads before sending them, and the host gets the schemas it validates every request against.

Defining a contract

ts
// src/contract.ts
import { defineContract, templatesFor } from 'sendwend';
import {
  email,
  looseObject,
  number,
  optional,
  strictObject,
  string,
} from 'zod/mini';

export const contract = defineContract({
  events: {
    login: looseObject({ method: string() }),
    purchase: looseObject({ value: number() }),
  },
  profile: strictObject({ email: optional(email()), name: string() }),
  subscriptions: { topics: ['promotions', 'tips'] },
});

/** The DSL's reference tables: `e.login`, `u.name`. */
export const e = contract.events;
export const u = contract.user;

/** Template factories with `topic` typed by this contract. */
export const { emailTemplate, pushTemplate } = templatesFor(contract);

Put this module where both the producer and the host can import it. In a monorepo that is usually a small package of its own; see Monorepo.

Events

Each event is an object schema. looseObject keeps fields you did not declare (useful when the same event also feeds analytics and carries extra properties); strictObject refuses them. Payloads may nest objects and arrays. Event names starting with $ are reserved.

Profile

The profile is a flat object of string, number, boolean, enum and literal fields. Nested objects are not allowed, because a profile is merged one property at a time.

Defaults, transforms, coercion, custom refinements and async checks are refused when the contract is defined, in events and profile alike. The reason: the same schema checks what the producer sends and describes what the engine stores, so its input and output must mean the same JSON. A default would fill values the producer never sent; a transform would store something other than what was checked.

Subscription topics

subscriptions.topics lists content categories a user can opt out of, such as 'promotions' or 'tips'. They are ids only (letters, digits, _, - and .); the display name belongs to your app's i18n. A plain array literal is enough: defineContract keeps the literal types without as const, and the union they form types every email and push template's topic, the config, and JourneyClient.setSubscriptions.

Topics are not channels. A user opts out of a topic per channel (the preference page is topic by channel), or out of a whole channel. Leave the field out when every email and push you send is transactional. Templates and channels covers how topics decide what is sent.

A declared field is a promise about values, not presence

The profile is merged a patch at a time. name: string() therefore means "a name, when there is one, is a string". A user nobody has sent a name for has none, and sending null removes a property.

The DSL takes the declaration at its word and types u.name as string. That holds only if your app writes the field for every user a journey can reach, for example at sign-up. Where it does not (a sign-in that gives no name, an event that arrives before the first profile update, a visitor who never signed in), declare the field optional(string()). Then u.name is string | undefined, a template whose prop is required no longer accepts it, and the template has to decide what to show instead. The engine fills no defaults.

If a required prop reads a profile field the user has no value for, the message is not sent and the journey fails at that step, with an error that names the field. Steps has the details.

Reference tables

contract.events and contract.user are the typed reference tables the rest of the DSL is written against:

  • e.purchase is an event reference. It carries the payload type, so trigger.event(e.purchase, (p) => gt(p.value, 100)) knows p.value is a number.
  • u.name is a profile reference: a pointer to a field, resolved when a step runs. u.userId is always there.

Only declared fields appear. A looseObject event accepts extra keys at runtime, but the reference table offers only the fields written down, so a condition or a template prop cannot read a field the contract never mentioned.

Without a contract, build the tables from TypeScript types. This is handy in tests and small scripts, but you lose runtime validation and topics:

ts
import { event, user } from 'sendwend';

const e = event<{
  demo_signup: Record<never, never>;
  demo_purchase: { value: number };
}>();
const u = user<{ userId: string; email: string }>();

templatesFor(contract)

templatesFor returns emailTemplate and pushTemplate factories with topic typed by the contract. A topic the contract does not declare is an error at the template's own topic line, in the editor and when the module loads, instead of a long type error where the registry meets the config. The bare emailTemplate and pushTemplate exported from sendwend are for a project without a contract, which can only have transactional templates. compileConfig checks every template's topic again either way.

Slack and Discord templates have no topics, so they come straight from sendwend (slackTemplate, discordTemplate).

The producer side

JourneyClient (from sendwend/client) is plain fetch with no dependencies. Given the contract, event names and payloads are typed, and the whole batch is checked before anything is sent:

ts
import { contract } from '@acme/workflow-contract';
import { JourneyClient } from 'sendwend/client';

export const journeys = new JourneyClient({
  contract,
  origin: 'https://workflow.acme.test',
  token: process.env.WORKFLOW_API_TOKEN,
});

await journeys.ingest({
  userId: user.id,
  profile: { email: user.email, name: user.name },
  events: [
    {
      event: 'login',
      payload: { method: 'google' },
      id: `login-${session.id}`,
    },
  ],
});

ingest is the one way to report. The profile and the events it belongs to travel as one batch, and the host merges the profile before recording the events, so a journey an event starts always finds its recipient. With separate calls, an email step could run before the address arrived. Give each event an id you can reproduce; Delivery explains why.

A payload or profile patch the contract refuses throws JourneyValidationError with the field paths, before any request. A request that fails throws JourneyClientError with its status and body. getSubscriptions and setSubscriptions are typed by the contract's topics too. For a producer that must neither lose a report nor wait for the engine, JourneyQueue sends the same batch through a Cloudflare Queue. See Sending events.

What is validated where

The same schemas are checked at several points, because no single one can be trusted to have run:

WhereWhat is checked
In the editorEvent names, payload fields and their types in conditions and template props; u.xxx exists; topics are declared
defineContract, at module loadSchemas are JSON-shaped (no defaults, transforms or refinements); the profile is flat; topic ids are valid and unique
compileConfigTemplate props that read u.xxx name a declared profile field; trigger payload fields read by a workflow are declared for that event; emitted events match the contract
JourneyClient, before sendingEach event is declared and its payload parses; the profile patch has only declared fields with valid values
The host, on /ingestThe same checks again, because the host never trusts that the caller used the SDK. One bad part refuses the whole batch with a 400 and the field paths, before anything is stored, woken or started
A journey's .sendEvent()An emitted event passes the same contract check as one arriving over HTTP
Each sendProps, resolved from the profile, are parsed by the template's own Zod schema

The host's check uses the host's copy of the contract. When a producer is deployed ahead of the host with a new event, the host refuses it until it catches up. With JourneyQueue such a batch is retried with backoff and ends in a dead letter queue if it never passes, rather than being dropped. A host can also run with contractMode: 'report', which logs contract refusals instead of answering 400.