@flowmails/flowmails-sdk 0.1.1 → 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/dist/index.js CHANGED
@@ -29,9 +29,18 @@ var ValidationError = class extends FlowmailsError {
29
29
  }
30
30
  };
31
31
  var RateLimitError = class extends FlowmailsError {
32
- constructor(code = "rate_limited", status = 429) {
32
+ /** The limit that was hit, when the server named one. */
33
+ limit;
34
+ /** The sends left in the window, when the server named one. */
35
+ remaining;
36
+ /** ISO-8601 instant the window rolls over, when the server named one. */
37
+ resetAt;
38
+ constructor(code = "rate_limited", status = 429, facts) {
33
39
  super(code, `Rate limited: ${code}`, status);
34
40
  this.name = "RateLimitError";
41
+ this.limit = facts?.limit;
42
+ this.remaining = facts?.remaining;
43
+ this.resetAt = facts?.resetAt;
35
44
  }
36
45
  };
37
46
  var UpstreamError = class extends FlowmailsError {
@@ -47,6 +56,7 @@ var UpstreamError = class extends FlowmailsError {
47
56
  var Flowmails = class {
48
57
  apiKey;
49
58
  baseURL;
59
+ platformURL;
50
60
  fetchFn;
51
61
  maxRetries;
52
62
  requestId;
@@ -59,14 +69,23 @@ var Flowmails = class {
59
69
  /\/+$/,
60
70
  ""
61
71
  );
62
- this.fetchFn = opts.fetch ?? globalThis.fetch;
72
+ this.platformURL = (opts.platformURL ?? "https://flowmails.net").replace(
73
+ /\/+$/,
74
+ ""
75
+ );
76
+ this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
63
77
  this.maxRetries = opts.maxRetries ?? 2;
64
78
  this.requestId = opts.requestId;
65
79
  }
66
80
  /**
67
- * Send mail through the SDK backend. The only v0.1 endpoint.
81
+ * Send mail through the SDK backend.
68
82
  *
69
- * Returns `{ id, status: "queued" }` on success; throws one of
83
+ * Pass `replyToMessageId` to answer a message in thread — the SDK
84
+ * backend resolves the parent and derives the `In-Reply-To` /
85
+ * `References` headers and the thread anchor, so the recipient's
86
+ * client threads it with the original conversation.
87
+ *
88
+ * Returns `{ id, status, messageId }` on success; throws one of
70
89
  * `AuthenticationError` / `ValidationError` / `RateLimitError` /
71
90
  * `UpstreamError` on failure (all subclasses of `FlowmailsError`).
72
91
  */
@@ -76,6 +95,10 @@ var Flowmails = class {
76
95
  fromName: opts.fromName,
77
96
  to: Array.isArray(opts.to) ? opts.to : [opts.to],
78
97
  replyTo: opts.replyTo,
98
+ // The SDK backend resolves this to the three `threading`
99
+ // fields. The caller names the **parent**, never the headers —
100
+ // hand-deriving `References` is how threads fork.
101
+ replyToMessageId: opts.replyToMessageId,
79
102
  subject: opts.subject,
80
103
  text: opts.text,
81
104
  html: opts.html,
@@ -83,34 +106,247 @@ var Flowmails = class {
83
106
  filename: a.filename,
84
107
  content: a.content instanceof Uint8Array ? bytesToBase64(a.content) : a.content,
85
108
  mimeType: a.mimeType
86
- }))
109
+ })),
110
+ // The idempotency key travels under the same name on the wire.
111
+ // It is deliberately **not** renamed: the backend's body is
112
+ // camelCase already, and a rename here would be one more place
113
+ // for the two sides to disagree.
114
+ idempotencyKey: opts.idempotencyKey
87
115
  };
88
- return this.request("/api/v1/messages", body);
116
+ return this.request(this.baseURL, "POST", "/api/v1/messages", {
117
+ body
118
+ });
119
+ }
120
+ /**
121
+ * The connection check — who the credential is.
122
+ *
123
+ * `flowmails test` (the CLI's documented first command) and every
124
+ * "is my setup right?" question end here. It verifies the key,
125
+ * names the account, names the bound domain and reports the
126
+ * scopes — and it sends nothing, so running it can never mail
127
+ * somebody by accident.
128
+ *
129
+ * @throws {AuthenticationError} when the key is missing, malformed
130
+ * or revoked.
131
+ */
132
+ async me() {
133
+ return this.request(this.baseURL, "GET", "/api/v1/me");
89
134
  }
90
135
  /**
91
- * Private: low-level request helper with retry+backoff+error
92
- * mapping. SDK callers must use the typed `send()` method
93
- * instead — this exists so future public methods can share the
94
- * same retry budget / error class mapping without re-implementing.
136
+ * The event log — the listen half of the surface, read with a
137
+ * cursor.
138
+ *
139
+ * ```ts
140
+ * const fm = new Flowmails({ apiKey: process.env.FLOWMAILS_API_KEY! });
141
+ * let after: string | undefined;
142
+ * for (;;) {
143
+ * const page = await fm.events.list({ after, subject: "invoice" });
144
+ * for (const event of page.events) { … }
145
+ * after = page.nextCursor ?? after;
146
+ * }
147
+ * ```
148
+ */
149
+ events = {
150
+ list: async (opts = {}) => {
151
+ const query = {
152
+ after: opts.after,
153
+ limit: opts.limit,
154
+ recipient: opts.recipient,
155
+ sender: opts.sender,
156
+ subject: opts.subject
157
+ };
158
+ return this.request(
159
+ this.platformURL,
160
+ "GET",
161
+ "/api/agent/events",
162
+ { query }
163
+ );
164
+ }
165
+ };
166
+ /**
167
+ * Read one message by its SMTP `Message-ID` — the id the event
168
+ * carried.
169
+ *
170
+ * The event log deliberately hands over routing facts and a
171
+ * subject and never a body (§4.2), so the content is an explicit
172
+ * ask. This is that ask.
173
+ */
174
+ messages = {
175
+ get: async (messageId, opts = {}) => {
176
+ if (!messageId) {
177
+ throw new ValidationError("message_id_required", "messageId is required");
178
+ }
179
+ return this.request(
180
+ this.platformURL,
181
+ "GET",
182
+ `/api/agent/messages/${encodeURIComponent(messageId)}`,
183
+ { query: { domainId: opts.domainId } }
184
+ );
185
+ },
186
+ /**
187
+ * Poll a **sent** message's delivery state.
188
+ *
189
+ * `id` is the value {@link send} returned as `id` (or the SMTP
190
+ * `Message-ID`). Returns the worker's lifecycle state so an agent
191
+ * can tell `sent` from `failed` (the two the worker writes)
192
+ * instead of assuming success.
193
+ */
194
+ status: async (id) => {
195
+ if (!id) {
196
+ throw new ValidationError("message_id_required", "id is required");
197
+ }
198
+ return this.request(
199
+ this.baseURL,
200
+ "GET",
201
+ `/api/v1/messages/${encodeURIComponent(id)}`
202
+ );
203
+ },
204
+ /**
205
+ * Look back through the mailbox.
206
+ *
207
+ * The event log is the primary listen path; this is the history
208
+ * path. A hit carries addressing, the subject and a preview — the
209
+ * body is a separate, explicit ask.
210
+ */
211
+ search: async (domainId, opts) => {
212
+ if (!domainId) {
213
+ throw new ValidationError("domain_id_required", "domainId is required");
214
+ }
215
+ if (!opts?.q || opts.q.trim().length < 2) {
216
+ throw new ValidationError(
217
+ "query_too_short",
218
+ "q must be at least 2 characters"
219
+ );
220
+ }
221
+ return this.request(
222
+ this.platformURL,
223
+ "GET",
224
+ "/api/agent/emails/search",
225
+ {
226
+ query: {
227
+ q: opts.q,
228
+ domainId,
229
+ limit: opts.limit,
230
+ field: opts.field,
231
+ type: opts.type
232
+ }
233
+ }
234
+ );
235
+ }
236
+ };
237
+ /**
238
+ * The conversation a message belongs to.
239
+ *
240
+ * The core listen/reply loop can store the message ids itself;
241
+ * this is for the agent that wants the platform to reconstruct the
242
+ * chain. The chain is read from the **conversation root's** SMTP
243
+ * `Message-ID`, which is exactly what `email.threadId` holds.
95
244
  */
96
- async request(path, body) {
97
- const url = `${this.baseURL}${path}`;
245
+ threads = {
246
+ get: async (threadId, opts = {}) => {
247
+ if (!threadId) {
248
+ throw new ValidationError("thread_id_required", "threadId is required");
249
+ }
250
+ return this.request(
251
+ this.platformURL,
252
+ "GET",
253
+ `/api/agent/threads/${encodeURIComponent(threadId)}`,
254
+ { query: { domainId: opts.domainId } }
255
+ );
256
+ }
257
+ };
258
+ /**
259
+ * The durable wait — the one thing an agent cannot build for
260
+ * itself.
261
+ *
262
+ * A suspended HTTP request dies on the edge long before a
263
+ * verification mail arrives (minutes to hours later), so the wait
264
+ * is a row on the platform and the agent polls it. `create()`
265
+ * answers **immediately**; it does not block.
266
+ */
267
+ waits = {
268
+ create: async (opts) => {
269
+ return this.request(
270
+ this.platformURL,
271
+ "POST",
272
+ "/api/agent/waits",
273
+ { body: opts }
274
+ );
275
+ },
276
+ get: async (waitId) => {
277
+ if (!waitId) {
278
+ throw new ValidationError("wait_id_required", "waitId is required");
279
+ }
280
+ return this.request(
281
+ this.platformURL,
282
+ "GET",
283
+ `/api/agent/waits/${encodeURIComponent(waitId)}`
284
+ );
285
+ }
286
+ };
287
+ /**
288
+ * The addresses (mailboxes) the key's account owns, and the one
289
+ * narrow write the agent surface has: create a single one.
290
+ */
291
+ addresses = {
292
+ listDomains: async () => {
293
+ const result = await this.request(
294
+ this.platformURL,
295
+ "GET",
296
+ "/api/agent/domains"
297
+ );
298
+ return result.domains;
299
+ },
300
+ list: async (domainId) => {
301
+ if (!domainId) {
302
+ throw new ValidationError("domain_id_required", "domainId is required");
303
+ }
304
+ const result = await this.request(
305
+ this.platformURL,
306
+ "GET",
307
+ `/api/agent/domains/${encodeURIComponent(domainId)}/addresses`
308
+ );
309
+ return result;
310
+ },
311
+ create: async (domainId, localPart) => {
312
+ if (!domainId) {
313
+ throw new ValidationError("domain_id_required", "domainId is required");
314
+ }
315
+ return this.request(
316
+ this.platformURL,
317
+ "POST",
318
+ `/api/agent/domains/${encodeURIComponent(domainId)}/addresses`,
319
+ { body: { localPart } }
320
+ );
321
+ }
322
+ };
323
+ /**
324
+ * Private: the one request path, with retry + backoff + error
325
+ * mapping shared by every public method.
326
+ *
327
+ * `origin` is explicit because the surface spans two deployments:
328
+ * the SDK backend (`baseURL`) for sending, the platform
329
+ * (`platformURL`) for reading and waiting. `method` is explicit
330
+ * because the listen endpoints are GETs — the v0.1 helper was
331
+ * POST-only, which is why reading used to mean hand-rolling HTTP.
332
+ */
333
+ async request(origin, method, path, opts = {}) {
334
+ const url = buildUrl(origin, path, opts.query);
98
335
  const headers = {
99
- Authorization: `Bearer ${this.apiKey}`,
100
- "Content-Type": "application/json"
336
+ Authorization: `Bearer ${this.apiKey}`
101
337
  };
338
+ if (method === "POST") headers["Content-Type"] = "application/json";
102
339
  if (this.requestId) headers["X-Flowmails-Request-Id"] = this.requestId;
103
340
  let lastError = null;
104
341
  for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
105
342
  let res;
106
343
  try {
107
344
  res = await this.fetchFn(url, {
108
- method: "POST",
345
+ method,
109
346
  headers,
110
- body: JSON.stringify(body),
111
- // 15s matches the SDK backend's upstream timeout — we want
112
- // our error to be "request timed out" rather than the
113
- // backend's generic 502.
347
+ ...method === "POST" ? { body: JSON.stringify(opts.body) } : {},
348
+ // 15s matches the platform's upstream timeout — we want our
349
+ // error to be "request timed out" rather than a generic 502.
114
350
  signal: AbortSignal.timeout(15e3)
115
351
  });
116
352
  } catch (err) {
@@ -133,10 +369,19 @@ var Flowmails = class {
133
369
  }
134
370
  const code = payload.error ?? "request_failed";
135
371
  if (res.status === 401) throw new AuthenticationError(code, res.status);
136
- if (res.status === 400 || res.status === 422) {
372
+ if (res.status === 400 || res.status === 404 || res.status === 422 || res.status === 409) {
137
373
  throw new ValidationError(code, payload.detail, res.status);
138
374
  }
139
- if (res.status === 429) throw new RateLimitError(code, res.status);
375
+ if (res.status === 429) {
376
+ const facts = readQuotaFacts(res, payload);
377
+ if (code === "idempotency_key_in_progress") {
378
+ lastError = new RateLimitError(code, res.status, facts);
379
+ if (attempt >= this.maxRetries) throw lastError;
380
+ await sleep(backoffMs(attempt));
381
+ continue;
382
+ }
383
+ throw new RateLimitError(code, res.status, facts);
384
+ }
140
385
  if (res.status >= 500 || res.status === 408) {
141
386
  lastError = new UpstreamError(code, payload.detail, res.status);
142
387
  if (attempt >= this.maxRetries) throw lastError;
@@ -148,6 +393,39 @@ var Flowmails = class {
148
393
  throw lastError ?? new FlowmailsError("unknown", "Unknown failure", 0);
149
394
  }
150
395
  };
396
+ function readQuotaFacts(res, payload) {
397
+ const limit = typeof payload.limit === "number" ? payload.limit : void 0;
398
+ let remaining = typeof payload.remaining === "number" ? payload.remaining : void 0;
399
+ let resetAt = typeof payload.resetAt === "string" ? payload.resetAt : void 0;
400
+ const headerRemaining = res.headers?.get?.(
401
+ "X-Flowmails-RateLimit-Remaining"
402
+ );
403
+ if (remaining === void 0 && headerRemaining) {
404
+ const parsed = Number(headerRemaining);
405
+ if (Number.isFinite(parsed)) remaining = parsed;
406
+ }
407
+ const headerReset = res.headers?.get?.("X-Flowmails-RateLimit-Reset");
408
+ if (resetAt === void 0 && headerReset) {
409
+ const parsed = Number(headerReset);
410
+ if (Number.isFinite(parsed)) {
411
+ resetAt = new Date(parsed * 1e3).toISOString();
412
+ }
413
+ }
414
+ if (limit === void 0 && remaining === void 0 && resetAt === void 0) {
415
+ return void 0;
416
+ }
417
+ return { limit, remaining, resetAt };
418
+ }
419
+ function buildUrl(origin, path, query) {
420
+ const url = new URL(`${origin}${path}`);
421
+ if (query) {
422
+ for (const [key, value] of Object.entries(query)) {
423
+ if (value === void 0 || value === null || value === "") continue;
424
+ url.searchParams.set(key, String(value));
425
+ }
426
+ }
427
+ return url.toString();
428
+ }
151
429
  function bytesToBase64(bytes) {
152
430
  let bin = "";
153
431
  for (let i = 0; i < bytes.length; i++) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/client.ts"],"names":[],"mappings":";AASO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA;AAAA,EAE/B,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EAET,WAAA,CAAY,IAAA,EAAc,OAAA,EAAiB,MAAA,EAAgB;AACzD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,SAAA,GAAY,MAAA,IAAU,GAAA,IAAO,MAAA,KAAW,OAAO,MAAA,KAAW,GAAA;AAAA,EACjE;AACF;AAKO,IAAM,mBAAA,GAAN,cAAkC,cAAA,CAAe;AAAA,EACtD,WAAA,CAAY,IAAA,GAAO,iBAAA,EAAmB,MAAA,GAAS,GAAA,EAAK;AAClD,IAAA,KAAA,CAAM,IAAA,EAAM,CAAA,uBAAA,EAA0B,IAAI,CAAA,CAAA,EAAI,MAAM,CAAA;AACpD,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAMO,IAAM,eA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A,CAAM,QAAQ,CAAA,EAAA,EAAK;AACrC,IAAA,GAAA,IAAO,MAAA,CAAO,YAAA,CAAa,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,EACrC;AACA,EAAA,OAAO,KAAK,GAAG,CAAA;AACjB;AAEA,SAAS,UAAU,OAAA,EAAyB;AAE1C,EAAA,MAAM,OAAO,IAAA,CAAK,GAAA,CAAI,GAAA,GAAM,CAAA,IAAK,SAAS,GAAK,CAAA;AAC/C,EAAA,OAAO,OAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,MAAA,KAAW,IAAI,CAAA;AAC/C;AAEA,SAAS,MAAM,EAAA,EAA2B;AACxC,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AACzD","file":"index.js","sourcesContent":["/**\n * Public error hierarchy. Mirrors the SDK backend's JSON contract\n * documented in `apps/sdk-backend/src/utils/errors.js`.\n *\n * The base `FlowmailsError` carries the raw `code` string (e.g.\n * `\"validation_failed\"`) plus the HTTP status. Subclasses add\n * richer contextual fields (validation `detail`, auth `reason`)\n * that the SDK backend actually emits.\n */\nexport class FlowmailsError extends Error {\n /** Machine-readable error slug, sent back from the SDK backend. */\n readonly code: string;\n /** HTTP status from the SDK backend response. */\n readonly status: number;\n /** Suggested retry hint (`true` for transient 5xx / 408 / 429). */\n readonly retryable: boolean;\n\n constructor(code: string, message: string, status: number) {\n super(message);\n this.name = \"FlowmailsError\";\n this.code = code;\n this.status = status;\n this.retryable = status >= 500 || status === 408 || status === 429;\n }\n}\n\n/**\n * 401 — API key missing / invalid / revoked. NOT retryable.\n */\nexport class AuthenticationError extends FlowmailsError {\n constructor(code = \"api_key_invalid\", status = 401) {\n super(code, `Authentication failed: ${code}`, status);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * 400 / 422 — request was syntactically valid but rejected by the\n * backend. NOT retryable without code changes.\n */\nexport class ValidationError extends FlowmailsError {\n readonly detail?: string;\n constructor(code: string, detail: string | undefined, status = 400) {\n super(code, `Validation failed: ${code}${detail ? ` — ${detail}` : \"\"}`, status);\n this.name = \"ValidationError\";\n this.detail = detail;\n }\n}\n\n/**\n * 408 / 429 — request was rate-limited or timed out. Retryable.\n */\nexport class RateLimitError extends FlowmailsError {\n constructor(code = \"rate_limited\", status = 429) {\n super(code, `Rate limited: ${code}`, status);\n this.name = \"RateLimitError\";\n }\n}\n\n/**\n * 502 / 504 — the SDK backend couldn't reach the upstream\n * receive-worker, or the upstream returned a malformed response.\n * Retryable.\n */\nexport class UpstreamError extends FlowmailsError {\n readonly upstreamMessage?: string;\n constructor(code: string, upstreamMessage: string | undefined, status = 502) {\n super(code, `Upstream failure: ${code}`, status);\n this.name = \"UpstreamError\";\n this.upstreamMessage = upstreamMessage;\n }\n}\n","/**\n * Public SDK facade. The whole shape of the package is:\n *\n * new Flowmails({ apiKey: \"fm_…\" }).send({...})\n *\n * No top-level helper functions, no globals, no implicit init.\n * Construction takes an `apiKey` and an optional `baseURL`\n * (mainly for testing / private-region deployments).\n *\n * `send` is the only public method in v0.1 — there is exactly\n * one outbound endpoint (`POST /api/v1/messages`). The\n * `request<T>` helper below it carries the retry / backoff /\n * error-mapping machinery and is private; future public methods\n * (e.g. `webhooks.send`) will call `request<T>` internally so\n * the choke point stays in one place.\n *\n * The payload DTOs (`SendOptions` / `SendResult` / `SendAttachment`)\n * mirror common email-clients (Gmail API, Resend, Postmark), NOT\n * the receive-worker's wire format. `send` does the rename to\n * wire on the way out (html → content, Uint8Array → base64).\n */\nimport {\n AuthenticationError,\n FlowmailsError,\n RateLimitError,\n UpstreamError,\n ValidationError,\n} from \"./errors.js\";\n\n// ---------- Public payload types ----------\n\n/**\n * A single file attached to the outbound message.\n *\n * `filename` and `content` are required. `mimeType` defaults to\n * `application/octet-stream` if the SDK backend cannot infer it\n * from the filename (the backend forwards `mimeType` to the\n * receive-worker which sets it on the SMTP part).\n */\nexport interface SendAttachment {\n filename: string;\n content: string | Uint8Array;\n mimeType?: string;\n}\n\n/**\n * Composed send payload.\n *\n * `to` accepts a single address or an array. `subject` is required.\n * At least one of `text` / `html` must be a non-empty string.\n */\nexport interface SendOptions {\n /**\n * Sender address. MUST land on the domain the API key is bound\n * to (the SDK backend enforces this with a 422 on mismatch).\n */\n from: string;\n /** Display name for the sender; the email-worker falls back to the\n * local-part capitalised. */\n fromName?: string;\n /** One recipient or an array. */\n to: string | string[];\n /** Optional reply-to override. */\n replyTo?: string;\n /** Subject line — required, non-empty. */\n subject: string;\n /** Plain-text body. Required iff `html` is also missing. */\n text?: string;\n /** HTML body. Required iff `text` is also missing. Inline\n * `cid:` images and remote `data:` urls are auto-extracted by\n * the email-worker into R2 embeds. */\n html?: string;\n /** Attachments. */\n attachments?: SendAttachment[];\n}\n\n/**\n * Result of a successful send. Matches the marketing-copy promise\n * in `apps/web/app/routes/home.tsx`:\n *\n * { \"id\": \"msg_8421\", \"status\": \"queued\" }\n */\nexport interface SendResult {\n /** Numeric email row id (stringified for JSON safety). */\n id: string;\n /** Always `\"queued\"` for now; the SDK backend doesn't surface\n * the SMTP `delivered` / `bounced` lifecycle — that comes via\n * webhooks in a future milestone. */\n status: \"queued\";\n}\n\n// ---------- Options & class ----------\n\nexport interface FlowmailsOptions {\n /** `fm_<32+hex>` API key issued in `apps/web/app/routes/dashboard/settings/api-keys.tsx`. */\n apiKey: string;\n /** Override the SDK backend base URL. Defaults to `https://sdk.flowmails.net`. */\n baseURL?: string;\n /** Inject a `fetch` implementation (Workers environments, test harnesses). */\n fetch?: typeof globalThis.fetch;\n /**\n * Number of automatic retries on transient failures (5xx, 408,\n * 429). Defaults to 2. Set to 0 to disable. The retry budget is\n * bounded; doesn't apply to 4xx validation / auth failures.\n */\n maxRetries?: number;\n /**\n * Optional request-id header for cross-stack tracing. If set,\n * every outbound request carries `X-Flowmails-Request-Id`, and\n * the SDK backend echoes it back on the response so callers can\n * correlate platform logs with their own.\n */\n requestId?: string;\n}\n\nexport class Flowmails {\n private readonly apiKey: string;\n private readonly baseURL: string;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly maxRetries: number;\n private readonly requestId?: string;\n\n constructor(opts: FlowmailsOptions) {\n if (!opts.apiKey) {\n throw new Error(\"Flowmails: apiKey is required\");\n }\n this.apiKey = opts.apiKey;\n this.baseURL = (opts.baseURL ?? \"https://sdk.flowmails.net\").replace(\n /\\/+$/,\n \"\",\n );\n this.fetchFn = opts.fetch ?? globalThis.fetch;\n this.maxRetries = opts.maxRetries ?? 2;\n this.requestId = opts.requestId;\n }\n\n /**\n * Send mail through the SDK backend. The only v0.1 endpoint.\n *\n * Returns `{ id, status: \"queued\" }` on success; throws one of\n * `AuthenticationError` / `ValidationError` / `RateLimitError` /\n * `UpstreamError` on failure (all subclasses of `FlowmailsError`).\n */\n async send(opts: SendOptions): Promise<SendResult> {\n // The wire-shape renames (html → content, Uint8Array → base64)\n // happen here. Keeping this logic adjacent to the type\n // definitions avoids a separate \"resource\" indirection for a\n // single endpoint — when a second endpoint ships, this is the\n // place to extract a small internal helper.\n const body = {\n from: opts.from,\n fromName: opts.fromName,\n to: Array.isArray(opts.to) ? opts.to : [opts.to],\n replyTo: opts.replyTo,\n subject: opts.subject,\n text: opts.text,\n html: opts.html,\n attachments: opts.attachments?.map((a) => ({\n filename: a.filename,\n content:\n a.content instanceof Uint8Array\n ? bytesToBase64(a.content)\n : a.content,\n mimeType: a.mimeType,\n })),\n };\n\n return this.request<SendResult>(\"/api/v1/messages\", body);\n }\n\n /**\n * Private: low-level request helper with retry+backoff+error\n * mapping. SDK callers must use the typed `send()` method\n * instead — this exists so future public methods can share the\n * same retry budget / error class mapping without re-implementing.\n */\n private async request<T>(path: string, body: unknown): Promise<T> {\n const url = `${this.baseURL}${path}`;\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n if (this.requestId) headers[\"X-Flowmails-Request-Id\"] = this.requestId;\n\n let lastError: FlowmailsError | null = null;\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n let res: Response;\n try {\n res = await this.fetchFn(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n // 15s matches the SDK backend's upstream timeout — we want\n // our error to be \"request timed out\" rather than the\n // backend's generic 502.\n signal: AbortSignal.timeout(15_000),\n });\n } catch (err) {\n lastError = new UpstreamError(\n \"network_error\",\n err instanceof Error ? err.message : undefined,\n 0,\n );\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n\n // 2xx — happy path. Decode and return.\n if (res.ok) {\n return (await res.json()) as T;\n }\n\n // Non-2xx — render to a typed error.\n let payload: { error?: string; detail?: string; reason?: string } = {};\n try {\n payload = (await res.json()) as typeof payload;\n } catch {\n // Body wasn't JSON; fall back to status-based error.\n }\n\n const code = payload.error ?? \"request_failed\";\n\n if (res.status === 401) throw new AuthenticationError(code, res.status);\n if (res.status === 400 || res.status === 422) {\n throw new ValidationError(code, payload.detail, res.status);\n }\n if (res.status === 429) throw new RateLimitError(code, res.status);\n if (res.status >= 500 || res.status === 408) {\n lastError = new UpstreamError(code, payload.detail, res.status);\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n\n // Anything else: not retryable, throw immediately.\n throw new FlowmailsError(code, `Request failed: ${code}`, res.status);\n }\n\n // Shouldn't reach here — last iteration always throws. Type\n // assertion keeps the compiler happy without `any`.\n throw lastError ?? new FlowmailsError(\"unknown\", \"Unknown failure\", 0);\n }\n}\n\n// ---------- Module-level helpers ----------\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n // Browser-safe base64 of a `Uint8Array`. Avoids pulling in a\n // Buffer polyfill in the worker / browser bundles.\n let bin = \"\";\n for (let i = 0; i < bytes.length; i++) {\n bin += String.fromCharCode(bytes[i]);\n }\n return btoa(bin);\n}\n\nfunction backoffMs(attempt: number): number {\n // Exponential backoff with jitter, capped at 4 s. attempt 0 → 250 ms.\n const base = Math.min(250 * 2 ** attempt, 4_000);\n return base + Math.floor(Math.random() * base);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts"],"names":[],"mappings":";AASO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA;AAAA,EAE/B,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EAET,WAAA,CAAY,IAAA,EAAc,OAAA,EAAiB,MAAA,EAAgB;AACzD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,SAAA,GAAY,MAAA,IAAU,GAAA,IAAO,MAAA,KAAW,OAAO,MAAA,KAAW,GAAA;AAAA,EACjE;AACF;AAKO,IAAM,mBAAA,GAAN,cAAkC,cAAA,CAAe;AAAA,EACtD,WAAA,CAAY,IAAA,GAAO,iBAAA,EAAmB,MAAA,GAAS,GAAA,EAAK;AAClD,IAAA,KAAA,CAAM,IAAA,EAAM,CAAA,uBAAA,EAA0B,IAAI,CAAA,CAAA,EAAI,MAAM,CAAA;AACpD,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAMO,IAAM,eAAA,GAAN,cAA8B,cAAA,CAAe;AAAA,EACzC,MAAA;AAAA,EACT,WAAA,CAAY,IAAA,EAAc,MAAA,EAA4B,MAAA,GAAS,GAAA,EAAK;AAClE,IAAA,KAAA,CAAM,IAAA,EAAM,CAAA,mBAAA,EAAsB,IAAI,CAAA,EAAG,MAAA,GAAS,WAAM,MAAM,CAAA,CAAA,GAAK,EAAE,CAAA,CAAA,EAAI,MAAM,CAAA;AAC/E,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAA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,OAAO,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AACzD","file":"index.js","sourcesContent":["/**\n * Public error hierarchy. Mirrors the SDK backend's JSON contract\n * documented in `apps/sdk-backend/src/utils/errors.js`.\n *\n * The base `FlowmailsError` carries the raw `code` string (e.g.\n * `\"validation_failed\"`) plus the HTTP status. Subclasses add\n * richer contextual fields (validation `detail`, auth `reason`)\n * that the SDK backend actually emits.\n */\nexport class FlowmailsError extends Error {\n /** Machine-readable error slug, sent back from the SDK backend. */\n readonly code: string;\n /** HTTP status from the SDK backend response. */\n readonly status: number;\n /** Suggested retry hint (`true` for transient 5xx / 408 / 429). */\n readonly retryable: boolean;\n\n constructor(code: string, message: string, status: number) {\n super(message);\n this.name = \"FlowmailsError\";\n this.code = code;\n this.status = status;\n this.retryable = status >= 500 || status === 408 || status === 429;\n }\n}\n\n/**\n * 401 — API key missing / invalid / revoked. NOT retryable.\n */\nexport class AuthenticationError extends FlowmailsError {\n constructor(code = \"api_key_invalid\", status = 401) {\n super(code, `Authentication failed: ${code}`, status);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * 400 / 422 — request was syntactically valid but rejected by the\n * backend. NOT retryable without code changes.\n */\nexport class ValidationError extends FlowmailsError {\n readonly detail?: string;\n constructor(code: string, detail: string | undefined, status = 400) {\n super(code, `Validation failed: ${code}${detail ? ` — ${detail}` : \"\"}`, status);\n this.name = \"ValidationError\";\n this.detail = detail;\n }\n}\n\n/**\n * 408 / 429 — request was rate-limited or timed out. Retryable.\n *\n * A 429 from Flowmails is either a **quota refusal**\n * (`rate_limit_exceeded`) or a request that is **already running**\n * (`idempotency_key_in_progress`). The two need different handling,\n * so the quota facts travel on the error:\n *\n * - `limit` — the limit that was hit.\n * - `remaining` — how many sends are left in the window (`0` when the\n * quota is exhausted).\n * - `resetAt` — ISO-8601 instant the window rolls over.\n */\nexport class RateLimitError extends FlowmailsError {\n /** The limit that was hit, when the server named one. */\n readonly limit?: number;\n /** The sends left in the window, when the server named one. */\n readonly remaining?: number;\n /** ISO-8601 instant the window rolls over, when the server named one. */\n readonly resetAt?: string;\n\n constructor(\n code = \"rate_limited\",\n status = 429,\n facts?: { limit?: number; remaining?: number; resetAt?: string },\n ) {\n super(code, `Rate limited: ${code}`, status);\n this.name = \"RateLimitError\";\n this.limit = facts?.limit;\n this.remaining = facts?.remaining;\n this.resetAt = facts?.resetAt;\n }\n}\n\n/**\n * 502 / 504 — the SDK backend couldn't reach the upstream\n * receive-worker, or the upstream returned a malformed response.\n * Retryable.\n */\nexport class UpstreamError extends FlowmailsError {\n readonly upstreamMessage?: string;\n constructor(code: string, upstreamMessage: string | undefined, status = 502) {\n super(code, `Upstream failure: ${code}`, status);\n this.name = \"UpstreamError\";\n this.upstreamMessage = upstreamMessage;\n }\n}\n","/**\n * Public SDK facade. The whole shape of the package is:\n *\n * new Flowmails({ apiKey: \"fm_…\" }).send({...})\n *\n * No top-level helper functions, no globals, no implicit init.\n * Construction takes an `apiKey` and an optional `baseURL`\n * (mainly for testing / private-region deployments).\n *\n * `send` is the only public method in v0.1 — there is exactly\n * one outbound endpoint (`POST /api/v1/messages`). The\n * `request<T>` helper below it carries the retry / backoff /\n * error-mapping machinery and is private; future public methods\n * (e.g. `webhooks.send`) will call `request<T>` internally so\n * the choke point stays in one place.\n *\n * The payload DTOs (`SendOptions` / `SendResult` / `SendAttachment`)\n * mirror common email-clients (Gmail API, Resend, Postmark), NOT\n * the receive-worker's wire format. `send` does the rename to\n * wire on the way out (html → content, Uint8Array → base64).\n */\nimport {\n AuthenticationError,\n FlowmailsError,\n RateLimitError,\n UpstreamError,\n ValidationError,\n} from \"./errors.js\";\n\n// ---------- Public payload types ----------\n\n/**\n * A single file attached to the outbound message.\n *\n * `filename` and `content` are required. `mimeType` defaults to\n * `application/octet-stream` if the SDK backend cannot infer it\n * from the filename (the backend forwards `mimeType` to the\n * receive-worker which sets it on the SMTP part).\n */\nexport interface SendAttachment {\n filename: string;\n content: string | Uint8Array;\n mimeType?: string;\n}\n\n/**\n * One event in the durable log — what arrived, where, and from whom.\n *\n * The event carries **routing facts plus the subject line**, never a\n * body: that is the platform's core promise (`docs/agent-platform.md`\n * §4.2), and the body is opt-in through {@link MessageDetail}. The\n * `messageId` is the SMTP `Message-ID` — the key every content read\n * takes.\n */\nexport interface AgentEvent {\n /** The cursor value. Treat it as opaque; pass it back as `after`. */\n id: string;\n /** The SMTP `Message-ID`. Pass this to `messages.get()`. */\n messageId: string;\n /** `inbound.received` — the only event type the platform emits. */\n event: string;\n /** The mailbox the message landed in, e.g. `billing@yourapp.com`. */\n recipient: string;\n /** The sender, when the receive worker could determine it. */\n sender: string | null;\n /** The subject line — the one content field on the event. */\n subject: string | null;\n /** ISO-8601 timestamp of when the platform recorded the event. */\n createdAt: string;\n}\n\n/** Options for {@link AgentEvents.list}. */\nexport interface ListEventsOptions {\n /**\n * Cursor: return events **after** this event id. Pass the\n * `nextCursor` of the previous page. Treat it as opaque — it is an\n * event id, not a timestamp, because two events can land in the\n * same millisecond and a cursor that can skip a row loses mail.\n */\n after?: string;\n /** Page size. The platform caps it; ask for what you will drain. */\n limit?: number;\n /** Exact recipient address filter. */\n recipient?: string;\n /** Exact sender address filter. */\n sender?: string;\n /** Case-insensitive **substring** of the subject. */\n subject?: string;\n}\n\n/** One page of the event log. */\nexport interface ListEventsResult {\n events: AgentEvent[];\n /**\n * The cursor to pass as `after` on the next call. Present whenever\n * the page was not empty; absent when the log is drained.\n */\n nextCursor?: string;\n}\n\n/** Options for {@link AgentWaits.create}. */\nexport interface CreateWaitOptions {\n /** The mailbox to watch, e.g. `billing@yourapp.com`. */\n address: string;\n /** Only resolve for mail from this sender. */\n sender?: string;\n /** Only resolve for a subject containing this substring. */\n subject?: string;\n /**\n * How long to keep the wait open, in milliseconds. Defaults to 15\n * minutes; the platform caps it at 24 hours.\n */\n timeoutMs?: number;\n}\n\n/** A durable wait, as the platform reports it. */\nexport interface WaitStatus {\n waitId: string;\n /** `pending` → `resolved` (a message landed) or `expired`. */\n status: \"pending\" | \"resolved\" | \"expired\";\n address: string;\n sender: string | null;\n subject: string | null;\n /** The SMTP `Message-ID` that resolved the wait, when it resolved. */\n resolvedMessageId: string | null;\n /** ISO-8601 deadline. A wait past it reads as `expired`. */\n expiresAt: string | number;\n}\n\n/**\n * A newly-opened wait.\n *\n * Returned **immediately** — the platform writes a row and answers,\n * it never suspends the request. A verification mail arrives minutes\n * to hours later and an edge request dies long before that, so the\n * wait is durable state the agent polls with {@link AgentWaits.get}.\n */\nexport interface CreateWaitResult extends WaitStatus {\n /** A hint for the poll loop: check again in a few seconds. */\n pollAfterMs: number;\n}\n\n/** The full content of one message. Fetched, never pushed. */\nexport interface MessageDetail {\n /** The worker's numeric row id. */\n id: number | string;\n /** The SMTP `Message-ID` the event carried. */\n messageId: string;\n from: string;\n fromName: string | null;\n to: string;\n toName: string | null;\n subject: string | null;\n /** Plain-text body. Ideal for regexing a verification code out. */\n text: string | null;\n /** Rendered HTML body, when the message had one. */\n html: string | null;\n receivedAt: string | null;\n attachments: Array<{\n filename: string | null;\n mimeType: string | null;\n size: number | null;\n url: string | null;\n }>;\n}\n\n/** One address (mailbox) the platform accepts mail for. */\nexport interface AgentAddress {\n address: string;\n localPart: string;\n}\n\n/**\n * One domain on the account.\n *\n * `routingMode` decides whether a new address needs anything to\n * happen: on `catchall` every local part already delivers, on\n * `rules` only the listed ones do.\n */\nexport interface AgentDomain {\n id: string;\n name: string;\n routingMode: \"catchall\" | \"rules\";\n localParts: string[];\n /** False when the per-account receive worker is not deployed yet. */\n ready: boolean;\n}\n\n/** Result of {@link AgentAddresses.create}. */\nexport interface CreateAddressResult {\n address: string;\n localPart: string;\n domainId: string;\n domain: string;\n /** False when the address already existed — the call is idempotent. */\n created: boolean;\n routingMode?: \"catchall\" | \"rules\";\n}\n\n/**\n * One message of a conversation chain.\n *\n * It extends {@link MessageDetail} because the thread route uses the\n * **same projection** the single-message read uses — the same\n * fields, the same shape. The only addition is the truncation flag.\n */\nexport interface ThreadMessage extends MessageDetail {\n /**\n * `1` when the receive worker shortened the body.\n *\n * The worker returns a bounded window of the chain and truncates\n * the bodies of the non-current members — a long thread must not\n * become a way to pull a whole mailbox. `total` / `hasMoreOlder` /\n * `hasMoreNewer` say whether the chain extends past the window.\n */\n bodyTruncated: 0 | 1;\n}\n\n/**\n * A conversation chain — `docs/agent-platform.md` §10.8 AP-27.\n */\nexport interface ThreadDetail {\n /** The conversation **root's** SMTP `Message-ID`. */\n threadId: string;\n /** The platform domain id the chain was read from. */\n domainId: string;\n /** The domain name the chain was read from. */\n domain: string;\n /** The full chain length — not just the returned window. */\n total: number;\n /** The chain extends past the window, older side. */\n hasMoreOlder: boolean;\n /** The chain extends past the window, newer side. */\n hasMoreNewer: boolean;\n /** The chain, oldest first. */\n messages: ThreadMessage[];\n}\n\n/**\n * One search hit.\n *\n * Addressing, the subject and a short preview — never the body. The\n * body is fetched per message, through {@link AgentMessages.get},\n * when the agent decides a message matters.\n */\nexport interface SearchMessageHit {\n /** The worker's row id. Accepted by {@link AgentMessages.get}. */\n id: number | null;\n /** The SMTP `Message-ID`, when the sender supplied one. */\n messageId: string;\n from: string | null;\n fromName: string | null;\n to: string | null;\n toName: string | null;\n subject: string | null;\n receivedAt: string | null;\n /** A short plain-text preview of the body. */\n preview: string | null;\n}\n\n/**\n * The arguments of a mailbox search.\n *\n * `domainId` is required on the call (not in this shape) because the\n * receive worker's search path is domain-scoped: one domain, one\n * round-trip, one stable ordering. `GET /api/agent/domains` is the\n * call that answers it.\n */\nexport interface SearchMessagesOptions {\n /** The query. At least two characters — the platform refuses less. */\n q: string;\n /** The page size. */\n limit?: number;\n /** Which field to match. Defaults to `body` (subject + from + to + text). */\n field?: \"subject\" | \"from\" | \"to\" | \"body\";\n /** Which mailbox direction. Defaults to `receive`. */\n type?: \"receive\" | \"send\";\n}\n\n/** The result of a mailbox search. */\nexport interface SearchMessagesResult {\n messages: SearchMessageHit[];\n /** How many rows match the filter, ignoring `limit`. */\n total: number;\n domainId: string;\n}\n\n/**\n * Composed send payload.\n *\n * `to` accepts a single address or an array. `subject` is required.\n * At least one of `text` / `html` must be a non-empty string.\n */\nexport interface SendOptions {\n /**\n * Sender address. MUST land on the domain the API key is bound\n * to (the SDK backend enforces this with a 422 on mismatch).\n */\n from: string;\n /** Display name for the sender; the email-worker falls back to the\n * local-part capitalised. */\n fromName?: string;\n /** One recipient or an array. */\n to: string | string[];\n /** Optional reply-to override. */\n replyTo?: string;\n /**\n * Reply in thread: the SMTP `Message-ID` (or numeric id) of the\n * message being answered.\n *\n * When set, the SDK backend resolves the parent row and derives\n * the `In-Reply-To` / `References` headers and the thread anchor,\n * so the recipient's mail client threads your message with the\n * original conversation — and the dashboard shows it in the same\n * thread. The caller supplies the **parent**, never the headers:\n * deriving `References` by hand is how threads fork.\n *\n * A parent with no `Message-ID` header is rejected: there is\n * nothing to point `In-Reply-To` at.\n */\n replyToMessageId?: string;\n /** Subject line — required, non-empty. */\n subject: string;\n /** Plain-text body. Required iff `html` is also missing. */\n text?: string;\n /** HTML body. Required iff `text` is also missing. Inline\n * `cid:` images and remote `data:` urls are auto-extracted by\n * the email-worker into R2 embeds. */\n html?: string;\n /** Attachments. */\n attachments?: SendAttachment[];\n /**\n * Idempotency key — the same key under the same account and the\n * same request returns the **original** result and does not send\n * twice.\n *\n * Give every send a key you can rebuild after a timeout (a UUID\n * per logical mail, not per attempt) and a retry becomes free: the\n * backend replays the first answer instead of delivering a second\n * message.\n *\n * The key is scoped to the **account**, not globally — two accounts\n * may use the same string. Reusing one key for a *different* payload\n * is a client bug and is refused with `idempotency_key_conflict`\n * (409) rather than answered with the first result.\n */\n idempotencyKey?: string;\n}\n\n/**\n * Result of a successful send.\n *\n * `id` is the platform's row id; `messageId` is the SMTP `Message-ID`\n * the relay assigned, which is the key every read path takes — pass\n * it to {@link AgentMessages.get} to read a reply, or to\n * {@link AgentMessages.status} to poll delivery.\n */\nexport interface SendResult {\n /** Numeric email row id (stringified for JSON safety). */\n id: string;\n /** The row's lifecycle state at send time. */\n status: string;\n /**\n * The SMTP `Message-ID` the relay assigned (the receive worker's\n * `resendEmailId`). Empty when the send failed before the relay\n * accepted it.\n */\n messageId?: string;\n}\n\n/**\n * What the credential behind the client is allowed to do, and which\n * account it belongs to.\n *\n * This is the **connection check** (`docs/agent-platform.md` §10.8\n * AP-05): it answers \"is my key live, which account is it, which\n * domain may it send from, and what may it do?\" without sending a\n * single message — the only two ways to get that answer before it\n * existed were to send real mail or to fail.\n */\nexport interface AccountInfo {\n /** The account the credential belongs to. */\n userId: string;\n /**\n * The domain the credential is bound to — the constraint on\n * sending. `null` when the credential carries no binding.\n */\n domain: string | null;\n /** The per-account receive worker the credential sends through. */\n workerHost: string | null;\n /**\n * Which credential type answered: `\"sdk_key\"` (the dashboard's\n * domain-bound API key) or `\"agent_credential\"` (a scoped\n * credential issued for one set of capabilities).\n */\n credentialType: string;\n /** The scopes this credential holds. */\n scopes: string[];\n}\n\n// ---------- Options & class ----------\n\nexport interface FlowmailsOptions {\n /** `fm_<32+hex>` API key issued in `apps/web/app/routes/dashboard/settings/api-keys.tsx`. */\n apiKey: string;\n /** Override the SDK backend base URL. Defaults to `https://sdk.flowmails.net`. */\n baseURL?: string;\n /**\n * The **platform** origin, used by the listen half of the surface\n * (`fm.events`, `fm.messages`, `fm.waits`, `fm.addresses`). The\n * send path goes to {@link baseURL} (the SDK backend); the event\n * log, the durable wait and the message read live on the platform\n * worker, which is a different deployment.\n *\n * Defaults to `https://flowmails.net`. Set it for a self-hosted or\n * staging deployment — the same API key authenticates both.\n */\n platformURL?: string;\n /** Inject a `fetch` implementation (Workers environments, test harnesses). */\n fetch?: typeof globalThis.fetch;\n /**\n * Number of automatic retries on transient failures (5xx, 408, and\n * a 429 that asks for another attempt). Defaults to 2. Set to 0 to\n * disable. The retry budget is bounded; doesn't apply to 4xx\n * validation / auth failures.\n *\n * A **quota** refusal (429 `rate_limit_exceeded`) is deliberately\n * NOT retried: the window is an hour, a retry inside it cannot\n * succeed, and it would only burn another slot. The error carries\n * `limit` / `remaining` / `resetAt` so the caller can wait for the\n * window instead of guessing.\n */\n maxRetries?: number;\n /**\n * Optional request-id header for cross-stack tracing. If set,\n * every outbound request carries `X-Flowmails-Request-Id`, and\n * the SDK backend echoes it back on the response so callers can\n * correlate platform logs with their own.\n */\n requestId?: string;\n}\n\nexport class Flowmails {\n private readonly apiKey: string;\n private readonly baseURL: string;\n private readonly platformURL: string;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly maxRetries: number;\n private readonly requestId?: string;\n\n constructor(opts: FlowmailsOptions) {\n if (!opts.apiKey) {\n throw new Error(\"Flowmails: apiKey is required\");\n }\n this.apiKey = opts.apiKey;\n this.baseURL = (opts.baseURL ?? \"https://sdk.flowmails.net\").replace(\n /\\/+$/,\n \"\",\n );\n // The listen half of the surface lives on the platform worker,\n // not the SDK backend: the event log, the durable wait and the\n // message read are platform D1 state, and the platform is where\n // the agent's key already authenticates. One key, two origins —\n // sending is the SDK backend's job, reading is the platform's.\n this.platformURL = (opts.platformURL ?? \"https://flowmails.net\").replace(\n /\\/+$/,\n \"\",\n );\n // `globalThis.fetch` MUST be bound before it is stored on an instance.\n // workerd implements `fetch` as a WebIDL operation whose `this` must be\n // the global object, so calling `this.fetchFn(url, …)` passes the\n // `Flowmails` instance instead and workerd throws\n // `TypeError: Illegal invocation`. That rejection lands in the catch\n // below and is reported as `UpstreamError(\"network_error\", …, 0)` — a\n // \"network\" failure that never touched the network, which is exactly how\n // it presented: auth mail silently never sending.\n //\n // Node's undici tolerates the detached call, so this is invisible in\n // `node --test` and in any browser; it only reproduces in the Workers\n // runtime. An *injected* `opts.fetch` is left unbound — it is the\n // caller's own function, not a WebIDL operation.\n this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);\n this.maxRetries = opts.maxRetries ?? 2;\n this.requestId = opts.requestId;\n }\n\n /**\n * Send mail through the SDK backend.\n *\n * Pass `replyToMessageId` to answer a message in thread — the SDK\n * backend resolves the parent and derives the `In-Reply-To` /\n * `References` headers and the thread anchor, so the recipient's\n * client threads it with the original conversation.\n *\n * Returns `{ id, status, messageId }` on success; throws one of\n * `AuthenticationError` / `ValidationError` / `RateLimitError` /\n * `UpstreamError` on failure (all subclasses of `FlowmailsError`).\n */\n async send(opts: SendOptions): Promise<SendResult> {\n // The wire-shape renames (html → content, Uint8Array → base64)\n // happen here: the SDK's DTO mirrors common email clients, the\n // wire mirrors the receive worker.\n const body = {\n from: opts.from,\n fromName: opts.fromName,\n to: Array.isArray(opts.to) ? opts.to : [opts.to],\n replyTo: opts.replyTo,\n // The SDK backend resolves this to the three `threading`\n // fields. The caller names the **parent**, never the headers —\n // hand-deriving `References` is how threads fork.\n replyToMessageId: opts.replyToMessageId,\n subject: opts.subject,\n text: opts.text,\n html: opts.html,\n attachments: opts.attachments?.map((a) => ({\n filename: a.filename,\n content:\n a.content instanceof Uint8Array\n ? bytesToBase64(a.content)\n : a.content,\n mimeType: a.mimeType,\n })),\n // The idempotency key travels under the same name on the wire.\n // It is deliberately **not** renamed: the backend's body is\n // camelCase already, and a rename here would be one more place\n // for the two sides to disagree.\n idempotencyKey: opts.idempotencyKey,\n };\n\n return this.request<SendResult>(this.baseURL, \"POST\", \"/api/v1/messages\", {\n body,\n });\n }\n\n /**\n * The connection check — who the credential is.\n *\n * `flowmails test` (the CLI's documented first command) and every\n * \"is my setup right?\" question end here. It verifies the key,\n * names the account, names the bound domain and reports the\n * scopes — and it sends nothing, so running it can never mail\n * somebody by accident.\n *\n * @throws {AuthenticationError} when the key is missing, malformed\n * or revoked.\n */\n async me(): Promise<AccountInfo> {\n return this.request<AccountInfo>(this.baseURL, \"GET\", \"/api/v1/me\");\n }\n\n /**\n * The event log — the listen half of the surface, read with a\n * cursor.\n *\n * ```ts\n * const fm = new Flowmails({ apiKey: process.env.FLOWMAILS_API_KEY! });\n * let after: string | undefined;\n * for (;;) {\n * const page = await fm.events.list({ after, subject: \"invoice\" });\n * for (const event of page.events) { … }\n * after = page.nextCursor ?? after;\n * }\n * ```\n */\n readonly events: AgentEvents = {\n list: async (opts: ListEventsOptions = {}) => {\n const query: Record<string, string | number | undefined> = {\n after: opts.after,\n limit: opts.limit,\n recipient: opts.recipient,\n sender: opts.sender,\n subject: opts.subject,\n };\n return this.request<ListEventsResult>(\n this.platformURL,\n \"GET\",\n \"/api/agent/events\",\n { query },\n );\n },\n };\n\n /**\n * Read one message by its SMTP `Message-ID` — the id the event\n * carried.\n *\n * The event log deliberately hands over routing facts and a\n * subject and never a body (§4.2), so the content is an explicit\n * ask. This is that ask.\n */\n readonly messages: AgentMessages = {\n get: async (messageId: string, opts: { domainId?: string } = {}) => {\n if (!messageId) {\n throw new ValidationError(\"message_id_required\", \"messageId is required\");\n }\n return this.request<MessageDetail>(\n this.platformURL,\n \"GET\",\n `/api/agent/messages/${encodeURIComponent(messageId)}`,\n { query: { domainId: opts.domainId } },\n );\n },\n\n /**\n * Poll a **sent** message's delivery state.\n *\n * `id` is the value {@link send} returned as `id` (or the SMTP\n * `Message-ID`). Returns the worker's lifecycle state so an agent\n * can tell `sent` from `failed` (the two the worker writes)\n * instead of assuming success.\n */\n status: async (id: string) => {\n if (!id) {\n throw new ValidationError(\"message_id_required\", \"id is required\");\n }\n return this.request<SendStatus>(\n this.baseURL,\n \"GET\",\n `/api/v1/messages/${encodeURIComponent(id)}`,\n );\n },\n\n /**\n * Look back through the mailbox.\n *\n * The event log is the primary listen path; this is the history\n * path. A hit carries addressing, the subject and a preview — the\n * body is a separate, explicit ask.\n */\n search: async (domainId: string, opts: SearchMessagesOptions) => {\n if (!domainId) {\n throw new ValidationError(\"domain_id_required\", \"domainId is required\");\n }\n if (!opts?.q || opts.q.trim().length < 2) {\n throw new ValidationError(\n \"query_too_short\",\n \"q must be at least 2 characters\",\n );\n }\n return this.request<SearchMessagesResult>(\n this.platformURL,\n \"GET\",\n \"/api/agent/emails/search\",\n {\n query: {\n q: opts.q,\n domainId,\n limit: opts.limit,\n field: opts.field,\n type: opts.type,\n },\n },\n );\n },\n };\n\n /**\n * The conversation a message belongs to.\n *\n * The core listen/reply loop can store the message ids itself;\n * this is for the agent that wants the platform to reconstruct the\n * chain. The chain is read from the **conversation root's** SMTP\n * `Message-ID`, which is exactly what `email.threadId` holds.\n */\n readonly threads: AgentThreads = {\n get: async (threadId: string, opts: { domainId?: string } = {}) => {\n if (!threadId) {\n throw new ValidationError(\"thread_id_required\", \"threadId is required\");\n }\n return this.request<ThreadDetail>(\n this.platformURL,\n \"GET\",\n `/api/agent/threads/${encodeURIComponent(threadId)}`,\n { query: { domainId: opts.domainId } },\n );\n },\n };\n\n /**\n * The durable wait — the one thing an agent cannot build for\n * itself.\n *\n * A suspended HTTP request dies on the edge long before a\n * verification mail arrives (minutes to hours later), so the wait\n * is a row on the platform and the agent polls it. `create()`\n * answers **immediately**; it does not block.\n */\n readonly waits: AgentWaits = {\n create: async (opts: CreateWaitOptions) => {\n return this.request<CreateWaitResult>(\n this.platformURL,\n \"POST\",\n \"/api/agent/waits\",\n { body: opts },\n );\n },\n get: async (waitId: string) => {\n if (!waitId) {\n throw new ValidationError(\"wait_id_required\", \"waitId is required\");\n }\n return this.request<WaitStatus>(\n this.platformURL,\n \"GET\",\n `/api/agent/waits/${encodeURIComponent(waitId)}`,\n );\n },\n };\n\n /**\n * The addresses (mailboxes) the key's account owns, and the one\n * narrow write the agent surface has: create a single one.\n */\n readonly addresses: AgentAddresses = {\n listDomains: async () => {\n const result = await this.request<{ domains: AgentDomain[] }>(\n this.platformURL,\n \"GET\",\n \"/api/agent/domains\",\n );\n return result.domains;\n },\n list: async (domainId: string) => {\n if (!domainId) {\n throw new ValidationError(\"domain_id_required\", \"domainId is required\");\n }\n const result = await this.request<{\n domainId: string;\n domain: string;\n routingMode: \"catchall\" | \"rules\";\n localParts: string[];\n addresses: string[];\n acceptsAnyLocalPart: boolean;\n }>(\n this.platformURL,\n \"GET\",\n `/api/agent/domains/${encodeURIComponent(domainId)}/addresses`,\n );\n return result;\n },\n create: async (domainId: string, localPart: string) => {\n if (!domainId) {\n throw new ValidationError(\"domain_id_required\", \"domainId is required\");\n }\n return this.request<CreateAddressResult>(\n this.platformURL,\n \"POST\",\n `/api/agent/domains/${encodeURIComponent(domainId)}/addresses`,\n { body: { localPart } },\n );\n },\n };\n\n /**\n * Private: the one request path, with retry + backoff + error\n * mapping shared by every public method.\n *\n * `origin` is explicit because the surface spans two deployments:\n * the SDK backend (`baseURL`) for sending, the platform\n * (`platformURL`) for reading and waiting. `method` is explicit\n * because the listen endpoints are GETs — the v0.1 helper was\n * POST-only, which is why reading used to mean hand-rolling HTTP.\n */\n private async request<T>(\n origin: string,\n method: \"GET\" | \"POST\",\n path: string,\n opts: {\n body?: unknown;\n query?: Record<string, string | number | undefined>;\n } = {},\n ): Promise<T> {\n const url = buildUrl(origin, path, opts.query);\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n };\n // A GET carries no body, and sending `Content-Type: application/json`\n // with one would be a lie some proxies act on.\n if (method === \"POST\") headers[\"Content-Type\"] = \"application/json\";\n if (this.requestId) headers[\"X-Flowmails-Request-Id\"] = this.requestId;\n\n let lastError: FlowmailsError | null = null;\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n let res: Response;\n try {\n res = await this.fetchFn(url, {\n method,\n headers,\n ...(method === \"POST\" ? { body: JSON.stringify(opts.body) } : {}),\n // 15s matches the platform's upstream timeout — we want our\n // error to be \"request timed out\" rather than a generic 502.\n signal: AbortSignal.timeout(15_000),\n });\n } catch (err) {\n lastError = new UpstreamError(\n \"network_error\",\n err instanceof Error ? err.message : undefined,\n 0,\n );\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n\n // 2xx — happy path. Decode and return.\n if (res.ok) {\n return (await res.json()) as T;\n }\n\n // Non-2xx — render to a typed error.\n let payload: {\n error?: string;\n detail?: string;\n reason?: string;\n limit?: number;\n remaining?: number;\n resetAt?: string;\n } = {};\n try {\n payload = (await res.json()) as typeof payload;\n } catch {\n // Body wasn't JSON; fall back to status-based error.\n }\n\n const code = payload.error ?? \"request_failed\";\n\n if (res.status === 401) throw new AuthenticationError(code, res.status);\n if (\n res.status === 400 ||\n res.status === 404 ||\n res.status === 422 ||\n res.status === 409\n ) {\n // 409 is the idempotency conflict: the same key was already\n // used for a **different** payload. That is a client bug, not\n // a transient failure — answering it with a retryable error\n // would have the agent send the same wrong thing again.\n throw new ValidationError(code, payload.detail, res.status);\n }\n if (res.status === 429) {\n // Two different 429s, and they need different handling:\n //\n // - `idempotency_key_in_progress` — the *same* request is\n // already running. Retrying it is exactly right, and it\n // replays the first attempt's answer.\n // - `rate_limit_exceeded` — the quota window is exhausted. A\n // retry inside the same window cannot succeed and would\n // only burn another slot, so it is **not** retried; the\n // error carries `resetAt` so the caller can wait for the\n // window instead of guessing.\n const facts = readQuotaFacts(res, payload);\n if (code === \"idempotency_key_in_progress\") {\n lastError = new RateLimitError(code, res.status, facts);\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n throw new RateLimitError(code, res.status, facts);\n }\n if (res.status >= 500 || res.status === 408) {\n lastError = new UpstreamError(code, payload.detail, res.status);\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n\n // Anything else: not retryable, throw immediately.\n throw new FlowmailsError(code, `Request failed: ${code}`, res.status);\n }\n\n // Shouldn't reach here — last iteration always throws. Type\n // assertion keeps the compiler happy without `any`.\n throw lastError ?? new FlowmailsError(\"unknown\", \"Unknown failure\", 0);\n }\n}\n\n/**\n * The event log namespace — see {@link Flowmails.events}.\n */\nexport interface AgentEvents {\n /**\n * One page of the log, oldest first, after `opts.after`.\n *\n * The cursor is an **event id**, never a timestamp: two events can\n * land in the same millisecond, and a cursor that can skip a row\n * loses mail. An unknown cursor is a `ValidationError`, never an\n * empty page — \"no new events\" would silently stop the agent\n * seeing mail.\n */\n list(opts?: ListEventsOptions): Promise<ListEventsResult>;\n}\n\n/**\n * The message-read namespace — see {@link Flowmails.messages}.\n */\nexport interface AgentMessages {\n /** Fetch the full content of one message by SMTP `Message-ID`. */\n get(\n messageId: string,\n opts?: { domainId?: string },\n ): Promise<MessageDetail>;\n /** Poll a sent message's delivery state by row id or `Message-ID`. */\n status(id: string): Promise<SendStatus>;\n /**\n * `search_emails`: look **back** through the mailbox.\n *\n * The event log is the primary listen path — a cursor over what\n * just arrived. Search is the history path: \"what did that\n * supplier mail me last quarter?\" is not an event-log question,\n * and the event log carries no body.\n *\n * A result carries addressing, the subject and a short **preview**;\n * the body is fetched per message with {@link AgentMessages.get},\n * so a search is never a way to pull the whole mailbox through a\n * query parameter.\n */\n search(\n domainId: string,\n opts: SearchMessagesOptions,\n ): Promise<SearchMessagesResult>;\n}\n\n/**\n * The conversation namespace — see {@link Flowmails.threads}.\n */\nexport interface AgentThreads {\n /**\n * Read the conversation a message belongs to.\n *\n * `threadId` is the conversation **root's** SMTP `Message-ID` —\n * the value `email.threadId` holds, never an intermediate parent's.\n * An agent that holds an intermediate message id still gets the\n * whole chain: the platform resolves it to its row and reads the\n * chain from that row's own anchor.\n */\n get(threadId: string, opts?: { domainId?: string }): Promise<ThreadDetail>;\n}\n\n/**\n * The durable-wait namespace — see {@link Flowmails.waits}.\n */\nexport interface AgentWaits {\n /** Open a wait. Answers immediately; poll {@link AgentWaits.get}. */\n create(opts: CreateWaitOptions): Promise<CreateWaitResult>;\n /** Read a wait. A wait past its deadline reads as `expired`. */\n get(waitId: string): Promise<WaitStatus>;\n}\n\n/**\n * The address namespace — see {@link Flowmails.addresses}.\n */\nexport interface AgentAddresses {\n /** `list_domains`: every domain on the key's account. */\n listDomains(): Promise<AgentDomain[]>;\n /** `list_addresses`: one domain's local parts and routing mode. */\n list(domainId: string): Promise<{\n domainId: string;\n domain: string;\n routingMode: \"catchall\" | \"rules\";\n localParts: string[];\n addresses: string[];\n /** True when every local part already delivers (catch-all mode). */\n acceptsAnyLocalPart: boolean;\n }>;\n /**\n * `create_address`: add **one** local part.\n *\n * Idempotent — creating an address that already exists answers\n * with `created: false` rather than an error. It never changes the\n * routing mode, never removes a part and never clears the table:\n * mode changes and route-table editing stay dashboard-only.\n */\n create(domainId: string, localPart: string): Promise<CreateAddressResult>;\n}\n\n/**\n * A sent message's delivery state.\n *\n * `status` is the receive worker's lifecycle literal, so an agent can\n * distinguish \"the relay took it\" from \"the recipient's server\n * accepted it\" from \"it bounced\" — the v0.1 SDK collapsed all of them\n * into `\"queued\"` and dropped the relay's `Message-ID` with them.\n */\nexport interface SendStatus {\n /** The worker's row id. */\n id: string;\n /**\n * `sent` (the relay accepted it) or `failed` (the relay rejected it)\n * — those are the two the receive worker writes for an outbound\n * message today.\n *\n * The vocabulary also holds `delivered` / `bounced` / `complained` /\n * `delayed`, and the backend maps them if they appear, but the\n * worker has no DSN or bounce ingestion and never writes them. **A\n * bounce is not observable today.**\n */\n status: string;\n /** The SMTP `Message-ID`; empty when the relay never accepted it. */\n messageId: string;\n /** The relay's error string when `status` is `failed`, else null. */\n sendFeedback: string | null;\n /** `CURRENT_TIMESTAMP` from the worker; opaque to the SDK. */\n createdAt: string | null;\n}\n\n// ---------- Module-level helpers ----------\n\n/**\n * Read the quota facts off a rate-limited response.\n *\n * The body is the source of truth (`limit` / `remaining` / `resetAt`);\n * the headers are the fallback, because something in front of the\n * backend may strip the body but not the headers.\n *\n * `X-Flowmails-RateLimit-Reset` is epoch **seconds** (the HTTP\n * convention); the body's `resetAt` is ISO-8601. The header is\n * converted so both end up in the same shape on the error.\n */\nfunction readQuotaFacts(\n res: Response,\n payload: { limit?: number; remaining?: number; resetAt?: string },\n): { limit?: number; remaining?: number; resetAt?: string } | undefined {\n const limit =\n typeof payload.limit === \"number\" ? payload.limit : undefined;\n let remaining =\n typeof payload.remaining === \"number\" ? payload.remaining : undefined;\n let resetAt =\n typeof payload.resetAt === \"string\" ? payload.resetAt : undefined;\n\n const headerRemaining = res.headers?.get?.(\n \"X-Flowmails-RateLimit-Remaining\",\n );\n if (remaining === undefined && headerRemaining) {\n const parsed = Number(headerRemaining);\n if (Number.isFinite(parsed)) remaining = parsed;\n }\n\n const headerReset = res.headers?.get?.(\"X-Flowmails-RateLimit-Reset\");\n if (resetAt === undefined && headerReset) {\n const parsed = Number(headerReset);\n if (Number.isFinite(parsed)) {\n resetAt = new Date(parsed * 1000).toISOString();\n }\n }\n\n if (limit === undefined && remaining === undefined && resetAt === undefined) {\n return undefined;\n }\n return { limit, remaining, resetAt };\n}\n\n/**\n * Compose a request URL, dropping undefined / empty query values.\n *\n * An absent filter must not travel as `?subject=undefined` or as an\n * empty `?subject=` — the platform treats an empty string as a real\n * filter value in some places, so \"not asked for\" and \"asked for the\n * empty string\" have to stay distinguishable on the wire.\n */\nfunction buildUrl(\n origin: string,\n path: string,\n query?: Record<string, string | number | undefined>,\n): string {\n const url = new URL(`${origin}${path}`);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null || value === \"\") continue;\n url.searchParams.set(key, String(value));\n }\n }\n return url.toString();\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n // Browser-safe base64 of a `Uint8Array`. Avoids pulling in a\n // Buffer polyfill in the worker / browser bundles.\n let bin = \"\";\n for (let i = 0; i < bytes.length; i++) {\n bin += String.fromCharCode(bytes[i]);\n }\n return btoa(bin);\n}\n\nfunction backoffMs(attempt: number): number {\n // Exponential backoff with jitter, capped at 4 s. attempt 0 → 250 ms.\n const base = Math.min(250 * 2 ** attempt, 4_000);\n return base + Math.floor(Math.random() * base);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@flowmails/flowmails-sdk",
3
- "version": "0.1.1",
4
- "description": "Official JavaScript / TypeScript SDK for the Flowmails transactional email API (https://sdk.flowmails.net).",
3
+ "version": "0.2.0",
4
+ "description": "Official JavaScript / TypeScript SDK for the Flowmails email API (https://sdk.flowmails.net): send, reply in thread, wait for inbound mail, read messages, and create addresses.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
7
7
  "module": "./dist/index.js",
@@ -18,16 +18,22 @@
18
18
  "README.md",
19
19
  "LICENSE"
20
20
  ],
21
- "scripts": {
22
- "build": "tsup",
23
- "dev": "tsup --watch",
24
- "typecheck": "tsc -p tsconfig.json --noEmit",
25
- "clean": "rm -rf dist",
26
- "test": "vitest run",
27
- "test:unit": "vitest run test/unit",
28
- "test:integration": "vitest run test/integration",
29
- "test:watch": "vitest"
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/wms-why/flowmails-cf.git",
24
+ "directory": "packages/sdk"
25
+ },
26
+ "homepage": "https://flowmails.net/docs",
27
+ "bugs": {
28
+ "url": "https://github.com/wms-why/flowmails-cf/issues"
30
29
  },
30
+ "keywords": [
31
+ "flowmails",
32
+ "email",
33
+ "sdk",
34
+ "agent",
35
+ "api"
36
+ ],
31
37
  "publishConfig": {
32
38
  "access": "public"
33
39
  },
@@ -39,5 +45,15 @@
39
45
  "engines": {
40
46
  "node": ">=18.0.0"
41
47
  },
42
- "license": "MIT"
48
+ "license": "MIT",
49
+ "scripts": {
50
+ "build": "tsup",
51
+ "dev": "tsup --watch",
52
+ "typecheck": "tsc -p tsconfig.json --noEmit",
53
+ "clean": "rm -rf dist",
54
+ "test": "vitest run",
55
+ "test:unit": "vitest run test/unit",
56
+ "test:integration": "vitest run test/integration",
57
+ "test:watch": "vitest"
58
+ }
43
59
  }