@classytic/notifications 2.2.0 → 2.4.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,62 @@
2
2
 
3
3
  All notable changes to `@classytic/notifications` will be documented in this file.
4
4
 
5
+ ## [2.4.0] - 2026-08-17
6
+
7
+ ### Fixed — `providerMessageId` now works the way 2.3.0 claimed
8
+
9
+ 2.3.0 introduced `SendResult.providerMessageId` as the cross-channel correlation
10
+ key but populated it on **email only**, so the property it exists to provide did not
11
+ hold: a consumer reading `providerMessageId` got a value for email and `undefined`
12
+ for push and sms, and still had to know which channel produced the result before it
13
+ could find the id in the untyped `metadata` bag. A half-migrated contract is worse
14
+ than none — it reads as available and silently isn't.
15
+
16
+ - **`PushChannel` sets `providerMessageId`** (from the provider's `messageId`).
17
+ - **`SmsChannel` sets `providerMessageId`** (from the provider's `sid`). This is the
18
+ case that motivates the field: three vendors, three spellings (`messageId`, `id`,
19
+ `sid`), one concept.
20
+ - `WebhookChannel` and `ConsoleChannel` deliberately leave it **unset** — a 2xx from
21
+ an HTTP POST is not a message identifier, and synthesising one would make an
22
+ unjoinable send look joinable. Absent means "no correlation is possible", never
23
+ "delivery unknown".
24
+
25
+ ### Fixed — restores `metadata.messageId` on `EmailChannel`
26
+
27
+ 2.3.0 deleted it in the same MINOR that added `providerMessageId`, so anyone reading
28
+ `metadata.messageId` lost it on a range-satisfying `^2.2.0` upgrade with nothing to
29
+ signal the change. The removal was right in direction and wrong in timing. It is
30
+ back for a deprecation window.
31
+
32
+ **All three id-bearing channels now mirror their provider id under both names** —
33
+ `providerMessageId` (read this) and the legacy `metadata` key (`messageId` for
34
+ email/push, `sid` for sms). **3.0.0 removes the legacy keys from every channel at
35
+ once**, as one deliberate break rather than three accidental ones.
36
+
37
+ Pinned by `tests/channels.test.ts` → `providerMessageId across channels`, including
38
+ a case that asserts a consumer can read the id **without branching on channel** —
39
+ the actual contract, so a channel regressing to metadata-only fails there.
40
+
41
+ ## [2.3.0] - 2026-08-16
42
+
43
+ Recorded retroactively; this release shipped without a changelog entry.
44
+
45
+ ### Added
46
+
47
+ - **`SendResult.providerMessageId`** — the typed cross-channel correlation key, so a
48
+ delivery receipt (SES bounce, SMS DLR, push feedback) can be joined back to the
49
+ send that produced it.
50
+ - **`SendResult.subject`** + `NotificationSubject` (`{ sourceModel, sourceId }`) —
51
+ the business document a notification concerns, so "show me every message we sent
52
+ about invoice X" stops being a scan over an unindexed `metadata` blob.
53
+
54
+ ### Changed — BREAKING, shipped as a minor
55
+
56
+ - `EmailChannel` stopped emitting `metadata.messageId`. Readers of that key broke on
57
+ upgrade with no signal. **Restored in 2.4.0**; upgrade straight to 2.4.0.
58
+ - Only `EmailChannel` populated `providerMessageId`; push and sms did not. **Fixed
59
+ in 2.4.0.**
60
+
5
61
  ## [2.2.0] - 2026-06-03
6
62
 
7
63
  - `SendResult.retryable?: boolean` — when `false`, service short-circuits `withRetry` immediately (permanent failures: bad credentials, invalid address, hard bounce, 4xx)
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-CeUVeVfB.mjs";
1
+ import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-1tNMyaXl.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-DI6BNBZ4.mjs";
1
+ import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-BkgxUc82.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-QIV0Th2F.mjs";
2
- import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-CeUVeVfB.mjs";
3
- import { C as resolveRetryConfig, S as calculateDelay, T as mergeHooks, _ as isQuietHours, a as createStatusHandler, b as ProviderNotInstalledError, c as InterpolateOptions, d as TemplateMap, f as createSimpleResolver, g as QuietHoursConfig, h as pMap, i as StatusUpdate, l as SimpleResolverOptions, m as PMapOptions, n as StatusHandler, o as FallbackOptions, p as interpolateHtml, r as StatusHandlerConfig, s as withFallback, t as DeliveryStatus, u as TemplateDefinition, v as ChannelError, w as withRetry, x as Emitter, y as NotificationError } from "./status-webhook-DxCdp0c_.mjs";
4
-
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-DkFudalo.mjs";
2
+ import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-1tNMyaXl.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-CuCdFeVN.mjs";
5
4
  //#region src/NotificationService.d.ts
6
5
  declare class NotificationService {
7
6
  private channels;
@@ -133,58 +132,5 @@ declare class NotificationService {
133
132
  /** Remove an event listener */
134
133
  off(event: ServiceEvent, handler: EventHandler): this;
135
134
  }
136
- //#endregion
137
- //#region src/index.d.ts
138
- /**
139
- * @classytic/notifications
140
- * Multi-Channel Notification System
141
- *
142
- * Pluggable channels, templates, retry, and preferences.
143
- * Zero required dependencies - bring your own providers.
144
- *
145
- * v2: Rate limiting, delivery tracking, queue adapter,
146
- * BCC batching, template engines, SMS & push channels.
147
- *
148
- * @module @classytic/notifications
149
- * @author Classytic (https://github.com/classytic)
150
- * @license MIT
151
- *
152
- * @example
153
- * ```typescript
154
- * import { NotificationService } from '@classytic/notifications';
155
- * import { EmailChannel, SmsChannel, PushChannel } from '@classytic/notifications/channels';
156
- * import { MemoryDeliveryLog, createSimpleResolver } from '@classytic/notifications/utils';
157
- *
158
- * const notifications = new NotificationService({
159
- * channels: [
160
- * new EmailChannel({
161
- * from: 'App <noreply@app.com>',
162
- * transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
163
- * rateLimit: { maxPerWindow: 500, windowMs: 86_400_000 }, // Gmail 500/day
164
- * }),
165
- * new SmsChannel({
166
- * from: '+15551234567',
167
- * provider: { send: async ({ to, from, body }) => ({ sid: 'custom' }) },
168
- * }),
169
- * new PushChannel({
170
- * provider: { send: async ({ token, title, body }) => ({ messageId: 'custom' }) },
171
- * }),
172
- * ],
173
- * templates: createSimpleResolver({
174
- * welcome: { subject: 'Welcome ${name}!', html: '<p>Hi ${name}</p>' },
175
- * }),
176
- * retry: { maxAttempts: 3, backoff: 'exponential' },
177
- * deliveryLog: new MemoryDeliveryLog(),
178
- * });
179
- *
180
- * await notifications.send({
181
- * event: 'user.created',
182
- * recipient: { email: 'user@example.com', phone: '+15559876543', name: 'John' },
183
- * data: { name: 'John' },
184
- * template: 'welcome',
185
- * });
186
- * ```
187
- */
188
-
189
135
  //#endregion
190
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 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";
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
2
  import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "./errors-BxRjct-E.mjs";
3
- import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-DI6BNBZ4.mjs";
3
+ import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-BkgxUc82.mjs";
4
4
 
5
5
  //#region src/NotificationService.ts
6
6
  /**
@@ -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,5 +1,4 @@
1
- import { C as RetryConfig, E as SmsChannelConfig, K as RateLimitConfig, a as ChannelConfig, c as EmailChannelConfig, h as NotificationPayload, i as Channel, j as WebhookChannelConfig, w as SendResult, y as PushChannelConfig } from "./types-QIV0Th2F.mjs";
2
-
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-DkFudalo.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;
@@ -99,7 +99,7 @@ var EmailChannel = class EmailChannel extends BaseChannel {
99
99
  }
100
100
  }
101
101
  /** Fields that defaults must never override */
102
- static PROTECTED_FIELDS = new Set([
102
+ static PROTECTED_FIELDS = /* @__PURE__ */ new Set([
103
103
  "to",
104
104
  "from",
105
105
  "subject",
@@ -166,6 +166,26 @@ var EmailChannel = class EmailChannel extends BaseChannel {
166
166
  return {
167
167
  status: "sent",
168
168
  channel: this.name,
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,
179
+ /**
180
+ * RESTORED in 2.4.0. 2.3.0 introduced `providerMessageId` and deleted this
181
+ * in the same MINOR, so a consumer reading `metadata.messageId` lost it on
182
+ * a range-satisfying upgrade with nothing to tell them — the removal was
183
+ * correct in direction and wrong in timing. It is back for the deprecation
184
+ * window, so all three id-bearing channels behave identically, and 3.0.0
185
+ * removes it from every channel at once as one deliberate break.
186
+ *
187
+ * @deprecated read `providerMessageId`; removed in 3.0.0
188
+ */
169
189
  metadata: { messageId: result.messageId }
170
190
  };
171
191
  } catch (err) {
@@ -404,6 +424,23 @@ var SmsChannel = class extends BaseChannel {
404
424
  return {
405
425
  status: "sent",
406
426
  channel: this.name,
427
+ /**
428
+ * The TYPED correlation key. SMS is the case that makes the argument:
429
+ * the provider calls it `sid`, email calls it `messageId`, push calls
430
+ * it `messageId` — three spellings for one concept, so a delivery
431
+ * receipt (a DLR) could only be joined back to its send by code that
432
+ * already knew which channel had produced the result. That is the
433
+ * exact coupling `SendResult.providerMessageId` removes.
434
+ */
435
+ providerMessageId: result.sid,
436
+ /**
437
+ * Kept for one release alongside the typed field. Dropping it here
438
+ * would be a silent removal in a MINOR — exactly what 2.3.0 did to
439
+ * email's `metadata.messageId`, breaking readers with no signal.
440
+ * Removed in 3.0.0, from every channel at once.
441
+ *
442
+ * @deprecated read `providerMessageId`; removed in 3.0.0
443
+ */
407
444
  metadata: { sid: result.sid }
408
445
  };
409
446
  } catch (err) {
@@ -528,6 +565,22 @@ var PushChannel = class extends BaseChannel {
528
565
  return {
529
566
  status: "sent",
530
567
  channel: this.name,
568
+ /**
569
+ * The TYPED correlation key — same contract email publishes. A push
570
+ * receipt (FCM/APNs feedback, an Expo receipt lookup) arrives naming
571
+ * this id, and until it was here a consumer had to know the result
572
+ * came from THIS channel before it could find it under the untyped
573
+ * key `metadata.messageId`.
574
+ */
575
+ providerMessageId: result.messageId,
576
+ /**
577
+ * Kept for one release alongside the typed field. Dropping it here
578
+ * would be a silent removal in a MINOR — exactly what 2.3.0 did to
579
+ * email's `metadata.messageId`, breaking readers with no signal.
580
+ * Removed in 3.0.0, from every channel at once.
581
+ *
582
+ * @deprecated read `providerMessageId`; removed in 3.0.0
583
+ */
531
584
  metadata: { messageId: result.messageId }
532
585
  };
533
586
  } catch (err) {
@@ -153,7 +153,7 @@ function getCurrentMinutes(now, timezone) {
153
153
  * advisory locks, etc.). The interface is intentionally async to allow this.
154
154
  */
155
155
  /** Default TTL: 24 hours */
156
- const DEFAULT_TTL = 1440 * 60 * 1e3;
156
+ const DEFAULT_TTL = 864e5;
157
157
  /**
158
158
  * In-memory idempotency store with TTL-based expiry.
159
159
  *
@@ -175,7 +175,7 @@ var MemoryIdempotencyStore = class {
175
175
  timer;
176
176
  constructor(options) {
177
177
  this.writeCleanupThreshold = options?.cleanupInterval ?? 100;
178
- const intervalMs = options?.cleanupIntervalMs ?? 300 * 1e3;
178
+ const intervalMs = options?.cleanupIntervalMs ?? 3e5;
179
179
  this.timer = intervalMs > 0 ? setInterval(() => this.cleanup(), intervalMs).unref?.() ?? setInterval(() => this.cleanup(), intervalMs) : null;
180
180
  }
181
181
  has(key) {
@@ -354,7 +354,8 @@ var MemoryDeliveryLog = class {
354
354
  results: dispatch.results,
355
355
  status: this.resolveStatus(dispatch),
356
356
  duration: dispatch.duration,
357
- metadata: payload.metadata
357
+ metadata: payload.metadata,
358
+ ...payload.subject ? { subject: payload.subject } : {}
358
359
  };
359
360
  this.entries.push(entry);
360
361
  if (this.entries.length > this.maxEntries) this.entries = this.entries.slice(-this.maxEntries);
@@ -365,6 +366,10 @@ var MemoryDeliveryLog = class {
365
366
  if (filter.recipientId) results = results.filter((e) => e.recipientId === filter.recipientId);
366
367
  if (filter.recipientEmail) results = results.filter((e) => e.recipientEmail === filter.recipientEmail);
367
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
+ }
368
373
  if (filter.channel) results = results.filter((e) => e.channels.includes(filter.channel));
369
374
  if (filter.status) results = results.filter((e) => e.status === filter.status);
370
375
  if (filter.after) {
@@ -554,7 +559,8 @@ var MemoryQueue = class {
554
559
  job.status = "completed";
555
560
  job.updatedAt = /* @__PURE__ */ new Date();
556
561
  }).catch((err) => {
557
- job.error = err instanceof Error ? err.message : String(err);
562
+ const message = err instanceof Error ? err.message : String(err);
563
+ job.error = message;
558
564
  job.updatedAt = /* @__PURE__ */ new Date();
559
565
  if (job.attempts < job.maxAttempts) {
560
566
  const base = Math.min(job.retryDelay * Math.pow(2, job.attempts - 1), job.maxRetryDelay);
@@ -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-QIV0Th2F.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-DkFudalo.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;
@@ -109,7 +109,8 @@ declare class MemoryIdempotencyStore implements IdempotencyStore {
109
109
  private readonly writeCleanupThreshold;
110
110
  private readonly timer;
111
111
  constructor(options?: {
112
- /** Trigger a cleanup sweep after this many writes. Default: 100. */cleanupInterval?: number;
112
+ /** Trigger a cleanup sweep after this many writes. Default: 100. */
113
+ cleanupInterval?: number;
113
114
  /**
114
115
  * Run a time-based cleanup sweep every N ms. Default: 5 minutes.
115
116
  * Set to 0 to disable the timer (useful in test environments with
@@ -157,12 +158,24 @@ interface DeliveryLogEntry {
157
158
  duration: number;
158
159
  /** Original payload metadata */
159
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;
160
167
  }
161
168
  /** Query filter for delivery log entries */
162
169
  interface DeliveryLogQuery {
163
170
  recipientId?: string;
164
171
  recipientEmail?: string;
165
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;
166
179
  channel?: string;
167
180
  status?: 'delivered' | 'partial' | 'failed' | 'skipped';
168
181
  /** Only entries after this date */
@@ -326,6 +339,20 @@ interface Recipient {
326
339
  metadata?: Record<string, unknown>;
327
340
  }
328
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
+ }
329
356
  interface NotificationPayload {
330
357
  /** Event name that triggered this notification */
331
358
  event: string;
@@ -339,6 +366,21 @@ interface NotificationPayload {
339
366
  channels?: string[];
340
367
  /** Arbitrary metadata (passed through to results) */
341
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;
342
384
  /** Idempotency key — duplicate sends with the same key are skipped */
343
385
  idempotencyKey?: string;
344
386
  /** Delay delivery by this many milliseconds (requires queue adapter) */
@@ -358,6 +400,39 @@ interface SendResult {
358
400
  * Unset / `true` means the failure is transient and should be retried.
359
401
  */
360
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
+ * Populated by every channel whose provider issues one: `email` (`messageId`),
423
+ * `push` (`messageId`), `sms` (`sid`). `webhook` and `console` leave it unset
424
+ * because there is no id to report — a 2xx from an HTTP POST is not a message
425
+ * identifier, and inventing one would make an unjoinable send look joinable.
426
+ */
427
+ providerMessageId?: string;
428
+ /**
429
+ * Free-form per-channel extras.
430
+ *
431
+ * Until 3.0.0 the id-bearing channels ALSO mirror their provider id here under
432
+ * the legacy key (`messageId` for email/push, `sid` for sms). That duplication
433
+ * is the deprecation window, not the contract: read {@link providerMessageId},
434
+ * which is the same value under one name on every channel.
435
+ */
361
436
  metadata?: Record<string, unknown>;
362
437
  }
363
438
  /** Result from dispatching to all channels */
@@ -471,7 +546,9 @@ interface EmailChannelConfig extends ChannelConfig {
471
546
  * channel-level default, allowing subscriber-specific unsubscribe links.
472
547
  */
473
548
  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 */
549
+ /** HTTPS URL that handles the one-click POST (RFC 8058 §3.2) */
550
+ url?: string;
551
+ /** Mailto address for clients that don't support HTTP unsubscribe */
475
552
  email?: string;
476
553
  };
477
554
  }
@@ -600,7 +677,9 @@ interface NotificationServiceConfig {
600
677
  logger?: Logger;
601
678
  /** Idempotency / deduplication config */
602
679
  idempotency?: {
603
- /** Store implementation (default: MemoryIdempotencyStore) */store?: IdempotencyStore; /** TTL in milliseconds (default: 86400000 = 24h) */
680
+ /** Store implementation (default: MemoryIdempotencyStore) */
681
+ store?: IdempotencyStore;
682
+ /** TTL in milliseconds (default: 86400000 = 24h) */
604
683
  ttl?: number;
605
684
  };
606
685
  /** 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-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";
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-DkFudalo.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-CuCdFeVN.mjs";
3
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 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";
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
2
  import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "../errors-BxRjct-E.mjs";
3
3
 
4
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.2.0",
3
+ "version": "2.4.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,
@@ -110,7 +110,7 @@
110
110
  "@types/nodemailer": "^8.0.0",
111
111
  "@vitest/coverage-v8": "4.1.8",
112
112
  "nodemailer": "^8.0.10",
113
- "tsdown": "0.22.1",
113
+ "tsdown": "^0.22.14",
114
114
  "typescript": "^6.0.3",
115
115
  "vitest": "^4.1.8"
116
116
  }