@miguelmorales13/nestkit 0.18.0 → 0.19.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.
@@ -0,0 +1,314 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+ var _chunkQ5Y33L7Bcjs = require('../chunk-Q5Y33L7B.cjs');
4
+ require('../chunk-PNK5WMPP.cjs');
5
+
6
+
7
+ var _chunk2REOCMUDcjs = require('../chunk-2REOCMUD.cjs');
8
+
9
+ // src/email/email.port.ts
10
+ var _common = require('@nestjs/common');
11
+ var EMAIL = /* @__PURE__ */ Symbol("EMAIL");
12
+ var EmailProviderException = class extends _chunkQ5Y33L7Bcjs.AppException {
13
+ constructor(provider, status, body, message) {
14
+ super(
15
+ "EMAIL_PROVIDER_ERROR",
16
+ _nullishCoalesce(message, () => ( `${provider} rejected the message (HTTP ${status})`)),
17
+ _common.HttpStatus.BAD_GATEWAY,
18
+ { provider, status, body }
19
+ );
20
+ }
21
+ };
22
+
23
+ // src/email/email.options.ts
24
+ var EMAIL_OPTIONS = /* @__PURE__ */ Symbol("EMAIL_OPTIONS");
25
+
26
+ // src/email/email.module.ts
27
+
28
+
29
+ // src/email/address.ts
30
+ var NAMED = /^\s*(?:"?([^"]*)"?\s*)?<\s*([^<>\s]+)\s*>\s*$/;
31
+ function parseAddress(address) {
32
+ if (typeof address !== "string") {
33
+ return address.name ? { email: address.email.trim(), name: address.name } : { email: address.email.trim() };
34
+ }
35
+ const match = NAMED.exec(address);
36
+ if (match) {
37
+ const name = _optionalChain([match, 'access', _ => _[1], 'optionalAccess', _2 => _2.trim, 'call', _3 => _3()]);
38
+ return name ? { email: match[2], name } : { email: match[2] };
39
+ }
40
+ return { email: address.trim() };
41
+ }
42
+ function formatAddress(address) {
43
+ const { email, name } = parseAddress(address);
44
+ if (!name) return email;
45
+ const safe = /[(),:;<>@[\]"]/.test(name) ? `"${name.replace(/"/g, '\\"')}"` : name;
46
+ return `${safe} <${email}>`;
47
+ }
48
+ function toList(value) {
49
+ if (value === void 0) return [];
50
+ return Array.isArray(value) ? value : [value];
51
+ }
52
+
53
+ // src/email/adapters/message.ts
54
+ function completeMessage(message, defaults) {
55
+ const from = _nullishCoalesce(message.from, () => ( defaults.from));
56
+ if (!from) {
57
+ throw new Error('EmailModule: the message has no "from" and no default was configured (EMAIL_FROM).');
58
+ }
59
+ if (!message.text && !message.html) {
60
+ throw new Error('EmailModule: a message needs "text" or "html".');
61
+ }
62
+ return { ...message, from, replyTo: _nullishCoalesce(message.replyTo, () => ( defaults.replyTo)) };
63
+ }
64
+ function attachmentBuffer(content) {
65
+ return Buffer.isBuffer(content) ? content : Buffer.from(content, "utf8");
66
+ }
67
+
68
+ // src/email/adapters/brevo.email.ts
69
+ var PROVIDER = "brevo";
70
+ var DEFAULT_BASE_URL = "https://api.brevo.com/v3";
71
+ var BrevoEmail = class {
72
+ constructor(options, defaults = {}) {
73
+ this.options = options;
74
+ this.defaults = defaults;
75
+ if (!options.apiKey) throw new Error('EmailModule: provider "brevo" selected but no apiKey / BREVO_API_KEY set.');
76
+ this.baseUrl = (_nullishCoalesce(options.baseUrl, () => ( DEFAULT_BASE_URL))).replace(/\/$/, "");
77
+ this.fetchImpl = _nullishCoalesce(options.fetchImpl, () => ( globalThis.fetch));
78
+ }
79
+ async send(input) {
80
+ const message = completeMessage(input, this.defaults);
81
+ const body = {
82
+ sender: parseAddress(message.from),
83
+ to: toList(message.to).map(parseAddress),
84
+ subject: message.subject
85
+ };
86
+ const cc = toList(message.cc).map(parseAddress);
87
+ const bcc = toList(message.bcc).map(parseAddress);
88
+ if (cc.length) body.cc = cc;
89
+ if (bcc.length) body.bcc = bcc;
90
+ if (message.replyTo) body.replyTo = parseAddress(message.replyTo);
91
+ if (message.html) body.htmlContent = message.html;
92
+ if (message.text) body.textContent = message.text;
93
+ if (message.headers) body.headers = message.headers;
94
+ if (message.tags) body.tags = Object.entries(message.tags).map(([k, v]) => `${k}:${v}`);
95
+ if (_optionalChain([message, 'access', _4 => _4.attachments, 'optionalAccess', _5 => _5.length])) {
96
+ body.attachment = message.attachments.map((a) => ({
97
+ name: a.filename,
98
+ content: attachmentBuffer(a.content).toString("base64")
99
+ }));
100
+ }
101
+ let response;
102
+ try {
103
+ response = await this.fetchImpl(`${this.baseUrl}/smtp/email`, {
104
+ method: "POST",
105
+ headers: {
106
+ "api-key": this.options.apiKey,
107
+ "content-type": "application/json",
108
+ accept: "application/json"
109
+ },
110
+ body: JSON.stringify(body)
111
+ });
112
+ } catch (cause) {
113
+ throw new EmailProviderException(
114
+ PROVIDER,
115
+ 0,
116
+ { error: cause instanceof Error ? cause.message : String(cause) },
117
+ `${PROVIDER} is unreachable`
118
+ );
119
+ }
120
+ const text = await response.text();
121
+ let parsed = text;
122
+ try {
123
+ parsed = text ? JSON.parse(text) : void 0;
124
+ } catch (e) {
125
+ }
126
+ if (!response.ok) throw new EmailProviderException(PROVIDER, response.status, parsed);
127
+ const id = _nullishCoalesce(_optionalChain([parsed, 'optionalAccess', _6 => _6.messageId]), () => ( null));
128
+ return { id, provider: PROVIDER };
129
+ }
130
+ };
131
+
132
+ // src/email/adapters/memory.email.ts
133
+ var MemoryEmail = class {
134
+ constructor(defaults = {}) {
135
+ this.defaults = defaults;
136
+ this.sent = [];
137
+ }
138
+ async send(message) {
139
+ this.sent.push(completeMessage(message, this.defaults));
140
+ return { id: `memory_${this.sent.length}`, provider: "memory" };
141
+ }
142
+ };
143
+
144
+ // src/email/adapters/resend.email.ts
145
+ var PROVIDER2 = "resend";
146
+ var ResendEmail = class {
147
+ constructor(options, defaults = {}, client) {
148
+ this.options = options;
149
+ this.defaults = defaults;
150
+ if (!options.apiKey) throw new Error('EmailModule: provider "resend" selected but no apiKey / RESEND_API_KEY set.');
151
+ if (client) this.clientPromise = Promise.resolve(client);
152
+ }
153
+ client() {
154
+ this.clientPromise ??= Promise.resolve().then(() => _interopRequireWildcard(require("resend"))).then(({ Resend }) => new Resend(this.options.apiKey));
155
+ return this.clientPromise;
156
+ }
157
+ async send(input) {
158
+ const message = completeMessage(input, this.defaults);
159
+ const client = await this.client();
160
+ const { data, error } = await client.emails.send({
161
+ from: formatAddress(message.from),
162
+ to: toList(message.to).map(formatAddress),
163
+ cc: toList(message.cc).map(formatAddress),
164
+ bcc: toList(message.bcc).map(formatAddress),
165
+ replyTo: message.replyTo ? formatAddress(message.replyTo) : void 0,
166
+ subject: message.subject,
167
+ html: message.html,
168
+ text: message.text,
169
+ headers: message.headers,
170
+ tags: message.tags ? Object.entries(message.tags).map(([name, value]) => ({ name, value })) : void 0,
171
+ attachments: _optionalChain([message, 'access', _7 => _7.attachments, 'optionalAccess', _8 => _8.map, 'call', _9 => _9((a) => ({
172
+ filename: a.filename,
173
+ content: attachmentBuffer(a.content),
174
+ contentType: a.contentType
175
+ }))])
176
+ });
177
+ if (error) {
178
+ throw new EmailProviderException(PROVIDER2, statusOf(error), error, `${PROVIDER2}: ${error.message}`);
179
+ }
180
+ return { id: _nullishCoalesce(_optionalChain([data, 'optionalAccess', _10 => _10.id]), () => ( null)), provider: PROVIDER2 };
181
+ }
182
+ };
183
+ function statusOf(error) {
184
+ return typeof error.statusCode === "number" ? error.statusCode : 0;
185
+ }
186
+
187
+ // src/email/adapters/smtp.email.ts
188
+ var PROVIDER3 = "smtp";
189
+ var SmtpEmail = class {
190
+ constructor(options, defaults = {}, transport) {
191
+ this.options = options;
192
+ this.defaults = defaults;
193
+ if (!options.host) throw new Error('EmailModule: provider "smtp" selected but no host / SMTP_HOST set.');
194
+ if (transport) this.transportPromise = Promise.resolve(transport);
195
+ }
196
+ transport() {
197
+ this.transportPromise ??= Promise.resolve().then(() => _interopRequireWildcard(require("nodemailer"))).then(
198
+ ({ default: nodemailer }) => nodemailer.createTransport({
199
+ host: this.options.host,
200
+ port: this.options.port,
201
+ secure: _nullishCoalesce(this.options.secure, () => ( false)),
202
+ auth: this.options.user ? { user: this.options.user, pass: this.options.password } : void 0
203
+ })
204
+ );
205
+ return this.transportPromise;
206
+ }
207
+ async send(input) {
208
+ const message = completeMessage(input, this.defaults);
209
+ const transport = await this.transport();
210
+ const headers = { ...message.headers };
211
+ for (const [name, value] of Object.entries(_nullishCoalesce(message.tags, () => ( {})))) headers[`X-Tag-${name}`] = value;
212
+ try {
213
+ const info = await transport.sendMail({
214
+ from: formatAddress(message.from),
215
+ to: toList(message.to).map(formatAddress),
216
+ cc: toList(message.cc).map(formatAddress),
217
+ bcc: toList(message.bcc).map(formatAddress),
218
+ replyTo: message.replyTo ? formatAddress(message.replyTo) : void 0,
219
+ subject: message.subject,
220
+ text: message.text,
221
+ html: message.html,
222
+ headers,
223
+ attachments: _optionalChain([message, 'access', _11 => _11.attachments, 'optionalAccess', _12 => _12.map, 'call', _13 => _13((a) => ({
224
+ filename: a.filename,
225
+ content: attachmentBuffer(a.content),
226
+ contentType: a.contentType
227
+ }))])
228
+ });
229
+ return { id: _nullishCoalesce(_optionalChain([info, 'optionalAccess', _14 => _14.messageId]), () => ( null)), provider: PROVIDER3 };
230
+ } catch (cause) {
231
+ const status = _nullishCoalesce(cause.responseCode, () => ( 0));
232
+ throw new EmailProviderException(
233
+ PROVIDER3,
234
+ status,
235
+ { error: cause instanceof Error ? cause.message : String(cause) },
236
+ `${PROVIDER3}: ${cause instanceof Error ? cause.message : "send failed"}`
237
+ );
238
+ }
239
+ }
240
+ };
241
+
242
+ // src/email/email.module.ts
243
+ var env = (k) => process.env[k] || void 0;
244
+ function resolveEmailOptions(options = {}) {
245
+ return {
246
+ provider: _nullishCoalesce(options.provider, () => ( env("EMAIL_PROVIDER"))),
247
+ from: _nullishCoalesce(options.from, () => ( env("EMAIL_FROM"))),
248
+ replyTo: _nullishCoalesce(options.replyTo, () => ( env("EMAIL_REPLY_TO"))),
249
+ resend: _nullishCoalesce(options.resend, () => ( (env("RESEND_API_KEY") ? { apiKey: env("RESEND_API_KEY") } : void 0))),
250
+ smtp: _nullishCoalesce(options.smtp, () => ( (env("SMTP_HOST") ? {
251
+ host: env("SMTP_HOST"),
252
+ port: Number(_nullishCoalesce(env("SMTP_PORT"), () => ( 587))),
253
+ secure: env("SMTP_SECURE") === "true",
254
+ user: env("SMTP_USER"),
255
+ password: env("SMTP_PASSWORD")
256
+ } : void 0))),
257
+ brevo: _nullishCoalesce(options.brevo, () => ( (env("BREVO_API_KEY") ? { apiKey: env("BREVO_API_KEY"), baseUrl: env("BREVO_BASE_URL") } : void 0)))
258
+ };
259
+ }
260
+ function createEmailAdapter(options = {}) {
261
+ const resolved = resolveEmailOptions(options);
262
+ const defaults = { from: resolved.from, replyTo: resolved.replyTo };
263
+ switch (resolved.provider) {
264
+ case "resend":
265
+ if (!resolved.resend) throw new Error('EmailModule: provider "resend" selected but no resend options / RESEND_API_KEY set.');
266
+ return new ResendEmail(resolved.resend, defaults);
267
+ case "smtp":
268
+ if (!resolved.smtp) throw new Error('EmailModule: provider "smtp" selected but no smtp options / SMTP_* env set.');
269
+ return new SmtpEmail(resolved.smtp, defaults);
270
+ case "brevo":
271
+ if (!resolved.brevo) throw new Error('EmailModule: provider "brevo" selected but no brevo options / BREVO_API_KEY set.');
272
+ return new BrevoEmail(resolved.brevo, defaults);
273
+ case "memory":
274
+ return new MemoryEmail(defaults);
275
+ case void 0:
276
+ throw new Error("EmailModule: no provider selected. Pass `provider` or set EMAIL_PROVIDER (resend | smtp | brevo | memory).");
277
+ default:
278
+ throw new Error(`EmailModule: unknown provider "${String(resolved.provider)}".`);
279
+ }
280
+ }
281
+ var EmailModule = class {
282
+ static forRoot(options = {}) {
283
+ const providers = [
284
+ { provide: EMAIL_OPTIONS, useValue: options },
285
+ { provide: EMAIL, useFactory: () => createEmailAdapter(options) }
286
+ ];
287
+ return { module: EmailModule, providers, exports: [EMAIL, EMAIL_OPTIONS] };
288
+ }
289
+ static forRootAsync(config) {
290
+ const providers = [
291
+ { provide: EMAIL_OPTIONS, useFactory: config.useFactory, inject: _nullishCoalesce(config.inject, () => ( [])) },
292
+ { provide: EMAIL, useFactory: (options) => createEmailAdapter(options), inject: [EMAIL_OPTIONS] }
293
+ ];
294
+ return { module: EmailModule, imports: _nullishCoalesce(config.imports, () => ( [])), providers, exports: [EMAIL, EMAIL_OPTIONS] };
295
+ }
296
+ };
297
+ EmailModule = exports.EmailModule = _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
298
+ _common.Global.call(void 0, ),
299
+ _common.Module.call(void 0, {})
300
+ ], EmailModule);
301
+
302
+
303
+
304
+
305
+
306
+
307
+
308
+
309
+
310
+
311
+
312
+
313
+
314
+ exports.BrevoEmail = BrevoEmail; exports.EMAIL = EMAIL; exports.EMAIL_OPTIONS = EMAIL_OPTIONS; exports.EmailModule = EmailModule; exports.EmailProviderException = EmailProviderException; exports.MemoryEmail = MemoryEmail; exports.ResendEmail = ResendEmail; exports.SmtpEmail = SmtpEmail; exports.createEmailAdapter = createEmailAdapter; exports.formatAddress = formatAddress; exports.parseAddress = parseAddress; exports.resolveEmailOptions = resolveEmailOptions;
@@ -0,0 +1,12 @@
1
+ export { EMAIL, EmailProviderException } from './email.port.js';
2
+ export type { EmailPort, EmailMessage, EmailAddress, EmailAttachment, SentEmail } from './email.port.js';
3
+ export { EMAIL_OPTIONS } from './email.options.js';
4
+ export type { EmailOptions, EmailProvider, ResendEmailOptions, SmtpEmailOptions, BrevoEmailOptions, } from './email.options.js';
5
+ export { EmailModule, createEmailAdapter, resolveEmailOptions } from './email.module.js';
6
+ export { parseAddress, formatAddress } from './address.js';
7
+ export { BrevoEmail } from './adapters/brevo.email.js';
8
+ export { ResendEmail } from './adapters/resend.email.js';
9
+ export type { ResendLike } from './adapters/resend.email.js';
10
+ export { SmtpEmail } from './adapters/smtp.email.js';
11
+ export type { TransporterLike } from './adapters/smtp.email.js';
12
+ export { MemoryEmail } from './adapters/memory.email.js';
@@ -0,0 +1,314 @@
1
+ import {
2
+ AppException
3
+ } from "../chunk-M3GQDRWR.js";
4
+ import "../chunk-VVMRZEIW.js";
5
+ import {
6
+ __decorateClass
7
+ } from "../chunk-4MGIQFAJ.js";
8
+
9
+ // src/email/email.port.ts
10
+ import { HttpStatus } from "@nestjs/common";
11
+ var EMAIL = /* @__PURE__ */ Symbol("EMAIL");
12
+ var EmailProviderException = class extends AppException {
13
+ constructor(provider, status, body, message) {
14
+ super(
15
+ "EMAIL_PROVIDER_ERROR",
16
+ message ?? `${provider} rejected the message (HTTP ${status})`,
17
+ HttpStatus.BAD_GATEWAY,
18
+ { provider, status, body }
19
+ );
20
+ }
21
+ };
22
+
23
+ // src/email/email.options.ts
24
+ var EMAIL_OPTIONS = /* @__PURE__ */ Symbol("EMAIL_OPTIONS");
25
+
26
+ // src/email/email.module.ts
27
+ import { Global, Module } from "@nestjs/common";
28
+
29
+ // src/email/address.ts
30
+ var NAMED = /^\s*(?:"?([^"]*)"?\s*)?<\s*([^<>\s]+)\s*>\s*$/;
31
+ function parseAddress(address) {
32
+ if (typeof address !== "string") {
33
+ return address.name ? { email: address.email.trim(), name: address.name } : { email: address.email.trim() };
34
+ }
35
+ const match = NAMED.exec(address);
36
+ if (match) {
37
+ const name = match[1]?.trim();
38
+ return name ? { email: match[2], name } : { email: match[2] };
39
+ }
40
+ return { email: address.trim() };
41
+ }
42
+ function formatAddress(address) {
43
+ const { email, name } = parseAddress(address);
44
+ if (!name) return email;
45
+ const safe = /[(),:;<>@[\]"]/.test(name) ? `"${name.replace(/"/g, '\\"')}"` : name;
46
+ return `${safe} <${email}>`;
47
+ }
48
+ function toList(value) {
49
+ if (value === void 0) return [];
50
+ return Array.isArray(value) ? value : [value];
51
+ }
52
+
53
+ // src/email/adapters/message.ts
54
+ function completeMessage(message, defaults) {
55
+ const from = message.from ?? defaults.from;
56
+ if (!from) {
57
+ throw new Error('EmailModule: the message has no "from" and no default was configured (EMAIL_FROM).');
58
+ }
59
+ if (!message.text && !message.html) {
60
+ throw new Error('EmailModule: a message needs "text" or "html".');
61
+ }
62
+ return { ...message, from, replyTo: message.replyTo ?? defaults.replyTo };
63
+ }
64
+ function attachmentBuffer(content) {
65
+ return Buffer.isBuffer(content) ? content : Buffer.from(content, "utf8");
66
+ }
67
+
68
+ // src/email/adapters/brevo.email.ts
69
+ var PROVIDER = "brevo";
70
+ var DEFAULT_BASE_URL = "https://api.brevo.com/v3";
71
+ var BrevoEmail = class {
72
+ constructor(options, defaults = {}) {
73
+ this.options = options;
74
+ this.defaults = defaults;
75
+ if (!options.apiKey) throw new Error('EmailModule: provider "brevo" selected but no apiKey / BREVO_API_KEY set.');
76
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
77
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
78
+ }
79
+ async send(input) {
80
+ const message = completeMessage(input, this.defaults);
81
+ const body = {
82
+ sender: parseAddress(message.from),
83
+ to: toList(message.to).map(parseAddress),
84
+ subject: message.subject
85
+ };
86
+ const cc = toList(message.cc).map(parseAddress);
87
+ const bcc = toList(message.bcc).map(parseAddress);
88
+ if (cc.length) body.cc = cc;
89
+ if (bcc.length) body.bcc = bcc;
90
+ if (message.replyTo) body.replyTo = parseAddress(message.replyTo);
91
+ if (message.html) body.htmlContent = message.html;
92
+ if (message.text) body.textContent = message.text;
93
+ if (message.headers) body.headers = message.headers;
94
+ if (message.tags) body.tags = Object.entries(message.tags).map(([k, v]) => `${k}:${v}`);
95
+ if (message.attachments?.length) {
96
+ body.attachment = message.attachments.map((a) => ({
97
+ name: a.filename,
98
+ content: attachmentBuffer(a.content).toString("base64")
99
+ }));
100
+ }
101
+ let response;
102
+ try {
103
+ response = await this.fetchImpl(`${this.baseUrl}/smtp/email`, {
104
+ method: "POST",
105
+ headers: {
106
+ "api-key": this.options.apiKey,
107
+ "content-type": "application/json",
108
+ accept: "application/json"
109
+ },
110
+ body: JSON.stringify(body)
111
+ });
112
+ } catch (cause) {
113
+ throw new EmailProviderException(
114
+ PROVIDER,
115
+ 0,
116
+ { error: cause instanceof Error ? cause.message : String(cause) },
117
+ `${PROVIDER} is unreachable`
118
+ );
119
+ }
120
+ const text = await response.text();
121
+ let parsed = text;
122
+ try {
123
+ parsed = text ? JSON.parse(text) : void 0;
124
+ } catch {
125
+ }
126
+ if (!response.ok) throw new EmailProviderException(PROVIDER, response.status, parsed);
127
+ const id = parsed?.messageId ?? null;
128
+ return { id, provider: PROVIDER };
129
+ }
130
+ };
131
+
132
+ // src/email/adapters/memory.email.ts
133
+ var MemoryEmail = class {
134
+ constructor(defaults = {}) {
135
+ this.defaults = defaults;
136
+ this.sent = [];
137
+ }
138
+ async send(message) {
139
+ this.sent.push(completeMessage(message, this.defaults));
140
+ return { id: `memory_${this.sent.length}`, provider: "memory" };
141
+ }
142
+ };
143
+
144
+ // src/email/adapters/resend.email.ts
145
+ var PROVIDER2 = "resend";
146
+ var ResendEmail = class {
147
+ constructor(options, defaults = {}, client) {
148
+ this.options = options;
149
+ this.defaults = defaults;
150
+ if (!options.apiKey) throw new Error('EmailModule: provider "resend" selected but no apiKey / RESEND_API_KEY set.');
151
+ if (client) this.clientPromise = Promise.resolve(client);
152
+ }
153
+ client() {
154
+ this.clientPromise ??= import("resend").then(({ Resend }) => new Resend(this.options.apiKey));
155
+ return this.clientPromise;
156
+ }
157
+ async send(input) {
158
+ const message = completeMessage(input, this.defaults);
159
+ const client = await this.client();
160
+ const { data, error } = await client.emails.send({
161
+ from: formatAddress(message.from),
162
+ to: toList(message.to).map(formatAddress),
163
+ cc: toList(message.cc).map(formatAddress),
164
+ bcc: toList(message.bcc).map(formatAddress),
165
+ replyTo: message.replyTo ? formatAddress(message.replyTo) : void 0,
166
+ subject: message.subject,
167
+ html: message.html,
168
+ text: message.text,
169
+ headers: message.headers,
170
+ tags: message.tags ? Object.entries(message.tags).map(([name, value]) => ({ name, value })) : void 0,
171
+ attachments: message.attachments?.map((a) => ({
172
+ filename: a.filename,
173
+ content: attachmentBuffer(a.content),
174
+ contentType: a.contentType
175
+ }))
176
+ });
177
+ if (error) {
178
+ throw new EmailProviderException(PROVIDER2, statusOf(error), error, `${PROVIDER2}: ${error.message}`);
179
+ }
180
+ return { id: data?.id ?? null, provider: PROVIDER2 };
181
+ }
182
+ };
183
+ function statusOf(error) {
184
+ return typeof error.statusCode === "number" ? error.statusCode : 0;
185
+ }
186
+
187
+ // src/email/adapters/smtp.email.ts
188
+ var PROVIDER3 = "smtp";
189
+ var SmtpEmail = class {
190
+ constructor(options, defaults = {}, transport) {
191
+ this.options = options;
192
+ this.defaults = defaults;
193
+ if (!options.host) throw new Error('EmailModule: provider "smtp" selected but no host / SMTP_HOST set.');
194
+ if (transport) this.transportPromise = Promise.resolve(transport);
195
+ }
196
+ transport() {
197
+ this.transportPromise ??= import("nodemailer").then(
198
+ ({ default: nodemailer }) => nodemailer.createTransport({
199
+ host: this.options.host,
200
+ port: this.options.port,
201
+ secure: this.options.secure ?? false,
202
+ auth: this.options.user ? { user: this.options.user, pass: this.options.password } : void 0
203
+ })
204
+ );
205
+ return this.transportPromise;
206
+ }
207
+ async send(input) {
208
+ const message = completeMessage(input, this.defaults);
209
+ const transport = await this.transport();
210
+ const headers = { ...message.headers };
211
+ for (const [name, value] of Object.entries(message.tags ?? {})) headers[`X-Tag-${name}`] = value;
212
+ try {
213
+ const info = await transport.sendMail({
214
+ from: formatAddress(message.from),
215
+ to: toList(message.to).map(formatAddress),
216
+ cc: toList(message.cc).map(formatAddress),
217
+ bcc: toList(message.bcc).map(formatAddress),
218
+ replyTo: message.replyTo ? formatAddress(message.replyTo) : void 0,
219
+ subject: message.subject,
220
+ text: message.text,
221
+ html: message.html,
222
+ headers,
223
+ attachments: message.attachments?.map((a) => ({
224
+ filename: a.filename,
225
+ content: attachmentBuffer(a.content),
226
+ contentType: a.contentType
227
+ }))
228
+ });
229
+ return { id: info?.messageId ?? null, provider: PROVIDER3 };
230
+ } catch (cause) {
231
+ const status = cause.responseCode ?? 0;
232
+ throw new EmailProviderException(
233
+ PROVIDER3,
234
+ status,
235
+ { error: cause instanceof Error ? cause.message : String(cause) },
236
+ `${PROVIDER3}: ${cause instanceof Error ? cause.message : "send failed"}`
237
+ );
238
+ }
239
+ }
240
+ };
241
+
242
+ // src/email/email.module.ts
243
+ var env = (k) => process.env[k] || void 0;
244
+ function resolveEmailOptions(options = {}) {
245
+ return {
246
+ provider: options.provider ?? env("EMAIL_PROVIDER"),
247
+ from: options.from ?? env("EMAIL_FROM"),
248
+ replyTo: options.replyTo ?? env("EMAIL_REPLY_TO"),
249
+ resend: options.resend ?? (env("RESEND_API_KEY") ? { apiKey: env("RESEND_API_KEY") } : void 0),
250
+ smtp: options.smtp ?? (env("SMTP_HOST") ? {
251
+ host: env("SMTP_HOST"),
252
+ port: Number(env("SMTP_PORT") ?? 587),
253
+ secure: env("SMTP_SECURE") === "true",
254
+ user: env("SMTP_USER"),
255
+ password: env("SMTP_PASSWORD")
256
+ } : void 0),
257
+ brevo: options.brevo ?? (env("BREVO_API_KEY") ? { apiKey: env("BREVO_API_KEY"), baseUrl: env("BREVO_BASE_URL") } : void 0)
258
+ };
259
+ }
260
+ function createEmailAdapter(options = {}) {
261
+ const resolved = resolveEmailOptions(options);
262
+ const defaults = { from: resolved.from, replyTo: resolved.replyTo };
263
+ switch (resolved.provider) {
264
+ case "resend":
265
+ if (!resolved.resend) throw new Error('EmailModule: provider "resend" selected but no resend options / RESEND_API_KEY set.');
266
+ return new ResendEmail(resolved.resend, defaults);
267
+ case "smtp":
268
+ if (!resolved.smtp) throw new Error('EmailModule: provider "smtp" selected but no smtp options / SMTP_* env set.');
269
+ return new SmtpEmail(resolved.smtp, defaults);
270
+ case "brevo":
271
+ if (!resolved.brevo) throw new Error('EmailModule: provider "brevo" selected but no brevo options / BREVO_API_KEY set.');
272
+ return new BrevoEmail(resolved.brevo, defaults);
273
+ case "memory":
274
+ return new MemoryEmail(defaults);
275
+ case void 0:
276
+ throw new Error("EmailModule: no provider selected. Pass `provider` or set EMAIL_PROVIDER (resend | smtp | brevo | memory).");
277
+ default:
278
+ throw new Error(`EmailModule: unknown provider "${String(resolved.provider)}".`);
279
+ }
280
+ }
281
+ var EmailModule = class {
282
+ static forRoot(options = {}) {
283
+ const providers = [
284
+ { provide: EMAIL_OPTIONS, useValue: options },
285
+ { provide: EMAIL, useFactory: () => createEmailAdapter(options) }
286
+ ];
287
+ return { module: EmailModule, providers, exports: [EMAIL, EMAIL_OPTIONS] };
288
+ }
289
+ static forRootAsync(config) {
290
+ const providers = [
291
+ { provide: EMAIL_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] },
292
+ { provide: EMAIL, useFactory: (options) => createEmailAdapter(options), inject: [EMAIL_OPTIONS] }
293
+ ];
294
+ return { module: EmailModule, imports: config.imports ?? [], providers, exports: [EMAIL, EMAIL_OPTIONS] };
295
+ }
296
+ };
297
+ EmailModule = __decorateClass([
298
+ Global(),
299
+ Module({})
300
+ ], EmailModule);
301
+ export {
302
+ BrevoEmail,
303
+ EMAIL,
304
+ EMAIL_OPTIONS,
305
+ EmailModule,
306
+ EmailProviderException,
307
+ MemoryEmail,
308
+ ResendEmail,
309
+ SmtpEmail,
310
+ createEmailAdapter,
311
+ formatAddress,
312
+ parseAddress,
313
+ resolveEmailOptions
314
+ };
@@ -1,17 +1,17 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});require('../chunk-7SOM7EZP.cjs');
2
2
 
3
3
 
4
- var _chunkMSTXS3MUcjs = require('../chunk-MSTXS3MU.cjs');
5
- require('../chunk-AXMW5JF7.cjs');
6
- require('../chunk-Y72D5L6I.cjs');
7
- require('../chunk-SDWHKPXI.cjs');
8
4
 
9
5
 
10
6
 
11
7
 
8
+ var _chunkHDFPSA2Vcjs = require('../chunk-HDFPSA2V.cjs');
12
9
 
13
10
 
14
- var _chunkHDFPSA2Vcjs = require('../chunk-HDFPSA2V.cjs');
11
+ var _chunkMSTXS3MUcjs = require('../chunk-MSTXS3MU.cjs');
12
+ require('../chunk-AXMW5JF7.cjs');
13
+ require('../chunk-Y72D5L6I.cjs');
14
+ require('../chunk-SDWHKPXI.cjs');
15
15
 
16
16
 
17
17
  var _chunkQ5Y33L7Bcjs = require('../chunk-Q5Y33L7B.cjs');
@@ -1,10 +1,4 @@
1
1
  import "../chunk-DQYAIQQ5.js";
2
- import {
3
- GlobalExceptionFilter
4
- } from "../chunk-A2DGK4ZL.js";
5
- import "../chunk-X4PQJZ4G.js";
6
- import "../chunk-TCAMLNUZ.js";
7
- import "../chunk-ETRUVZTJ.js";
8
2
  import {
9
3
  ConflictAppException,
10
4
  ForbiddenAppException,
@@ -12,6 +6,12 @@ import {
12
6
  UnauthorizedAppException,
13
7
  ValidationAppException
14
8
  } from "../chunk-ZFIDAX7K.js";
9
+ import {
10
+ GlobalExceptionFilter
11
+ } from "../chunk-A2DGK4ZL.js";
12
+ import "../chunk-X4PQJZ4G.js";
13
+ import "../chunk-TCAMLNUZ.js";
14
+ import "../chunk-ETRUVZTJ.js";
15
15
  import {
16
16
  AppException
17
17
  } from "../chunk-M3GQDRWR.js";