@repa/mail 0.0.0-stage → 0.1.0-alpha.21

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 ADDED
@@ -0,0 +1,280 @@
1
+ import { MAXIMUM_SEND_BODY_BYTES, MAXIMUM_SEND_BYTES, headlessOperations } from './chunk-RQOWWVHG.js';
2
+ import { EmailError, publicErrorCodes } from './chunk-XW4CRZRY.js';
3
+ export { EmailError } from './chunk-XW4CRZRY.js';
4
+ import { createHmac, timingSafeEqual } from 'crypto';
5
+
6
+ // src/headless.ts
7
+ function headlessMethods(call) {
8
+ async function invoke(name, input, options = {}) {
9
+ const operation = headlessOperations[name];
10
+ const parsed = operation.input.safeParse(input);
11
+ if (!parsed.success) throw new EmailError("INVALID_REQUEST");
12
+ const body = JSON.stringify(parsed.data);
13
+ if (Buffer.byteLength(body) > operation.requestBytes) throw new EmailError("INVALID_REQUEST");
14
+ const key = operation.key ? parsed.data[operation.key] : void 0;
15
+ return call(operation.path, (value) => {
16
+ const result = operation.output.safeParse(value);
17
+ if (!result.success) throw new EmailError("PROTOCOL");
18
+ return result.data;
19
+ }, options, { body, ...key ? { key } : {} }, void 0, void 0, operation.responseBytes);
20
+ }
21
+ const readMessage = (async (input, options) => {
22
+ const message = await invoke("read", input, options);
23
+ if ("newText" in message !== (input.content === "new")) throw new EmailError("PROTOCOL");
24
+ return message;
25
+ });
26
+ const draftNames = { schedule: "draftSchedule", unschedule: "draftUnschedule", list: "draftList", get: "draftGet", save: "draftSave", discard: "draftDiscard", prepare: "draftPrepare", send: "draftSend" };
27
+ return {
28
+ listMailboxes: (input, options) => invoke("mailboxes", input, options),
29
+ openMailbox: (accountId, options) => invoke("open", { accountId }, options),
30
+ listMessages: (input, options) => invoke("list", input, options),
31
+ readMessage,
32
+ listConversations: (input, options) => invoke("conversations", input, options),
33
+ readConversation: (input, options) => invoke("conversation", input, options),
34
+ downloadMessage: (input, options) => invoke("download", input, options),
35
+ changeMessage: (input, options) => invoke("change", input, options),
36
+ createFolder: (input, options) => invoke("createFolder", input, options),
37
+ renameFolder: (input, options) => invoke("renameFolder", input, options),
38
+ deleteFolder: (input, options) => invoke("deleteFolder", input, options),
39
+ getStorage: (accountId, options) => invoke("storage", { accountId }, options),
40
+ /** Mailbox rules need the "Read and organize" level or higher. Writes are compare-and-swap on
41
+ * `expectedRevision` (0: no rules yet) and send no Idempotency-Key; a refusal resolves `{status: 'rejected'}`. */
42
+ getRules: (input, options) => invoke("rulesGet", input, options),
43
+ checkRules: (input, options) => invoke("rulesCheck", input, options),
44
+ saveRules: (input, options) => invoke("rulesSave", input, options),
45
+ changeRules: (input, options) => invoke("rulesItems", input, options),
46
+ submitRaw: (input, options) => {
47
+ if (!(input.raw instanceof Uint8Array)) throw new EmailError("INVALID_REQUEST");
48
+ if (input.raw.byteLength > MAXIMUM_SEND_BYTES) throw new EmailError("MESSAGE_TOO_LARGE", { limitBytes: MAXIMUM_SEND_BYTES });
49
+ return invoke("submit", { ...input, raw: Buffer.from(input.raw).toString("base64") }, options);
50
+ },
51
+ draft: (action, input, options) => {
52
+ const name = draftNames[action];
53
+ if (!name) throw new EmailError("INVALID_REQUEST");
54
+ return invoke(name, input, options);
55
+ }
56
+ };
57
+ }
58
+ function createMailTransport(client) {
59
+ return {
60
+ mailboxes: (after, signal) => client.listMailboxes({ ...after ? { after } : {}, limit: 100 }, { signal }),
61
+ open: (accountId, signal) => client.openMailbox(accountId, { signal }),
62
+ list: (location, before, signal) => client.listMessages({ ...location, before, limit: 20 }, { signal }),
63
+ read: (location, signal) => client.readMessage(location, { signal }),
64
+ conversations: (location, cursor, signal) => client.listConversations({ ...location, cursor, limit: 20 }, { signal }),
65
+ conversation: (target, cursor, signal) => client.readConversation({ ...target, cursor, limit: 20 }, { signal }),
66
+ download: (location, signal) => client.downloadMessage(location, { signal }),
67
+ change: (input, signal) => client.changeMessage(input, { signal }),
68
+ createFolder: (input, signal) => client.createFolder(input, { signal }),
69
+ renameFolder: (input, signal) => client.renameFolder(input, { signal }),
70
+ deleteFolder: (input, signal) => client.deleteFolder(input, { signal }),
71
+ storage: (accountId, signal) => client.getStorage(accountId, { signal }),
72
+ draft: (action, input, signal) => client.draft(action, input, { signal }),
73
+ submit: (input, signal) => client.submitRaw(input, { signal })
74
+ };
75
+ }
76
+
77
+ // src/validation.ts
78
+ var uuid = (value) => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(value);
79
+ var subject = (value) => typeof value === "string" && /^[\x21-\x7e]{1,256}$/.test(value);
80
+ var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
81
+ var date = (value) => typeof value === "string" && /^\d{4}-\d\d-\d\dT/.test(value) && Number.isFinite(Date.parse(value));
82
+ var states = ["preparing", "pending", "accepted", "queued", "dispatching", "acceptance_unknown", "provider_accepted", "failed", "cancelled"];
83
+ var feedback = ["Send", "Delivery", "Bounce", "Complaint", "Reject", "Rendering Failure", "DeliveryDelay"];
84
+ var keys = (value, allowed) => Object.keys(value).length === allowed.length && Object.keys(value).every((k) => allowed.includes(k));
85
+ function assertUUID(value) {
86
+ if (!uuid(value)) throw new EmailError("INVALID_REQUEST");
87
+ }
88
+ function assertSubject(value) {
89
+ if (!subject(value)) throw new EmailError("INVALID_REQUEST");
90
+ }
91
+ function timeout(value) {
92
+ if (!Number.isInteger(value) || value < 1 || value > 12e4) throw new EmailError("INVALID_REQUEST");
93
+ return value;
94
+ }
95
+ var domainScopes = ["all", "except_personal", "without_mailbox"];
96
+ var exactSender = (v) => keys(v, ["grant", "id", "address", "sentAccountId", "ready"]) && uuid(v.id) && uuid(v.sentAccountId) && typeof v.address === "string" && v.address.length <= 320;
97
+ var domainSender = (v) => keys(v, ["grant", "domainId", "domain", "scope", "ready"]) && uuid(v.domainId) && typeof v.domain === "string" && v.domain.length <= 253 && domainScopes.includes(String(v.scope));
98
+ function senders(value) {
99
+ if (!Array.isArray(value) || value.length > 200 || value.some((v) => !record(v) || typeof v.ready !== "boolean" || !(v.grant === "sender" ? exactSender(v) : v.grant === "domain" && domainSender(v)))) throw new EmailError("PROTOCOL");
100
+ return value;
101
+ }
102
+ function submission(value) {
103
+ if (!record(value) || !keys(value, ["operationId", "state", "createdAt", "acceptedAt", "recipients"]) || !uuid(value.operationId) || !states.includes(String(value.state)) || !date(value.createdAt) || !(value.acceptedAt === null || date(value.acceptedAt)) || !Array.isArray(value.recipients) || value.recipients.length > 1e3 || value.recipients.some((v) => !record(v) || !keys(v, ["ordinal", "type", "at", "possibleComplainant"]) || !Number.isInteger(v.ordinal) || Number(v.ordinal) < 0 || Number(v.ordinal) > 50 || !feedback.includes(String(v.type)) || !date(v.at) || typeof v.possibleComplainant !== "boolean")) throw new EmailError("PROTOCOL");
104
+ return value;
105
+ }
106
+ function event(value) {
107
+ if (!record(value) || !keys(value, ["version", "id", "operationId", "type", "occurredAt"]) || value.version !== 1 || !uuid(value.id) || !uuid(value.operationId) || ![...states, ...feedback].includes(String(value.type)) || !date(value.occurredAt)) throw new EmailError("PROTOCOL");
108
+ return value;
109
+ }
110
+ function events(value) {
111
+ if (!record(value) || !keys(value, ["events", "next"]) || !Array.isArray(value.events) || value.events.length > 100 || !Number.isSafeInteger(value.next) || Number(value.next) < 0) throw new EmailError("PROTOCOL");
112
+ return { events: value.events.map(event), next: Number(value.next) };
113
+ }
114
+
115
+ // src/client.ts
116
+ var REPA_EMAIL_API_BASE_URL = "https://api.repa.run";
117
+ function createEmailClient(options) {
118
+ if ("window" in globalThis || typeof options.apiKey !== "string" || !/^repa_mail_api_[A-Za-z0-9_-]{43}$/.test(options.apiKey)) throw new EmailError("INVALID_REQUEST");
119
+ assertSubject(options.subject);
120
+ const key = options.apiKey, defaultSubject = options.subject, fetcher = options.fetch ?? globalThis.fetch;
121
+ const defaultTimeout = timeout(options.timeoutMs ?? 45e3);
122
+ let url;
123
+ try {
124
+ url = new URL(options.baseUrl ?? REPA_EMAIL_API_BASE_URL);
125
+ } catch {
126
+ throw new EmailError("INVALID_REQUEST");
127
+ }
128
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "[::1]"].includes(url.hostname)) || url.username || url.password || url.search || url.hash || url.pathname !== "/") throw new EmailError("INVALID_REQUEST");
129
+ const base = `${url.origin}/api/mail/v1`;
130
+ async function call(path, decode, request = {}, mutation, operationId, lookupKey, maximum = 1024 * 1024) {
131
+ const partition = request.subject ?? defaultSubject;
132
+ assertSubject(partition);
133
+ const deadline = AbortSignal.timeout(timeout(request.timeoutMs ?? defaultTimeout));
134
+ const signal = request.signal ? AbortSignal.any([request.signal, deadline]) : deadline;
135
+ const metadata = { ...mutation || lookupKey ? { idempotencyKey: mutation?.key ?? lookupKey } : {}, ...operationId ? { operationId } : {} };
136
+ try {
137
+ const response = await raceSignal(fetcher(`${base}/${path}`, {
138
+ method: mutation ? "POST" : "GET",
139
+ headers: {
140
+ "x-api-key": key,
141
+ "x-repa-mail-subject": partition,
142
+ ...mutation ? { "content-type": "application/json", ...mutation.key ? { "idempotency-key": mutation.key } : {} } : {}
143
+ },
144
+ ...mutation ? { body: mutation.body } : {},
145
+ signal,
146
+ redirect: "error",
147
+ cache: "no-store"
148
+ }), signal);
149
+ const text = await boundedBody(response, signal, response.ok ? maximum : 4096);
150
+ let value;
151
+ try {
152
+ value = JSON.parse(text);
153
+ } catch {
154
+ throw new EmailError("PROTOCOL", metadata);
155
+ }
156
+ const requestId = response.headers.get("x-request-id");
157
+ if (!response.ok) {
158
+ const error = record(value) && record(value.error) ? value.error : null;
159
+ const code = error && typeof error.code === "string" && publicErrorCodes.includes(error.code) ? error.code : "PROTOCOL";
160
+ const retry = response.headers.get("retry-after");
161
+ throw new EmailError(code, {
162
+ ...metadata,
163
+ status: response.status,
164
+ ...code === "MESSAGE_TOO_LARGE" && error?.limitBytes === MAXIMUM_SEND_BYTES ? {
165
+ limitBytes: MAXIMUM_SEND_BYTES,
166
+ ...Number.isSafeInteger(error.attachmentBytes) && Number(error.attachmentBytes) >= 0 ? { attachmentBytes: Number(error.attachmentBytes) } : {},
167
+ ...Number.isSafeInteger(error.attachmentCapacityBytes) && Number(error.attachmentCapacityBytes) >= 0 ? { attachmentCapacityBytes: Number(error.attachmentCapacityBytes) } : {}
168
+ } : {},
169
+ ...requestId && /^[a-zA-Z0-9-]{1,80}$/.test(requestId) ? { requestId } : {},
170
+ ...retry && /^\d{1,5}$/.test(retry) ? { retryAfterSeconds: Number(retry) } : {}
171
+ });
172
+ }
173
+ if (!record(value) || Object.keys(value).length !== 1 || !Object.hasOwn(value, "data")) throw new EmailError("PROTOCOL", metadata);
174
+ return decode(value.data);
175
+ } catch (error) {
176
+ if (request.signal?.aborted) throw new EmailError("ABORTED", metadata);
177
+ if (deadline.aborted) throw new EmailError("TIMEOUT", metadata);
178
+ if (error instanceof EmailError) {
179
+ if (error.code === "PROTOCOL") throw new EmailError("PROTOCOL", metadata);
180
+ throw error;
181
+ }
182
+ throw new EmailError("CONNECTION", metadata);
183
+ }
184
+ }
185
+ return Object.freeze({
186
+ ...headlessMethods(call),
187
+ listSenders: (request) => call("senders", senders, request),
188
+ send: (message, request) => {
189
+ assertUUID(request.idempotencyKey);
190
+ let body;
191
+ try {
192
+ body = JSON.stringify(message);
193
+ } catch {
194
+ throw new EmailError("INVALID_REQUEST");
195
+ }
196
+ if (typeof body !== "string" || !record(message)) throw new EmailError("INVALID_REQUEST");
197
+ if (Buffer.byteLength(body) > MAXIMUM_SEND_BODY_BYTES) throw new EmailError("MESSAGE_TOO_LARGE", { limitBytes: MAXIMUM_SEND_BYTES });
198
+ return call("submissions", submission, request, { body, key: request.idempotencyKey });
199
+ },
200
+ getSubmission: (operationId, request) => {
201
+ assertUUID(operationId);
202
+ return call(`submissions/${operationId}`, submission, request, void 0, operationId);
203
+ },
204
+ findSubmissionByKey: (idempotencyKey, request) => {
205
+ assertUUID(idempotencyKey);
206
+ return call(`submissions/by-key/${idempotencyKey}`, submission, request, void 0, void 0, idempotencyKey);
207
+ },
208
+ listEvents: (page = {}, request) => {
209
+ const after = page.after ?? 0, limit = page.limit ?? 100;
210
+ if (!Number.isSafeInteger(after) || after < 0 || !Number.isInteger(limit) || limit < 1 || limit > 100) throw new EmailError("INVALID_REQUEST");
211
+ return call(`events?after=${after}&limit=${limit}`, events, request);
212
+ }
213
+ });
214
+ }
215
+ async function boundedBody(response, signal, maximum) {
216
+ const reader = response.body?.getReader();
217
+ if (!reader) throw new EmailError("PROTOCOL");
218
+ const chunks = [];
219
+ let length = 0;
220
+ try {
221
+ for (; ; ) {
222
+ const { done, value } = await raceSignal(reader.read(), signal);
223
+ if (done) break;
224
+ length += value.byteLength;
225
+ if (length > maximum) throw new EmailError("PROTOCOL");
226
+ chunks.push(value);
227
+ }
228
+ return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks, length));
229
+ } finally {
230
+ void reader.cancel().catch(() => void 0);
231
+ reader.releaseLock();
232
+ }
233
+ }
234
+ function raceSignal(pending, signal) {
235
+ return new Promise((resolve, reject) => {
236
+ const abort = () => reject(new EmailError("ABORTED"));
237
+ pending.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
238
+ if (signal.aborted) abort();
239
+ else signal.addEventListener("abort", abort, { once: true });
240
+ });
241
+ }
242
+ function verifyEmailWebhook(input) {
243
+ try {
244
+ const headers = new Headers(input.headers), body = Buffer.from(input.body);
245
+ if (body.byteLength > 16 * 1024 || body.byteLength === 0) throw new Error();
246
+ const endpointId = headers.get("repa-endpoint-id"), deliveryId = headers.get("repa-delivery-id"), eventId = headers.get("repa-event-id");
247
+ const type = headers.get("repa-event-type"), version = headers.get("repa-secret-version");
248
+ const signature = /^t=(0|[1-9][0-9]{0,10}),v1=([A-Za-z0-9_-]{43})$/.exec(headers.get("repa-signature") ?? "");
249
+ if (!uuid(input.endpointId) || endpointId !== input.endpointId || !uuid(deliveryId) || !uuid(eventId) || type !== "mail.submission.status" || !version || !/^[1-9][0-9]{0,8}$/.test(version) || !signature) throw new Error();
250
+ const now = (input.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3, tolerance = input.toleranceSeconds ?? 300;
251
+ if (!Number.isFinite(now) || !Number.isInteger(tolerance) || tolerance < 0 || tolerance > 300 || Math.abs(now - Number(signature[1])) > tolerance) throw new Error();
252
+ const secretValue = input.secrets[Number(version)];
253
+ if (!secretValue || !/^[A-Za-z0-9_-]{43,86}$/.test(secretValue)) throw new Error();
254
+ const secret = Buffer.from(secretValue, "base64url");
255
+ if (secret.toString("base64url") !== secretValue || secret.length < 32 || secret.length > 64) throw new Error();
256
+ const frame = `v1
257
+ ${signature[1]}
258
+ ${deliveryId}
259
+ ${endpointId}
260
+ ${eventId}
261
+ ${type}
262
+ ${version}
263
+ ${body.byteLength}
264
+ `;
265
+ const expected = createHmac("sha256", secret).update(frame).update(body).digest();
266
+ secret.fill(0);
267
+ const supplied = Buffer.from(signature[2], "base64url");
268
+ if (supplied.toString("base64url") !== signature[2] || supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) throw new Error();
269
+ const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
270
+ if (!record(parsed) || Object.keys(parsed).length !== 5 || parsed.schemaVersion !== "devcited-webhook-event.v1" || parsed.id !== eventId || parsed.type !== type || !record(parsed.data) || Object.keys(parsed.data).length !== 7 || !Number.isSafeInteger(parsed.data.tenantId) || Number(parsed.data.tenantId) < 1 || !uuid(parsed.data.integrationId)) throw new Error();
271
+ const { tenantId: workspaceId, integrationId: _principal, ...mailEvent } = parsed.data;
272
+ const validated = event(mailEvent);
273
+ if (validated.id !== eventId || validated.occurredAt !== parsed.occurredAt) throw new Error();
274
+ return { ...parsed, data: { ...mailEvent, workspaceId, integrationId: _principal } };
275
+ } catch {
276
+ throw new EmailError("INVALID_SIGNATURE");
277
+ }
278
+ }
279
+
280
+ export { REPA_EMAIL_API_BASE_URL, createEmailClient, createMailTransport, verifyEmailWebhook };