@classytic/notifications 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,582 @@
1
+ //#region src/utils/emitter.ts
2
+ var Emitter = class {
3
+ handlers = /* @__PURE__ */ new Map();
4
+ /** Register an event handler */
5
+ on(event, handler) {
6
+ const list = this.handlers.get(event) ?? [];
7
+ list.push(handler);
8
+ this.handlers.set(event, list);
9
+ return this;
10
+ }
11
+ /** Remove an event handler */
12
+ off(event, handler) {
13
+ const list = this.handlers.get(event);
14
+ if (list) this.handlers.set(event, list.filter((h) => h !== handler));
15
+ return this;
16
+ }
17
+ /** Emit an event (runs handlers sequentially, awaits async) */
18
+ async emit(event, ...args) {
19
+ const list = this.handlers.get(event);
20
+ if (!list) return;
21
+ for (const handler of list) await handler(...args);
22
+ }
23
+ /** Remove all handlers for an event (or all events) */
24
+ removeAll(event) {
25
+ if (event) this.handlers.delete(event);
26
+ else this.handlers.clear();
27
+ return this;
28
+ }
29
+ };
30
+
31
+ //#endregion
32
+ //#region src/utils/retry.ts
33
+ /** Resolve retry config with defaults */
34
+ function resolveRetryConfig(config) {
35
+ return {
36
+ maxAttempts: config?.maxAttempts ?? 1,
37
+ backoff: config?.backoff ?? "exponential",
38
+ initialDelay: config?.initialDelay ?? 500,
39
+ maxDelay: config?.maxDelay ?? 3e4
40
+ };
41
+ }
42
+ /** Calculate delay for a given attempt */
43
+ function calculateDelay(attempt, config) {
44
+ let delay;
45
+ switch (config.backoff) {
46
+ case "exponential":
47
+ delay = config.initialDelay * Math.pow(2, attempt - 1);
48
+ break;
49
+ case "linear":
50
+ delay = config.initialDelay * attempt;
51
+ break;
52
+ default: delay = config.initialDelay;
53
+ }
54
+ const jitter = delay * .25 * (Math.random() * 2 - 1);
55
+ delay = Math.min(delay + jitter, config.maxDelay);
56
+ return Math.max(0, Math.round(delay));
57
+ }
58
+ /** Sleep for a given duration */
59
+ function sleep(ms) {
60
+ return new Promise((resolve) => setTimeout(resolve, ms));
61
+ }
62
+ /**
63
+ * Execute a function with retry and backoff
64
+ *
65
+ * @param fn - Async function to retry
66
+ * @param config - Retry configuration
67
+ * @param onRetry - Called before each retry attempt
68
+ * @returns Result of fn
69
+ * @throws Last error after all attempts exhausted
70
+ */
71
+ async function withRetry(fn, config, onRetry) {
72
+ let lastError;
73
+ for (let attempt = 1; attempt <= config.maxAttempts; attempt++) try {
74
+ return await fn();
75
+ } catch (err) {
76
+ lastError = err instanceof Error ? err : new Error(String(err));
77
+ if (attempt === config.maxAttempts) break;
78
+ const delay = calculateDelay(attempt, config);
79
+ onRetry?.(attempt, lastError);
80
+ await sleep(delay);
81
+ }
82
+ throw lastError;
83
+ }
84
+
85
+ //#endregion
86
+ //#region src/utils/quiet-hours.ts
87
+ /**
88
+ * Check if the current time falls within quiet hours.
89
+ *
90
+ * Supports overnight ranges (e.g. 22:00 - 07:00).
91
+ * Returns false if start/end are missing or malformed.
92
+ *
93
+ * @param quiet - Quiet hours config with start, end, and optional timezone
94
+ * @param now - Current date (defaults to new Date(), injectable for testing)
95
+ */
96
+ function isQuietHours(quiet, now = /* @__PURE__ */ new Date()) {
97
+ if (!quiet.start || !quiet.end) return false;
98
+ const startMinutes = parseTimeToMinutes(quiet.start);
99
+ const endMinutes = parseTimeToMinutes(quiet.end);
100
+ if (startMinutes === -1 || endMinutes === -1) return false;
101
+ const currentMinutes = getCurrentMinutes(now, quiet.timezone);
102
+ if (startMinutes <= endMinutes) return currentMinutes >= startMinutes && currentMinutes < endMinutes;
103
+ return currentMinutes >= startMinutes || currentMinutes < endMinutes;
104
+ }
105
+ /** Parse "HH:MM" to minutes since midnight. Returns -1 on invalid input. */
106
+ function parseTimeToMinutes(time) {
107
+ const match = time.match(/^(\d{1,2}):(\d{2})$/);
108
+ if (!match) return -1;
109
+ const hours = parseInt(match[1], 10);
110
+ const minutes = parseInt(match[2], 10);
111
+ if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return -1;
112
+ return hours * 60 + minutes;
113
+ }
114
+ /** Get current minutes-since-midnight in the given timezone (or UTC). */
115
+ function getCurrentMinutes(now, timezone) {
116
+ if (!timezone) return now.getUTCHours() * 60 + now.getUTCMinutes();
117
+ const parts = new Intl.DateTimeFormat("en-US", {
118
+ timeZone: timezone,
119
+ hour: "numeric",
120
+ minute: "numeric",
121
+ hour12: false
122
+ }).formatToParts(now);
123
+ const hour = parseInt(parts.find((p) => p.type === "hour")?.value ?? "0", 10);
124
+ const minute = parseInt(parts.find((p) => p.type === "minute")?.value ?? "0", 10);
125
+ return hour * 60 + minute;
126
+ }
127
+
128
+ //#endregion
129
+ //#region src/utils/idempotency.ts
130
+ /**
131
+ * Idempotency / deduplication utilities
132
+ * @module @classytic/notifications/utils
133
+ *
134
+ * Prevents duplicate notification delivery using idempotency keys.
135
+ * Ships with an in-memory store; implement IdempotencyStore for
136
+ * Redis, database, or other distributed backends.
137
+ */
138
+ /** Default TTL: 24 hours */
139
+ const DEFAULT_TTL = 1440 * 60 * 1e3;
140
+ /**
141
+ * In-memory idempotency store with TTL-based expiry.
142
+ *
143
+ * Suitable for single-process apps. For distributed systems,
144
+ * implement `IdempotencyStore` with Redis or your database.
145
+ *
146
+ * Expired entries are lazily cleaned up every `cleanupInterval` writes.
147
+ */
148
+ var MemoryIdempotencyStore = class {
149
+ store = /* @__PURE__ */ new Map();
150
+ cleanupCounter = 0;
151
+ cleanupInterval;
152
+ constructor(options) {
153
+ this.cleanupInterval = options?.cleanupInterval ?? 100;
154
+ }
155
+ has(key) {
156
+ const expiry = this.store.get(key);
157
+ if (expiry === void 0) return false;
158
+ if (Date.now() > expiry) {
159
+ this.store.delete(key);
160
+ return false;
161
+ }
162
+ return true;
163
+ }
164
+ set(key, ttlMs) {
165
+ this.store.set(key, Date.now() + ttlMs);
166
+ this.maybeCleanup();
167
+ }
168
+ /** Number of entries (including possibly expired) */
169
+ get size() {
170
+ return this.store.size;
171
+ }
172
+ /** Remove all entries */
173
+ clear() {
174
+ this.store.clear();
175
+ }
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);
181
+ }
182
+ };
183
+ /** Default TTL for idempotency keys (24 hours) */
184
+ const IDEMPOTENCY_DEFAULT_TTL = DEFAULT_TTL;
185
+
186
+ //#endregion
187
+ //#region src/utils/rate-limiter.ts
188
+ /**
189
+ * In-memory sliding window rate limiter.
190
+ *
191
+ * Tracks timestamps of recent sends per channel and checks
192
+ * against the configured window. Suitable for single-process apps.
193
+ * For distributed systems, implement `RateLimitStore` with Redis.
194
+ */
195
+ var MemoryRateLimitStore = class {
196
+ windows = /* @__PURE__ */ new Map();
197
+ consume(channelName, config) {
198
+ const now = Date.now();
199
+ const timestamps = this.getActive(channelName, now, config.windowMs);
200
+ if (timestamps.length >= config.maxPerWindow) return false;
201
+ timestamps.push(now);
202
+ this.windows.set(channelName, timestamps);
203
+ return true;
204
+ }
205
+ remaining(channelName, config) {
206
+ const now = Date.now();
207
+ const timestamps = this.getActive(channelName, now, config.windowMs);
208
+ return Math.max(0, config.maxPerWindow - timestamps.length);
209
+ }
210
+ reset(channelName) {
211
+ this.windows.delete(channelName);
212
+ }
213
+ /** Get only the timestamps that fall within the current window */
214
+ getActive(channelName, now, windowMs) {
215
+ const cutoff = now - windowMs;
216
+ const active = (this.windows.get(channelName) ?? []).filter((t) => t > cutoff);
217
+ this.windows.set(channelName, active);
218
+ return active;
219
+ }
220
+ };
221
+
222
+ //#endregion
223
+ //#region src/utils/concurrency.ts
224
+ /**
225
+ * Map over items with controlled concurrency.
226
+ *
227
+ * Like `Promise.all(items.map(fn))` but with a max number of
228
+ * parallel operations. Results are returned in input order.
229
+ *
230
+ * Uses a worker-pool pattern: N workers pull from a shared index,
231
+ * so the pipeline stays full even when some items are slower.
232
+ *
233
+ * @param items - Array of items to process
234
+ * @param fn - Async function to apply to each item
235
+ * @param options - Concurrency options
236
+ * @returns Array of results in the same order as input
237
+ */
238
+ async function pMap(items, fn, options = {}) {
239
+ const { concurrency = 10 } = options;
240
+ if (!Number.isInteger(concurrency) || concurrency < 1) throw new RangeError(`pMap: concurrency must be a positive integer, got ${concurrency}`);
241
+ if (items.length === 0) return [];
242
+ const results = new Array(items.length);
243
+ let nextIndex = 0;
244
+ async function worker() {
245
+ while (nextIndex < items.length) {
246
+ const i = nextIndex++;
247
+ results[i] = await fn(items[i], i);
248
+ }
249
+ }
250
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, () => worker()));
251
+ return results;
252
+ }
253
+
254
+ //#endregion
255
+ //#region src/utils/merge-hooks.ts
256
+ function mergeHooks(...hookConfigs) {
257
+ const merged = {};
258
+ for (const config of hookConfigs) {
259
+ if (!config || typeof config !== "object") continue;
260
+ for (const [event, handlers] of Object.entries(config)) {
261
+ if (!merged[event]) merged[event] = [];
262
+ const handlerArray = Array.isArray(handlers) ? handlers : [handlers];
263
+ merged[event].push(...handlerArray);
264
+ }
265
+ }
266
+ return merged;
267
+ }
268
+
269
+ //#endregion
270
+ //#region src/utils/delivery-log.ts
271
+ /** Generate a simple unique ID */
272
+ function generateId$1() {
273
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
274
+ }
275
+ /**
276
+ * In-memory delivery log with query support.
277
+ *
278
+ * Keeps entries in memory with optional max size (evicts oldest).
279
+ * For production, implement `DeliveryLog` with your database.
280
+ */
281
+ var MemoryDeliveryLog = class {
282
+ entries = [];
283
+ maxEntries;
284
+ constructor(options) {
285
+ this.maxEntries = options?.maxEntries ?? 1e4;
286
+ }
287
+ record(payload, dispatch) {
288
+ const entry = {
289
+ id: generateId$1(),
290
+ timestamp: /* @__PURE__ */ new Date(),
291
+ event: dispatch.event,
292
+ recipientId: payload.recipient.id,
293
+ recipientEmail: payload.recipient.email,
294
+ channels: dispatch.results.map((r) => r.channel),
295
+ results: dispatch.results,
296
+ status: this.resolveStatus(dispatch),
297
+ duration: dispatch.duration,
298
+ metadata: payload.metadata
299
+ };
300
+ this.entries.push(entry);
301
+ if (this.entries.length > this.maxEntries) this.entries = this.entries.slice(-this.maxEntries);
302
+ }
303
+ query(filter) {
304
+ const limit = filter.limit ?? 100;
305
+ let results = this.entries;
306
+ if (filter.recipientId) results = results.filter((e) => e.recipientId === filter.recipientId);
307
+ if (filter.recipientEmail) results = results.filter((e) => e.recipientEmail === filter.recipientEmail);
308
+ if (filter.event) results = results.filter((e) => e.event === filter.event);
309
+ if (filter.channel) results = results.filter((e) => e.channels.includes(filter.channel));
310
+ if (filter.status) results = results.filter((e) => e.status === filter.status);
311
+ if (filter.after) {
312
+ const after = filter.after.getTime();
313
+ results = results.filter((e) => e.timestamp.getTime() >= after);
314
+ }
315
+ if (filter.before) {
316
+ const before = filter.before.getTime();
317
+ results = results.filter((e) => e.timestamp.getTime() <= before);
318
+ }
319
+ return results.slice(-limit).reverse();
320
+ }
321
+ get(id) {
322
+ return this.entries.find((e) => e.id === id) ?? null;
323
+ }
324
+ /** Get total number of entries */
325
+ get size() {
326
+ return this.entries.length;
327
+ }
328
+ /** Clear all entries */
329
+ clear() {
330
+ this.entries = [];
331
+ }
332
+ resolveStatus(dispatch) {
333
+ if (dispatch.sent > 0 && dispatch.failed === 0) return "delivered";
334
+ if (dispatch.sent > 0 && dispatch.failed > 0) return "partial";
335
+ return "failed";
336
+ }
337
+ };
338
+
339
+ //#endregion
340
+ //#region src/utils/queue.ts
341
+ /** Generate a simple unique ID */
342
+ function generateId() {
343
+ return `q-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
344
+ }
345
+ /**
346
+ * In-memory queue for development and testing.
347
+ *
348
+ * Jobs are processed immediately in FIFO order with concurrency control.
349
+ * **Not crash-resilient** — use BullMQ or a database-backed adapter for production.
350
+ */
351
+ var MemoryQueue = class {
352
+ jobs = /* @__PURE__ */ new Map();
353
+ pending = [];
354
+ processor = null;
355
+ paused = false;
356
+ concurrency;
357
+ activeCount = 0;
358
+ delayTimers = /* @__PURE__ */ new Map();
359
+ constructor(options) {
360
+ this.concurrency = options?.concurrency ?? 5;
361
+ }
362
+ enqueue(payload, options) {
363
+ const id = generateId();
364
+ const job = {
365
+ id,
366
+ payload,
367
+ status: "pending",
368
+ attempts: 0,
369
+ maxAttempts: options?.maxAttempts ?? 3,
370
+ createdAt: /* @__PURE__ */ new Date(),
371
+ updatedAt: /* @__PURE__ */ new Date()
372
+ };
373
+ this.jobs.set(id, job);
374
+ if (options?.delay) {
375
+ const timer = setTimeout(() => {
376
+ this.delayTimers.delete(id);
377
+ this.pending.push(id);
378
+ this.drain_queue();
379
+ }, options.delay);
380
+ this.delayTimers.set(id, timer);
381
+ } else {
382
+ this.pending.push(id);
383
+ this.drain_queue();
384
+ }
385
+ return id;
386
+ }
387
+ process(processor) {
388
+ this.processor = processor;
389
+ this.drain_queue();
390
+ }
391
+ getJob(id) {
392
+ return this.jobs.get(id) ?? null;
393
+ }
394
+ size() {
395
+ let count = 0;
396
+ for (const job of this.jobs.values()) if (job.status === "pending" || job.status === "processing") count++;
397
+ return count;
398
+ }
399
+ pause() {
400
+ this.paused = true;
401
+ }
402
+ resume() {
403
+ this.paused = false;
404
+ this.drain_queue();
405
+ }
406
+ drain() {
407
+ for (const timer of this.delayTimers.values()) clearTimeout(timer);
408
+ for (const [id] of this.delayTimers) {
409
+ const job = this.jobs.get(id);
410
+ if (job && job.status === "pending") {
411
+ job.status = "completed";
412
+ job.updatedAt = /* @__PURE__ */ new Date();
413
+ }
414
+ }
415
+ this.delayTimers.clear();
416
+ for (const id of this.pending) {
417
+ const job = this.jobs.get(id);
418
+ if (job) {
419
+ job.status = "completed";
420
+ job.updatedAt = /* @__PURE__ */ new Date();
421
+ }
422
+ }
423
+ this.pending = [];
424
+ }
425
+ /** Get all jobs (for testing/debugging) */
426
+ getAllJobs() {
427
+ return Array.from(this.jobs.values());
428
+ }
429
+ /** Clear all jobs and cancel all timers */
430
+ clear() {
431
+ for (const timer of this.delayTimers.values()) clearTimeout(timer);
432
+ this.delayTimers.clear();
433
+ this.jobs.clear();
434
+ this.pending = [];
435
+ }
436
+ drain_queue() {
437
+ if (this.paused || !this.processor || this.pending.length === 0) return;
438
+ while (this.activeCount < this.concurrency && this.pending.length > 0) {
439
+ const jobId = this.pending.shift();
440
+ if (!jobId) break;
441
+ const job = this.jobs.get(jobId);
442
+ if (!job || job.status !== "pending") continue;
443
+ this.activeCount++;
444
+ job.status = "processing";
445
+ job.attempts++;
446
+ job.updatedAt = /* @__PURE__ */ new Date();
447
+ this.processor(job.payload).then(() => {
448
+ job.status = "completed";
449
+ job.updatedAt = /* @__PURE__ */ new Date();
450
+ }).catch((err) => {
451
+ const message = err instanceof Error ? err.message : String(err);
452
+ if (job.attempts < job.maxAttempts) {
453
+ 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
+ }
462
+ }).finally(() => {
463
+ this.activeCount--;
464
+ this.drain_queue();
465
+ });
466
+ }
467
+ }
468
+ };
469
+
470
+ //#endregion
471
+ //#region src/utils/template-engine.ts
472
+ /**
473
+ * Simple string interpolation resolver (zero dependencies).
474
+ *
475
+ * Replaces `${key}` patterns with values from the data object.
476
+ * Supports nested access: `${user.name}`.
477
+ *
478
+ * For advanced templating (loops, conditionals, partials),
479
+ * plug in any engine via the `TemplateResolver` interface.
480
+ */
481
+ function createSimpleResolver(templates) {
482
+ return (templateId, data) => {
483
+ const template = templates[templateId];
484
+ if (!template) throw new Error(`Template "${templateId}" not found`);
485
+ const result = {};
486
+ for (const [field, value] of Object.entries(template)) if (typeof value === "string") result[field] = interpolate(value, data);
487
+ return result;
488
+ };
489
+ }
490
+ /** Resolve nested property access like "user.name" */
491
+ function getNestedValue(obj, path) {
492
+ return path.split(".").reduce((current, key) => {
493
+ if (current != null && typeof current === "object") return current[key];
494
+ }, obj);
495
+ }
496
+ /** Replace ${key} patterns with values from data */
497
+ function interpolate(template, data) {
498
+ return template.replace(/\$\{([^}]+)\}/g, (_, key) => {
499
+ const value = getNestedValue(data, key.trim());
500
+ return value != null ? String(value) : "";
501
+ });
502
+ }
503
+
504
+ //#endregion
505
+ //#region src/utils/fallback.ts
506
+ /**
507
+ * A dispatch was accepted — either sent directly or enqueued.
508
+ *
509
+ * Direct mode: `sent > 0` means at least one channel delivered.
510
+ * Queue mode: `queued === true` means the job was accepted by the queue.
511
+ */
512
+ function wasAccepted(result) {
513
+ return result.sent > 0 || result.queued === true;
514
+ }
515
+ /**
516
+ * Try channels in priority order, stopping at the first successful delivery.
517
+ *
518
+ * Sends to one channel at a time. If it fails or is skipped (rate limited,
519
+ * no recipient field, etc.), tries the next channel in the list.
520
+ * Returns the result from the first channel that succeeds, or the
521
+ * last channel's result if all fail.
522
+ *
523
+ * Works with both direct and queued delivery modes.
524
+ *
525
+ * @param service - NotificationService instance
526
+ * @param payload - Notification payload (channels field is overridden per attempt)
527
+ * @param channelOrder - Channel names in priority order (e.g., ['push', 'sms', 'email'])
528
+ * @param options - Fallback behavior options
529
+ * @returns DispatchResult from the first accepted channel, or last failure
530
+ */
531
+ async function withFallback(service, payload, channelOrder, options) {
532
+ if (channelOrder.length === 0) return {
533
+ event: payload.event,
534
+ results: [],
535
+ sent: 0,
536
+ failed: 0,
537
+ skipped: 0,
538
+ duration: 0
539
+ };
540
+ let lastResult;
541
+ for (let i = 0; i < channelOrder.length; i++) {
542
+ const channelName = channelOrder[i];
543
+ const result = await service.send({
544
+ ...payload,
545
+ channels: [channelName]
546
+ });
547
+ if (wasAccepted(result)) return result;
548
+ lastResult = result;
549
+ if (i < channelOrder.length - 1 && options?.onFallback) {
550
+ const error = result.results[0]?.error ?? "No successful delivery";
551
+ options.onFallback(channelName, error, channelOrder[i + 1]);
552
+ }
553
+ }
554
+ return lastResult;
555
+ }
556
+
557
+ //#endregion
558
+ //#region src/utils/status-webhook.ts
559
+ /**
560
+ * Create a status webhook handler.
561
+ *
562
+ * Collects delivery status updates from provider webhooks.
563
+ * You normalize the provider's payload into a `StatusUpdate` and call `handle()`.
564
+ */
565
+ function createStatusHandler(config = {}) {
566
+ const updates = [];
567
+ return {
568
+ async handle(update) {
569
+ updates.push(update);
570
+ if (config.onStatusChange) await config.onStatusChange(update);
571
+ },
572
+ getUpdates() {
573
+ return [...updates];
574
+ },
575
+ getUpdatesFor(notificationId) {
576
+ return updates.filter((u) => u.notificationId === notificationId);
577
+ }
578
+ };
579
+ }
580
+
581
+ //#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 };