@classytic/notifications 2.1.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  All notable changes to `@classytic/notifications` will be documented in this file.
4
4
 
5
+ ## [2.2.0] - 2026-06-03
6
+
7
+ - `SendResult.retryable?: boolean` — when `false`, service short-circuits `withRetry` immediately (permanent failures: bad credentials, invalid address, hard bounce, 4xx)
8
+ - `Channel.rateLimit` / `Channel.retry` promoted to first-class interface properties; `BaseChannel` exposes both from config via getters (removes internal casts)
9
+ - `EmailChannel.allowSenderOverride` — opt-in per-send `data.from` override (default `false`; guards multi-tenant sender-spoofing footgun)
10
+ - `EmailChannel` RFC 8058 `List-Unsubscribe` / `List-Unsubscribe-Post` header injection
11
+ - `interpolateHtml` + `InterpolateOptions` / `SimpleResolverOptions` exported from main entry
12
+ - Retry-layer clarification comment: queue retry × channel retry compose multiplicatively; docs advise setting one to 1 when the other owns durability
13
+ - Rate-limit token accounting clarified: one token per `sendToChannel` call; retries inside `withRetry` do not each consume a token
14
+
5
15
  ## [2.1.0] - 2026-05-17
6
16
 
7
17
  ### Added
@@ -1,2 +1,2 @@
1
- import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-YtZrCCH1.mjs";
1
+ import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-CeUVeVfB.mjs";
2
2
  export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, WebhookChannel };
@@ -1,3 +1,3 @@
1
- import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-OkjPEVTN.mjs";
1
+ import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-DI6BNBZ4.mjs";
2
2
 
3
3
  export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, WebhookChannel };
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { A as TemplateResult, B as DeliveryLogQuery, C as RetryConfig, D as SmsProvider, E as SmsChannelConfig, F as QueueJob, G as MemoryRateLimitStore, H as IDEMPOTENCY_DEFAULT_TTL, I as QueueJobStatus, K as RateLimitConfig, L as QueueProcessor, M as MemoryQueue, N as QueueAdapter, O as SmtpTransportOptions, P as QueueEnqueueOptions, R as DeliveryLog, S as ResolvedRetryConfig, T as ServiceEvent, U as IdempotencyStore, V as MemoryDeliveryLog, W as MemoryIdempotencyStore, _ as NotificationServiceConfig, a as ChannelConfig, b as PushProvider, c as EmailChannelConfig, d as HookMap, f as Logger, g as NotificationPreferences, h as NotificationPayload, i as Channel, j as WebhookChannelConfig, k as TemplateResolver, l as EventHandler, m as NotificationHookConfig, n as BatchProgress, o as DispatchResult, p as NodemailerTransporter, q as RateLimitStore, r as BatchResult, s as EmailAttachment, t as BatchOptions, u as HookHandler, v as PreferenceResolver, w as SendResult, x as Recipient, y as PushChannelConfig, z as DeliveryLogEntry } from "./types-BMs4UhKD.mjs";
2
- import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-YtZrCCH1.mjs";
3
- import { S as mergeHooks, _ as ProviderNotInstalledError, a as createStatusHandler, b as resolveRetryConfig, c as TemplateDefinition, d as PMapOptions, f as pMap, g as NotificationError, h as ChannelError, i as StatusUpdate, l as TemplateMap, m as isQuietHours, n as StatusHandler, o as FallbackOptions, p as QuietHoursConfig, r as StatusHandlerConfig, s as withFallback, t as DeliveryStatus, u as createSimpleResolver, v as Emitter, x as withRetry, y as calculateDelay } from "./status-webhook-Bb4UoinT.mjs";
1
+ import { A as TemplateResult, B as DeliveryLogQuery, C as RetryConfig, D as SmsProvider, E as SmsChannelConfig, F as QueueJob, G as MemoryRateLimitStore, H as IDEMPOTENCY_DEFAULT_TTL, I as QueueJobStatus, K as RateLimitConfig, L as QueueProcessor, M as MemoryQueue, N as QueueAdapter, O as SmtpTransportOptions, P as QueueEnqueueOptions, R as DeliveryLog, S as ResolvedRetryConfig, T as ServiceEvent, U as IdempotencyStore, V as MemoryDeliveryLog, W as MemoryIdempotencyStore, _ as NotificationServiceConfig, a as ChannelConfig, b as PushProvider, c as EmailChannelConfig, d as HookMap, f as Logger, g as NotificationPreferences, h as NotificationPayload, i as Channel, j as WebhookChannelConfig, k as TemplateResolver, l as EventHandler, m as NotificationHookConfig, n as BatchProgress, o as DispatchResult, p as NodemailerTransporter, q as RateLimitStore, r as BatchResult, s as EmailAttachment, t as BatchOptions, u as HookHandler, v as PreferenceResolver, w as SendResult, x as Recipient, y as PushChannelConfig, z as DeliveryLogEntry } from "./types-QIV0Th2F.mjs";
2
+ import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-CeUVeVfB.mjs";
3
+ import { C as resolveRetryConfig, S as calculateDelay, T as mergeHooks, _ as isQuietHours, a as createStatusHandler, b as ProviderNotInstalledError, c as InterpolateOptions, d as TemplateMap, f as createSimpleResolver, g as QuietHoursConfig, h as pMap, i as StatusUpdate, l as SimpleResolverOptions, m as PMapOptions, n as StatusHandler, o as FallbackOptions, p as interpolateHtml, r as StatusHandlerConfig, s as withFallback, t as DeliveryStatus, u as TemplateDefinition, v as ChannelError, w as withRetry, x as Emitter, y as NotificationError } from "./status-webhook-DxCdp0c_.mjs";
4
4
 
5
5
  //#region src/NotificationService.d.ts
6
6
  declare class NotificationService {
@@ -134,4 +134,57 @@ declare class NotificationService {
134
134
  off(event: ServiceEvent, handler: EventHandler): this;
135
135
  }
136
136
  //#endregion
137
- export { BaseChannel, type BatchOptions, type BatchProgress, type BatchResult, type Channel, type ChannelConfig, ChannelError, ConsoleChannel, type DeliveryLog, type DeliveryLogEntry, type DeliveryLogQuery, type DeliveryStatus, type DispatchResult, type EmailAttachment, EmailChannel, type EmailChannelConfig, Emitter, type EventHandler, type FallbackOptions, type HookHandler, type HookMap, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, type Logger, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, type NodemailerTransporter, NotificationError, type NotificationHookConfig, type NotificationPayload, type NotificationPreferences, NotificationService, type NotificationServiceConfig, type PMapOptions, type PreferenceResolver, ProviderNotInstalledError, PushChannel, type PushChannelConfig, type PushProvider, type QueueAdapter, type QueueEnqueueOptions, type QueueJob, type QueueJobStatus, type QueueProcessor, type QuietHoursConfig, type RateLimitConfig, type RateLimitStore, type Recipient, type ResolvedRetryConfig, type RetryConfig, type SendResult, type ServiceEvent, SmsChannel, type SmsChannelConfig, type SmsProvider, type SmtpTransportOptions, type StatusHandler, type StatusHandlerConfig, type StatusUpdate, type TemplateDefinition, type TemplateMap, type TemplateResolver, type TemplateResult, WebhookChannel, type WebhookChannelConfig, calculateDelay, createSimpleResolver, createStatusHandler, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
137
+ //#region src/index.d.ts
138
+ /**
139
+ * @classytic/notifications
140
+ * Multi-Channel Notification System
141
+ *
142
+ * Pluggable channels, templates, retry, and preferences.
143
+ * Zero required dependencies - bring your own providers.
144
+ *
145
+ * v2: Rate limiting, delivery tracking, queue adapter,
146
+ * BCC batching, template engines, SMS & push channels.
147
+ *
148
+ * @module @classytic/notifications
149
+ * @author Classytic (https://github.com/classytic)
150
+ * @license MIT
151
+ *
152
+ * @example
153
+ * ```typescript
154
+ * import { NotificationService } from '@classytic/notifications';
155
+ * import { EmailChannel, SmsChannel, PushChannel } from '@classytic/notifications/channels';
156
+ * import { MemoryDeliveryLog, createSimpleResolver } from '@classytic/notifications/utils';
157
+ *
158
+ * const notifications = new NotificationService({
159
+ * channels: [
160
+ * new EmailChannel({
161
+ * from: 'App <noreply@app.com>',
162
+ * transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
163
+ * rateLimit: { maxPerWindow: 500, windowMs: 86_400_000 }, // Gmail 500/day
164
+ * }),
165
+ * new SmsChannel({
166
+ * from: '+15551234567',
167
+ * provider: { send: async ({ to, from, body }) => ({ sid: 'custom' }) },
168
+ * }),
169
+ * new PushChannel({
170
+ * provider: { send: async ({ token, title, body }) => ({ messageId: 'custom' }) },
171
+ * }),
172
+ * ],
173
+ * templates: createSimpleResolver({
174
+ * welcome: { subject: 'Welcome ${name}!', html: '<p>Hi ${name}</p>' },
175
+ * }),
176
+ * retry: { maxAttempts: 3, backoff: 'exponential' },
177
+ * deliveryLog: new MemoryDeliveryLog(),
178
+ * });
179
+ *
180
+ * await notifications.send({
181
+ * event: 'user.created',
182
+ * recipient: { email: 'user@example.com', phone: '+15559876543', name: 'John' },
183
+ * data: { name: 'John' },
184
+ * template: 'welcome',
185
+ * });
186
+ * ```
187
+ */
188
+
189
+ //#endregion
190
+ export { BaseChannel, type BatchOptions, type BatchProgress, type BatchResult, type Channel, type ChannelConfig, ChannelError, ConsoleChannel, type DeliveryLog, type DeliveryLogEntry, type DeliveryLogQuery, type DeliveryStatus, type DispatchResult, type EmailAttachment, EmailChannel, type EmailChannelConfig, Emitter, type EventHandler, type FallbackOptions, type HookHandler, type HookMap, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, type InterpolateOptions, type Logger, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, type NodemailerTransporter, NotificationError, type NotificationHookConfig, type NotificationPayload, type NotificationPreferences, NotificationService, type NotificationServiceConfig, type PMapOptions, type PreferenceResolver, ProviderNotInstalledError, PushChannel, type PushChannelConfig, type PushProvider, type QueueAdapter, type QueueEnqueueOptions, type QueueJob, type QueueJobStatus, type QueueProcessor, type QuietHoursConfig, type RateLimitConfig, type RateLimitStore, type Recipient, type ResolvedRetryConfig, type RetryConfig, type SendResult, type ServiceEvent, type SimpleResolverOptions, SmsChannel, type SmsChannelConfig, type SmsProvider, type SmtpTransportOptions, type StatusHandler, type StatusHandlerConfig, type StatusUpdate, type TemplateDefinition, type TemplateMap, type TemplateResolver, type TemplateResult, WebhookChannel, type WebhookChannelConfig, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { a as MemoryDeliveryLog, c as MemoryRateLimitStore, d as isQuietHours, f as calculateDelay, h as Emitter, i as MemoryQueue, l as IDEMPOTENCY_DEFAULT_TTL, m as withRetry, n as withFallback, o as mergeHooks, p as resolveRetryConfig, r as createSimpleResolver, s as pMap, t as createStatusHandler, u as MemoryIdempotencyStore } from "./status-webhook-XY42DCj_.mjs";
2
- import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "./errors-FYJYmfvj.mjs";
3
- import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-OkjPEVTN.mjs";
1
+ import { a as MemoryQueue, c as pMap, d as MemoryIdempotencyStore, f as isQuietHours, g as Emitter, h as withRetry, i as interpolateHtml, l as MemoryRateLimitStore, m as resolveRetryConfig, n as withFallback, o as MemoryDeliveryLog, p as calculateDelay, r as createSimpleResolver, s as mergeHooks, t as createStatusHandler, u as IDEMPOTENCY_DEFAULT_TTL } from "./status-webhook-C69Vrc2v.mjs";
2
+ import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "./errors-BxRjct-E.mjs";
3
+ import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-DI6BNBZ4.mjs";
4
4
 
5
5
  //#region src/NotificationService.ts
6
6
  /**
@@ -297,12 +297,16 @@ var NotificationService = class {
297
297
  };
298
298
  }
299
299
  }
300
- const channelRetryRaw = channel.config?.retry;
301
- const retryConfig = channelRetryRaw ? resolveRetryConfig(channelRetryRaw) : this.retryConfig;
300
+ const retryConfig = channel.retry ? resolveRetryConfig(channel.retry) : this.retryConfig;
302
301
  const start = Date.now();
302
+ const NON_RETRYABLE = Symbol("non_retryable");
303
303
  try {
304
304
  return {
305
- ...await withRetry(() => channel.send(payload), retryConfig, (attempt, error) => {
305
+ ...await withRetry(async () => {
306
+ const r = await channel.send(payload);
307
+ if (r.status === "failed" && r.retryable === false) throw Object.assign(new Error(r.error ?? "non-retryable failure"), { [NON_RETRYABLE]: r });
308
+ return r;
309
+ }, retryConfig, (attempt, error) => {
306
310
  this.logger.warn(`[${channel.name}] Retry ${attempt}/${retryConfig.maxAttempts}: ${error.message}`);
307
311
  this.emitter.emit("send:retry", {
308
312
  channel: channel.name,
@@ -315,6 +319,10 @@ var NotificationService = class {
315
319
  duration: Date.now() - start
316
320
  };
317
321
  } catch (err) {
322
+ if (err instanceof Error && NON_RETRYABLE in err) return {
323
+ ...err[NON_RETRYABLE],
324
+ duration: Date.now() - start
325
+ };
318
326
  const message = err instanceof Error ? err.message : String(err);
319
327
  this.logger.error(`[${channel.name}] Failed: ${message}`);
320
328
  return {
@@ -327,7 +335,7 @@ var NotificationService = class {
327
335
  }
328
336
  /** Extract rate limit config from a channel */
329
337
  getChannelRateLimit(channel) {
330
- return channel.config?.rateLimit;
338
+ return channel.rateLimit;
331
339
  }
332
340
  /**
333
341
  * Send multiple notifications with controlled concurrency.
@@ -467,4 +475,57 @@ var NotificationService = class {
467
475
  };
468
476
 
469
477
  //#endregion
470
- export { BaseChannel, ChannelError, ConsoleChannel, EmailChannel, Emitter, IDEMPOTENCY_DEFAULT_TTL, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, NotificationService, ProviderNotInstalledError, PushChannel, SmsChannel, WebhookChannel, calculateDelay, createSimpleResolver, createStatusHandler, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
478
+ //#region src/index.ts
479
+ /**
480
+ * @classytic/notifications
481
+ * Multi-Channel Notification System
482
+ *
483
+ * Pluggable channels, templates, retry, and preferences.
484
+ * Zero required dependencies - bring your own providers.
485
+ *
486
+ * v2: Rate limiting, delivery tracking, queue adapter,
487
+ * BCC batching, template engines, SMS & push channels.
488
+ *
489
+ * @module @classytic/notifications
490
+ * @author Classytic (https://github.com/classytic)
491
+ * @license MIT
492
+ *
493
+ * @example
494
+ * ```typescript
495
+ * import { NotificationService } from '@classytic/notifications';
496
+ * import { EmailChannel, SmsChannel, PushChannel } from '@classytic/notifications/channels';
497
+ * import { MemoryDeliveryLog, createSimpleResolver } from '@classytic/notifications/utils';
498
+ *
499
+ * const notifications = new NotificationService({
500
+ * channels: [
501
+ * new EmailChannel({
502
+ * from: 'App <noreply@app.com>',
503
+ * transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
504
+ * rateLimit: { maxPerWindow: 500, windowMs: 86_400_000 }, // Gmail 500/day
505
+ * }),
506
+ * new SmsChannel({
507
+ * from: '+15551234567',
508
+ * provider: { send: async ({ to, from, body }) => ({ sid: 'custom' }) },
509
+ * }),
510
+ * new PushChannel({
511
+ * provider: { send: async ({ token, title, body }) => ({ messageId: 'custom' }) },
512
+ * }),
513
+ * ],
514
+ * templates: createSimpleResolver({
515
+ * welcome: { subject: 'Welcome ${name}!', html: '<p>Hi ${name}</p>' },
516
+ * }),
517
+ * retry: { maxAttempts: 3, backoff: 'exponential' },
518
+ * deliveryLog: new MemoryDeliveryLog(),
519
+ * });
520
+ *
521
+ * await notifications.send({
522
+ * event: 'user.created',
523
+ * recipient: { email: 'user@example.com', phone: '+15559876543', name: 'John' },
524
+ * data: { name: 'John' },
525
+ * template: 'welcome',
526
+ * });
527
+ * ```
528
+ */
529
+
530
+ //#endregion
531
+ export { BaseChannel, ChannelError, ConsoleChannel, EmailChannel, Emitter, IDEMPOTENCY_DEFAULT_TTL, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, NotificationService, ProviderNotInstalledError, PushChannel, SmsChannel, WebhookChannel, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
@@ -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-BMs4UhKD.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 */
@@ -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");
@@ -127,9 +136,10 @@ var EmailChannel = class EmailChannel extends BaseChannel {
127
136
  if (this.config.defaults) {
128
137
  for (const [key, value] of Object.entries(this.config.defaults)) if (!EmailChannel.PROTECTED_FIELDS.has(key)) safeDefaults[key] = value;
129
138
  }
139
+ const sender = this.config.allowSenderOverride && typeof data.from === "string" ? data.from : this.config.from;
130
140
  const mailOptions = {
131
141
  ...safeDefaults,
132
- from: data.from ?? this.config.from,
142
+ from: sender,
133
143
  to: recipient.email,
134
144
  subject: data.subject ?? ""
135
145
  };
@@ -139,6 +149,18 @@ var EmailChannel = class EmailChannel extends BaseChannel {
139
149
  if (data.cc) mailOptions.cc = data.cc;
140
150
  if (data.bcc) mailOptions.bcc = data.bcc;
141
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
+ }
142
164
  try {
143
165
  const result = await transporter.sendMail(mailOptions);
144
166
  return {
@@ -1,3 +1,5 @@
1
+ import { randomUUID } from "node:crypto";
2
+
1
3
  //#region src/utils/emitter.ts
2
4
  var Emitter = class {
3
5
  handlers = /* @__PURE__ */ new Map();
@@ -90,6 +92,12 @@ async function withRetry(fn, config, onRetry) {
90
92
  * Supports overnight ranges (e.g. 22:00 - 07:00).
91
93
  * Returns false if start/end are missing or malformed.
92
94
  *
95
+ * Note: an invalid `timezone` (not a recognised IANA zone) causes
96
+ * `Intl.DateTimeFormat` to throw a `RangeError` — this function does not
97
+ * catch it. `NotificationService` calls this inside its preference try/catch
98
+ * and fails open (sends anyway) on such errors; standalone callers should
99
+ * validate the timezone or wrap the call themselves.
100
+ *
93
101
  * @param quiet - Quiet hours config with start, end, and optional timezone
94
102
  * @param now - Current date (defaults to new Date(), injectable for testing)
95
103
  */
@@ -134,6 +142,15 @@ function getCurrentMinutes(now, timezone) {
134
142
  * Prevents duplicate notification delivery using idempotency keys.
135
143
  * Ships with an in-memory store; implement IdempotencyStore for
136
144
  * Redis, database, or other distributed backends.
145
+ *
146
+ * ## Distributed systems note
147
+ *
148
+ * `MemoryIdempotencyStore` is not suitable for multi-process deployments.
149
+ * The `has()` + `set()` pair is not atomic — two concurrent processes can
150
+ * both call `has()`, both see `false`, and both deliver the notification.
151
+ * For distributed safety, implement `IdempotencyStore` backed by a store
152
+ * that supports atomic `SET key value NX PX ttl` semantics (Redis, Postgres
153
+ * advisory locks, etc.). The interface is intentionally async to allow this.
137
154
  */
138
155
  /** Default TTL: 24 hours */
139
156
  const DEFAULT_TTL = 1440 * 60 * 1e3;
@@ -143,14 +160,23 @@ const DEFAULT_TTL = 1440 * 60 * 1e3;
143
160
  * Suitable for single-process apps. For distributed systems,
144
161
  * implement `IdempotencyStore` with Redis or your database.
145
162
  *
146
- * Expired entries are lazily cleaned up every `cleanupInterval` writes.
163
+ * Cleanup strategy:
164
+ * - **Write-triggered**: every `cleanupInterval` writes a full pass
165
+ * removes expired keys (prevents unbounded growth under high write load).
166
+ * - **Time-triggered**: a background `setInterval` runs every
167
+ * `cleanupIntervalMs` so sparse-traffic apps don't accumulate stale keys
168
+ * indefinitely. Pass `cleanupIntervalMs: 0` to disable the timer
169
+ * (e.g. in tests that use fake timers).
147
170
  */
148
171
  var MemoryIdempotencyStore = class {
149
172
  store = /* @__PURE__ */ new Map();
150
- cleanupCounter = 0;
151
- cleanupInterval;
173
+ writeCounter = 0;
174
+ writeCleanupThreshold;
175
+ timer;
152
176
  constructor(options) {
153
- this.cleanupInterval = options?.cleanupInterval ?? 100;
177
+ this.writeCleanupThreshold = options?.cleanupInterval ?? 100;
178
+ const intervalMs = options?.cleanupIntervalMs ?? 300 * 1e3;
179
+ this.timer = intervalMs > 0 ? setInterval(() => this.cleanup(), intervalMs).unref?.() ?? setInterval(() => this.cleanup(), intervalMs) : null;
154
180
  }
155
181
  has(key) {
156
182
  const expiry = this.store.get(key);
@@ -163,21 +189,31 @@ var MemoryIdempotencyStore = class {
163
189
  }
164
190
  set(key, ttlMs) {
165
191
  this.store.set(key, Date.now() + ttlMs);
166
- this.maybeCleanup();
192
+ if (++this.writeCounter >= this.writeCleanupThreshold) {
193
+ this.writeCounter = 0;
194
+ this.cleanup();
195
+ }
167
196
  }
168
- /** Number of entries (including possibly expired) */
197
+ /** Remove all expired entries. Safe to call at any time. */
198
+ cleanup() {
199
+ const now = Date.now();
200
+ for (const [key, expiry] of this.store) if (now > expiry) this.store.delete(key);
201
+ }
202
+ /** Number of entries (including possibly expired). */
169
203
  get size() {
170
204
  return this.store.size;
171
205
  }
172
- /** Remove all entries */
206
+ /** Remove all entries and stop the background timer. */
173
207
  clear() {
174
208
  this.store.clear();
209
+ if (this.timer) clearInterval(this.timer);
175
210
  }
176
- maybeCleanup() {
177
- if (++this.cleanupCounter < this.cleanupInterval) return;
178
- this.cleanupCounter = 0;
179
- const now = Date.now();
180
- for (const [key, expiry] of this.store) if (now > expiry) this.store.delete(key);
211
+ /**
212
+ * Stop the background cleanup timer without clearing entries.
213
+ * Call in tests / shutdown hooks to avoid open-handle warnings.
214
+ */
215
+ destroy() {
216
+ if (this.timer) clearInterval(this.timer);
181
217
  }
182
218
  };
183
219
  /** Default TTL for idempotency keys (24 hours) */
@@ -268,9 +304,32 @@ function mergeHooks(...hookConfigs) {
268
304
 
269
305
  //#endregion
270
306
  //#region src/utils/delivery-log.ts
271
- /** Generate a simple unique ID */
307
+ /**
308
+ * Delivery Log / Audit Trail
309
+ * @module @classytic/notifications/utils
310
+ *
311
+ * Tracks what was sent to whom, when, and via which channel.
312
+ * Ships with an in-memory store; implement DeliveryLog for
313
+ * database-backed persistence.
314
+ *
315
+ * @example
316
+ * ```typescript
317
+ * import { NotificationService } from '@classytic/notifications';
318
+ * import { MemoryDeliveryLog } from '@classytic/notifications/utils';
319
+ *
320
+ * const log = new MemoryDeliveryLog();
321
+ * const service = new NotificationService({
322
+ * channels: [...],
323
+ * deliveryLog: log,
324
+ * });
325
+ *
326
+ * // Query delivery history
327
+ * const entries = log.query({ recipientId: 'u1', event: 'user.created' });
328
+ * ```
329
+ */
330
+ /** Generate a collision-free log entry ID (Node 18+ `crypto.randomUUID`). */
272
331
  function generateId$1() {
273
- return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
332
+ return randomUUID();
274
333
  }
275
334
  /**
276
335
  * In-memory delivery log with query support.
@@ -332,15 +391,45 @@ var MemoryDeliveryLog = class {
332
391
  resolveStatus(dispatch) {
333
392
  if (dispatch.sent > 0 && dispatch.failed === 0) return "delivered";
334
393
  if (dispatch.sent > 0 && dispatch.failed > 0) return "partial";
394
+ if (dispatch.failed === 0 && dispatch.skipped > 0) return "skipped";
335
395
  return "failed";
336
396
  }
337
397
  };
338
398
 
339
399
  //#endregion
340
400
  //#region src/utils/queue.ts
341
- /** Generate a simple unique ID */
401
+ /**
402
+ * Queue Adapter
403
+ * @module @classytic/notifications/utils
404
+ *
405
+ * Optional queue layer for crash-resilient notification delivery.
406
+ * Without a queue, notifications are fire-and-forget (lost on crash).
407
+ *
408
+ * Ships with a MemoryQueue (dev/testing); use BullMQ, Redis, or
409
+ * database-backed adapters in production.
410
+ *
411
+ * @example
412
+ * ```typescript
413
+ * import { NotificationService } from '@classytic/notifications';
414
+ * import { MemoryQueue } from '@classytic/notifications/utils';
415
+ *
416
+ * const queue = new MemoryQueue();
417
+ * const service = new NotificationService({
418
+ * channels: [...],
419
+ * queue,
420
+ * });
421
+ *
422
+ * // Notifications are now queued before sending
423
+ * await service.send({ event: 'user.created', ... });
424
+ *
425
+ * // For production, implement QueueAdapter with BullMQ:
426
+ * // import { BullMQAdapter } from './your-bullmq-adapter';
427
+ * // const queue = new BullMQAdapter({ connection: { host: 'redis' } });
428
+ * ```
429
+ */
430
+ /** Generate a collision-free job ID (Node 18+ `crypto.randomUUID`). */
342
431
  function generateId() {
343
- return `q-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
432
+ return `q-${randomUUID()}`;
344
433
  }
345
434
  /**
346
435
  * In-memory queue for development and testing.
@@ -356,8 +445,12 @@ var MemoryQueue = class {
356
445
  concurrency;
357
446
  activeCount = 0;
358
447
  delayTimers = /* @__PURE__ */ new Map();
448
+ defaultRetryDelay;
449
+ defaultMaxRetryDelay;
359
450
  constructor(options) {
360
451
  this.concurrency = options?.concurrency ?? 5;
452
+ this.defaultRetryDelay = options?.retryDelay ?? 1e3;
453
+ this.defaultMaxRetryDelay = options?.maxRetryDelay ?? 3e4;
361
454
  }
362
455
  enqueue(payload, options) {
363
456
  const id = generateId();
@@ -367,6 +460,8 @@ var MemoryQueue = class {
367
460
  status: "pending",
368
461
  attempts: 0,
369
462
  maxAttempts: options?.maxAttempts ?? 3,
463
+ retryDelay: options?.retryDelay ?? this.defaultRetryDelay,
464
+ maxRetryDelay: options?.maxRetryDelay ?? this.defaultMaxRetryDelay,
370
465
  createdAt: /* @__PURE__ */ new Date(),
371
466
  updatedAt: /* @__PURE__ */ new Date()
372
467
  };
@@ -403,6 +498,17 @@ var MemoryQueue = class {
403
498
  this.paused = false;
404
499
  this.drain_queue();
405
500
  }
501
+ /**
502
+ * Drain the queue: cancel delayed timers and remove all not-yet-running
503
+ * jobs from the pipeline.
504
+ *
505
+ * Semantics note: drained jobs (both delayed-but-unfired and pending) are
506
+ * marked with status `'completed'`, NOT a distinct "drained"/"cancelled"
507
+ * state — `QueueJobStatus` has no such value. So `'completed'` here means
508
+ * "no longer in the queue", which is NOT the same as "delivered". Anything
509
+ * that treats `completed` as proof of delivery (dashboards, metrics) should
510
+ * read delivery success from the delivery log, not from queue job status.
511
+ */
406
512
  drain() {
407
513
  for (const timer of this.delayTimers.values()) clearTimeout(timer);
408
514
  for (const [id] of this.delayTimers) {
@@ -448,17 +554,20 @@ var MemoryQueue = class {
448
554
  job.status = "completed";
449
555
  job.updatedAt = /* @__PURE__ */ new Date();
450
556
  }).catch((err) => {
451
- const message = err instanceof Error ? err.message : String(err);
557
+ job.error = err instanceof Error ? err.message : String(err);
558
+ job.updatedAt = /* @__PURE__ */ new Date();
452
559
  if (job.attempts < job.maxAttempts) {
560
+ const base = Math.min(job.retryDelay * Math.pow(2, job.attempts - 1), job.maxRetryDelay);
561
+ const jitter = base * .25 * (Math.random() * 2 - 1);
562
+ const delay = Math.max(0, Math.round(base + jitter));
453
563
  job.status = "pending";
454
- job.error = message;
455
- job.updatedAt = /* @__PURE__ */ new Date();
456
- this.pending.push(jobId);
457
- } else {
458
- job.status = "failed";
459
- job.error = message;
460
- job.updatedAt = /* @__PURE__ */ new Date();
461
- }
564
+ const timer = setTimeout(() => {
565
+ this.delayTimers.delete(jobId);
566
+ this.pending.push(jobId);
567
+ this.drain_queue();
568
+ }, delay);
569
+ this.delayTimers.set(jobId, timer);
570
+ } else job.status = "failed";
462
571
  }).finally(() => {
463
572
  this.activeCount--;
464
573
  this.drain_queue();
@@ -475,15 +584,21 @@ var MemoryQueue = class {
475
584
  * Replaces `${key}` patterns with values from the data object.
476
585
  * Supports nested access: `${user.name}`.
477
586
  *
587
+ * **Safe by default:** values interpolated into the `html` field are
588
+ * HTML-escaped to prevent injection/XSS from user-controlled data. Pass
589
+ * `{ escape: false }` to opt out for pre-trusted HTML. The `subject` and
590
+ * `text` fields are never escaped.
591
+ *
478
592
  * For advanced templating (loops, conditionals, partials),
479
593
  * plug in any engine via the `TemplateResolver` interface.
480
594
  */
481
- function createSimpleResolver(templates) {
595
+ function createSimpleResolver(templates, options = {}) {
596
+ const escapeHtmlField = options.escape ?? true;
482
597
  return (templateId, data) => {
483
598
  const template = templates[templateId];
484
599
  if (!template) throw new Error(`Template "${templateId}" not found`);
485
600
  const result = {};
486
- for (const [field, value] of Object.entries(template)) if (typeof value === "string") result[field] = interpolate(value, data);
601
+ for (const [field, value] of Object.entries(template)) if (typeof value === "string") result[field] = interpolate(value, data, escapeHtmlField && field === "html");
487
602
  return result;
488
603
  };
489
604
  }
@@ -493,13 +608,58 @@ function getNestedValue(obj, path) {
493
608
  if (current != null && typeof current === "object") return current[key];
494
609
  }, obj);
495
610
  }
496
- /** Replace ${key} patterns with values from data */
497
- function interpolate(template, data) {
611
+ /**
612
+ * Replace `${key}` patterns with values from data.
613
+ * When `escape` is true, substituted values are HTML-escaped (the template
614
+ * skeleton is never escaped — only the interpolated value).
615
+ */
616
+ function interpolate(template, data, escape = false) {
498
617
  return template.replace(/\$\{([^}]+)\}/g, (_, key) => {
499
618
  const value = getNestedValue(data, key.trim());
500
- return value != null ? String(value) : "";
619
+ if (value == null) return "";
620
+ const str = String(value);
621
+ return escape ? escapeHtml(str) : str;
622
+ });
623
+ }
624
+ /**
625
+ * Interpolate `{{key}}` / `{{ key }}` placeholders (Handlebars/Mustache style).
626
+ *
627
+ * Supports nested access: `{{ contact.email }}`.
628
+ * Values are HTML-escaped by default — safe to use with untrusted contact data.
629
+ * Use `escape: false` only for plain-text subjects or pre-sanitised HTML fragments.
630
+ *
631
+ * @example
632
+ * interpolateHtml('<p>Hi {{firstName}},</p>', { firstName: 'Alice' })
633
+ * // → '<p>Hi Alice,</p>'
634
+ *
635
+ * interpolateHtml('Hello {{ contact.email }}', { contact: { email: 'a@b.com' } })
636
+ * // → 'Hello a@b.com'
637
+ *
638
+ * // Strict mode: throws on missing keys (useful in tests)
639
+ * interpolateHtml('Hi {{name}}', {}, { strict: true })
640
+ * // → throws Error: Template variable "name" is not defined
641
+ *
642
+ * // Raw HTML values (opt out of escaping)
643
+ * interpolateHtml('<p>{{content}}</p>', { content: '<b>Bold</b>' }, { escape: false })
644
+ * // → '<p><b>Bold</b></p>'
645
+ */
646
+ function interpolateHtml(template, vars, options = {}) {
647
+ const { escape: shouldEscape = true, strict = false } = options;
648
+ return template.replace(/\{\{\s*([^}]+?)\s*\}\}/g, (full, key) => {
649
+ const trimmed = key.trim();
650
+ const value = getNestedValue(vars, trimmed);
651
+ if (value == null) {
652
+ if (strict) throw new Error(`Template variable "${trimmed}" is not defined`);
653
+ return "";
654
+ }
655
+ const str = String(value);
656
+ return shouldEscape ? escapeHtml(str) : str;
501
657
  });
502
658
  }
659
+ /** Escape HTML entities to prevent XSS when interpolating untrusted values. */
660
+ function escapeHtml(str) {
661
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;").replace(/`/g, "&#x60;");
662
+ }
503
663
 
504
664
  //#endregion
505
665
  //#region src/utils/fallback.ts
@@ -579,4 +739,4 @@ function createStatusHandler(config = {}) {
579
739
  }
580
740
 
581
741
  //#endregion
582
- export { MemoryDeliveryLog as a, MemoryRateLimitStore as c, isQuietHours as d, calculateDelay as f, Emitter as h, MemoryQueue as i, IDEMPOTENCY_DEFAULT_TTL as l, withRetry as m, withFallback as n, mergeHooks as o, resolveRetryConfig as p, createSimpleResolver as r, pMap as s, createStatusHandler as t, MemoryIdempotencyStore as u };
742
+ export { MemoryQueue as a, pMap as c, MemoryIdempotencyStore as d, isQuietHours as f, Emitter as g, withRetry as h, interpolateHtml as i, MemoryRateLimitStore as l, resolveRetryConfig as m, withFallback as n, MemoryDeliveryLog as o, calculateDelay as p, createSimpleResolver as r, mergeHooks as s, createStatusHandler as t, IDEMPOTENCY_DEFAULT_TTL as u };
@@ -1,4 +1,4 @@
1
- import { C as RetryConfig, S as ResolvedRetryConfig, d as HookMap, h as NotificationPayload, k as TemplateResolver, o as DispatchResult, u as HookHandler } from "./types-BMs4UhKD.mjs";
1
+ import { C as RetryConfig, S as ResolvedRetryConfig, d as HookMap, h as NotificationPayload, k as TemplateResolver, o as DispatchResult, u as HookHandler } from "./types-QIV0Th2F.mjs";
2
2
 
3
3
  //#region src/utils/merge-hooks.d.ts
4
4
  type HookInput = Record<string, HookHandler | HookHandler[]>;
@@ -86,6 +86,12 @@ interface QuietHoursConfig {
86
86
  * Supports overnight ranges (e.g. 22:00 - 07:00).
87
87
  * Returns false if start/end are missing or malformed.
88
88
  *
89
+ * Note: an invalid `timezone` (not a recognised IANA zone) causes
90
+ * `Intl.DateTimeFormat` to throw a `RangeError` — this function does not
91
+ * catch it. `NotificationService` calls this inside its preference try/catch
92
+ * and fails open (sends anyway) on such errors; standalone callers should
93
+ * validate the timezone or wrap the call themselves.
94
+ *
89
95
  * @param quiet - Quiet hours config with start, end, and optional timezone
90
96
  * @param now - Current date (defaults to new Date(), injectable for testing)
91
97
  */
@@ -146,16 +152,80 @@ interface TemplateDefinition {
146
152
  }
147
153
  /** Map of template ID to template definition */
148
154
  type TemplateMap = Record<string, TemplateDefinition>;
155
+ /** Options for `createSimpleResolver` */
156
+ interface SimpleResolverOptions {
157
+ /**
158
+ * HTML-escape interpolated values in the `html` field. Default `true`.
159
+ *
160
+ * Interpolated *values* are escaped (`&`, `<`, `>`, `"`, `'`, `` ` ``);
161
+ * the template skeleton is left untouched, so `<h1>Hi ${name}</h1>` keeps
162
+ * its tags while a malicious `${name}` like `<script>…` is neutralised.
163
+ * This is safe-by-default — most callers feed user-controlled data
164
+ * (names, order details) straight into an email `html` body.
165
+ *
166
+ * The `subject` and `text` fields are NEVER HTML-escaped (they are not
167
+ * HTML contexts — escaping would corrupt plain text into `&amp;` noise).
168
+ *
169
+ * Set `false` only when the `html` values are already trusted HTML
170
+ * fragments (e.g. pre-sanitised rich content you intentionally inline).
171
+ */
172
+ escape?: boolean;
173
+ }
149
174
  /**
150
175
  * Simple string interpolation resolver (zero dependencies).
151
176
  *
152
177
  * Replaces `${key}` patterns with values from the data object.
153
178
  * Supports nested access: `${user.name}`.
154
179
  *
180
+ * **Safe by default:** values interpolated into the `html` field are
181
+ * HTML-escaped to prevent injection/XSS from user-controlled data. Pass
182
+ * `{ escape: false }` to opt out for pre-trusted HTML. The `subject` and
183
+ * `text` fields are never escaped.
184
+ *
155
185
  * For advanced templating (loops, conditionals, partials),
156
186
  * plug in any engine via the `TemplateResolver` interface.
157
187
  */
158
- declare function createSimpleResolver(templates: TemplateMap): TemplateResolver;
188
+ declare function createSimpleResolver(templates: TemplateMap, options?: SimpleResolverOptions): TemplateResolver;
189
+ /** Options for `interpolateHtml` */
190
+ interface InterpolateOptions {
191
+ /**
192
+ * Escape HTML entities in substituted values.
193
+ * Default `true` — safe for HTML email bodies. Set `false` only
194
+ * when the template is plain text or values are already trusted HTML.
195
+ *
196
+ * Escapes: `&`, `<`, `>`, `"`, `'`, `` ` ``.
197
+ */
198
+ escape?: boolean;
199
+ /**
200
+ * Throw when a placeholder references a key that is absent from `vars`.
201
+ * Default `false` — missing keys are replaced with an empty string.
202
+ * Enable in CI / tests to catch typos in template definitions.
203
+ */
204
+ strict?: boolean;
205
+ }
206
+ /**
207
+ * Interpolate `{{key}}` / `{{ key }}` placeholders (Handlebars/Mustache style).
208
+ *
209
+ * Supports nested access: `{{ contact.email }}`.
210
+ * Values are HTML-escaped by default — safe to use with untrusted contact data.
211
+ * Use `escape: false` only for plain-text subjects or pre-sanitised HTML fragments.
212
+ *
213
+ * @example
214
+ * interpolateHtml('<p>Hi {{firstName}},</p>', { firstName: 'Alice' })
215
+ * // → '<p>Hi Alice,</p>'
216
+ *
217
+ * interpolateHtml('Hello {{ contact.email }}', { contact: { email: 'a@b.com' } })
218
+ * // → 'Hello a@b.com'
219
+ *
220
+ * // Strict mode: throws on missing keys (useful in tests)
221
+ * interpolateHtml('Hi {{name}}', {}, { strict: true })
222
+ * // → throws Error: Template variable "name" is not defined
223
+ *
224
+ * // Raw HTML values (opt out of escaping)
225
+ * interpolateHtml('<p>{{content}}</p>', { content: '<b>Bold</b>' }, { escape: false })
226
+ * // → '<p><b>Bold</b></p>'
227
+ */
228
+ declare function interpolateHtml(template: string, vars: Record<string, unknown>, options?: InterpolateOptions): string;
159
229
  //#endregion
160
230
  //#region src/utils/fallback.d.ts
161
231
  /** Service-like object that can send to specific channels */
@@ -265,4 +335,4 @@ interface StatusHandler {
265
335
  */
266
336
  declare function createStatusHandler(config?: StatusHandlerConfig): StatusHandler;
267
337
  //#endregion
268
- export { mergeHooks as S, ProviderNotInstalledError as _, createStatusHandler as a, resolveRetryConfig as b, TemplateDefinition as c, PMapOptions as d, pMap as f, NotificationError as g, ChannelError as h, StatusUpdate as i, TemplateMap as l, isQuietHours as m, StatusHandler as n, FallbackOptions as o, QuietHoursConfig as p, StatusHandlerConfig as r, withFallback as s, DeliveryStatus as t, createSimpleResolver as u, Emitter as v, withRetry as x, calculateDelay as y };
338
+ export { resolveRetryConfig as C, calculateDelay as S, mergeHooks as T, isQuietHours as _, createStatusHandler as a, ProviderNotInstalledError as b, InterpolateOptions as c, TemplateMap as d, createSimpleResolver as f, QuietHoursConfig as g, pMap as h, StatusUpdate as i, SimpleResolverOptions as l, PMapOptions as m, StatusHandler as n, FallbackOptions as o, interpolateHtml as p, StatusHandlerConfig as r, withFallback as s, DeliveryStatus as t, TemplateDefinition as u, ChannelError as v, withRetry as w, Emitter as x, NotificationError as y };
@@ -63,12 +63,25 @@ declare class MemoryRateLimitStore implements RateLimitStore {
63
63
  * Prevents duplicate notification delivery using idempotency keys.
64
64
  * Ships with an in-memory store; implement IdempotencyStore for
65
65
  * Redis, database, or other distributed backends.
66
+ *
67
+ * ## Distributed systems note
68
+ *
69
+ * `MemoryIdempotencyStore` is not suitable for multi-process deployments.
70
+ * The `has()` + `set()` pair is not atomic — two concurrent processes can
71
+ * both call `has()`, both see `false`, and both deliver the notification.
72
+ * For distributed safety, implement `IdempotencyStore` backed by a store
73
+ * that supports atomic `SET key value NX PX ttl` semantics (Redis, Postgres
74
+ * advisory locks, etc.). The interface is intentionally async to allow this.
66
75
  */
67
76
  /**
68
77
  * Interface for idempotency stores.
69
78
  *
70
79
  * Methods may be sync or async to support both in-memory and
71
80
  * distributed backends (Redis, DB).
81
+ *
82
+ * **Atomicity requirement**: for distributed deployments, `has()`/`set()`
83
+ * MUST be implemented as a single atomic operation (e.g. Redis `SET NX`).
84
+ * The two-method interface exists for in-process convenience only.
72
85
  */
73
86
  interface IdempotencyStore {
74
87
  /** Check if a key has been seen (within TTL) */
@@ -82,22 +95,41 @@ interface IdempotencyStore {
82
95
  * Suitable for single-process apps. For distributed systems,
83
96
  * implement `IdempotencyStore` with Redis or your database.
84
97
  *
85
- * Expired entries are lazily cleaned up every `cleanupInterval` writes.
98
+ * Cleanup strategy:
99
+ * - **Write-triggered**: every `cleanupInterval` writes a full pass
100
+ * removes expired keys (prevents unbounded growth under high write load).
101
+ * - **Time-triggered**: a background `setInterval` runs every
102
+ * `cleanupIntervalMs` so sparse-traffic apps don't accumulate stale keys
103
+ * indefinitely. Pass `cleanupIntervalMs: 0` to disable the timer
104
+ * (e.g. in tests that use fake timers).
86
105
  */
87
106
  declare class MemoryIdempotencyStore implements IdempotencyStore {
88
107
  private store;
89
- private cleanupCounter;
90
- private readonly cleanupInterval;
108
+ private writeCounter;
109
+ private readonly writeCleanupThreshold;
110
+ private readonly timer;
91
111
  constructor(options?: {
92
- cleanupInterval?: number;
112
+ /** Trigger a cleanup sweep after this many writes. Default: 100. */cleanupInterval?: number;
113
+ /**
114
+ * Run a time-based cleanup sweep every N ms. Default: 5 minutes.
115
+ * Set to 0 to disable the timer (useful in test environments with
116
+ * fake timers — drive cleanup via writes or call `cleanup()` manually).
117
+ */
118
+ cleanupIntervalMs?: number;
93
119
  });
94
120
  has(key: string): boolean;
95
121
  set(key: string, ttlMs: number): void;
96
- /** Number of entries (including possibly expired) */
122
+ /** Remove all expired entries. Safe to call at any time. */
123
+ cleanup(): void;
124
+ /** Number of entries (including possibly expired). */
97
125
  get size(): number;
98
- /** Remove all entries */
126
+ /** Remove all entries and stop the background timer. */
99
127
  clear(): void;
100
- private maybeCleanup;
128
+ /**
129
+ * Stop the background cleanup timer without clearing entries.
130
+ * Call in tests / shutdown hooks to avoid open-handle warnings.
131
+ */
132
+ destroy(): void;
101
133
  }
102
134
  /** Default TTL for idempotency keys (24 hours) */
103
135
  declare const IDEMPOTENCY_DEFAULT_TTL: number;
@@ -120,7 +152,7 @@ interface DeliveryLogEntry {
120
152
  /** Per-channel results */
121
153
  results: SendResult[];
122
154
  /** Overall status */
123
- status: 'delivered' | 'partial' | 'failed';
155
+ status: 'delivered' | 'partial' | 'failed' | 'skipped';
124
156
  /** Total duration in ms */
125
157
  duration: number;
126
158
  /** Original payload metadata */
@@ -132,7 +164,7 @@ interface DeliveryLogQuery {
132
164
  recipientEmail?: string;
133
165
  event?: string;
134
166
  channel?: string;
135
- status?: 'delivered' | 'partial' | 'failed';
167
+ status?: 'delivered' | 'partial' | 'failed' | 'skipped';
136
168
  /** Only entries after this date */
137
169
  after?: Date;
138
170
  /** Only entries before this date */
@@ -181,6 +213,8 @@ interface QueueJob {
181
213
  status: QueueJobStatus;
182
214
  attempts: number;
183
215
  maxAttempts: number;
216
+ retryDelay: number;
217
+ maxRetryDelay: number;
184
218
  createdAt: Date;
185
219
  updatedAt: Date;
186
220
  error?: string;
@@ -214,6 +248,17 @@ interface QueueEnqueueOptions {
214
248
  delay?: number;
215
249
  /** Max processing attempts (default: 3) */
216
250
  maxAttempts?: number;
251
+ /**
252
+ * Base delay in ms between retry attempts.
253
+ * Actual delay uses exponential backoff with ±25% jitter:
254
+ * attempt 1 → retryDelay * 2^0 = retryDelay
255
+ * attempt 2 → retryDelay * 2^1
256
+ * attempt 3 → retryDelay * 2^2
257
+ * Capped at `maxRetryDelay`. Default: 1000 (1 second).
258
+ */
259
+ retryDelay?: number;
260
+ /** Maximum backoff delay cap in ms. Default: 30000 (30 seconds). */
261
+ maxRetryDelay?: number;
217
262
  }
218
263
  /** Processor function called by the queue for each job */
219
264
  type QueueProcessor = (payload: NotificationPayload) => Promise<void>;
@@ -231,8 +276,12 @@ declare class MemoryQueue implements QueueAdapter {
231
276
  private readonly concurrency;
232
277
  private activeCount;
233
278
  private delayTimers;
279
+ private readonly defaultRetryDelay;
280
+ private readonly defaultMaxRetryDelay;
234
281
  constructor(options?: {
235
282
  concurrency?: number;
283
+ retryDelay?: number;
284
+ maxRetryDelay?: number;
236
285
  });
237
286
  enqueue(payload: NotificationPayload, options?: QueueEnqueueOptions): string;
238
287
  process(processor: QueueProcessor): void;
@@ -240,6 +289,17 @@ declare class MemoryQueue implements QueueAdapter {
240
289
  size(): number;
241
290
  pause(): void;
242
291
  resume(): void;
292
+ /**
293
+ * Drain the queue: cancel delayed timers and remove all not-yet-running
294
+ * jobs from the pipeline.
295
+ *
296
+ * Semantics note: drained jobs (both delayed-but-unfired and pending) are
297
+ * marked with status `'completed'`, NOT a distinct "drained"/"cancelled"
298
+ * state — `QueueJobStatus` has no such value. So `'completed'` here means
299
+ * "no longer in the queue", which is NOT the same as "delivered". Anything
300
+ * that treats `completed` as proof of delivery (dashboards, metrics) should
301
+ * read delivery success from the delivery log, not from queue job status.
302
+ */
243
303
  drain(): void;
244
304
  /** Get all jobs (for testing/debugging) */
245
305
  getAllJobs(): QueueJob[];
@@ -290,6 +350,14 @@ interface SendResult {
290
350
  channel: string;
291
351
  duration?: number;
292
352
  error?: string;
353
+ /**
354
+ * When `false`, the service will NOT retry this result even if the global
355
+ * `retry.maxAttempts > 1`. Use for permanent failures: invalid recipient
356
+ * address, bad credentials, hard bounce, 4xx from provider.
357
+ *
358
+ * Unset / `true` means the failure is transient and should be retried.
359
+ */
360
+ retryable?: boolean;
293
361
  metadata?: Record<string, unknown>;
294
362
  }
295
363
  /** Result from dispatching to all channels */
@@ -319,6 +387,19 @@ interface ChannelConfig {
319
387
  /** Channel interface - implement this for custom channels */
320
388
  interface Channel {
321
389
  readonly name: string;
390
+ /**
391
+ * Optional per-channel rate limit, read by the service before sending.
392
+ * `BaseChannel` exposes this from `config.rateLimit`; custom channels that
393
+ * implement `Channel` directly should surface it here so the service
394
+ * applies the limit (otherwise the channel is treated as unlimited).
395
+ */
396
+ readonly rateLimit?: RateLimitConfig;
397
+ /**
398
+ * Optional per-channel retry override, read by the service. When unset the
399
+ * service's global retry config applies. `BaseChannel` exposes this from
400
+ * `config.retry`.
401
+ */
402
+ readonly retry?: RetryConfig;
322
403
  shouldHandle(event: string): boolean;
323
404
  send(payload: NotificationPayload): Promise<SendResult>;
324
405
  /**
@@ -364,6 +445,35 @@ interface EmailChannelConfig extends ChannelConfig {
364
445
  transporter?: NodemailerTransporter;
365
446
  /** Default mail options merged into every send */
366
447
  defaults?: Record<string, unknown>;
448
+ /**
449
+ * Allow a per-send `payload.data.from` to override the channel's `from`
450
+ * address. Default `false` (safe).
451
+ *
452
+ * The `data` bag is frequently populated from template output and
453
+ * upstream/user-controlled input, so honouring `data.from` unconditionally
454
+ * is a sender-spoofing footgun in multi-tenant systems. Keep this `false`
455
+ * unless you fully control `data.from` and genuinely need per-send senders
456
+ * (e.g. sending on behalf of verified sub-accounts).
457
+ */
458
+ allowSenderOverride?: boolean;
459
+ /**
460
+ * RFC 8058 `List-Unsubscribe` header injection.
461
+ *
462
+ * When set, every outbound email receives:
463
+ * `List-Unsubscribe: <https://…/unsubscribe>, <mailto:…>`
464
+ * `List-Unsubscribe-Post: List-Unsubscribe=One-Click`
465
+ *
466
+ * Gmail, Outlook and Yahoo surface the one-click unsubscribe button
467
+ * when these headers are present. Required by CAN-SPAM, CASL, and the
468
+ * 2024 Google/Yahoo bulk-sender requirements for marketing email.
469
+ *
470
+ * Per-send values (from `payload.data.listUnsubscribeUrl`) override this
471
+ * channel-level default, allowing subscriber-specific unsubscribe links.
472
+ */
473
+ listUnsubscribe?: {
474
+ /** HTTPS URL that handles the one-click POST (RFC 8058 §3.2) */url?: string; /** Mailto address for clients that don't support HTTP unsubscribe */
475
+ email?: string;
476
+ };
367
477
  }
368
478
  /** Minimal Nodemailer transporter interface (avoids hard dep) */
369
479
  interface NodemailerTransporter {
@@ -1,3 +1,3 @@
1
- import { B as DeliveryLogQuery, F as QueueJob, G as MemoryRateLimitStore, H as IDEMPOTENCY_DEFAULT_TTL, I as QueueJobStatus, K as RateLimitConfig, L as QueueProcessor, M as MemoryQueue, N as QueueAdapter, P as QueueEnqueueOptions, R as DeliveryLog, U as IdempotencyStore, V as MemoryDeliveryLog, W as MemoryIdempotencyStore, q as RateLimitStore, z as DeliveryLogEntry } from "../types-BMs4UhKD.mjs";
2
- import { S as mergeHooks, _ as ProviderNotInstalledError, a as createStatusHandler, b as resolveRetryConfig, c as TemplateDefinition, d as PMapOptions, f as pMap, g as NotificationError, h as ChannelError, i as StatusUpdate, l as TemplateMap, m as isQuietHours, n as StatusHandler, o as FallbackOptions, p as QuietHoursConfig, r as StatusHandlerConfig, s as withFallback, t as DeliveryStatus, u as createSimpleResolver, v as Emitter, x as withRetry, y as calculateDelay } from "../status-webhook-Bb4UoinT.mjs";
3
- export { ChannelError, type DeliveryLog, type DeliveryLogEntry, type DeliveryLogQuery, type DeliveryStatus, Emitter, type FallbackOptions, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, type PMapOptions, ProviderNotInstalledError, type QueueAdapter, type QueueEnqueueOptions, type QueueJob, type QueueJobStatus, type QueueProcessor, type QuietHoursConfig, type RateLimitConfig, type RateLimitStore, type StatusHandler, type StatusHandlerConfig, type StatusUpdate, type TemplateDefinition, type TemplateMap, calculateDelay, createSimpleResolver, createStatusHandler, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
1
+ import { B as DeliveryLogQuery, F as QueueJob, G as MemoryRateLimitStore, H as IDEMPOTENCY_DEFAULT_TTL, I as QueueJobStatus, K as RateLimitConfig, L as QueueProcessor, M as MemoryQueue, N as QueueAdapter, P as QueueEnqueueOptions, R as DeliveryLog, U as IdempotencyStore, V as MemoryDeliveryLog, W as MemoryIdempotencyStore, q as RateLimitStore, z as DeliveryLogEntry } from "../types-QIV0Th2F.mjs";
2
+ import { C as resolveRetryConfig, S as calculateDelay, T as mergeHooks, _ as isQuietHours, a as createStatusHandler, b as ProviderNotInstalledError, c as InterpolateOptions, d as TemplateMap, f as createSimpleResolver, g as QuietHoursConfig, h as pMap, i as StatusUpdate, m as PMapOptions, n as StatusHandler, o as FallbackOptions, p as interpolateHtml, r as StatusHandlerConfig, s as withFallback, t as DeliveryStatus, u as TemplateDefinition, v as ChannelError, w as withRetry, x as Emitter, y as NotificationError } from "../status-webhook-DxCdp0c_.mjs";
3
+ export { ChannelError, type DeliveryLog, type DeliveryLogEntry, type DeliveryLogQuery, type DeliveryStatus, Emitter, type FallbackOptions, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, type InterpolateOptions, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, type PMapOptions, ProviderNotInstalledError, type QueueAdapter, type QueueEnqueueOptions, type QueueJob, type QueueJobStatus, type QueueProcessor, type QuietHoursConfig, type RateLimitConfig, type RateLimitStore, type StatusHandler, type StatusHandlerConfig, type StatusUpdate, type TemplateDefinition, type TemplateMap, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
@@ -1,4 +1,4 @@
1
- import { a as MemoryDeliveryLog, c as MemoryRateLimitStore, d as isQuietHours, f as calculateDelay, h as Emitter, i as MemoryQueue, l as IDEMPOTENCY_DEFAULT_TTL, m as withRetry, n as withFallback, o as mergeHooks, p as resolveRetryConfig, r as createSimpleResolver, s as pMap, t as createStatusHandler, u as MemoryIdempotencyStore } from "../status-webhook-XY42DCj_.mjs";
2
- import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "../errors-FYJYmfvj.mjs";
1
+ import { a as MemoryQueue, c as pMap, d as MemoryIdempotencyStore, f as isQuietHours, g as Emitter, h as withRetry, i as interpolateHtml, l as MemoryRateLimitStore, m as resolveRetryConfig, n as withFallback, o as MemoryDeliveryLog, p as calculateDelay, r as createSimpleResolver, s as mergeHooks, t as createStatusHandler, u as IDEMPOTENCY_DEFAULT_TTL } from "../status-webhook-C69Vrc2v.mjs";
2
+ import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "../errors-BxRjct-E.mjs";
3
3
 
4
- export { ChannelError, Emitter, IDEMPOTENCY_DEFAULT_TTL, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, ProviderNotInstalledError, calculateDelay, createSimpleResolver, createStatusHandler, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
4
+ export { ChannelError, Emitter, IDEMPOTENCY_DEFAULT_TTL, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, ProviderNotInstalledError, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classytic/notifications",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Multi-channel notifications (Email, SMS, Push, Webhook) with rate limiting, delivery tracking, queue adapters, channel fallback, templates, retry — zero required dependencies",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -107,11 +107,11 @@
107
107
  "devDependencies": {
108
108
  "@classytic/dev-tools": "^0.2.0",
109
109
  "@types/node": "^22.0.0",
110
- "@types/nodemailer": "^6.4.17",
111
- "@vitest/coverage-v8": "3.2.4",
112
- "nodemailer": "^6.10.1",
113
- "tsdown": "0.21.4",
114
- "typescript": "^5.7.0",
115
- "vitest": "^3.0.0"
110
+ "@types/nodemailer": "^8.0.0",
111
+ "@vitest/coverage-v8": "4.1.8",
112
+ "nodemailer": "^8.0.10",
113
+ "tsdown": "0.22.1",
114
+ "typescript": "^6.0.3",
115
+ "vitest": "^4.1.8"
116
116
  }
117
117
  }