@classytic/notifications 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,280 @@
1
+ //#region src/providers/email/presets.ts
2
+ const EMAIL_PRESETS = {
3
+ resend: {
4
+ displayName: "Resend",
5
+ description: "Transactional + broadcast email via Resend SMTP relay.",
6
+ host: "smtp.resend.com",
7
+ port: 465,
8
+ secure: true,
9
+ userSource: "literal:resend",
10
+ passSource: "apiKey",
11
+ setupHint: "Verify your sending domain in resend.com → Domains. Create an API key (full access) and paste it below."
12
+ },
13
+ gmail: {
14
+ displayName: "Gmail (App Password)",
15
+ description: "Send via a personal Gmail account using a 16-character app password.",
16
+ host: "smtp.gmail.com",
17
+ port: 465,
18
+ secure: true,
19
+ userSource: "user",
20
+ passSource: "password",
21
+ setupHint: "Enable 2-Step Verification, then generate an App Password at myaccount.google.com/apppasswords. The from-address must match the Gmail account."
22
+ },
23
+ sendgrid: {
24
+ displayName: "SendGrid",
25
+ description: "SendGrid SMTP relay (username is literally \"apikey\").",
26
+ host: "smtp.sendgrid.net",
27
+ port: 587,
28
+ secure: false,
29
+ userSource: "literal:apikey",
30
+ passSource: "apiKey",
31
+ setupHint: "Verify your sending domain in app.sendgrid.com → Sender Authentication. Create an API key with Mail Send permission."
32
+ },
33
+ mailgun: {
34
+ displayName: "Mailgun",
35
+ description: "Mailgun SMTP relay using per-domain SMTP credentials.",
36
+ host: "smtp.mailgun.org",
37
+ port: 465,
38
+ secure: true,
39
+ userSource: "user",
40
+ passSource: "password",
41
+ setupHint: "Verify your sending domain in app.mailgun.com. The SMTP credentials shown on the domain page (user + password) go below — these are NOT your account password."
42
+ },
43
+ ses: {
44
+ displayName: "AWS SES (SMTP)",
45
+ description: "Amazon SES via SMTP. Host defaults to us-east-1; override for other regions.",
46
+ host: "email-smtp.us-east-1.amazonaws.com",
47
+ port: 465,
48
+ secure: true,
49
+ userSource: "user",
50
+ passSource: "password",
51
+ allowHostOverride: true,
52
+ setupHint: "In the SES console (your region), Account dashboard → SMTP settings → Create SMTP credentials. The IAM user gets an SMTP username and password — those go below (NOT your AWS access key). To use a non-default region, set host to email-smtp.<region>.amazonaws.com."
53
+ },
54
+ smtp: {
55
+ displayName: "Custom SMTP",
56
+ description: "Any SMTP relay — supply host, port, user, and password manually.",
57
+ host: null,
58
+ port: 587,
59
+ secure: false,
60
+ userSource: "user",
61
+ passSource: "password",
62
+ setupHint: "Use for SMTP servers without a preset. Standard auth-SMTP only — no OAuth-XOAUTH2."
63
+ }
64
+ };
65
+ /** Convenience dropdown options for the credential UI. */
66
+ const EMAIL_PROVIDER_OPTIONS = Object.keys(EMAIL_PRESETS).map((name) => ({
67
+ value: name,
68
+ label: EMAIL_PRESETS[name].displayName
69
+ }));
70
+
71
+ //#endregion
72
+ //#region src/providers/email/transport.ts
73
+ function resolveUser(data, userSource) {
74
+ if (userSource.startsWith("literal:")) return userSource.slice(8);
75
+ if (userSource === "user") {
76
+ if (!data.user) throw new Error("SMTP user is required for this provider");
77
+ return data.user;
78
+ }
79
+ throw new Error(`Unknown userSource: ${userSource}`);
80
+ }
81
+ function resolvePass(data, passSource) {
82
+ const value = passSource === "apiKey" ? data.apiKey : data.password;
83
+ if (!value) throw new Error(passSource === "apiKey" ? "API key is required for this provider" : "Password is required for this provider");
84
+ return value;
85
+ }
86
+ /**
87
+ * Build a `nodemailer` `Transporter` from the credential blob.
88
+ *
89
+ * @throws `Error` when required fields are missing for the chosen provider.
90
+ * @throws `Error` when `nodemailer` is not installed (optional peer).
91
+ */
92
+ async function buildEmailTransport(data) {
93
+ const preset = EMAIL_PRESETS[data.provider];
94
+ if (!preset) throw new Error(`Unknown email provider: ${data.provider}`);
95
+ const allowOverride = preset.host === null || preset.allowHostOverride === true;
96
+ const overrideHost = data.host?.trim();
97
+ const host = allowOverride && overrideHost ? overrideHost : preset.host;
98
+ if (!host) throw new Error("SMTP host is required");
99
+ const port = allowOverride && data.port !== void 0 && data.port !== "" ? typeof data.port === "number" ? data.port : parseInt(String(data.port), 10) : preset.port;
100
+ let secure = preset.secure;
101
+ if (allowOverride && data.secure !== void 0 && data.secure !== "") {
102
+ if (typeof data.secure === "boolean") secure = data.secure;
103
+ else if (typeof data.secure === "string") secure = data.secure === "true";
104
+ }
105
+ let nodemailer;
106
+ try {
107
+ nodemailer = await import("nodemailer");
108
+ } catch {
109
+ throw new Error("nodemailer is required to build an email transport — install it: `npm install nodemailer`");
110
+ }
111
+ return (nodemailer.default ?? nodemailer).createTransport({
112
+ host,
113
+ port,
114
+ secure,
115
+ auth: {
116
+ user: resolveUser(data, preset.userSource),
117
+ pass: resolvePass(data, preset.passSource)
118
+ }
119
+ });
120
+ }
121
+ /**
122
+ * Compose the RFC-5322 `From` header value from the credential blob.
123
+ * Returns `"Display Name" <email@example.com>` when `fromName` is set,
124
+ * otherwise just `email@example.com`.
125
+ */
126
+ function buildFromHeader(data) {
127
+ const name = data.fromName?.trim();
128
+ return name ? `"${name}" <${data.fromEmail}>` : data.fromEmail;
129
+ }
130
+
131
+ //#endregion
132
+ //#region src/providers/email/schema.ts
133
+ /**
134
+ * Credential field schema for the email provider.
135
+ *
136
+ * Hosts that ship a dynamic credential form (driven by a provider's
137
+ * `getCredentialSchema()`-style method) read this to render the right
138
+ * fields. Returning the UNION of all provider-specific fields keeps the
139
+ * form generic — the UI hides irrelevant fields based on the chosen
140
+ * `provider`. Only relevant fields get saved into the encrypted blob.
141
+ *
142
+ * Shape is host-agnostic (no `@classytic/social` import). Hosts that
143
+ * use the social registry's `CredentialField` type can structurally cast.
144
+ */
145
+ /** Union-of-fields schema — every field appears; the UI hides what's
146
+ * not relevant for the chosen `provider`. */
147
+ function getEmailCredentialSchema() {
148
+ return [
149
+ {
150
+ name: "provider",
151
+ displayName: "Provider",
152
+ type: "select",
153
+ required: true,
154
+ options: EMAIL_PROVIDER_OPTIONS,
155
+ description: "Which SMTP relay handles your sends."
156
+ },
157
+ {
158
+ name: "fromEmail",
159
+ displayName: "From Email",
160
+ type: "text",
161
+ required: true,
162
+ placeholder: "hello@yourdomain.com",
163
+ description: "Must be verified with your provider — sends from unverified addresses are rejected."
164
+ },
165
+ {
166
+ name: "fromName",
167
+ displayName: "From Name",
168
+ type: "text",
169
+ required: false,
170
+ placeholder: "Your Brand",
171
+ description: "Optional. Shown as the sender name in inboxes."
172
+ },
173
+ {
174
+ name: "apiKey",
175
+ displayName: "API Key",
176
+ type: "password",
177
+ required: false,
178
+ description: "Resend or SendGrid only."
179
+ },
180
+ {
181
+ name: "user",
182
+ displayName: "SMTP Username",
183
+ type: "text",
184
+ required: false,
185
+ description: "Gmail address, Mailgun SMTP user, or custom SMTP user."
186
+ },
187
+ {
188
+ name: "password",
189
+ displayName: "SMTP Password",
190
+ type: "password",
191
+ required: false,
192
+ description: "Gmail app password, Mailgun SMTP password, or custom SMTP password."
193
+ },
194
+ {
195
+ name: "host",
196
+ displayName: "SMTP Host",
197
+ type: "text",
198
+ required: false,
199
+ placeholder: "smtp.example.com",
200
+ description: "Custom SMTP only — preset hosts are filled automatically."
201
+ },
202
+ {
203
+ name: "port",
204
+ displayName: "SMTP Port",
205
+ type: "text",
206
+ required: false,
207
+ placeholder: "587",
208
+ description: "Custom SMTP only."
209
+ },
210
+ {
211
+ name: "secure",
212
+ displayName: "Secure (implicit TLS)",
213
+ type: "select",
214
+ required: false,
215
+ options: [{
216
+ value: "true",
217
+ label: "true (port 465 / implicit TLS)"
218
+ }, {
219
+ value: "false",
220
+ label: "false (port 587 / STARTTLS)"
221
+ }],
222
+ description: "Custom SMTP only."
223
+ }
224
+ ];
225
+ }
226
+
227
+ //#endregion
228
+ //#region src/providers/email/test.ts
229
+ /**
230
+ * Validate an email credential by building its transport and asking the
231
+ * underlying SMTP server to verify the auth tuple. Used by hosts during
232
+ * "Test Connection" flows.
233
+ *
234
+ * Returns a typed result rather than throwing — UI consumers usually
235
+ * want to surface the message + status pair regardless of outcome.
236
+ */
237
+ async function testEmailCredential(data) {
238
+ if (!data.provider) return {
239
+ status: "Error",
240
+ message: "Provider is required"
241
+ };
242
+ if (!data.fromEmail) return {
243
+ status: "Error",
244
+ message: "From email is required"
245
+ };
246
+ if (!Object.keys(EMAIL_PRESETS).includes(data.provider)) return {
247
+ status: "Error",
248
+ message: `Unknown provider: ${data.provider}`
249
+ };
250
+ let transport;
251
+ try {
252
+ transport = await buildEmailTransport(data);
253
+ } catch (err) {
254
+ return {
255
+ status: "Error",
256
+ message: err?.message ?? "Failed to build SMTP transport"
257
+ };
258
+ }
259
+ try {
260
+ if (typeof transport.verify === "function") await transport.verify();
261
+ return {
262
+ status: "OK",
263
+ message: `SMTP connection verified for ${data.fromEmail}`,
264
+ data: {
265
+ provider: data.provider,
266
+ fromEmail: data.fromEmail
267
+ }
268
+ };
269
+ } catch (err) {
270
+ return {
271
+ status: "Error",
272
+ message: err?.message ?? "SMTP verification failed"
273
+ };
274
+ } finally {
275
+ if (typeof transport.close === "function") transport.close();
276
+ }
277
+ }
278
+
279
+ //#endregion
280
+ export { EMAIL_PRESETS, EMAIL_PROVIDER_OPTIONS, buildEmailTransport, buildFromHeader, getEmailCredentialSchema, testEmailCredential };
@@ -1,10 +1,14 @@
1
- import { E as SmsChannelConfig, a as ChannelConfig, c as EmailChannelConfig, h as NotificationPayload, i as Channel, j as WebhookChannelConfig, w as SendResult, y as PushChannelConfig } from "./types-D94B3VNX.mjs";
1
+ import { C as RetryConfig, E as SmsChannelConfig, K as RateLimitConfig, a as ChannelConfig, c as EmailChannelConfig, h as NotificationPayload, i as Channel, j as WebhookChannelConfig, w as SendResult, y as PushChannelConfig } from "./types-QIV0Th2F.mjs";
2
2
 
3
3
  //#region src/channels/BaseChannel.d.ts
4
4
  declare abstract class BaseChannel<TConfig extends ChannelConfig = ChannelConfig> implements Channel {
5
5
  readonly name: string;
6
6
  protected config: TConfig;
7
7
  constructor(config: TConfig);
8
+ /** Per-channel rate limit (from config) — read by the service. */
9
+ get rateLimit(): RateLimitConfig | undefined;
10
+ /** Per-channel retry override (from config) — read by the service. */
11
+ get retry(): RetryConfig | undefined;
8
12
  /** Check if this channel should handle a given event */
9
13
  shouldHandle(event: string): boolean;
10
14
  /** Send notification - must be implemented by subclass */
@@ -19,6 +23,13 @@ declare class EmailChannel extends BaseChannel<EmailChannelConfig> {
19
23
  private getTransporter;
20
24
  /** Fields that defaults must never override */
21
25
  private static readonly PROTECTED_FIELDS;
26
+ /**
27
+ * Pre-flight check called by the service before consuming a rate-limit
28
+ * token. Returning a skip result here avoids burning quota on payloads
29
+ * that obviously can't deliver (e.g., a mixed-channel batch where the
30
+ * recipient has a phone but no email).
31
+ */
32
+ canSend(payload: NotificationPayload): SendResult | null;
22
33
  send(payload: NotificationPayload): Promise<SendResult>;
23
34
  /** Verify the SMTP connection (useful for health checks) */
24
35
  verify(): Promise<boolean>;
@@ -42,6 +53,12 @@ declare class ConsoleChannel extends BaseChannel<ChannelConfig> {
42
53
  declare class SmsChannel extends BaseChannel<SmsChannelConfig> {
43
54
  private provider;
44
55
  constructor(config: SmsChannelConfig);
56
+ /**
57
+ * Pre-flight check called by the service before consuming a rate-limit
58
+ * token. Skip if the payload lacks a recipient phone OR a body — these
59
+ * skips are deterministic and shouldn't burn SMS quota.
60
+ */
61
+ canSend(payload: NotificationPayload): SendResult | null;
45
62
  send(payload: NotificationPayload): Promise<SendResult>;
46
63
  }
47
64
  //#endregion
@@ -49,6 +66,11 @@ declare class SmsChannel extends BaseChannel<SmsChannelConfig> {
49
66
  declare class PushChannel extends BaseChannel<PushChannelConfig> {
50
67
  private provider;
51
68
  constructor(config: PushChannelConfig);
69
+ /**
70
+ * Pre-flight check called by the service before consuming a rate-limit
71
+ * token. Skip when there's no device token or no displayable content.
72
+ */
73
+ canSend(payload: NotificationPayload): SendResult | null;
52
74
  send(payload: NotificationPayload): Promise<SendResult>;
53
75
  }
54
76
  //#endregion
@@ -1,4 +1,4 @@
1
- import { r as ProviderNotInstalledError, t as ChannelError } from "./errors-FYJYmfvj.mjs";
1
+ import { r as ProviderNotInstalledError, t as ChannelError } from "./errors-BxRjct-E.mjs";
2
2
  import { createHmac } from "node:crypto";
3
3
 
4
4
  //#region src/channels/BaseChannel.ts
@@ -9,6 +9,14 @@ var BaseChannel = class {
9
9
  this.name = config.name ?? this.constructor.name;
10
10
  this.config = config;
11
11
  }
12
+ /** Per-channel rate limit (from config) — read by the service. */
13
+ get rateLimit() {
14
+ return this.config.rateLimit;
15
+ }
16
+ /** Per-channel retry override (from config) — read by the service. */
17
+ get retry() {
18
+ return this.config.retry;
19
+ }
12
20
  /** Check if this channel should handle a given event */
13
21
  shouldHandle(event) {
14
22
  if (this.config.enabled === false) return false;
@@ -83,7 +91,8 @@ var EmailChannel = class EmailChannel extends BaseChannel {
83
91
  }
84
92
  if (!this.config.transport) throw new ChannelError(this.name, "Either transport options or a transporter instance is required");
85
93
  try {
86
- this.transporter = (await import("nodemailer")).default.createTransport(this.config.transport);
94
+ const nodemailer = await import("nodemailer");
95
+ this.transporter = nodemailer.default.createTransport(this.config.transport);
87
96
  return this.transporter;
88
97
  } catch {
89
98
  throw new ProviderNotInstalledError("nodemailer", "npm install nodemailer");
@@ -101,6 +110,20 @@ var EmailChannel = class EmailChannel extends BaseChannel {
101
110
  "replyTo",
102
111
  "attachments"
103
112
  ]);
113
+ /**
114
+ * Pre-flight check called by the service before consuming a rate-limit
115
+ * token. Returning a skip result here avoids burning quota on payloads
116
+ * that obviously can't deliver (e.g., a mixed-channel batch where the
117
+ * recipient has a phone but no email).
118
+ */
119
+ canSend(payload) {
120
+ if (!payload.recipient.email) return {
121
+ status: "skipped",
122
+ channel: this.name,
123
+ error: "No recipient email"
124
+ };
125
+ return null;
126
+ }
104
127
  async send(payload) {
105
128
  const { recipient, data } = payload;
106
129
  if (!recipient.email) return {
@@ -113,9 +136,10 @@ var EmailChannel = class EmailChannel extends BaseChannel {
113
136
  if (this.config.defaults) {
114
137
  for (const [key, value] of Object.entries(this.config.defaults)) if (!EmailChannel.PROTECTED_FIELDS.has(key)) safeDefaults[key] = value;
115
138
  }
139
+ const sender = this.config.allowSenderOverride && typeof data.from === "string" ? data.from : this.config.from;
116
140
  const mailOptions = {
117
141
  ...safeDefaults,
118
- from: data.from ?? this.config.from,
142
+ from: sender,
119
143
  to: recipient.email,
120
144
  subject: data.subject ?? ""
121
145
  };
@@ -125,6 +149,18 @@ var EmailChannel = class EmailChannel extends BaseChannel {
125
149
  if (data.cc) mailOptions.cc = data.cc;
126
150
  if (data.bcc) mailOptions.bcc = data.bcc;
127
151
  if (data.attachments) mailOptions.attachments = data.attachments;
152
+ const unsubUrl = data.listUnsubscribeUrl ?? this.config.listUnsubscribe?.url;
153
+ const unsubEmail = data.listUnsubscribeEmail ?? this.config.listUnsubscribe?.email;
154
+ if (unsubUrl || unsubEmail) {
155
+ const parts = [];
156
+ if (unsubUrl) parts.push(`<${unsubUrl}>`);
157
+ if (unsubEmail) parts.push(`<mailto:${unsubEmail}>`);
158
+ mailOptions.headers = {
159
+ ...mailOptions.headers ?? {},
160
+ "List-Unsubscribe": parts.join(", "),
161
+ "List-Unsubscribe-Post": "List-Unsubscribe=One-Click"
162
+ };
163
+ }
128
164
  try {
129
165
  const result = await transporter.sendMail(mailOptions);
130
166
  return {
@@ -328,6 +364,24 @@ var SmsChannel = class extends BaseChannel {
328
364
  });
329
365
  this.provider = config.provider;
330
366
  }
367
+ /**
368
+ * Pre-flight check called by the service before consuming a rate-limit
369
+ * token. Skip if the payload lacks a recipient phone OR a body — these
370
+ * skips are deterministic and shouldn't burn SMS quota.
371
+ */
372
+ canSend(payload) {
373
+ if (!payload.recipient.phone) return {
374
+ status: "skipped",
375
+ channel: this.name,
376
+ error: "No recipient phone number"
377
+ };
378
+ if (!(payload.data.text ?? payload.data.message ?? payload.data.subject ?? "")) return {
379
+ status: "skipped",
380
+ channel: this.name,
381
+ error: "No message body (data.text, data.message, or data.subject)"
382
+ };
383
+ return null;
384
+ }
331
385
  async send(payload) {
332
386
  const { recipient, data } = payload;
333
387
  if (!recipient.phone) return {
@@ -430,6 +484,25 @@ var PushChannel = class extends BaseChannel {
430
484
  });
431
485
  this.provider = config.provider;
432
486
  }
487
+ /**
488
+ * Pre-flight check called by the service before consuming a rate-limit
489
+ * token. Skip when there's no device token or no displayable content.
490
+ */
491
+ canSend(payload) {
492
+ if (!payload.recipient.deviceToken) return {
493
+ status: "skipped",
494
+ channel: this.name,
495
+ error: "No recipient deviceToken"
496
+ };
497
+ const title = payload.data.title ?? payload.data.subject ?? "";
498
+ const body = payload.data.body ?? payload.data.text ?? payload.data.message ?? "";
499
+ if (!title && !body) return {
500
+ status: "skipped",
501
+ channel: this.name,
502
+ error: "No title or body (data.title, data.body)"
503
+ };
504
+ return null;
505
+ }
433
506
  async send(payload) {
434
507
  const { recipient, data } = payload;
435
508
  if (!recipient.deviceToken) return {