@marlinjai/mail-sdk 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 marlinjai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,293 @@
1
+ # @marlinjai/mail-sdk
2
+
3
+ The typed client for the Lumitra Mail v1 Application Programming Interface (API).
4
+ Every request and response shape comes from `@marlinjai/mail-contract`
5
+ (workspace dependency): this package only adds the Hypertext Transfer Protocol
6
+ (HTTP) mechanics on top (authentication, retries, idempotency, cursor
7
+ pagination). Nothing here redefines a shape the contract already owns.
8
+
9
+ Runs in Node 20+ (Node 18/19 need `--experimental-global-webcrypto` for
10
+ `crypto.randomUUID`, which the SDK uses to mint idempotency keys) and on every
11
+ major edge runtime: only `fetch`, `FormData`, `AbortController` and
12
+ `globalThis.crypto` are used, no `node:` built-ins.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pnpm add @marlinjai/mail-sdk
18
+ ```
19
+
20
+ ## Quick start: a server-side client in a Next.js app (ŌPUNTIA's Studio)
21
+
22
+ ŌPUNTIA's admin keeps its own people and pushes recipients per mailing; the mail
23
+ service is its mail infrastructure. A workspace application programming
24
+ interface (API) key is created once in the mail service's dashboard and stored
25
+ as a server-only secret (never shipped to the browser).
26
+
27
+ ```ts
28
+ // lib/mail-client.ts (server-only module)
29
+ import { createMailClient } from '@marlinjai/mail-sdk';
30
+
31
+ export const mail = createMailClient({
32
+ baseUrl: process.env.MAIL_SERVICE_URL!, // e.g. https://mail.lumitra.co
33
+ apiKey: process.env.MAIL_API_KEY!, // a workspace key, scope "send" is enough to mail people
34
+ });
35
+ ```
36
+
37
+ ```ts
38
+ // app/actions/send-programme-update.ts ("use server")
39
+ import { mail } from '@/lib/mail-client';
40
+
41
+ export async function sendProgrammeUpdate(document: unknown, recipients: { email: string; external_id: string }[]) {
42
+ const mailing = await mail.mailings.create({
43
+ subject: 'This week at ŌPUNTIA',
44
+ topic: 'programme-updates',
45
+ provider_id: process.env.MAIL_PROVIDER_ID!,
46
+ document: document as never, // the editor's TemplateDocument
47
+ });
48
+
49
+ await mail.mailings.addRecipients(mailing.id, { recipients });
50
+ await mail.mailings.send(mailing.id);
51
+ return mailing;
52
+ }
53
+ ```
54
+
55
+ Every mutating call carries its own `Idempotency-Key` automatically, reused
56
+ across retries, so calling `sendProgrammeUpdate` again after a network blip
57
+ never double-sends: a retried `mailings.send` with the same key returns the
58
+ first response instead of starting a second send.
59
+
60
+ ### Paginating a list
61
+
62
+ ```ts
63
+ for await (const contact of mail.paginate('contacts.list', { query: { topic: 'programme-updates' } })) {
64
+ console.log(contact.email);
65
+ }
66
+ ```
67
+
68
+ `paginate` only accepts operations whose response is a cursor page (`{ data,
69
+ next_cursor }`); passing `billing.plans` or `contactProperties.list`, which
70
+ return a bare `{ data }` array, is a compile error, not a runtime surprise.
71
+
72
+ ### Anything the friendly methods do not cover
73
+
74
+ Every namespaced method (`mail.mailings.*`, `mail.contacts.*`, and so on) is a
75
+ thin wrapper over `mail.request(operationId, { params, query, body })`, which
76
+ accepts any operation id from `@marlinjai/mail-contract`'s route table and is
77
+ typed from the same source. Reach for it directly for an operation this
78
+ package has not wrapped yet, or to pass a raw `AbortSignal`.
79
+
80
+ ```ts
81
+ const workspace = await mail.request('workspace.get');
82
+ ```
83
+
84
+ ## The dashboard variant: server-only, per signed-in person
85
+
86
+ The mail service's own dashboard (`apps/dashboard`) signs people in through
87
+ auth-brain and calls the service with its own service token plus the signed-in
88
+ person's auth-brain subject and workspace. **`createDashboardMailClient` must
89
+ never run in a browser**: its service token authenticates as the whole
90
+ dashboard, not one person, and shipping it to a browser bundle would leak it to
91
+ every visitor. The constructor throws immediately if it detects a `window`
92
+ global, but the real guarantee has to come from where you call it: only from
93
+ server-side code (a Next.js server action, route handler or server component).
94
+
95
+ ```ts
96
+ // lib/dashboard-mail-client.ts (server-only module)
97
+ import { createDashboardMailClient } from '@marlinjai/mail-sdk';
98
+
99
+ const dashboardMail = createDashboardMailClient({
100
+ baseUrl: process.env.MAIL_SERVICE_URL!,
101
+ serviceToken: process.env.MAIL_DASHBOARD_SERVICE_TOKEN!,
102
+ });
103
+
104
+ export function mailClientFor(subject: string, workspaceId: string) {
105
+ return dashboardMail.forUser({ subject, workspaceId });
106
+ }
107
+ ```
108
+
109
+ ```ts
110
+ // app/dashboard/mailings/actions.ts ("use server")
111
+ import { auth } from '@/lib/auth-brain'; // however the app resolves the signed-in person
112
+ import { mailClientFor } from '@/lib/dashboard-mail-client';
113
+
114
+ export async function pauseMailing(mailingId: string) {
115
+ const session = await auth();
116
+ const client = mailClientFor(session.subject, session.workspaceId);
117
+ return client.mailings.pause(mailingId);
118
+ }
119
+ ```
120
+
121
+ The service checks that `subject`'s membership and role in `workspaceId` on
122
+ every call; the SDK never assumes the caller is authorized, it only carries the
123
+ headers.
124
+
125
+ ### Creating a workspace: the one call with no workspace yet
126
+
127
+ `workspaces.create` and `workspaces.list` are `dashboard`-access routes: they
128
+ run before the signed-in person has a workspace to be scoped to, so
129
+ `workspaceId` is optional on `forUser` for exactly these two calls (every other
130
+ route needs it, and the service checks membership against it on every call).
131
+
132
+ ```ts
133
+ const client = dashboardMail.forUser({ subject: session.subject }); // no workspaceId yet
134
+ const workspace = await client.workspaces.create({
135
+ slug: 'opuntia',
136
+ name: 'ŌPUNTIA',
137
+ owner: { email: session.email, name: session.name },
138
+ });
139
+ // From here on, calls for this workspace pass its id: forUser({ subject, workspaceId: workspace.id }).
140
+ ```
141
+
142
+ Adding a person to an existing workspace binds them by their auth-brain
143
+ subject, not an email invite (the service never sees a login, so the caller
144
+ resolves the person first):
145
+
146
+ ```ts
147
+ await client.members.add({ subject: person.subject, email: person.email, name: person.name, role: 'editor' });
148
+ ```
149
+
150
+ ## A webhook receiver
151
+
152
+ The webhook signature helpers and the `WebhookEvent` union are re-exported from
153
+ `@marlinjai/mail-contract`, so a receiver needs only this one package.
154
+
155
+ ```ts
156
+ // app/api/mail-webhooks/route.ts
157
+ import { WEBHOOK_SIGNATURE_HEADER, WEBHOOK_TIMESTAMP_HEADER, WebhookEvent, verifyWebhook } from '@marlinjai/mail-sdk';
158
+
159
+ export async function POST(req: Request) {
160
+ const rawBody = await req.text();
161
+ const check = await verifyWebhook({
162
+ secret: process.env.MAIL_WEBHOOK_SECRET!,
163
+ rawBody,
164
+ signatureHeader: req.headers.get(WEBHOOK_SIGNATURE_HEADER),
165
+ timestampHeader: req.headers.get(WEBHOOK_TIMESTAMP_HEADER),
166
+ });
167
+ if (!check.ok) return new Response(check.reason, { status: 401 });
168
+
169
+ const event = WebhookEvent.parse(JSON.parse(rawBody));
170
+ // Deliveries may repeat: deduplicate on event.id before acting on it.
171
+ switch (event.type) {
172
+ case 'message.sent':
173
+ // archive event.data.html next to your own record of the send
174
+ break;
175
+ case 'contact.unsubscribed':
176
+ // mirror the unsubscribe into your own system of record
177
+ break;
178
+ case 'contact.resubscribed':
179
+ // the person opted back in on the hosted page: lift your mirror of the unsubscribe
180
+ break;
181
+ // ...
182
+ }
183
+ return new Response(null, { status: 204 });
184
+ }
185
+ ```
186
+
187
+ ## Errors
188
+
189
+ Every failure is one of four typed classes; a switch on `instanceof` (or on
190
+ `MailApiError.code`) is always enough, never on `.message`, which is for
191
+ humans:
192
+
193
+ | Class | When |
194
+ | --- | --- |
195
+ | `MailApiError` | The service answered a non-2xx response. Carries `code` (`ErrorCode` from the contract), `status`, `message`, `details` and `requestId`. |
196
+ | `MailNetworkError` | The request never reached the service (Domain Name System (DNS), Transport Layer Security (TLS), connection reset). |
197
+ | `MailTimeoutError` | A single attempt exceeded `timeoutMs`. |
198
+ | `MailResponseValidationError` | The service answered 2xx but the body did not match the contract's schema (a service bug or a contract version mismatch). Never retried: retrying an already-succeeded mutating call risks a duplicate. |
199
+
200
+ ```ts
201
+ import { MailApiError } from '@marlinjai/mail-sdk';
202
+
203
+ try {
204
+ await mail.mailings.send(mailingId);
205
+ } catch (err) {
206
+ if (err instanceof MailApiError && err.code === 'missing_unsubscribe_url') {
207
+ // the document has no {{unsubscribe_url}}; show the editor error, don't retry
208
+ }
209
+ throw err;
210
+ }
211
+ ```
212
+
213
+ ## Retries
214
+
215
+ Retries apply only to network failures, request timeouts, and responses whose
216
+ error `code` is in the contract's `RETRYABLE_ERRORS` (`rate_limited`,
217
+ `provider_error`, `internal_error`, `service_unavailable`). Every other error,
218
+ including `daily_budget_exhausted` and `plan_limit_reached` even though both
219
+ are HTTP 429, is never retried: retrying them would not help, since the
220
+ condition they report does not clear on its own within the request's lifetime.
221
+ For the same reason a `service_unavailable` whose `details.reason` is
222
+ `billing_not_configured` (checkout or the portal while Stripe is not set up) is
223
+ answered at once; the contract's `isRetryableError` holds the rule.
224
+
225
+ - Exponential backoff with full jitter, capped at 8 seconds between attempts.
226
+ - `Retry-After` (seconds or a Hypertext Transfer Protocol (HTTP) date) is
227
+ honoured when the service sends it, capped at 60 seconds so a large value can
228
+ never hang a caller.
229
+ - A fresh `Idempotency-Key` is minted once per call (via `crypto.randomUUID()`)
230
+ and reused across every attempt of that call: this is what makes a retry safe.
231
+ A caller may also pass its own key through the last `opts` argument any
232
+ mutating method takes (`{ idempotencyKey }`).
233
+ - `maxRetries` (default 3) and `timeoutMs` (default 10000, per attempt) are
234
+ configurable on `createMailClient`.
235
+ - A caller-provided `AbortSignal` (also in the last `opts` argument) is never
236
+ itself retried: an abort you asked for propagates immediately.
237
+
238
+ ## Response headers: usage warnings
239
+
240
+ A successful call's headers are available through `onResponse` in the last
241
+ `opts` argument. It receives the status, the request id, the raw `Headers`,
242
+ and `usageWarnings`: the `x-mail-usage-warning` header (sent on
243
+ `mailings.send` and `mailings.test` once the workspace is at 80 percent of a
244
+ plan limit) already parsed into `{ metric, used, limit }` entries.
245
+
246
+ ```ts
247
+ let warnings: UsageWarningHeaderEntry[] = [];
248
+ await mail.mailings.send(mailingId, { onResponse: (meta) => (warnings = meta.usageWarnings) });
249
+ if (warnings.length > 0) {
250
+ // e.g. "messages: 8200 of 10000 this period"; show it before the next send
251
+ }
252
+ ```
253
+
254
+ `onResponse` runs once the body has parsed and validated, just before the call
255
+ returns; it is not called for a failed call (a `MailApiError` carries its own
256
+ status and request id). A limit that is already exceeded fails the call
257
+ with `plan_limit_reached` (HTTP 429), whose `details` name the `metric`, the
258
+ `used` count, the `limit` and the `plan`.
259
+
260
+ ## Health check
261
+
262
+ `client.health()` hits the service's liveness probe (`HEALTH_PATH`, outside
263
+ `/v1`, no credentials) and never throws: a network failure or a non-2xx status
264
+ both resolve `false`. Meant for a caller polling "is it up" (a deploy script, a
265
+ monitor), not for anything that needs a typed error.
266
+
267
+ ```ts
268
+ if (!(await mail.health())) {
269
+ // back off and retry, or alert
270
+ }
271
+ ```
272
+
273
+ ## Configuration
274
+
275
+ ```ts
276
+ createMailClient({
277
+ baseUrl: string; // the mail service's origin, e.g. "https://mail.lumitra.co"
278
+ apiKey: string; // a workspace API key: `Authorization: Bearer <key>`
279
+ fetch?: typeof fetch; // defaults to the runtime's global fetch
280
+ timeoutMs?: number; // default 10000, per attempt
281
+ maxRetries?: number; // default 3
282
+ userAgent?: string;
283
+ validateResponses?: boolean; // default true; disable only once you trust the deployment
284
+ });
285
+ ```
286
+
287
+ ## Development
288
+
289
+ ```bash
290
+ pnpm -F @marlinjai/mail-sdk run build # tsup, dual CJS/ESM + .d.ts
291
+ pnpm -F @marlinjai/mail-sdk run lint # tsc --noEmit (the linter for this repo)
292
+ pnpm -F @marlinjai/mail-sdk run test # vitest, a mocked fetch, no network
293
+ ```