@fmontoya/aws-ses-adapter 1.0.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 ADDED
@@ -0,0 +1,446 @@
1
+ 'use strict';
2
+
3
+ var clientSes = require('@aws-sdk/client-ses');
4
+
5
+ // src/adapter.ts
6
+ function buildSesClient(config) {
7
+ return new clientSes.SESClient({
8
+ region: config.region,
9
+ credentials: {
10
+ accessKeyId: config.accessKeyId,
11
+ secretAccessKey: config.secretAccessKey
12
+ }
13
+ });
14
+ }
15
+
16
+ // src/errors.ts
17
+ var SesNotInitializedError = class extends Error {
18
+ constructor() {
19
+ super(
20
+ "SES Adapter has not been initialized. Call init() before using any adapter methods."
21
+ );
22
+ /** @override */
23
+ this.name = "SesNotInitializedError";
24
+ }
25
+ };
26
+ var SesConfigError = class extends Error {
27
+ /**
28
+ * @param message - Description of the configuration issue.
29
+ */
30
+ constructor(message) {
31
+ super(message);
32
+ /** @override */
33
+ this.name = "SesConfigError";
34
+ }
35
+ };
36
+ var SesSendError = class extends Error {
37
+ /**
38
+ * @param message - Description of the send failure.
39
+ * @param cause - The underlying error from AWS SDK.
40
+ */
41
+ constructor(message, cause) {
42
+ super(message, { cause });
43
+ /** @override */
44
+ this.name = "SesSendError";
45
+ }
46
+ };
47
+ var SesValidationError = class extends Error {
48
+ /**
49
+ * @param message - Description of the validation failure.
50
+ */
51
+ constructor(message) {
52
+ super(message);
53
+ /** @override */
54
+ this.name = "SesValidationError";
55
+ }
56
+ };
57
+
58
+ // src/adapter.ts
59
+ function resolveConfig(config = {}) {
60
+ const region = config.region ?? process.env["AWS_SES_REGION"];
61
+ const accessKeyId = config.accessKeyId ?? process.env["AWS_ACCESS_KEY_ID"];
62
+ const secretAccessKey = config.secretAccessKey ?? process.env["AWS_SECRET_ACCESS_KEY"];
63
+ const defaultFrom = config.defaultFrom ?? process.env["AWS_SES_FROM_EMAIL"];
64
+ if (!region) {
65
+ throw new SesConfigError(
66
+ "AWS SES region is required. Provide it via config.region or the AWS_SES_REGION environment variable."
67
+ );
68
+ }
69
+ if (!accessKeyId) {
70
+ throw new SesConfigError(
71
+ "AWS access key ID is required. Provide it via config.accessKeyId or the AWS_ACCESS_KEY_ID environment variable."
72
+ );
73
+ }
74
+ if (!secretAccessKey) {
75
+ throw new SesConfigError(
76
+ "AWS secret access key is required. Provide it via config.secretAccessKey or the AWS_SECRET_ACCESS_KEY environment variable."
77
+ );
78
+ }
79
+ return { region, accessKeyId, secretAccessKey, defaultFrom };
80
+ }
81
+ function toArray(value) {
82
+ return Array.isArray(value) ? value : [value];
83
+ }
84
+ function encodeHeaderValue(value) {
85
+ if (!/[\u0080-\uFFFF]/.test(value)) return value;
86
+ return `=?UTF-8?B?${Buffer.from(value, "utf-8").toString("base64")}?=`;
87
+ }
88
+ function buildMimeMessage(options, from) {
89
+ const mixedBoundary = `----=_Mixed_${Date.now()}_${Math.random().toString(36).slice(2)}`;
90
+ const altBoundary = `----=_Alt_${Date.now()}_${Math.random().toString(36).slice(2)}`;
91
+ const lines = [];
92
+ lines.push(`From: ${from}`);
93
+ lines.push(`To: ${toArray(options.to).join(", ")}`);
94
+ if (options.cc) lines.push(`Cc: ${toArray(options.cc).join(", ")}`);
95
+ if (options.bcc) lines.push(`Bcc: ${toArray(options.bcc).join(", ")}`);
96
+ if (options.replyTo)
97
+ lines.push(`Reply-To: ${toArray(options.replyTo).join(", ")}`);
98
+ lines.push(`Subject: ${encodeHeaderValue(options.subject)}`);
99
+ lines.push("MIME-Version: 1.0");
100
+ lines.push(`Content-Type: multipart/mixed; boundary="${mixedBoundary}"`);
101
+ lines.push("");
102
+ if (options.html && options.text) {
103
+ lines.push(`--${mixedBoundary}`);
104
+ lines.push(
105
+ `Content-Type: multipart/alternative; boundary="${altBoundary}"`
106
+ );
107
+ lines.push("");
108
+ lines.push(`--${altBoundary}`);
109
+ lines.push("Content-Type: text/plain; charset=UTF-8");
110
+ lines.push("Content-Transfer-Encoding: 8bit");
111
+ lines.push("");
112
+ lines.push(options.text);
113
+ lines.push("");
114
+ lines.push(`--${altBoundary}`);
115
+ lines.push("Content-Type: text/html; charset=UTF-8");
116
+ lines.push("Content-Transfer-Encoding: 8bit");
117
+ lines.push("");
118
+ lines.push(options.html);
119
+ lines.push("");
120
+ lines.push(`--${altBoundary}--`);
121
+ lines.push("");
122
+ } else if (options.html) {
123
+ lines.push(`--${mixedBoundary}`);
124
+ lines.push("Content-Type: text/html; charset=UTF-8");
125
+ lines.push("Content-Transfer-Encoding: 8bit");
126
+ lines.push("");
127
+ lines.push(options.html);
128
+ lines.push("");
129
+ } else if (options.text) {
130
+ lines.push(`--${mixedBoundary}`);
131
+ lines.push("Content-Type: text/plain; charset=UTF-8");
132
+ lines.push("Content-Transfer-Encoding: 8bit");
133
+ lines.push("");
134
+ lines.push(options.text);
135
+ lines.push("");
136
+ }
137
+ for (const attachment of options.attachments) {
138
+ const encoded = encodeAttachment(attachment);
139
+ const safeName = attachment.filename.replace(/"/g, "");
140
+ lines.push(`--${mixedBoundary}`);
141
+ lines.push(`Content-Type: ${attachment.contentType}; name="${safeName}"`);
142
+ lines.push("Content-Transfer-Encoding: base64");
143
+ lines.push(`Content-Disposition: attachment; filename="${safeName}"`);
144
+ lines.push("");
145
+ lines.push(encoded.match(/.{1,76}/g)?.join("\r\n") ?? encoded);
146
+ lines.push("");
147
+ }
148
+ lines.push(`--${mixedBoundary}--`);
149
+ return lines.join("\r\n");
150
+ }
151
+ function encodeAttachment(attachment) {
152
+ if (Buffer.isBuffer(attachment.content)) {
153
+ return attachment.content.toString("base64");
154
+ }
155
+ return Buffer.from(attachment.content).toString("base64");
156
+ }
157
+ var SesAdapter = class {
158
+ /**
159
+ * Creates a new SesAdapter instance.
160
+ *
161
+ * @param userConfig - Optional configuration. Missing fields fall back to environment variables.
162
+ * @throws {SesConfigError} When required configuration fields are missing.
163
+ */
164
+ constructor(userConfig = {}) {
165
+ this.config = resolveConfig(userConfig);
166
+ this.sesClient = buildSesClient(this.config);
167
+ }
168
+ /**
169
+ * Sends an email using AWS SES.
170
+ *
171
+ * At least one of `options.html` or `options.text` must be provided.
172
+ * If `options.from` is not specified, the `defaultFrom` configured during
173
+ * initialization is used. If neither is available, the call throws.
174
+ *
175
+ * @param options - Email sending options.
176
+ * @returns A promise resolving to a {@link SendEmailResult}.
177
+ * @throws {SesValidationError} When required email fields are missing or invalid.
178
+ * @throws {SesSendError} When the AWS SES API call fails.
179
+ *
180
+ * @example
181
+ * ```ts
182
+ * const result = await adapter.sendEmail({
183
+ * to: ['alice@example.com', 'bob@example.com'],
184
+ * subject: 'Hello!',
185
+ * html: '<p>Hello World</p>',
186
+ * text: 'Hello World',
187
+ * cc: 'manager@example.com',
188
+ * });
189
+ * ```
190
+ */
191
+ async sendEmail(options) {
192
+ if (!options.html && !options.text) {
193
+ throw new SesValidationError(
194
+ 'At least one of "html" or "text" must be provided in SendEmailOptions.'
195
+ );
196
+ }
197
+ const from = options.from ?? this.config.defaultFrom;
198
+ if (!from) {
199
+ throw new SesValidationError(
200
+ 'A sender address is required. Provide "from" in SendEmailOptions or set "defaultFrom" during init().'
201
+ );
202
+ }
203
+ const toAddresses = toArray(options.to);
204
+ const params = {
205
+ Source: from,
206
+ Destination: {
207
+ ToAddresses: toAddresses,
208
+ CcAddresses: options.cc ? toArray(options.cc) : void 0,
209
+ BccAddresses: options.bcc ? toArray(options.bcc) : void 0
210
+ },
211
+ Message: {
212
+ Subject: {
213
+ Data: options.subject,
214
+ Charset: "UTF-8"
215
+ },
216
+ Body: {
217
+ Html: options.html ? { Data: options.html, Charset: "UTF-8" } : void 0,
218
+ Text: options.text ? { Data: options.text, Charset: "UTF-8" } : void 0
219
+ }
220
+ },
221
+ ReplyToAddresses: options.replyTo ? toArray(options.replyTo) : void 0
222
+ };
223
+ try {
224
+ const command = new clientSes.SendEmailCommand(params);
225
+ const response = await this.sesClient.send(command);
226
+ return {
227
+ success: true,
228
+ messageId: response.MessageId
229
+ };
230
+ } catch (error) {
231
+ throw new SesSendError(
232
+ `Failed to send email to ${toAddresses.join(", ")}: ${error instanceof Error ? error.message : String(error)}`,
233
+ error
234
+ );
235
+ }
236
+ }
237
+ /**
238
+ * Sends a raw MIME email using AWS SES.
239
+ *
240
+ * Use this method when you need full control over the email format, such as
241
+ * sending emails with attachments or custom headers.
242
+ *
243
+ * @param rawMessage - The raw MIME email message as a string.
244
+ * @returns A promise resolving to a {@link SendEmailResult}.
245
+ * @throws {SesValidationError} When the raw message is empty.
246
+ * @throws {SesSendError} When the AWS SES API call fails.
247
+ *
248
+ * @example
249
+ * ```ts
250
+ * const mimeMessage = [
251
+ * 'From: sender@example.com',
252
+ * 'To: recipient@example.com',
253
+ * 'Subject: Test',
254
+ * 'MIME-Version: 1.0',
255
+ * 'Content-Type: text/plain',
256
+ * '',
257
+ * 'Hello World',
258
+ * ].join('\r\n');
259
+ *
260
+ * const result = await adapter.sendRawEmail(mimeMessage);
261
+ * ```
262
+ */
263
+ async sendRawEmail(rawMessage) {
264
+ if (!rawMessage || rawMessage.trim().length === 0) {
265
+ throw new SesValidationError("rawMessage cannot be empty.");
266
+ }
267
+ const params = {
268
+ RawMessage: {
269
+ Data: Buffer.from(rawMessage)
270
+ }
271
+ };
272
+ try {
273
+ const command = new clientSes.SendRawEmailCommand(params);
274
+ const response = await this.sesClient.send(command);
275
+ return {
276
+ success: true,
277
+ messageId: response.MessageId
278
+ };
279
+ } catch (error) {
280
+ throw new SesSendError(
281
+ `Failed to send raw email: ${error instanceof Error ? error.message : String(error)}`,
282
+ error
283
+ );
284
+ }
285
+ }
286
+ /**
287
+ * Sends an email with one or more file attachments using AWS SES.
288
+ *
289
+ * Internally builds a multipart/mixed MIME message and dispatches it via
290
+ * `SendRawEmailCommand`, giving you full attachment support without needing
291
+ * to craft raw MIME by hand.
292
+ *
293
+ * At least one of `options.html` or `options.text` must be provided.
294
+ * The `options.attachments` array must contain at least one item.
295
+ *
296
+ * @param options - Email options including the attachments array.
297
+ * @returns A promise resolving to a {@link SendEmailResult}.
298
+ * @throws {SesValidationError} When required fields are missing or invalid.
299
+ * @throws {SesSendError} When the AWS SES API call fails.
300
+ *
301
+ * @example
302
+ * ```ts
303
+ * const result = await adapter.sendEmailWithAttachments({
304
+ * to: 'alice@example.com',
305
+ * subject: 'Your invoice',
306
+ * html: '<p>Please find the invoice attached.</p>',
307
+ * attachments: [
308
+ * {
309
+ * filename: 'invoice.pdf',
310
+ * content: fs.readFileSync('./invoice.pdf'),
311
+ * contentType: 'application/pdf',
312
+ * },
313
+ * ],
314
+ * });
315
+ * ```
316
+ */
317
+ async sendEmailWithAttachments(options) {
318
+ if (!options.html && !options.text) {
319
+ throw new SesValidationError(
320
+ 'At least one of "html" or "text" must be provided in SendEmailWithAttachmentsOptions.'
321
+ );
322
+ }
323
+ if (!options.attachments || options.attachments.length === 0) {
324
+ throw new SesValidationError(
325
+ "At least one attachment must be provided in SendEmailWithAttachmentsOptions.attachments."
326
+ );
327
+ }
328
+ const from = options.from ?? this.config.defaultFrom;
329
+ if (!from) {
330
+ throw new SesValidationError(
331
+ 'A sender address is required. Provide "from" in SendEmailWithAttachmentsOptions or set "defaultFrom" during init().'
332
+ );
333
+ }
334
+ const rawMessage = buildMimeMessage(options, from);
335
+ const toAddresses = toArray(options.to);
336
+ const params = {
337
+ RawMessage: {
338
+ Data: Buffer.from(rawMessage)
339
+ }
340
+ };
341
+ try {
342
+ const command = new clientSes.SendRawEmailCommand(params);
343
+ const response = await this.sesClient.send(command);
344
+ return {
345
+ success: true,
346
+ messageId: response.MessageId
347
+ };
348
+ } catch (error) {
349
+ throw new SesSendError(
350
+ `Failed to send email with attachments to ${toAddresses.join(", ")}: ${error instanceof Error ? error.message : String(error)}`,
351
+ error
352
+ );
353
+ }
354
+ }
355
+ /**
356
+ * Returns whether the adapter has a default "From" address configured.
357
+ *
358
+ * @returns `true` if a default from address is available.
359
+ *
360
+ * @example
361
+ * ```ts
362
+ * if (adapter.hasDefaultFrom()) {
363
+ * console.log('Default from:', adapter.getDefaultFrom());
364
+ * }
365
+ * ```
366
+ */
367
+ hasDefaultFrom() {
368
+ return !!this.config.defaultFrom;
369
+ }
370
+ /**
371
+ * Returns the default "From" email address, or `undefined` if not set.
372
+ *
373
+ * @returns The default sender address, or `undefined`.
374
+ *
375
+ * @example
376
+ * ```ts
377
+ * const from = adapter.getDefaultFrom();
378
+ * // => 'noreply@example.com' or undefined
379
+ * ```
380
+ */
381
+ getDefaultFrom() {
382
+ return this.config.defaultFrom;
383
+ }
384
+ /**
385
+ * Returns the AWS region the adapter is configured to use.
386
+ *
387
+ * @returns The AWS region string.
388
+ *
389
+ * @example
390
+ * ```ts
391
+ * console.log(adapter.getRegion()); // => 'us-east-1'
392
+ * ```
393
+ */
394
+ getRegion() {
395
+ return this.config.region;
396
+ }
397
+ };
398
+
399
+ // src/index.ts
400
+ var _instance = null;
401
+ function getInstance() {
402
+ if (!_instance) {
403
+ throw new SesNotInitializedError();
404
+ }
405
+ return _instance;
406
+ }
407
+ function init(config = {}) {
408
+ _instance = new SesAdapter(config);
409
+ }
410
+ async function sendEmail(options) {
411
+ return getInstance().sendEmail(options);
412
+ }
413
+ async function sendEmailWithAttachments(options) {
414
+ return getInstance().sendEmailWithAttachments(options);
415
+ }
416
+ async function sendRawEmail(rawMessage) {
417
+ return getInstance().sendRawEmail(rawMessage);
418
+ }
419
+ function isInitialized() {
420
+ return _instance !== null;
421
+ }
422
+ function hasDefaultFrom() {
423
+ return getInstance().hasDefaultFrom();
424
+ }
425
+ function getDefaultFrom() {
426
+ return getInstance().getDefaultFrom();
427
+ }
428
+ function getRegion() {
429
+ return getInstance().getRegion();
430
+ }
431
+
432
+ exports.SesAdapter = SesAdapter;
433
+ exports.SesConfigError = SesConfigError;
434
+ exports.SesNotInitializedError = SesNotInitializedError;
435
+ exports.SesSendError = SesSendError;
436
+ exports.SesValidationError = SesValidationError;
437
+ exports.getDefaultFrom = getDefaultFrom;
438
+ exports.getRegion = getRegion;
439
+ exports.hasDefaultFrom = hasDefaultFrom;
440
+ exports.init = init;
441
+ exports.isInitialized = isInitialized;
442
+ exports.sendEmail = sendEmail;
443
+ exports.sendEmailWithAttachments = sendEmailWithAttachments;
444
+ exports.sendRawEmail = sendRawEmail;
445
+ //# sourceMappingURL=index.js.map
446
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts","../src/errors.ts","../src/adapter.ts","../src/index.ts"],"names":["SESClient","SendEmailCommand","SendRawEmailCommand"],"mappings":";;;;;AA2BO,SAAS,eAAe,MAAA,EAA6C;AAC1E,EAAA,OAAO,IAAIA,mBAAA,CAAU;AAAA,IACnB,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,WAAA,EAAa;AAAA,MACX,aAAa,MAAA,CAAO,WAAA;AAAA,MACpB,iBAAiB,MAAA,CAAO;AAAA;AAC1B,GACD,CAAA;AACH;;;ACVO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EAIhD,WAAA,GAAc;AACZ,IAAA,KAAA;AAAA,MACE;AAAA,KACF;AALF;AAAA,IAAA,IAAA,CAAS,IAAA,GAAO,wBAAA;AAAA,EAMhB;AACF;AAoBO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA,EAOxC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AANf;AAAA,IAAA,IAAA,CAAS,IAAA,GAAO,gBAAA;AAAA,EAOhB;AACF;AAoBO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA,EAQtC,WAAA,CAAY,SAAiB,KAAA,EAAiB;AAC5C,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,CAAA;AAP1B;AAAA,IAAA,IAAA,CAAS,IAAA,GAAO,cAAA;AAAA,EAQhB;AACF;AAoBO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA;A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,CAAE,wBAAA,CAAyB,OAAO,CAAA;AACvD;AA+BA,eAAsB,aACpB,UAAA,EAC0B;AAC1B,EAAA,OAAO,WAAA,EAAY,CAAE,YAAA,CAAa,UAAU,CAAA;AAC9C;AAgBO,SAAS,aAAA,GAAyB;AACvC,EAAA,OAAO,SAAA,KAAc,IAAA;AACvB;AAeO,SAAS,cAAA,GAA0B;AACxC,EAAA,OAAO,WAAA,GAAc,cAAA,EAAe;AACtC;AAiBO,SAAS,cAAA,GAAqC;AACnD,EAAA,OAAO,WAAA,GAAc,cAAA,EAAe;AACtC;AAeO,SAAS,SAAA,GAAoB;AAClC,EAAA,OAAO,WAAA,GAAc,SAAA,EAAU;AACjC","file":"index.js","sourcesContent":["/**\n * @module client\n * Factory and utilities for building an AWS SESClient instance\n * from a resolved adapter configuration.\n */\n\nimport { SESClient } from '@aws-sdk/client-ses';\nimport type { ResolvedSesAdapterConfig } from './types.js';\n\n/**\n * Creates and returns a configured {@link SESClient} instance using the\n * resolved adapter configuration.\n *\n * @param config - The resolved configuration containing region and credentials.\n * @returns A ready-to-use AWS SESClient.\n *\n * @example\n * ```ts\n * const client = buildSesClient({\n * region: 'us-east-1',\n * accessKeyId: 'AKIAIOSFODNN7EXAMPLE',\n * secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',\n * });\n * ```\n *\n * @internal\n */\nexport function buildSesClient(config: ResolvedSesAdapterConfig): SESClient {\n return new SESClient({\n region: config.region,\n credentials: {\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n },\n });\n}\n","/**\n * @module errors\n * Custom error classes for the aws-ses-adapter library.\n * All errors extend the native `Error` class and include a `name` property\n * suitable for programmatic error identification.\n */\n\n/**\n * Thrown when an operation is attempted before the adapter has been initialized\n * via {@link init}.\n *\n * @example\n * ```ts\n * import { sendEmail } from 'aws-ses-adapter';\n *\n * // Calling sendEmail before init() throws this error\n * try {\n * await sendEmail({ to: 'user@example.com', subject: 'Hi', text: 'Hello' });\n * } catch (err) {\n * if (err instanceof SesNotInitializedError) {\n * console.error('Call init() first');\n * }\n * }\n * ```\n */\nexport class SesNotInitializedError extends Error {\n /** @override */\n readonly name = 'SesNotInitializedError' as const;\n\n constructor() {\n super(\n 'SES Adapter has not been initialized. Call init() before using any adapter methods.',\n );\n }\n}\n\n/**\n * Thrown when the configuration provided to {@link init} is invalid or incomplete.\n * This typically happens when required credentials are missing from both the config\n * object and the environment variables.\n *\n * @example\n * ```ts\n * import { init } from 'aws-ses-adapter';\n *\n * try {\n * init({}); // No region, no env vars set\n * } catch (err) {\n * if (err instanceof SesConfigError) {\n * console.error('Config error:', err.message);\n * }\n * }\n * ```\n */\nexport class SesConfigError extends Error {\n /** @override */\n readonly name = 'SesConfigError' as const;\n\n /**\n * @param message - Description of the configuration issue.\n */\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * Thrown when an email send operation fails at the AWS SES level.\n * The original AWS error is available via the `cause` property (ES2022+).\n *\n * @example\n * ```ts\n * import { sendEmail, SesSendError } from 'aws-ses-adapter';\n *\n * try {\n * await sendEmail({ to: 'user@example.com', subject: 'Hi', text: 'Hello' });\n * } catch (err) {\n * if (err instanceof SesSendError) {\n * console.error('Send failed:', err.message);\n * console.error('Original cause:', err.cause);\n * }\n * }\n * ```\n */\nexport class SesSendError extends Error {\n /** @override */\n readonly name = 'SesSendError' as const;\n\n /**\n * @param message - Description of the send failure.\n * @param cause - The underlying error from AWS SDK.\n */\n constructor(message: string, cause?: unknown) {\n super(message, { cause });\n }\n}\n\n/**\n * Thrown when {@link SendEmailOptions} are invalid, such as missing both\n * `html` and `text`, or having an invalid email address format.\n *\n * @example\n * ```ts\n * import { sendEmail, SesValidationError } from 'aws-ses-adapter';\n *\n * try {\n * // Missing both html and text\n * await sendEmail({ to: 'user@example.com', subject: 'Hi' });\n * } catch (err) {\n * if (err instanceof SesValidationError) {\n * console.error('Validation error:', err.message);\n * }\n * }\n * ```\n */\nexport class SesValidationError extends Error {\n /** @override */\n readonly name = 'SesValidationError' as const;\n\n /**\n * @param message - Description of the validation failure.\n */\n constructor(message: string) {\n super(message);\n }\n}\n","/**\n * @module adapter\n * Core SesAdapter class that wraps the AWS SES client and provides\n * simplified email sending methods.\n */\n\nimport type {\n SendEmailCommandInput,\n SendRawEmailCommandInput,\n SESClient,\n} from '@aws-sdk/client-ses';\nimport { SendEmailCommand, SendRawEmailCommand } from '@aws-sdk/client-ses';\nimport { buildSesClient } from './client.js';\nimport { SesConfigError, SesSendError, SesValidationError } from './errors.js';\nimport type {\n EmailAttachment,\n ResolvedSesAdapterConfig,\n SendEmailOptions,\n SendEmailResult,\n SendEmailWithAttachmentsOptions,\n SesAdapterConfig,\n} from './types.js';\n\n/**\n * Resolves the adapter configuration by merging user-provided values with\n * environment variable fallbacks.\n *\n * @param config - Optional user-provided configuration.\n * @returns The resolved configuration with all required fields populated.\n * @throws {SesConfigError} When required fields cannot be resolved from config or env vars.\n *\n * @internal\n */\nfunction resolveConfig(\n config: SesAdapterConfig = {},\n): ResolvedSesAdapterConfig {\n const region = config.region ?? process.env['AWS_SES_REGION'];\n const accessKeyId = config.accessKeyId ?? process.env['AWS_ACCESS_KEY_ID'];\n const secretAccessKey =\n config.secretAccessKey ?? process.env['AWS_SECRET_ACCESS_KEY'];\n const defaultFrom = config.defaultFrom ?? process.env['AWS_SES_FROM_EMAIL'];\n\n if (!region) {\n throw new SesConfigError(\n 'AWS SES region is required. Provide it via config.region or the AWS_SES_REGION environment variable.',\n );\n }\n if (!accessKeyId) {\n throw new SesConfigError(\n 'AWS access key ID is required. Provide it via config.accessKeyId or the AWS_ACCESS_KEY_ID environment variable.',\n );\n }\n if (!secretAccessKey) {\n throw new SesConfigError(\n 'AWS secret access key is required. Provide it via config.secretAccessKey or the AWS_SECRET_ACCESS_KEY environment variable.',\n );\n }\n\n return { region, accessKeyId, secretAccessKey, defaultFrom };\n}\n\n/**\n * Normalizes a value that can be a single string or an array of strings\n * into a guaranteed array.\n *\n * @param value - A string or array of strings.\n * @returns An array of strings.\n *\n * @internal\n */\nfunction toArray(value: string | string[]): string[] {\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Encodes a MIME header value using RFC 2047 Base64 encoded-word syntax\n * when the value contains non-ASCII characters.\n *\n * @param value - The raw header value (e.g. a subject line).\n * @returns The value as-is if it is pure ASCII, otherwise `=?UTF-8?B?...?=`.\n *\n * @internal\n */\nfunction encodeHeaderValue(value: string): string {\n // If no non-ASCII characters are present, return as-is\n if (!/[\\u0080-\\uFFFF]/.test(value)) return value;\n return `=?UTF-8?B?${Buffer.from(value, 'utf-8').toString('base64')}?=`;\n}\n\n/**\n * Builds a multipart/mixed MIME email message ready to be sent via\n * `SendRawEmailCommand`.\n *\n * The body section uses multipart/alternative when both `html` and `text` are\n * supplied so that email clients can choose the best representation.\n *\n * @internal\n */\nfunction buildMimeMessage(\n options: SendEmailWithAttachmentsOptions,\n from: string,\n): string {\n const mixedBoundary = `----=_Mixed_${Date.now()}_${Math.random().toString(36).slice(2)}`;\n const altBoundary = `----=_Alt_${Date.now()}_${Math.random().toString(36).slice(2)}`;\n\n const lines: string[] = [];\n\n // RFC 2822 headers\n lines.push(`From: ${from}`);\n lines.push(`To: ${toArray(options.to).join(', ')}`);\n if (options.cc) lines.push(`Cc: ${toArray(options.cc).join(', ')}`);\n if (options.bcc) lines.push(`Bcc: ${toArray(options.bcc).join(', ')}`);\n if (options.replyTo)\n lines.push(`Reply-To: ${toArray(options.replyTo).join(', ')}`);\n lines.push(`Subject: ${encodeHeaderValue(options.subject)}`);\n lines.push('MIME-Version: 1.0');\n lines.push(`Content-Type: multipart/mixed; boundary=\"${mixedBoundary}\"`);\n lines.push('');\n\n // ── Body part ────────────────────────────────────────────────────────────\n if (options.html && options.text) {\n // Both formats: wrap in multipart/alternative\n lines.push(`--${mixedBoundary}`);\n lines.push(\n `Content-Type: multipart/alternative; boundary=\"${altBoundary}\"`,\n );\n lines.push('');\n\n lines.push(`--${altBoundary}`);\n lines.push('Content-Type: text/plain; charset=UTF-8');\n lines.push('Content-Transfer-Encoding: 8bit');\n lines.push('');\n lines.push(options.text);\n lines.push('');\n\n lines.push(`--${altBoundary}`);\n lines.push('Content-Type: text/html; charset=UTF-8');\n lines.push('Content-Transfer-Encoding: 8bit');\n lines.push('');\n lines.push(options.html);\n lines.push('');\n\n lines.push(`--${altBoundary}--`);\n lines.push('');\n } else if (options.html) {\n lines.push(`--${mixedBoundary}`);\n lines.push('Content-Type: text/html; charset=UTF-8');\n lines.push('Content-Transfer-Encoding: 8bit');\n lines.push('');\n lines.push(options.html);\n lines.push('');\n } else if (options.text) {\n lines.push(`--${mixedBoundary}`);\n lines.push('Content-Type: text/plain; charset=UTF-8');\n lines.push('Content-Transfer-Encoding: 8bit');\n lines.push('');\n lines.push(options.text);\n lines.push('');\n }\n\n // ── Attachment parts ─────────────────────────────────────────────────────\n for (const attachment of options.attachments) {\n const encoded = encodeAttachment(attachment);\n const safeName = attachment.filename.replace(/\"/g, '');\n\n lines.push(`--${mixedBoundary}`);\n lines.push(`Content-Type: ${attachment.contentType}; name=\"${safeName}\"`);\n lines.push('Content-Transfer-Encoding: base64');\n lines.push(`Content-Disposition: attachment; filename=\"${safeName}\"`);\n lines.push('');\n // RFC 2045: base64 lines must not exceed 76 characters\n lines.push(encoded.match(/.{1,76}/g)?.join('\\r\\n') ?? encoded);\n lines.push('');\n }\n\n lines.push(`--${mixedBoundary}--`);\n\n return lines.join('\\r\\n');\n}\n\n/**\n * Encodes an attachment's content as a base64 string.\n *\n * @param attachment - The attachment to encode.\n * @returns Base64-encoded string.\n *\n * @internal\n */\nfunction encodeAttachment(attachment: EmailAttachment): string {\n if (Buffer.isBuffer(attachment.content)) {\n return attachment.content.toString('base64');\n }\n return Buffer.from(attachment.content).toString('base64');\n}\n\n/**\n * Core adapter class that wraps the AWS SES client and provides a simplified\n * API for sending emails.\n *\n * This class is not meant to be instantiated directly by consumers.\n * Use the singleton functions exported from the main module instead.\n *\n * @see {@link init} to initialize the singleton.\n * @see {@link sendEmail} to send a standard email.\n * @see {@link sendRawEmail} to send a raw MIME email.\n */\nexport class SesAdapter {\n /** @internal */\n private readonly sesClient: SESClient;\n\n /** @internal */\n private readonly config: ResolvedSesAdapterConfig;\n\n /**\n * Creates a new SesAdapter instance.\n *\n * @param userConfig - Optional configuration. Missing fields fall back to environment variables.\n * @throws {SesConfigError} When required configuration fields are missing.\n */\n constructor(userConfig: SesAdapterConfig = {}) {\n this.config = resolveConfig(userConfig);\n this.sesClient = buildSesClient(this.config);\n }\n\n /**\n * Sends an email using AWS SES.\n *\n * At least one of `options.html` or `options.text` must be provided.\n * If `options.from` is not specified, the `defaultFrom` configured during\n * initialization is used. If neither is available, the call throws.\n *\n * @param options - Email sending options.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesValidationError} When required email fields are missing or invalid.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * const result = await adapter.sendEmail({\n * to: ['alice@example.com', 'bob@example.com'],\n * subject: 'Hello!',\n * html: '<p>Hello World</p>',\n * text: 'Hello World',\n * cc: 'manager@example.com',\n * });\n * ```\n */\n async sendEmail(options: SendEmailOptions): Promise<SendEmailResult> {\n if (!options.html && !options.text) {\n throw new SesValidationError(\n 'At least one of \"html\" or \"text\" must be provided in SendEmailOptions.',\n );\n }\n\n const from = options.from ?? this.config.defaultFrom;\n if (!from) {\n throw new SesValidationError(\n 'A sender address is required. Provide \"from\" in SendEmailOptions or set \"defaultFrom\" during init().',\n );\n }\n\n const toAddresses = toArray(options.to);\n\n const params: SendEmailCommandInput = {\n Source: from,\n Destination: {\n ToAddresses: toAddresses,\n CcAddresses: options.cc ? toArray(options.cc) : undefined,\n BccAddresses: options.bcc ? toArray(options.bcc) : undefined,\n },\n Message: {\n Subject: {\n Data: options.subject,\n Charset: 'UTF-8',\n },\n Body: {\n Html: options.html\n ? { Data: options.html, Charset: 'UTF-8' }\n : undefined,\n Text: options.text\n ? { Data: options.text, Charset: 'UTF-8' }\n : undefined,\n },\n },\n ReplyToAddresses: options.replyTo ? toArray(options.replyTo) : undefined,\n };\n\n try {\n const command = new SendEmailCommand(params);\n const response = await this.sesClient.send(command);\n\n return {\n success: true,\n messageId: response.MessageId,\n };\n } catch (error) {\n throw new SesSendError(\n `Failed to send email to ${toAddresses.join(', ')}: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Sends a raw MIME email using AWS SES.\n *\n * Use this method when you need full control over the email format, such as\n * sending emails with attachments or custom headers.\n *\n * @param rawMessage - The raw MIME email message as a string.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesValidationError} When the raw message is empty.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * const mimeMessage = [\n * 'From: sender@example.com',\n * 'To: recipient@example.com',\n * 'Subject: Test',\n * 'MIME-Version: 1.0',\n * 'Content-Type: text/plain',\n * '',\n * 'Hello World',\n * ].join('\\r\\n');\n *\n * const result = await adapter.sendRawEmail(mimeMessage);\n * ```\n */\n async sendRawEmail(rawMessage: string): Promise<SendEmailResult> {\n if (!rawMessage || rawMessage.trim().length === 0) {\n throw new SesValidationError('rawMessage cannot be empty.');\n }\n\n const params: SendRawEmailCommandInput = {\n RawMessage: {\n Data: Buffer.from(rawMessage),\n },\n };\n\n try {\n const command = new SendRawEmailCommand(params);\n const response = await this.sesClient.send(command);\n\n return {\n success: true,\n messageId: response.MessageId,\n };\n } catch (error) {\n throw new SesSendError(\n `Failed to send raw email: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Sends an email with one or more file attachments using AWS SES.\n *\n * Internally builds a multipart/mixed MIME message and dispatches it via\n * `SendRawEmailCommand`, giving you full attachment support without needing\n * to craft raw MIME by hand.\n *\n * At least one of `options.html` or `options.text` must be provided.\n * The `options.attachments` array must contain at least one item.\n *\n * @param options - Email options including the attachments array.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesValidationError} When required fields are missing or invalid.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * const result = await adapter.sendEmailWithAttachments({\n * to: 'alice@example.com',\n * subject: 'Your invoice',\n * html: '<p>Please find the invoice attached.</p>',\n * attachments: [\n * {\n * filename: 'invoice.pdf',\n * content: fs.readFileSync('./invoice.pdf'),\n * contentType: 'application/pdf',\n * },\n * ],\n * });\n * ```\n */\n async sendEmailWithAttachments(\n options: SendEmailWithAttachmentsOptions,\n ): Promise<SendEmailResult> {\n if (!options.html && !options.text) {\n throw new SesValidationError(\n 'At least one of \"html\" or \"text\" must be provided in SendEmailWithAttachmentsOptions.',\n );\n }\n\n if (!options.attachments || options.attachments.length === 0) {\n throw new SesValidationError(\n 'At least one attachment must be provided in SendEmailWithAttachmentsOptions.attachments.',\n );\n }\n\n const from = options.from ?? this.config.defaultFrom;\n if (!from) {\n throw new SesValidationError(\n 'A sender address is required. Provide \"from\" in SendEmailWithAttachmentsOptions or set \"defaultFrom\" during init().',\n );\n }\n\n const rawMessage = buildMimeMessage(options, from);\n const toAddresses = toArray(options.to);\n\n const params: SendRawEmailCommandInput = {\n RawMessage: {\n Data: Buffer.from(rawMessage),\n },\n };\n\n try {\n const command = new SendRawEmailCommand(params);\n const response = await this.sesClient.send(command);\n\n return {\n success: true,\n messageId: response.MessageId,\n };\n } catch (error) {\n throw new SesSendError(\n `Failed to send email with attachments to ${toAddresses.join(', ')}: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Returns whether the adapter has a default \"From\" address configured.\n *\n * @returns `true` if a default from address is available.\n *\n * @example\n * ```ts\n * if (adapter.hasDefaultFrom()) {\n * console.log('Default from:', adapter.getDefaultFrom());\n * }\n * ```\n */\n hasDefaultFrom(): boolean {\n return !!this.config.defaultFrom;\n }\n\n /**\n * Returns the default \"From\" email address, or `undefined` if not set.\n *\n * @returns The default sender address, or `undefined`.\n *\n * @example\n * ```ts\n * const from = adapter.getDefaultFrom();\n * // => 'noreply@example.com' or undefined\n * ```\n */\n getDefaultFrom(): string | undefined {\n return this.config.defaultFrom;\n }\n\n /**\n * Returns the AWS region the adapter is configured to use.\n *\n * @returns The AWS region string.\n *\n * @example\n * ```ts\n * console.log(adapter.getRegion()); // => 'us-east-1'\n * ```\n */\n getRegion(): string {\n return this.config.region;\n }\n}\n","/**\n * @module aws-ses-adapter\n *\n * A lightweight adapter that simplifies the AWS SES email sending API for Node.js.\n *\n * ## Quick Start\n *\n * **1. Initialize once** (at application startup):\n * ```ts\n * import { init } from 'aws-ses-adapter';\n *\n * init({\n * region: 'us-east-1',\n * accessKeyId: 'YOUR_KEY',\n * secretAccessKey: 'YOUR_SECRET',\n * defaultFrom: 'noreply@example.com',\n * });\n * ```\n *\n * **2. Use anywhere** in your application:\n * ```ts\n * import { sendEmail } from 'aws-ses-adapter';\n *\n * await sendEmail({\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * html: '<h1>Welcome</h1>',\n * });\n * ```\n *\n * ## Environment Variables\n *\n * If credentials are not passed to `init()`, the adapter reads:\n * - `AWS_SES_REGION`\n * - `AWS_ACCESS_KEY_ID`\n * - `AWS_SECRET_ACCESS_KEY`\n * - `AWS_SES_FROM_EMAIL` (optional default sender)\n */\n\nimport { SesAdapter } from './adapter.js';\nimport { SesNotInitializedError } from './errors.js';\nimport type {\n SendEmailOptions,\n SendEmailResult,\n SendEmailWithAttachmentsOptions,\n SesAdapterConfig,\n} from './types.js';\n\n// ─── Singleton state ──────────────────────────────────────────────────────────\n\n/** @internal */\nlet _instance: SesAdapter | null = null;\n\n/**\n * Returns the current singleton instance.\n * @throws {SesNotInitializedError} If `init()` has not been called yet.\n * @internal\n */\nfunction getInstance(): SesAdapter {\n if (!_instance) {\n throw new SesNotInitializedError();\n }\n return _instance;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Initializes the SES Adapter singleton.\n *\n * Must be called **once** before any other function in this module.\n * Calling `init()` again will replace the existing singleton instance,\n * which is useful for reconfiguration during testing.\n *\n * Credentials are resolved in the following order:\n * 1. Values provided in the `config` argument.\n * 2. Environment variables (`AWS_SES_REGION`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`).\n *\n * @param config - Optional configuration. Omit any field to fall back to environment variables.\n * @throws {SesConfigError} When required credentials cannot be resolved.\n *\n * @example\n * ```ts\n * // Using explicit credentials\n * init({\n * region: 'us-east-1',\n * accessKeyId: process.env.MY_KEY_ID,\n * secretAccessKey: process.env.MY_SECRET,\n * defaultFrom: 'no-reply@myapp.com',\n * });\n *\n * // Relying entirely on environment variables\n * init();\n * ```\n */\nexport function init(config: SesAdapterConfig = {}): void {\n _instance = new SesAdapter(config);\n}\n\n/**\n * Sends an email using the initialized SES Adapter.\n *\n * At least one of `options.html` or `options.text` must be provided.\n * If `options.from` is not specified, the `defaultFrom` set during {@link init} is used.\n *\n * @param options - Email sending options.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n * @throws {SesValidationError} When required email fields are missing or invalid.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * import { sendEmail } from 'aws-ses-adapter';\n *\n * const result = await sendEmail({\n * to: 'alice@example.com',\n * subject: 'Hello Alice',\n * html: '<p>Hi Alice!</p>',\n * text: 'Hi Alice!',\n * cc: 'manager@example.com',\n * bcc: ['audit@example.com'],\n * replyTo: 'support@example.com',\n * });\n *\n * console.log(result.messageId);\n * ```\n */\nexport async function sendEmail(\n options: SendEmailOptions,\n): Promise<SendEmailResult> {\n return getInstance().sendEmail(options);\n}\n\n/**\n * Sends an email with one or more file attachments using the initialized SES Adapter.\n *\n * Internally builds a multipart/mixed MIME message, so you don't need to\n * construct raw MIME yourself. At least one of `options.html` or `options.text`\n * must be provided, and `options.attachments` must contain at least one item.\n *\n * @param options - Email options including the attachments array.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n * @throws {SesValidationError} When required fields are missing or invalid.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * import { sendEmailWithAttachments } from 'aws-ses-adapter';\n * import { readFileSync } from 'fs';\n *\n * const result = await sendEmailWithAttachments({\n * to: 'alice@example.com',\n * subject: 'Your invoice',\n * html: '<p>Please find the invoice attached.</p>',\n * attachments: [\n * {\n * filename: 'invoice.pdf',\n * content: readFileSync('./invoice.pdf'),\n * contentType: 'application/pdf',\n * },\n * ],\n * });\n *\n * console.log(result.messageId);\n * ```\n */\nexport async function sendEmailWithAttachments(\n options: SendEmailWithAttachmentsOptions,\n): Promise<SendEmailResult> {\n return getInstance().sendEmailWithAttachments(options);\n}\n\n/**\n * Sends a raw MIME email using the initialized SES Adapter.\n *\n * Use this when you need full control over the email, such as including\n * attachments or custom MIME headers.\n *\n * @param rawMessage - The raw MIME email message as a string.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n * @throws {SesValidationError} When the raw message is empty.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * import { sendRawEmail } from 'aws-ses-adapter';\n *\n * const mime = [\n * 'From: sender@example.com',\n * 'To: recipient@example.com',\n * 'Subject: File attached',\n * 'MIME-Version: 1.0',\n * 'Content-Type: text/plain',\n * '',\n * 'Please find the attachment.',\n * ].join('\\r\\n');\n *\n * const result = await sendRawEmail(mime);\n * ```\n */\nexport async function sendRawEmail(\n rawMessage: string,\n): Promise<SendEmailResult> {\n return getInstance().sendRawEmail(rawMessage);\n}\n\n/**\n * Returns whether the singleton has been initialized via {@link init}.\n *\n * @returns `true` if `init()` has been called successfully.\n *\n * @example\n * ```ts\n * import { isInitialized } from 'aws-ses-adapter';\n *\n * if (!isInitialized()) {\n * init();\n * }\n * ```\n */\nexport function isInitialized(): boolean {\n return _instance !== null;\n}\n\n/**\n * Returns whether a default \"From\" address is configured in the singleton.\n *\n * @returns `true` if a default sender address is set.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n *\n * @example\n * ```ts\n * import { hasDefaultFrom } from 'aws-ses-adapter';\n *\n * console.log(hasDefaultFrom()); // => true\n * ```\n */\nexport function hasDefaultFrom(): boolean {\n return getInstance().hasDefaultFrom();\n}\n\n/**\n * Returns the default \"From\" email address configured in the singleton,\n * or `undefined` if none was set.\n *\n * @returns The default sender address, or `undefined`.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n *\n * @example\n * ```ts\n * import { getDefaultFrom } from 'aws-ses-adapter';\n *\n * const from = getDefaultFrom();\n * // => 'noreply@example.com' or undefined\n * ```\n */\nexport function getDefaultFrom(): string | undefined {\n return getInstance().getDefaultFrom();\n}\n\n/**\n * Returns the AWS region the singleton is configured to use.\n *\n * @returns The AWS region string (e.g. `'us-east-1'`).\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n *\n * @example\n * ```ts\n * import { getRegion } from 'aws-ses-adapter';\n *\n * console.log(getRegion()); // => 'us-east-1'\n * ```\n */\nexport function getRegion(): string {\n return getInstance().getRegion();\n}\n\n// ─── Re-exports ───────────────────────────────────────────────────────────────\n\n/**\n * Re-export the core adapter class for advanced use cases such as\n * creating multiple independent instances or building framework integrations\n * (e.g., a NestJS module).\n */\nexport { SesAdapter } from './adapter.js';\n\n/** Re-export all custom error classes for consumer-side `instanceof` checks. */\nexport {\n SesConfigError,\n SesNotInitializedError,\n SesSendError,\n SesValidationError,\n} from './errors.js';\n\n/** Re-export all public types and interfaces. */\nexport type {\n EmailAttachment,\n SendEmailOptions,\n SendEmailResult,\n SendEmailWithAttachmentsOptions,\n SesAdapterConfig,\n} from './types.js';\n"]}