@classytic/notifications 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,8 +387,33 @@ 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>;
405
+ /**
406
+ * Optional pre-flight check. Return a `SendResult` (typically with
407
+ * `status: 'skipped'`) to short-circuit before the service consumes a
408
+ * rate-limit token or starts the retry loop. Return `null` to proceed.
409
+ *
410
+ * Built-in channels use this to skip when the payload obviously can't
411
+ * be delivered (no `recipient.email` for `EmailChannel`, no
412
+ * `recipient.phone` for `SmsChannel`, etc.) so a mixed-channel batch
413
+ * doesn't burn the quota of one channel because another channel's
414
+ * recipient field is missing.
415
+ */
416
+ canSend?(payload: NotificationPayload): SendResult | null;
324
417
  }
325
418
  /** SMTP / Nodemailer transport options */
326
419
  interface SmtpTransportOptions {
@@ -352,6 +445,35 @@ interface EmailChannelConfig extends ChannelConfig {
352
445
  transporter?: NodemailerTransporter;
353
446
  /** Default mail options merged into every send */
354
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
+ };
355
477
  }
356
478
  /** Minimal Nodemailer transporter interface (avoids hard dep) */
357
479
  interface NodemailerTransporter {
@@ -487,6 +609,20 @@ interface NotificationServiceConfig {
487
609
  rateLimitStore?: RateLimitStore;
488
610
  /** Queue adapter for crash-resilient delivery. Service owns the queue. */
489
611
  queue?: QueueAdapter;
612
+ /**
613
+ * How the queue processor signals failure back to the queue adapter.
614
+ *
615
+ * - `'throw-on-total-failure'` (default) — the processor throws
616
+ * when a dispatch had `sent === 0 && failed > 0`, so the queue
617
+ * marks the job failed (and retries up to `maxAttempts`). Partial
618
+ * successes (some channels sent) resolve normally to avoid
619
+ * double-sending the channels that already succeeded.
620
+ * - `'always-complete'` — legacy behavior. The processor never
621
+ * throws; queued jobs always resolve as completed, regardless of
622
+ * channel outcome. Keep this if your delivery log is the source
623
+ * of truth for failures and you don't want queue-level retries.
624
+ */
625
+ queueFailureMode?: 'throw-on-total-failure' | 'always-complete';
490
626
  }
491
627
  /** Service lifecycle events */
492
628
  type ServiceEvent = 'before:send' | 'after:send' | 'send:success' | 'send:failed' | 'send:retry' | 'send:rate_limited' | 'send:queued';
@@ -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-D94B3VNX.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-BDaI1BMy.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.0.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,
@@ -16,11 +16,22 @@
16
16
  "types": "./dist/channels/index.d.mts",
17
17
  "default": "./dist/channels/index.mjs"
18
18
  },
19
+ "./providers": {
20
+ "types": "./dist/providers/index.d.mts",
21
+ "default": "./dist/providers/index.mjs"
22
+ },
19
23
  "./utils": {
20
24
  "types": "./dist/utils/index.d.mts",
21
25
  "default": "./dist/utils/index.mjs"
22
26
  }
23
27
  },
28
+ "typesVersions": {
29
+ "*": {
30
+ "channels": ["./dist/channels/index.d.mts"],
31
+ "providers": ["./dist/providers/index.d.mts"],
32
+ "utils": ["./dist/utils/index.d.mts"]
33
+ }
34
+ },
24
35
  "files": [
25
36
  "dist",
26
37
  "README.md",
@@ -54,6 +65,9 @@
54
65
  "Sadman Chowdhury (https://github.com/siam923)"
55
66
  ],
56
67
  "license": "MIT",
68
+ "publishConfig": {
69
+ "access": "public"
70
+ },
57
71
  "repository": {
58
72
  "type": "git",
59
73
  "url": "git+https://github.com/classytic/notifications.git"
@@ -79,22 +93,25 @@
79
93
  "test": "vitest run",
80
94
  "test:watch": "vitest",
81
95
  "test:coverage": "vitest run --coverage",
96
+ "test:live": "vitest run --config vitest.live.config.ts",
82
97
  "typecheck": "tsc --noEmit",
83
- "prepublishOnly": "npm run build && npm run typecheck",
98
+ "prepublishOnly": "npm run build && npm run typecheck && npm test",
99
+ "push": "classytic-push",
84
100
  "publish:dry": "npm publish --dry-run --access public",
85
101
  "publish:npm": "npm publish --access public",
86
- "release": "npm run build && npm run typecheck && npm publish --access public",
102
+ "release": "npm run build && npm run typecheck && npm test && npm publish --access public",
87
103
  "release:patch": "npm version patch && npm run release",
88
104
  "release:minor": "npm version minor && npm run release",
89
105
  "release:major": "npm version major && npm run release"
90
106
  },
91
107
  "devDependencies": {
108
+ "@classytic/dev-tools": "^0.2.0",
92
109
  "@types/node": "^22.0.0",
93
- "@types/nodemailer": "^6.4.17",
94
- "@vitest/coverage-v8": "3.2.4",
95
- "nodemailer": "^6.10.1",
96
- "tsdown": "0.21.4",
97
- "typescript": "^5.7.0",
98
- "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"
99
116
  }
100
117
  }