Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ jobs:
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
- run: node --import tsx --test test/emails.test.ts test/webhooks.test.ts
# Files listed explicitly: Node 18's --test takes no globs.
- run: node --import tsx --test test/contacts.test.ts test/emails.test.ts test/events.test.ts test/webhooks.test.ts
- name: Built package loads (CJS + ESM)
run: |
node -e "const { Zalify } = require('./dist/index.cjs'); new Zalify('k')"
Expand Down
54 changes: 51 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

The official Node.js / TypeScript SDK for the [Zalify](https://zalify.com) API.

It sends transactional and marketing email from your own domains through Zalify, with retries, idempotency, and typed errors. It has no runtime dependencies and needs Node 18+ (or any runtime with `fetch`).
It sends transactional and marketing email from your own domains through Zalify, keeps contacts in sync, and records your own events for automations, with retries, idempotency, and typed errors. It has no runtime dependencies and needs Node 18+ (or any runtime with `fetch`).

```bash
npm install @zalify/sdk
Expand All @@ -11,7 +11,7 @@ npm install @zalify/sdk
## Before you start

1. In your Zalify workspace, go to **Settings → Email** and add a sending domain, then publish the DNS records it shows (DKIM TXT + MAIL FROM CNAME). Add a `_dmarc` TXT too (`v=DMARC1; p=none` to start).
2. In **Settings → Developer**, create an API key and tick **Send email** (and **Manage contacts** to add contacts). A key can only do what it was created with.
2. In **Settings → Developer**, create an API key and tick **Send email** (**Manage contacts** to add contacts, **Track events** to record events). A key can only do what it was created with.
3. Keep the key on your server, e.g. in `ZALIFY_API_KEY`. Never ship it to a browser.

## Send an email
Expand Down Expand Up @@ -88,6 +88,48 @@ const contact = await zalify.contacts.upsert({
- Adding a contact to a list can start that list's automations, such as a welcome series.
- Calls are safe to retry; the same email updates the same contact.

## Events

Record what people do in your product, e.g. a finished quiz or a confirmed booking, so automations can start on it, filter on its properties and stop on it. The key needs the **Track events** permission (记录事件).

```ts
await zalify.events.track({
event: "Quiz Completed",
customer: { externalId: user.id, email: user.email },
properties: { result: "dry skin", score: 82 },
uniqueId: `quiz:${attempt.id}`,
});
// { id, profileId, duplicate: false, recordedOnly: false }
```

- Any name works and needs no setup: the first time an event arrives it appears in the automation editor, with its properties. Names an integration owns (`shopify_*`, `zalify.*`) are refused (`reserved_event`).
- The person is found by `externalId`, then `email`, then `phone`. Someone new is created as a contact **without** a subscription, so an event never makes anyone marketable.
- Give each event a `uniqueId`: the same id is recorded once, however often you send it. `duplicate: true` means it was already recorded, by an earlier call or by an earlier attempt of this one that the SDK retried.
- Without a `uniqueId`, the API dedupes on the event's content (name, person, `time`, properties). The SDK sets `time` before the first attempt, so its own retries can't record an event twice.
- `time` defaults to now and may be up to 365 days back. Events more than 24 hours old are recorded but never start or end an automation (`recordedOnly: true`), so importing history won't email anyone.
- `properties` is any JSON object up to 64 KB. Automations compare a field the way the condition asks (`82` and `"82"` are the same to "at least 80"), so changing a field's type doesn't break them.

Send up to 100 at once; each event succeeds or fails on its own:

```ts
const { accepted, failed, results } = await zalify.events.trackBatch([
{ event: "Booking Confirmed", customer: { email: "[email protected]" }, uniqueId: "booking:1" },
{ event: "Booking Confirmed", customer: { email: "[email protected]" }, uniqueId: "booking:2" },
]);
for (const item of results) {
if (item.status === "error") console.warn(item.index, item.error.code, item.error.message);
}
```

List the events your automations can use:

```ts
const { events } = await zalify.events.catalog();
// [{ name: "Quiz Completed", source: "custom", canTrigger: true, properties: [{ path: "/score", type: "number", … }], … }]
```

A batch counts as one request against the key's limit of 120 requests a minute, and a workspace can record up to 1,000,000 events a day (`daily_limit`).

## Errors, retries and idempotency

Every failure is a `ZalifyError` with a stable `code`, the HTTP `status`, and `details` for validation errors.
Expand All @@ -108,7 +150,7 @@ try {
| code | status | meaning |
| --- | --- | --- |
| `unauthorized` | 401 | missing or invalid API key |
| `missing_scope` | 403 | the key lacks the permission: **Send email** or **Manage contacts** |
| `missing_scope` | 403 | the key lacks the permission: **Send email**, **Manage contacts** or **Track events** |
| `email_not_enabled` | 403 | the workspace has no sending set up yet |
| `contacts_not_enabled` | 403 | the workspace has no contacts set up yet |
| `list_not_found` | 404 | a list in `lists` isn't in your workspace (nothing was written) |
Expand All @@ -119,10 +161,16 @@ try {
| `idempotency_conflict` | 409 | the idempotency key was used for a different request |
| `rate_limited` | 429 | over 120 requests a minute for this key (a batch counts once) |
| `new_recipient_limit` | 429 | the recipient is new to your workspace and today's allowance of new recipients is used; it resets at 00:00 UTC (`retryAfter`) |
| `invalid_event` | 422 | an event was refused, e.g. properties over 64 KB or `time` out of range (see `field`) |
| `reserved_event` | 422 | the event name belongs to an integration (`shopify_*`, `zalify.*`, …) |
| `payload_too_large` | 413 | the body is over 2 MB (one event) or 8 MB (a batch); not retried |
| `daily_limit` | 429 | the workspace recorded 1,000,000 events today (UTC) |
| `unavailable` | 503 | temporary; safe to retry with the same idempotency key |

The SDK retries `rate_limited`, `unavailable`, `idempotency_in_progress`, timeouts and network errors on its own, up to `maxRetries` (default 3). It honors `Retry-After`, and won't wait longer than `maxRetryDelayMs` (default 10 s). Retries always reuse the request's idempotency key, so they never send twice.

For events, give each one a `uniqueId` rather than an `idempotencyKey`. If you do pass an `idempotencyKey` to `track`/`trackBatch`, use a new one for every call: events without a `uniqueId` take `<key>` (or `<key>:<index>` in a batch) as their dedupe key, so reusing a key across different batches makes the later ones come back as duplicates without being recorded.

Pass your own `idempotencyKey` per logical email, such as `reset:${tokenId}` or `invite:${inviteId}`. Then even retrying the whole call after a crash or deploy sends once. Without one, the SDK makes a key per call, which only covers its own retries.

## Options
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"name": "@zalify/sdk",
"version": "0.4.0",
"version": "0.5.0",
"description": "Official Node.js / TypeScript SDK for the Zalify API",
"keywords": ["zalify", "email", "transactional email", "contacts", "sdk"],
"keywords": ["zalify", "email", "transactional email", "contacts", "events", "sdk"],
"homepage": "https://github.com/zalify/zalify-node#readme",
"repository": {
"type": "git",
Expand Down
5 changes: 4 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Contacts } from "./contacts";
import { Emails } from "./emails";
import { Events } from "./events";
import { Webhooks } from "./webhooks";
import type { HttpConfig } from "./http";

export const VERSION = "0.4.0";
export const VERSION = "0.5.0";

export type ZalifyOptions = {
/** A Zalify Public API key (`zalify_api_…`). Defaults to `ZALIFY_API_KEY`. */
Expand All @@ -25,6 +26,7 @@ export type ZalifyOptions = {
export class Zalify {
readonly emails: Emails;
readonly contacts: Contacts;
readonly events: Events;
readonly webhooks: Webhooks;

constructor(apiKeyOrOptions?: string | ZalifyOptions) {
Expand Down Expand Up @@ -58,6 +60,7 @@ export class Zalify {
};
this.emails = new Emails(http);
this.contacts = new Contacts(http);
this.events = new Events(http);
this.webhooks = new Webhooks(options.webhookSecret);
}
}
9 changes: 9 additions & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ export type ZalifyErrorCode =
| "unverified_sender"
| "not_subscribed"
| "new_recipient_limit"
| "payload_too_large"
| "invalid_event"
| "reserved_event"
| "undeclared_event"
| "daily_limit"
| "suppressed"
| "rejected"
| "network_error"
Expand All @@ -32,6 +37,8 @@ export class ZalifyError extends Error {
readonly status: number;
/** Field-level validation messages for `invalid_request`. */
readonly details?: string[];
/** The offending field for event errors, e.g. `customer.externalId`. */
readonly field?: string;
/** Seconds the API asked to wait (429, 409 in progress). */
readonly retryAfter?: number;

Expand All @@ -40,13 +47,15 @@ export class ZalifyError extends Error {
code: ZalifyErrorCode;
status: number;
details?: string[];
field?: string;
retryAfter?: number;
}) {
super(init.message);
this.name = "ZalifyError";
this.code = init.code;
this.status = init.status;
if (init.details) this.details = init.details;
if (init.field) this.field = init.field;
if (init.retryAfter !== undefined) this.retryAfter = init.retryAfter;
}

Expand Down
202 changes: 202 additions & 0 deletions src/events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
import { ZalifyError } from "./errors";
import { type HttpConfig, request } from "./http";

export type EventCustomer = {
/** Your own id for the person (scoped to your workspace). */
externalId?: string;
email?: string;
/** E.164, e.g. `+14155550123`. */
phone?: string;
};

export type EventInput = {
/**
* The event name, e.g. `Quiz Completed` (1–64 characters, as written).
* Names owned by an integration (`shopify_*`, `zalify.*`, …) are refused.
* No registration needed: a new name shows up in the event catalog once
* it arrives.
*/
event: string;
/**
* Who did it: found by `externalId`, then `email`, then `phone`. Someone
* new is created with no subscription or consent. At least one is needed.
*/
customer: EventCustomer;
/** Any JSON object (≤ 64 KB, ≤ 5 levels deep). Flows filter on it. */
properties?: Record<string, unknown>;
/** An amount the event carries, e.g. an order total. */
value?: number;
/** ISO 4217 code for `value`, e.g. `USD`. */
valueCurrency?: string;
/**
* Your dedupe key: the same `uniqueId` is recorded once, however often
* it's sent. Without one, the API dedupes on the event's content (name,
* person, time, properties); the SDK fixes `time` before the first
* attempt so its own retries resend the same event.
*/
uniqueId?: string;
/**
* When it happened (default: now). Up to 365 days back; events more than
* 24 hours old are recorded but never start or end a flow.
*/
time?: Date | string;
};

export type TrackEventResult = {
id: string;
profileId: string;
/**
* The event was already recorded, by an earlier call or by an earlier
* attempt of this one that the SDK retried. Either way it's recorded once.
*/
duplicate: boolean;
/** More than 24 hours old: recorded, but no flow starts or ends on it. */
recordedOnly: boolean;
};

export type TrackBatchItem =
| {
index: number;
status: "accepted" | "duplicate";
id: string;
profileId: string;
duplicate: boolean;
recordedOnly: boolean;
}
| {
index: number;
status: "error";
error: { code: string; message: string; field?: string };
};

export type TrackBatchResult = {
accepted: number;
duplicates: number;
failed: number;
/** One per event, in request order. */
results: TrackBatchItem[];
};

export type CatalogEventProperty = {
/** JSON pointer into the event's properties, e.g. `/quiz/score`. */
path: string;
/** The type last seen; a hint only, flows choose their own comparison. */
type: "string" | "number" | "boolean" | "date" | "list" | "object";
label: { en: string; zh: string } | null;
/** Your own events: when the key was last seen. */
lastSeenAt: string | null;
};

export type CatalogEvent = {
name: string;
label: { en: string; zh: string } | null;
/** The integration (`shopify`, `zalify`, …) or `custom` for your own events. */
source: string;
canTrigger: boolean;
canExit: boolean;
valuePath: string | null;
properties: CatalogEventProperty[];
available: boolean;
/** e.g. `integration_not_connected`. */
unavailableReason: string | null;
lastSeenAt: string | null;
eventCount: number | null;
};

export type EventCatalog = { events: CatalogEvent[] };

export type TrackOptions = {
/**
* Optional. Retrying the whole call with the same key records each event
* once: an event without a `uniqueId` takes the key as its dedupe key
* (`<key>:<index>` on a batch). Use a new key for every call: reusing one
* across different batches makes event N of each batch collide, and the
* later ones come back as duplicates without being recorded. Prefer
* `uniqueId` on the events themselves. At most 255 characters (251 on a
* batch).
*/
idempotencyKey?: string;
};

const MAX_IDEMPOTENCY_KEY = 255;

const invalid = (message: string, field?: string) =>
new ZalifyError({ message, code: "invalid_request", status: 0, field });

/**
* The event as sent. `time` is fixed here, once, before the first attempt
* (now when not given), so a retry resends an identical body and the API's
* content dedupe records the event once.
*/
const toBody = (input: EventInput, now: string, field = "time") => {
let time: string;
if (input.time === undefined) {
time = now;
} else if (input.time instanceof Date) {
if (Number.isNaN(input.time.getTime())) {
throw invalid("time is an invalid Date", field);
}
time = input.time.toISOString();
} else {
time = input.time;
}
return { ...input, time };
};

const checkKey = (key: string | undefined, max: number) => {
if (key !== undefined && key.length > max) {
throw invalid(`idempotencyKey must be ${max} characters or fewer`);
}
};

export class Events {
constructor(private readonly http: HttpConfig) {}

/**
* Record one event. Needs a key with Track events. Counts as one request
* against the key's rate limit.
*/
async track(
input: EventInput,
options: TrackOptions = {}
): Promise<TrackEventResult> {
checkKey(options.idempotencyKey, MAX_IDEMPOTENCY_KEY);
const body = toBody(input, new Date().toISOString());
return request<TrackEventResult>(this.http, {
method: "POST",
path: "/events",
body,
idempotencyKey: options.idempotencyKey,
});
}

/**
* Record up to 100 events in one request; each succeeds or fails on its
* own (check `results`). The whole batch counts as one request against
* the rate limit.
*/
async trackBatch(
inputs: EventInput[],
options: TrackOptions = {}
): Promise<TrackBatchResult> {
checkKey(options.idempotencyKey, MAX_IDEMPOTENCY_KEY - 4);
const now = new Date().toISOString();
const events = inputs.map((input, index) =>
toBody(input, now, `events.${index}.time`)
);
return request<TrackBatchResult>(this.http, {
method: "POST",
path: "/events/batch",
body: { events },
idempotencyKey: options.idempotencyKey,
});
}

/** The events your flows can start, filter and exit on. */
async catalog(): Promise<EventCatalog> {
return request<EventCatalog>(this.http, {
method: "GET",
path: "/events/catalog",
});
}
}
7 changes: 7 additions & 0 deletions src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,13 @@ async function once<T>(config: HttpConfig, init: RequestInit): Promise<T> {
details: Array.isArray(payload.details)
? payload.details.filter((d): d is string => typeof d === "string")
: undefined,
field:
payload.details &&
typeof payload.details === "object" &&
!Array.isArray(payload.details) &&
typeof (payload.details as { field?: unknown }).field === "string"
? (payload.details as { field: string }).field
: undefined,
retryAfter: parseRetryAfter(response.headers.get("retry-after")),
});
}
Loading
Loading