@classytic/notifications 2.1.0 → 2.3.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
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2024 Classytic
3
+ Copyright (c) 2024 Classytic LLC
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # @classytic/notifications
2
2
 
3
+ [![Sponsor](https://img.shields.io/github/sponsors/classytic?style=flat-square&label=Sponsor&logo=GitHub&color=EA4AAA)](https://github.com/sponsors/classytic)
4
+
3
5
  > Multi-channel notification system for TypeScript/Node.js
4
6
 
5
7
  Pluggable channels, templates, retry with backoff, rate limiting, delivery tracking, and user preferences. Zero required dependencies — bring your own providers.
@@ -724,3 +726,7 @@ import type {
724
726
  ## License
725
727
 
726
728
  MIT
729
+
730
+ ## Trademark
731
+
732
+ MIT-licensed code. "Classytic"/"arc" names + logos are trademarks of Classytic LLC — see [TRADEMARK.md](TRADEMARK.md).
@@ -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-CfPaV8z5.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-BhktEp30.mjs";
2
2
 
3
3
  export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, WebhookChannel };
package/dist/index.d.mts CHANGED
@@ -1,7 +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";
4
-
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-B5InMRIc.mjs";
2
+ import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-CfPaV8z5.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-NDUgykHA.mjs";
5
4
  //#region src/NotificationService.d.ts
6
5
  declare class NotificationService {
7
6
  private channels;
@@ -134,4 +133,4 @@ declare class NotificationService {
134
133
  off(event: ServiceEvent, handler: EventHandler): this;
135
134
  }
136
135
  //#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 };
136
+ 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-B4Sv8X_G.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-BhktEp30.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,5 +1,4 @@
1
1
  import { Transporter } from "nodemailer";
2
-
3
2
  //#region src/providers/email/presets.d.ts
4
3
  /**
5
4
  * Email provider presets — Resend, Gmail, SendGrid, Mailgun, custom SMTP.
@@ -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,14 +91,15 @@ 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");
90
99
  }
91
100
  }
92
101
  /** Fields that defaults must never override */
93
- static PROTECTED_FIELDS = new Set([
102
+ static PROTECTED_FIELDS = /* @__PURE__ */ new Set([
94
103
  "to",
95
104
  "from",
96
105
  "subject",
@@ -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,12 +149,33 @@ 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 {
145
167
  status: "sent",
146
168
  channel: this.name,
147
- metadata: { messageId: result.messageId }
169
+ /**
170
+ * The TYPED field, not `metadata.messageId`.
171
+ *
172
+ * This id is what a bounce or complaint webhook arrives under, so it is the
173
+ * only thing joining this send to what actually happened to the mail. It sat
174
+ * in the untyped `metadata` bag, where every channel spells it differently
175
+ * and a consumer has to know which channel produced the result before it can
176
+ * find the id — which is why `SendResult.providerMessageId` exists.
177
+ */
178
+ providerMessageId: result.messageId
148
179
  };
149
180
  } catch (err) {
150
181
  const message = err instanceof Error ? err.message : String(err);
@@ -1,10 +1,13 @@
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";
2
-
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-B5InMRIc.mjs";
3
2
  //#region src/channels/BaseChannel.d.ts
4
3
  declare abstract class BaseChannel<TConfig extends ChannelConfig = ChannelConfig> implements Channel {
5
4
  readonly name: string;
6
5
  protected config: TConfig;
7
6
  constructor(config: TConfig);
7
+ /** Per-channel rate limit (from config) — read by the service. */
8
+ get rateLimit(): RateLimitConfig | undefined;
9
+ /** Per-channel retry override (from config) — read by the service. */
10
+ get retry(): RetryConfig | undefined;
8
11
  /** Check if this channel should handle a given event */
9
12
  shouldHandle(event: string): boolean;
10
13
  /** Send notification - must be implemented by subclass */
@@ -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,23 +142,41 @@ 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
- const DEFAULT_TTL = 1440 * 60 * 1e3;
156
+ const DEFAULT_TTL = 864e5;
140
157
  /**
141
158
  * In-memory idempotency store with TTL-based expiry.
142
159
  *
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 ?? 3e5;
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.
@@ -295,7 +354,8 @@ var MemoryDeliveryLog = class {
295
354
  results: dispatch.results,
296
355
  status: this.resolveStatus(dispatch),
297
356
  duration: dispatch.duration,
298
- metadata: payload.metadata
357
+ metadata: payload.metadata,
358
+ ...payload.subject ? { subject: payload.subject } : {}
299
359
  };
300
360
  this.entries.push(entry);
301
361
  if (this.entries.length > this.maxEntries) this.entries = this.entries.slice(-this.maxEntries);
@@ -306,6 +366,10 @@ var MemoryDeliveryLog = class {
306
366
  if (filter.recipientId) results = results.filter((e) => e.recipientId === filter.recipientId);
307
367
  if (filter.recipientEmail) results = results.filter((e) => e.recipientEmail === filter.recipientEmail);
308
368
  if (filter.event) results = results.filter((e) => e.event === filter.event);
369
+ if (filter.subject) {
370
+ const { sourceModel, sourceId } = filter.subject;
371
+ results = results.filter((e) => e.subject?.sourceModel === sourceModel && e.subject?.sourceId === sourceId);
372
+ }
309
373
  if (filter.channel) results = results.filter((e) => e.channels.includes(filter.channel));
310
374
  if (filter.status) results = results.filter((e) => e.status === filter.status);
311
375
  if (filter.after) {
@@ -332,15 +396,45 @@ var MemoryDeliveryLog = class {
332
396
  resolveStatus(dispatch) {
333
397
  if (dispatch.sent > 0 && dispatch.failed === 0) return "delivered";
334
398
  if (dispatch.sent > 0 && dispatch.failed > 0) return "partial";
399
+ if (dispatch.failed === 0 && dispatch.skipped > 0) return "skipped";
335
400
  return "failed";
336
401
  }
337
402
  };
338
403
 
339
404
  //#endregion
340
405
  //#region src/utils/queue.ts
341
- /** Generate a simple unique ID */
406
+ /**
407
+ * Queue Adapter
408
+ * @module @classytic/notifications/utils
409
+ *
410
+ * Optional queue layer for crash-resilient notification delivery.
411
+ * Without a queue, notifications are fire-and-forget (lost on crash).
412
+ *
413
+ * Ships with a MemoryQueue (dev/testing); use BullMQ, Redis, or
414
+ * database-backed adapters in production.
415
+ *
416
+ * @example
417
+ * ```typescript
418
+ * import { NotificationService } from '@classytic/notifications';
419
+ * import { MemoryQueue } from '@classytic/notifications/utils';
420
+ *
421
+ * const queue = new MemoryQueue();
422
+ * const service = new NotificationService({
423
+ * channels: [...],
424
+ * queue,
425
+ * });
426
+ *
427
+ * // Notifications are now queued before sending
428
+ * await service.send({ event: 'user.created', ... });
429
+ *
430
+ * // For production, implement QueueAdapter with BullMQ:
431
+ * // import { BullMQAdapter } from './your-bullmq-adapter';
432
+ * // const queue = new BullMQAdapter({ connection: { host: 'redis' } });
433
+ * ```
434
+ */
435
+ /** Generate a collision-free job ID (Node 18+ `crypto.randomUUID`). */
342
436
  function generateId() {
343
- return `q-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
437
+ return `q-${randomUUID()}`;
344
438
  }
345
439
  /**
346
440
  * In-memory queue for development and testing.
@@ -356,8 +450,12 @@ var MemoryQueue = class {
356
450
  concurrency;
357
451
  activeCount = 0;
358
452
  delayTimers = /* @__PURE__ */ new Map();
453
+ defaultRetryDelay;
454
+ defaultMaxRetryDelay;
359
455
  constructor(options) {
360
456
  this.concurrency = options?.concurrency ?? 5;
457
+ this.defaultRetryDelay = options?.retryDelay ?? 1e3;
458
+ this.defaultMaxRetryDelay = options?.maxRetryDelay ?? 3e4;
361
459
  }
362
460
  enqueue(payload, options) {
363
461
  const id = generateId();
@@ -367,6 +465,8 @@ var MemoryQueue = class {
367
465
  status: "pending",
368
466
  attempts: 0,
369
467
  maxAttempts: options?.maxAttempts ?? 3,
468
+ retryDelay: options?.retryDelay ?? this.defaultRetryDelay,
469
+ maxRetryDelay: options?.maxRetryDelay ?? this.defaultMaxRetryDelay,
370
470
  createdAt: /* @__PURE__ */ new Date(),
371
471
  updatedAt: /* @__PURE__ */ new Date()
372
472
  };
@@ -403,6 +503,17 @@ var MemoryQueue = class {
403
503
  this.paused = false;
404
504
  this.drain_queue();
405
505
  }
506
+ /**
507
+ * Drain the queue: cancel delayed timers and remove all not-yet-running
508
+ * jobs from the pipeline.
509
+ *
510
+ * Semantics note: drained jobs (both delayed-but-unfired and pending) are
511
+ * marked with status `'completed'`, NOT a distinct "drained"/"cancelled"
512
+ * state — `QueueJobStatus` has no such value. So `'completed'` here means
513
+ * "no longer in the queue", which is NOT the same as "delivered". Anything
514
+ * that treats `completed` as proof of delivery (dashboards, metrics) should
515
+ * read delivery success from the delivery log, not from queue job status.
516
+ */
406
517
  drain() {
407
518
  for (const timer of this.delayTimers.values()) clearTimeout(timer);
408
519
  for (const [id] of this.delayTimers) {
@@ -449,16 +560,20 @@ var MemoryQueue = class {
449
560
  job.updatedAt = /* @__PURE__ */ new Date();
450
561
  }).catch((err) => {
451
562
  const message = err instanceof Error ? err.message : String(err);
563
+ job.error = message;
564
+ job.updatedAt = /* @__PURE__ */ new Date();
452
565
  if (job.attempts < job.maxAttempts) {
566
+ const base = Math.min(job.retryDelay * Math.pow(2, job.attempts - 1), job.maxRetryDelay);
567
+ const jitter = base * .25 * (Math.random() * 2 - 1);
568
+ const delay = Math.max(0, Math.round(base + jitter));
453
569
  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
- }
570
+ const timer = setTimeout(() => {
571
+ this.delayTimers.delete(jobId);
572
+ this.pending.push(jobId);
573
+ this.drain_queue();
574
+ }, delay);
575
+ this.delayTimers.set(jobId, timer);
576
+ } else job.status = "failed";
462
577
  }).finally(() => {
463
578
  this.activeCount--;
464
579
  this.drain_queue();
@@ -475,15 +590,21 @@ var MemoryQueue = class {
475
590
  * Replaces `${key}` patterns with values from the data object.
476
591
  * Supports nested access: `${user.name}`.
477
592
  *
593
+ * **Safe by default:** values interpolated into the `html` field are
594
+ * HTML-escaped to prevent injection/XSS from user-controlled data. Pass
595
+ * `{ escape: false }` to opt out for pre-trusted HTML. The `subject` and
596
+ * `text` fields are never escaped.
597
+ *
478
598
  * For advanced templating (loops, conditionals, partials),
479
599
  * plug in any engine via the `TemplateResolver` interface.
480
600
  */
481
- function createSimpleResolver(templates) {
601
+ function createSimpleResolver(templates, options = {}) {
602
+ const escapeHtmlField = options.escape ?? true;
482
603
  return (templateId, data) => {
483
604
  const template = templates[templateId];
484
605
  if (!template) throw new Error(`Template "${templateId}" not found`);
485
606
  const result = {};
486
- for (const [field, value] of Object.entries(template)) if (typeof value === "string") result[field] = interpolate(value, data);
607
+ for (const [field, value] of Object.entries(template)) if (typeof value === "string") result[field] = interpolate(value, data, escapeHtmlField && field === "html");
487
608
  return result;
488
609
  };
489
610
  }
@@ -493,13 +614,58 @@ function getNestedValue(obj, path) {
493
614
  if (current != null && typeof current === "object") return current[key];
494
615
  }, obj);
495
616
  }
496
- /** Replace ${key} patterns with values from data */
497
- function interpolate(template, data) {
617
+ /**
618
+ * Replace `${key}` patterns with values from data.
619
+ * When `escape` is true, substituted values are HTML-escaped (the template
620
+ * skeleton is never escaped — only the interpolated value).
621
+ */
622
+ function interpolate(template, data, escape = false) {
498
623
  return template.replace(/\$\{([^}]+)\}/g, (_, key) => {
499
624
  const value = getNestedValue(data, key.trim());
500
- return value != null ? String(value) : "";
625
+ if (value == null) return "";
626
+ const str = String(value);
627
+ return escape ? escapeHtml(str) : str;
501
628
  });
502
629
  }
630
+ /**
631
+ * Interpolate `{{key}}` / `{{ key }}` placeholders (Handlebars/Mustache style).
632
+ *
633
+ * Supports nested access: `{{ contact.email }}`.
634
+ * Values are HTML-escaped by default — safe to use with untrusted contact data.
635
+ * Use `escape: false` only for plain-text subjects or pre-sanitised HTML fragments.
636
+ *
637
+ * @example
638
+ * interpolateHtml('<p>Hi {{firstName}},</p>', { firstName: 'Alice' })
639
+ * // → '<p>Hi Alice,</p>'
640
+ *
641
+ * interpolateHtml('Hello {{ contact.email }}', { contact: { email: 'a@b.com' } })
642
+ * // → 'Hello a@b.com'
643
+ *
644
+ * // Strict mode: throws on missing keys (useful in tests)
645
+ * interpolateHtml('Hi {{name}}', {}, { strict: true })
646
+ * // → throws Error: Template variable "name" is not defined
647
+ *
648
+ * // Raw HTML values (opt out of escaping)
649
+ * interpolateHtml('<p>{{content}}</p>', { content: '<b>Bold</b>' }, { escape: false })
650
+ * // → '<p><b>Bold</b></p>'
651
+ */
652
+ function interpolateHtml(template, vars, options = {}) {
653
+ const { escape: shouldEscape = true, strict = false } = options;
654
+ return template.replace(/\{\{\s*([^}]+?)\s*\}\}/g, (full, key) => {
655
+ const trimmed = key.trim();
656
+ const value = getNestedValue(vars, trimmed);
657
+ if (value == null) {
658
+ if (strict) throw new Error(`Template variable "${trimmed}" is not defined`);
659
+ return "";
660
+ }
661
+ const str = String(value);
662
+ return shouldEscape ? escapeHtml(str) : str;
663
+ });
664
+ }
665
+ /** Escape HTML entities to prevent XSS when interpolating untrusted values. */
666
+ function escapeHtml(str) {
667
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;").replace(/`/g, "&#x60;");
668
+ }
503
669
 
504
670
  //#endregion
505
671
  //#region src/utils/fallback.ts
@@ -579,4 +745,4 @@ function createStatusHandler(config = {}) {
579
745
  }
580
746
 
581
747
  //#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 };
748
+ 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,5 +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";
2
-
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-B5InMRIc.mjs";
3
2
  //#region src/utils/merge-hooks.d.ts
4
3
  type HookInput = Record<string, HookHandler | HookHandler[]>;
5
4
  declare function mergeHooks(...hookConfigs: (HookInput | null | undefined)[]): HookMap;
@@ -86,6 +85,12 @@ interface QuietHoursConfig {
86
85
  * Supports overnight ranges (e.g. 22:00 - 07:00).
87
86
  * Returns false if start/end are missing or malformed.
88
87
  *
88
+ * Note: an invalid `timezone` (not a recognised IANA zone) causes
89
+ * `Intl.DateTimeFormat` to throw a `RangeError` — this function does not
90
+ * catch it. `NotificationService` calls this inside its preference try/catch
91
+ * and fails open (sends anyway) on such errors; standalone callers should
92
+ * validate the timezone or wrap the call themselves.
93
+ *
89
94
  * @param quiet - Quiet hours config with start, end, and optional timezone
90
95
  * @param now - Current date (defaults to new Date(), injectable for testing)
91
96
  */
@@ -146,16 +151,80 @@ interface TemplateDefinition {
146
151
  }
147
152
  /** Map of template ID to template definition */
148
153
  type TemplateMap = Record<string, TemplateDefinition>;
154
+ /** Options for `createSimpleResolver` */
155
+ interface SimpleResolverOptions {
156
+ /**
157
+ * HTML-escape interpolated values in the `html` field. Default `true`.
158
+ *
159
+ * Interpolated *values* are escaped (`&`, `<`, `>`, `"`, `'`, `` ` ``);
160
+ * the template skeleton is left untouched, so `<h1>Hi ${name}</h1>` keeps
161
+ * its tags while a malicious `${name}` like `<script>…` is neutralised.
162
+ * This is safe-by-default — most callers feed user-controlled data
163
+ * (names, order details) straight into an email `html` body.
164
+ *
165
+ * The `subject` and `text` fields are NEVER HTML-escaped (they are not
166
+ * HTML contexts — escaping would corrupt plain text into `&amp;` noise).
167
+ *
168
+ * Set `false` only when the `html` values are already trusted HTML
169
+ * fragments (e.g. pre-sanitised rich content you intentionally inline).
170
+ */
171
+ escape?: boolean;
172
+ }
149
173
  /**
150
174
  * Simple string interpolation resolver (zero dependencies).
151
175
  *
152
176
  * Replaces `${key}` patterns with values from the data object.
153
177
  * Supports nested access: `${user.name}`.
154
178
  *
179
+ * **Safe by default:** values interpolated into the `html` field are
180
+ * HTML-escaped to prevent injection/XSS from user-controlled data. Pass
181
+ * `{ escape: false }` to opt out for pre-trusted HTML. The `subject` and
182
+ * `text` fields are never escaped.
183
+ *
155
184
  * For advanced templating (loops, conditionals, partials),
156
185
  * plug in any engine via the `TemplateResolver` interface.
157
186
  */
158
- declare function createSimpleResolver(templates: TemplateMap): TemplateResolver;
187
+ declare function createSimpleResolver(templates: TemplateMap, options?: SimpleResolverOptions): TemplateResolver;
188
+ /** Options for `interpolateHtml` */
189
+ interface InterpolateOptions {
190
+ /**
191
+ * Escape HTML entities in substituted values.
192
+ * Default `true` — safe for HTML email bodies. Set `false` only
193
+ * when the template is plain text or values are already trusted HTML.
194
+ *
195
+ * Escapes: `&`, `<`, `>`, `"`, `'`, `` ` ``.
196
+ */
197
+ escape?: boolean;
198
+ /**
199
+ * Throw when a placeholder references a key that is absent from `vars`.
200
+ * Default `false` — missing keys are replaced with an empty string.
201
+ * Enable in CI / tests to catch typos in template definitions.
202
+ */
203
+ strict?: boolean;
204
+ }
205
+ /**
206
+ * Interpolate `{{key}}` / `{{ key }}` placeholders (Handlebars/Mustache style).
207
+ *
208
+ * Supports nested access: `{{ contact.email }}`.
209
+ * Values are HTML-escaped by default — safe to use with untrusted contact data.
210
+ * Use `escape: false` only for plain-text subjects or pre-sanitised HTML fragments.
211
+ *
212
+ * @example
213
+ * interpolateHtml('<p>Hi {{firstName}},</p>', { firstName: 'Alice' })
214
+ * // → '<p>Hi Alice,</p>'
215
+ *
216
+ * interpolateHtml('Hello {{ contact.email }}', { contact: { email: 'a@b.com' } })
217
+ * // → 'Hello a@b.com'
218
+ *
219
+ * // Strict mode: throws on missing keys (useful in tests)
220
+ * interpolateHtml('Hi {{name}}', {}, { strict: true })
221
+ * // → throws Error: Template variable "name" is not defined
222
+ *
223
+ * // Raw HTML values (opt out of escaping)
224
+ * interpolateHtml('<p>{{content}}</p>', { content: '<b>Bold</b>' }, { escape: false })
225
+ * // → '<p><b>Bold</b></p>'
226
+ */
227
+ declare function interpolateHtml(template: string, vars: Record<string, unknown>, options?: InterpolateOptions): string;
159
228
  //#endregion
160
229
  //#region src/utils/fallback.d.ts
161
230
  /** Service-like object that can send to specific channels */
@@ -265,4 +334,4 @@ interface StatusHandler {
265
334
  */
266
335
  declare function createStatusHandler(config?: StatusHandlerConfig): StatusHandler;
267
336
  //#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 };
337
+ 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,42 @@ 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?: {
112
+ /** Trigger a cleanup sweep after this many writes. Default: 100. */
92
113
  cleanupInterval?: number;
114
+ /**
115
+ * Run a time-based cleanup sweep every N ms. Default: 5 minutes.
116
+ * Set to 0 to disable the timer (useful in test environments with
117
+ * fake timers — drive cleanup via writes or call `cleanup()` manually).
118
+ */
119
+ cleanupIntervalMs?: number;
93
120
  });
94
121
  has(key: string): boolean;
95
122
  set(key: string, ttlMs: number): void;
96
- /** Number of entries (including possibly expired) */
123
+ /** Remove all expired entries. Safe to call at any time. */
124
+ cleanup(): void;
125
+ /** Number of entries (including possibly expired). */
97
126
  get size(): number;
98
- /** Remove all entries */
127
+ /** Remove all entries and stop the background timer. */
99
128
  clear(): void;
100
- private maybeCleanup;
129
+ /**
130
+ * Stop the background cleanup timer without clearing entries.
131
+ * Call in tests / shutdown hooks to avoid open-handle warnings.
132
+ */
133
+ destroy(): void;
101
134
  }
102
135
  /** Default TTL for idempotency keys (24 hours) */
103
136
  declare const IDEMPOTENCY_DEFAULT_TTL: number;
@@ -120,19 +153,31 @@ interface DeliveryLogEntry {
120
153
  /** Per-channel results */
121
154
  results: SendResult[];
122
155
  /** Overall status */
123
- status: 'delivered' | 'partial' | 'failed';
156
+ status: 'delivered' | 'partial' | 'failed' | 'skipped';
124
157
  /** Total duration in ms */
125
158
  duration: number;
126
159
  /** Original payload metadata */
127
160
  metadata?: Record<string, unknown>;
161
+ /**
162
+ * The business document this delivery was about (see
163
+ * `NotificationPayload.subject`). Carried verbatim so a store can index it —
164
+ * this is what makes "every message sent about invoice X" a keyed read.
165
+ */
166
+ subject?: NotificationSubject;
128
167
  }
129
168
  /** Query filter for delivery log entries */
130
169
  interface DeliveryLogQuery {
131
170
  recipientId?: string;
132
171
  recipientEmail?: string;
133
172
  event?: string;
173
+ /**
174
+ * Filter to one business document. A store MUST support this as an indexed
175
+ * read — a `metadata` scan would work at ten rows and time out at ten million,
176
+ * which is the version of "supported" that fails only in production.
177
+ */
178
+ subject?: NotificationSubject;
134
179
  channel?: string;
135
- status?: 'delivered' | 'partial' | 'failed';
180
+ status?: 'delivered' | 'partial' | 'failed' | 'skipped';
136
181
  /** Only entries after this date */
137
182
  after?: Date;
138
183
  /** Only entries before this date */
@@ -181,6 +226,8 @@ interface QueueJob {
181
226
  status: QueueJobStatus;
182
227
  attempts: number;
183
228
  maxAttempts: number;
229
+ retryDelay: number;
230
+ maxRetryDelay: number;
184
231
  createdAt: Date;
185
232
  updatedAt: Date;
186
233
  error?: string;
@@ -214,6 +261,17 @@ interface QueueEnqueueOptions {
214
261
  delay?: number;
215
262
  /** Max processing attempts (default: 3) */
216
263
  maxAttempts?: number;
264
+ /**
265
+ * Base delay in ms between retry attempts.
266
+ * Actual delay uses exponential backoff with ±25% jitter:
267
+ * attempt 1 → retryDelay * 2^0 = retryDelay
268
+ * attempt 2 → retryDelay * 2^1
269
+ * attempt 3 → retryDelay * 2^2
270
+ * Capped at `maxRetryDelay`. Default: 1000 (1 second).
271
+ */
272
+ retryDelay?: number;
273
+ /** Maximum backoff delay cap in ms. Default: 30000 (30 seconds). */
274
+ maxRetryDelay?: number;
217
275
  }
218
276
  /** Processor function called by the queue for each job */
219
277
  type QueueProcessor = (payload: NotificationPayload) => Promise<void>;
@@ -231,8 +289,12 @@ declare class MemoryQueue implements QueueAdapter {
231
289
  private readonly concurrency;
232
290
  private activeCount;
233
291
  private delayTimers;
292
+ private readonly defaultRetryDelay;
293
+ private readonly defaultMaxRetryDelay;
234
294
  constructor(options?: {
235
295
  concurrency?: number;
296
+ retryDelay?: number;
297
+ maxRetryDelay?: number;
236
298
  });
237
299
  enqueue(payload: NotificationPayload, options?: QueueEnqueueOptions): string;
238
300
  process(processor: QueueProcessor): void;
@@ -240,6 +302,17 @@ declare class MemoryQueue implements QueueAdapter {
240
302
  size(): number;
241
303
  pause(): void;
242
304
  resume(): void;
305
+ /**
306
+ * Drain the queue: cancel delayed timers and remove all not-yet-running
307
+ * jobs from the pipeline.
308
+ *
309
+ * Semantics note: drained jobs (both delayed-but-unfired and pending) are
310
+ * marked with status `'completed'`, NOT a distinct "drained"/"cancelled"
311
+ * state — `QueueJobStatus` has no such value. So `'completed'` here means
312
+ * "no longer in the queue", which is NOT the same as "delivered". Anything
313
+ * that treats `completed` as proof of delivery (dashboards, metrics) should
314
+ * read delivery success from the delivery log, not from queue job status.
315
+ */
243
316
  drain(): void;
244
317
  /** Get all jobs (for testing/debugging) */
245
318
  getAllJobs(): QueueJob[];
@@ -266,6 +339,20 @@ interface Recipient {
266
339
  metadata?: Record<string, unknown>;
267
340
  }
268
341
  /** Notification payload sent through the service */
342
+ /**
343
+ * A reference to the business document a notification concerns.
344
+ *
345
+ * Deliberately the same `{ sourceModel, sourceId }` shape as
346
+ * `@classytic/primitives`' `ExternalRef` — declared structurally here rather than
347
+ * imported, because this kernel takes no dependency on primitives. A host that
348
+ * uses `ExternalRef` can pass it straight through.
349
+ */
350
+ interface NotificationSubject {
351
+ /** Owning model name, stated by the owning package (e.g. 'Invoice'). */
352
+ sourceModel: string;
353
+ /** The document id. */
354
+ sourceId: string;
355
+ }
269
356
  interface NotificationPayload {
270
357
  /** Event name that triggered this notification */
271
358
  event: string;
@@ -279,6 +366,21 @@ interface NotificationPayload {
279
366
  channels?: string[];
280
367
  /** Arbitrary metadata (passed through to results) */
281
368
  metadata?: Record<string, unknown>;
369
+ /**
370
+ * The BUSINESS DOCUMENT this notification is about — `{ sourceModel, sourceId }`,
371
+ * the `ExternalRef` shape used across the platform for cross-collection refs.
372
+ *
373
+ * Distinct from `event` (what happened) and from `metadata` (a free-form bag):
374
+ * this is the correlation key that answers "show me every message we sent about
375
+ * invoice X". Without it that question is a collection scan over an unindexed
376
+ * `metadata` blob, so in practice nothing asks it — a document screen cannot
377
+ * show its own send history, and a support agent cannot answer "did the customer
378
+ * ever receive it?".
379
+ *
380
+ * Optional: a broadcast to a segment is about no single document, and a
381
+ * `subject` invented for it would be a lie.
382
+ */
383
+ subject?: NotificationSubject;
282
384
  /** Idempotency key — duplicate sends with the same key are skipped */
283
385
  idempotencyKey?: string;
284
386
  /** Delay delivery by this many milliseconds (requires queue adapter) */
@@ -290,6 +392,34 @@ interface SendResult {
290
392
  channel: string;
291
393
  duration?: number;
292
394
  error?: string;
395
+ /**
396
+ * When `false`, the service will NOT retry this result even if the global
397
+ * `retry.maxAttempts > 1`. Use for permanent failures: invalid recipient
398
+ * address, bad credentials, hard bounce, 4xx from provider.
399
+ *
400
+ * Unset / `true` means the failure is transient and should be retried.
401
+ */
402
+ retryable?: boolean;
403
+ /**
404
+ * The PROVIDER's id for the message it accepted — the correlation key.
405
+ *
406
+ * Delivery is asynchronous everywhere it matters: a gateway accepts a message and
407
+ * reports what happened to it later, over a webhook (WhatsApp `statuses[]`, an SES
408
+ * bounce, an SMS DLR). That callback identifies the message by the id it issued at
409
+ * send time, so without this the two halves cannot be joined — a receipt arrives
410
+ * naming a message nothing here can find, and `status: 'sent'` stays the last word
411
+ * on a message that was never delivered.
412
+ *
413
+ * FIRST-CLASS rather than another key in `metadata`: a correlation identifier that
414
+ * every asynchronous channel needs is a contract, and in an untyped bag each
415
+ * channel spells it differently (`messageId`, `id`, `sid`) until the consumer has
416
+ * to know which channel it is looking at.
417
+ *
418
+ * Optional because it is genuinely absent for synchronous channels (in-app feed) and
419
+ * for providers that acknowledge without issuing an id. Absent means "no correlation
420
+ * is possible", NOT "delivery unknown" — a consumer must not infer failure from it.
421
+ */
422
+ providerMessageId?: string;
293
423
  metadata?: Record<string, unknown>;
294
424
  }
295
425
  /** Result from dispatching to all channels */
@@ -319,6 +449,19 @@ interface ChannelConfig {
319
449
  /** Channel interface - implement this for custom channels */
320
450
  interface Channel {
321
451
  readonly name: string;
452
+ /**
453
+ * Optional per-channel rate limit, read by the service before sending.
454
+ * `BaseChannel` exposes this from `config.rateLimit`; custom channels that
455
+ * implement `Channel` directly should surface it here so the service
456
+ * applies the limit (otherwise the channel is treated as unlimited).
457
+ */
458
+ readonly rateLimit?: RateLimitConfig;
459
+ /**
460
+ * Optional per-channel retry override, read by the service. When unset the
461
+ * service's global retry config applies. `BaseChannel` exposes this from
462
+ * `config.retry`.
463
+ */
464
+ readonly retry?: RetryConfig;
322
465
  shouldHandle(event: string): boolean;
323
466
  send(payload: NotificationPayload): Promise<SendResult>;
324
467
  /**
@@ -364,6 +507,37 @@ interface EmailChannelConfig extends ChannelConfig {
364
507
  transporter?: NodemailerTransporter;
365
508
  /** Default mail options merged into every send */
366
509
  defaults?: Record<string, unknown>;
510
+ /**
511
+ * Allow a per-send `payload.data.from` to override the channel's `from`
512
+ * address. Default `false` (safe).
513
+ *
514
+ * The `data` bag is frequently populated from template output and
515
+ * upstream/user-controlled input, so honouring `data.from` unconditionally
516
+ * is a sender-spoofing footgun in multi-tenant systems. Keep this `false`
517
+ * unless you fully control `data.from` and genuinely need per-send senders
518
+ * (e.g. sending on behalf of verified sub-accounts).
519
+ */
520
+ allowSenderOverride?: boolean;
521
+ /**
522
+ * RFC 8058 `List-Unsubscribe` header injection.
523
+ *
524
+ * When set, every outbound email receives:
525
+ * `List-Unsubscribe: <https://…/unsubscribe>, <mailto:…>`
526
+ * `List-Unsubscribe-Post: List-Unsubscribe=One-Click`
527
+ *
528
+ * Gmail, Outlook and Yahoo surface the one-click unsubscribe button
529
+ * when these headers are present. Required by CAN-SPAM, CASL, and the
530
+ * 2024 Google/Yahoo bulk-sender requirements for marketing email.
531
+ *
532
+ * Per-send values (from `payload.data.listUnsubscribeUrl`) override this
533
+ * channel-level default, allowing subscriber-specific unsubscribe links.
534
+ */
535
+ listUnsubscribe?: {
536
+ /** HTTPS URL that handles the one-click POST (RFC 8058 §3.2) */
537
+ url?: string;
538
+ /** Mailto address for clients that don't support HTTP unsubscribe */
539
+ email?: string;
540
+ };
367
541
  }
368
542
  /** Minimal Nodemailer transporter interface (avoids hard dep) */
369
543
  interface NodemailerTransporter {
@@ -490,7 +664,9 @@ interface NotificationServiceConfig {
490
664
  logger?: Logger;
491
665
  /** Idempotency / deduplication config */
492
666
  idempotency?: {
493
- /** Store implementation (default: MemoryIdempotencyStore) */store?: IdempotencyStore; /** TTL in milliseconds (default: 86400000 = 24h) */
667
+ /** Store implementation (default: MemoryIdempotencyStore) */
668
+ store?: IdempotencyStore;
669
+ /** TTL in milliseconds (default: 86400000 = 24h) */
494
670
  ttl?: number;
495
671
  };
496
672
  /** Delivery log for audit trail — records every send attempt */
@@ -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-B5InMRIc.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-NDUgykHA.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-B4Sv8X_G.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.3.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.14",
114
+ "typescript": "^6.0.3",
115
+ "vitest": "^4.1.8"
116
116
  }
117
117
  }