@upyo/mailgun 0.1.0-dev.10

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/README.md ADDED
@@ -0,0 +1,62 @@
1
+ <!-- deno-fmt-ignore-file -->
2
+
3
+ @upyo/mailgun
4
+ =============
5
+
6
+ [Mailgun] transport for Upyo email library.
7
+
8
+ [Mailgun]: https://www.mailgun.com/
9
+
10
+
11
+ Installation
12
+ ------------
13
+
14
+ ~~~~ sh
15
+ npm add @upyo/core @upyo/mailgun
16
+ pnpm add @upyo/core @upyo/mailgun
17
+ yarn add @upyo/core @upyo/mailgun
18
+ deno add --jsr @upyo/core @upyo/mailgun
19
+ bun add @upyo/core @upyo/mailgun
20
+ ~~~~
21
+
22
+
23
+ Usage
24
+ -----
25
+
26
+ ~~~~ typescript
27
+ import { MailgunTransport } from '@upyo/mailgun';
28
+
29
+ const transport = new MailgunTransport({
30
+ apiKey: 'your-api-key',
31
+ domain: 'your-domain.com'
32
+ });
33
+
34
+ const message = {
35
+ sender: { address: 'sender@example.com' },
36
+ recipients: [{ address: 'recipient@example.com' }],
37
+ subject: 'Hello from Mailgun!',
38
+ content: { text: 'Hello, World!' }
39
+ };
40
+
41
+ const receipt = await transport.send(message);
42
+ console.log('Message sent:', receipt.messageId);
43
+ ~~~~
44
+
45
+
46
+ Configuration
47
+ -------------
48
+
49
+ See the [Mailgun docs] for more information about configuration options.
50
+
51
+ [Mailgun docs]: https://documentation.mailgun.com/
52
+
53
+ ### Available Options
54
+
55
+ - `apiKey`: Your Mailgun API key
56
+ - `domain`: Your Mailgun domain
57
+ - `region`: Mailgun region (`us` or `eu`, defaults to `us`)
58
+ - `timeout`: Request timeout in milliseconds (default: 30000)
59
+ - `retries`: Number of retry attempts (default: 3)
60
+ - `tracking`: Enable tracking (default: true)
61
+ - `clickTracking`: Enable click tracking (default: true)
62
+ - `openTracking`: Enable open tracking (default: true)
package/dist/index.cjs ADDED
@@ -0,0 +1,403 @@
1
+
2
+ //#region src/config.ts
3
+ /**
4
+ * Creates a resolved Mailgun configuration by applying default values to optional fields.
5
+ *
6
+ * This function takes a partial Mailgun configuration and returns a complete
7
+ * configuration with all optional fields filled with sensible defaults.
8
+ *
9
+ * @param config - The Mailgun configuration with optional fields
10
+ * @returns A resolved configuration with all defaults applied
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * const resolved = createMailgunConfig({
15
+ * apiKey: 'your-api-key',
16
+ * domain: 'your-domain.com'
17
+ * });
18
+ *
19
+ * // resolved.region will be 'us' (default)
20
+ * // resolved.timeout will be 30000 (default)
21
+ * // resolved.retries will be 3 (default)
22
+ * ```
23
+ */
24
+ function createMailgunConfig(config) {
25
+ const region = config.region ?? "us";
26
+ const baseUrl = config.baseUrl ?? getDefaultBaseUrl(region);
27
+ return {
28
+ apiKey: config.apiKey,
29
+ domain: config.domain,
30
+ region,
31
+ baseUrl,
32
+ timeout: config.timeout ?? 3e4,
33
+ retries: config.retries ?? 3,
34
+ validateSsl: config.validateSsl ?? true,
35
+ headers: config.headers ?? {},
36
+ tracking: config.tracking ?? true,
37
+ clickTracking: config.clickTracking ?? true,
38
+ openTracking: config.openTracking ?? true
39
+ };
40
+ }
41
+ /**
42
+ * Gets the default base URL for a given Mailgun region.
43
+ *
44
+ * @param region - The Mailgun region
45
+ * @returns The default base URL for the region
46
+ */
47
+ function getDefaultBaseUrl(region) {
48
+ switch (region) {
49
+ case "us": return "https://api.mailgun.net/v3";
50
+ case "eu": return "https://api.eu.mailgun.net/v3";
51
+ default: throw new Error(`Unsupported region: ${region}`);
52
+ }
53
+ }
54
+
55
+ //#endregion
56
+ //#region src/http-client.ts
57
+ /**
58
+ * HTTP client wrapper for Mailgun API requests.
59
+ *
60
+ * This class handles authentication, request formatting, error handling,
61
+ * and retry logic for Mailgun API calls.
62
+ */
63
+ var MailgunHttpClient = class {
64
+ config;
65
+ constructor(config) {
66
+ this.config = config;
67
+ }
68
+ /**
69
+ * Sends a message via Mailgun API.
70
+ *
71
+ * @param formData The form data to send to Mailgun.
72
+ * @param signal Optional AbortSignal for cancellation.
73
+ * @returns Promise that resolves to the Mailgun response.
74
+ */
75
+ sendMessage(formData, signal) {
76
+ const url = `${this.config.baseUrl}/${this.config.domain}/messages`;
77
+ return this.makeRequest(url, {
78
+ method: "POST",
79
+ body: formData,
80
+ signal
81
+ });
82
+ }
83
+ /**
84
+ * Makes an HTTP request to Mailgun API with retry logic.
85
+ *
86
+ * @param url The URL to make the request to.
87
+ * @param options Fetch options.
88
+ * @returns Promise that resolves to the parsed response.
89
+ */
90
+ async makeRequest(url, options) {
91
+ let lastError = null;
92
+ for (let attempt = 0; attempt <= this.config.retries; attempt++) try {
93
+ const response = await this.fetchWithAuth(url, options);
94
+ const text = await response.text();
95
+ let data;
96
+ try {
97
+ data = JSON.parse(text);
98
+ } catch {
99
+ throw new Error(text);
100
+ }
101
+ if (!response.ok) throw new MailgunApiError(data.message ?? `HTTP ${response.status}`, response.status);
102
+ return data;
103
+ } catch (error) {
104
+ lastError = error instanceof Error ? error : new Error(String(error));
105
+ if (error instanceof MailgunApiError && error.statusCode && error.statusCode >= 400 && error.statusCode < 500) throw error;
106
+ if (attempt === this.config.retries) throw error;
107
+ const delay = Math.pow(2, attempt) * 1e3;
108
+ await new Promise((resolve) => setTimeout(resolve, delay));
109
+ }
110
+ throw lastError || /* @__PURE__ */ new Error("Request failed after all retries");
111
+ }
112
+ /**
113
+ * Makes a fetch request with Mailgun authentication.
114
+ *
115
+ * @param url The URL to make the request to.
116
+ * @param options Fetch options.
117
+ * @returns Promise that resolves to the fetch response.
118
+ */
119
+ async fetchWithAuth(url, options) {
120
+ const headers = new Headers(options.headers);
121
+ const auth = btoa(`api:${this.config.apiKey}`);
122
+ headers.set("Authorization", `Basic ${auth}`);
123
+ for (const [key, value] of Object.entries(this.config.headers)) headers.set(key, value);
124
+ const controller = new AbortController();
125
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
126
+ let signal = controller.signal;
127
+ if (options.signal) signal = AbortSignal.any([controller.signal, options.signal]);
128
+ try {
129
+ return await globalThis.fetch(url, {
130
+ ...options,
131
+ headers,
132
+ signal
133
+ });
134
+ } finally {
135
+ clearTimeout(timeoutId);
136
+ }
137
+ }
138
+ };
139
+ /**
140
+ * Custom error class for Mailgun API errors.
141
+ */
142
+ var MailgunApiError = class extends Error {
143
+ statusCode;
144
+ constructor(message, statusCode) {
145
+ super(message);
146
+ this.name = "MailgunApiError";
147
+ this.statusCode = statusCode;
148
+ }
149
+ };
150
+
151
+ //#endregion
152
+ //#region src/message-converter.ts
153
+ /**
154
+ * Converts a Upyo Message to Mailgun API FormData format.
155
+ *
156
+ * This function transforms the standardized Upyo message format into
157
+ * the specific format expected by the Mailgun API.
158
+ *
159
+ * @param message - The Upyo message to convert
160
+ * @param config - The resolved Mailgun configuration
161
+ * @returns FormData object ready for Mailgun API submission
162
+ *
163
+ * @example
164
+ * ```typescript
165
+ * const formData = convertMessage(message, config);
166
+ * const response = await fetch(url, { method: 'POST', body: formData });
167
+ * ```
168
+ */
169
+ function convertMessage(message, config) {
170
+ const formData = new FormData();
171
+ formData.append("from", formatAddress(message.sender));
172
+ for (const recipient of message.recipients) formData.append("to", formatAddress(recipient));
173
+ for (const ccRecipient of message.ccRecipients) formData.append("cc", formatAddress(ccRecipient));
174
+ for (const bccRecipient of message.bccRecipients) formData.append("bcc", formatAddress(bccRecipient));
175
+ if (message.replyRecipients.length > 0) {
176
+ const replyTo = message.replyRecipients.map(formatAddress).join(", ");
177
+ formData.append("h:Reply-To", replyTo);
178
+ }
179
+ formData.append("subject", message.subject);
180
+ if ("html" in message.content) {
181
+ formData.append("html", message.content.html);
182
+ if (message.content.text) formData.append("text", message.content.text);
183
+ } else formData.append("text", message.content.text);
184
+ if (message.priority !== "normal") {
185
+ const priorityMap = {
186
+ "high": "1",
187
+ "normal": "3",
188
+ "low": "5"
189
+ };
190
+ formData.append("h:X-Priority", priorityMap[message.priority]);
191
+ }
192
+ for (const tag of message.tags) formData.append("o:tag", tag);
193
+ for (const [key, value] of message.headers.entries()) if (!isStandardHeader(key)) formData.append(`h:${key}`, value);
194
+ for (const attachment of message.attachments) appendAttachment(formData, attachment);
195
+ if (config.tracking !== void 0) formData.append("o:tracking", config.tracking ? "yes" : "no");
196
+ if (config.clickTracking !== void 0) formData.append("o:tracking-clicks", config.clickTracking ? "yes" : "no");
197
+ if (config.openTracking !== void 0) formData.append("o:tracking-opens", config.openTracking ? "yes" : "no");
198
+ return formData;
199
+ }
200
+ /**
201
+ * Formats an address for Mailgun API.
202
+ *
203
+ * @param address - The address to format
204
+ * @returns Formatted address string
205
+ */
206
+ function formatAddress(address) {
207
+ if (address.name) {
208
+ const escapedName = address.name.replace(/"/g, "\\\"");
209
+ return `"${escapedName}" <${address.address}>`;
210
+ }
211
+ return address.address;
212
+ }
213
+ /**
214
+ * Appends an attachment to the FormData.
215
+ *
216
+ * @param formData - The FormData to append to
217
+ * @param attachment - The attachment to append
218
+ */
219
+ function appendAttachment(formData, attachment) {
220
+ const blob = new Blob([attachment.content], { type: attachment.contentType });
221
+ if (attachment.contentId) formData.append("inline", blob, attachment.filename);
222
+ else formData.append("attachment", blob, attachment.filename);
223
+ }
224
+ /**
225
+ * Checks if a header is a standard email header that should not be prefixed with 'h:'.
226
+ *
227
+ * @param headerName - The header name to check
228
+ * @returns True if it's a standard header
229
+ */
230
+ function isStandardHeader(headerName) {
231
+ const standardHeaders = [
232
+ "from",
233
+ "to",
234
+ "cc",
235
+ "bcc",
236
+ "reply-to",
237
+ "subject",
238
+ "date",
239
+ "message-id",
240
+ "content-type",
241
+ "content-transfer-encoding",
242
+ "mime-version"
243
+ ];
244
+ return standardHeaders.includes(headerName.toLowerCase());
245
+ }
246
+
247
+ //#endregion
248
+ //#region src/mailgun-transport.ts
249
+ /**
250
+ * Mailgun transport implementation for sending emails via Mailgun API.
251
+ *
252
+ * This transport provides efficient email delivery using Mailgun's HTTP API,
253
+ * with support for authentication, retry logic, and batch sending capabilities.
254
+ *
255
+ * @example
256
+ * ```typescript
257
+ * import { MailgunTransport } from '@upyo/mailgun';
258
+ *
259
+ * const transport = new MailgunTransport({
260
+ * apiKey: 'your-api-key',
261
+ * domain: 'your-domain.com',
262
+ * region: 'us' // or 'eu'
263
+ * });
264
+ *
265
+ * const receipt = await transport.send(message);
266
+ * console.log('Message sent:', receipt.messageId);
267
+ * ```
268
+ */
269
+ var MailgunTransport = class {
270
+ config;
271
+ httpClient;
272
+ /**
273
+ * Creates a new Mailgun transport instance.
274
+ *
275
+ * @param config Mailgun configuration including API key, domain, and options.
276
+ */
277
+ constructor(config) {
278
+ this.config = createMailgunConfig(config);
279
+ this.httpClient = new MailgunHttpClient(this.config);
280
+ }
281
+ /**
282
+ * Sends a single email message via Mailgun API.
283
+ *
284
+ * This method converts the message to Mailgun format, makes an HTTP request
285
+ * to the Mailgun API, and returns a receipt with the result.
286
+ *
287
+ * @example
288
+ * ```typescript
289
+ * const receipt = await transport.send({
290
+ * sender: { address: 'from@example.com' },
291
+ * recipients: [{ address: 'to@example.com' }],
292
+ * ccRecipients: [],
293
+ * bccRecipients: [],
294
+ * replyRecipients: [],
295
+ * subject: 'Hello',
296
+ * content: { text: 'Hello World!' },
297
+ * attachments: [],
298
+ * priority: 'normal',
299
+ * tags: [],
300
+ * headers: new Headers()
301
+ * });
302
+ *
303
+ * if (receipt.successful) {
304
+ * console.log('Message sent with ID:', receipt.messageId);
305
+ * }
306
+ * ```
307
+ *
308
+ * @param message The email message to send.
309
+ * @param options Optional transport options including `AbortSignal` for
310
+ * cancellation.
311
+ * @returns A promise that resolves to a receipt indicating success or
312
+ * failure.
313
+ */
314
+ async send(message, options) {
315
+ options?.signal?.throwIfAborted();
316
+ try {
317
+ const formData = convertMessage(message, this.config);
318
+ options?.signal?.throwIfAborted();
319
+ const response = await this.httpClient.sendMessage(formData, options?.signal);
320
+ return {
321
+ messageId: response.id,
322
+ errorMessages: [],
323
+ successful: true
324
+ };
325
+ } catch (error) {
326
+ const errorMessage = error instanceof Error ? error.message : String(error);
327
+ return {
328
+ messageId: "",
329
+ errorMessages: [errorMessage],
330
+ successful: false
331
+ };
332
+ }
333
+ }
334
+ /**
335
+ * Sends multiple email messages efficiently via Mailgun API.
336
+ *
337
+ * This method sends each message individually but provides a streamlined
338
+ * interface for processing multiple messages. Each message is sent as a
339
+ * separate API request to Mailgun.
340
+ *
341
+ * @example
342
+ * ```typescript
343
+ * const messages = [
344
+ * {
345
+ * sender: { address: 'from@example.com' },
346
+ * recipients: [{ address: 'user1@example.com' }],
347
+ * ccRecipients: [],
348
+ * bccRecipients: [],
349
+ * replyRecipients: [],
350
+ * subject: 'Message 1',
351
+ * content: { text: 'Hello User 1!' },
352
+ * attachments: [],
353
+ * priority: 'normal',
354
+ * tags: [],
355
+ * headers: new Headers()
356
+ * },
357
+ * {
358
+ * sender: { address: 'from@example.com' },
359
+ * recipients: [{ address: 'user2@example.com' }],
360
+ * ccRecipients: [],
361
+ * bccRecipients: [],
362
+ * replyRecipients: [],
363
+ * subject: 'Message 2',
364
+ * content: { text: 'Hello User 2!' },
365
+ * attachments: [],
366
+ * priority: 'normal',
367
+ * tags: [],
368
+ * headers: new Headers()
369
+ * }
370
+ * ];
371
+ *
372
+ * for await (const receipt of transport.sendMany(messages)) {
373
+ * if (receipt.successful) {
374
+ * console.log('Sent:', receipt.messageId);
375
+ * } else {
376
+ * console.error('Failed:', receipt.errorMessages);
377
+ * }
378
+ * }
379
+ * ```
380
+ *
381
+ * @param messages An iterable or async iterable of messages to send.
382
+ * @param options Optional transport options including `AbortSignal` for
383
+ * cancellation.
384
+ * @returns An async iterable of receipts, one for each message.
385
+ */
386
+ async *sendMany(messages, options) {
387
+ options?.signal?.throwIfAborted();
388
+ const isAsyncIterable = Symbol.asyncIterator in messages;
389
+ if (isAsyncIterable) for await (const message of messages) {
390
+ options?.signal?.throwIfAborted();
391
+ yield await this.send(message, options);
392
+ }
393
+ else for (const message of messages) {
394
+ options?.signal?.throwIfAborted();
395
+ yield await this.send(message, options);
396
+ }
397
+ }
398
+ };
399
+
400
+ //#endregion
401
+ exports.MailgunApiError = MailgunApiError;
402
+ exports.MailgunTransport = MailgunTransport;
403
+ exports.createMailgunConfig = createMailgunConfig;