@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.
- package/CHANGELOG.md +94 -0
- package/README.md +86 -0
- package/dist/channels/index.d.mts +1 -1
- package/dist/channels/index.mjs +1 -1
- package/dist/index.d.mts +58 -4
- package/dist/index.mjs +82 -9
- package/dist/providers/index.d.mts +136 -0
- package/dist/providers/index.mjs +280 -0
- package/dist/{push.channel-4mRkzrEu.d.mts → push.channel-CeUVeVfB.d.mts} +23 -1
- package/dist/{push.channel-D1FdTPUi.mjs → push.channel-DI6BNBZ4.mjs} +76 -3
- package/dist/{status-webhook-XY42DCj_.mjs → status-webhook-C69Vrc2v.mjs} +191 -31
- package/dist/{status-webhook-BDaI1BMy.d.mts → status-webhook-DxCdp0c_.d.mts} +73 -3
- package/dist/{types-D94B3VNX.d.mts → types-QIV0Th2F.d.mts} +145 -9
- package/dist/utils/index.d.mts +3 -3
- package/dist/utils/index.mjs +3 -3
- package/package.json +26 -9
- /package/dist/{errors-FYJYmfvj.mjs → errors-BxRjct-E.mjs} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,100 @@
|
|
|
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
|
+
|
|
15
|
+
## [2.1.0] - 2026-05-17
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
|
|
19
|
+
- **Email provider abstraction** at the new `@classytic/notifications/providers`
|
|
20
|
+
subpath export — for multi-tenant hosts that need to store an SMTP
|
|
21
|
+
credential per organization and route sends through it:
|
|
22
|
+
- `EMAIL_PRESETS` / `EMAIL_PROVIDER_OPTIONS` — Resend, Gmail (App
|
|
23
|
+
Password), SendGrid, Mailgun, AWS SES (SMTP), and Custom SMTP. Every
|
|
24
|
+
preset is SMTP-based; the table captures host / port / secure /
|
|
25
|
+
userSource / passSource and leaves the secret bits to the
|
|
26
|
+
credential blob.
|
|
27
|
+
- `buildEmailTransport(data)` — turns an `EmailCredentialData` blob
|
|
28
|
+
into a `nodemailer.Transporter`. Dynamic `import('nodemailer')` so
|
|
29
|
+
the peer stays optional.
|
|
30
|
+
- `buildFromHeader(data)` — formats `"Brand" <hello@…>` (or bare
|
|
31
|
+
email).
|
|
32
|
+
- `getEmailCredentialSchema()` — union-of-fields form schema; the UI
|
|
33
|
+
hides irrelevant fields based on the selected provider.
|
|
34
|
+
- `testEmailCredential(data)` — opens an SMTP connection and runs
|
|
35
|
+
`verify()`. Returns `{ status: 'OK' | 'Error', message }` instead
|
|
36
|
+
of throwing.
|
|
37
|
+
- SES preset opts into `allowHostOverride` so callers can target a
|
|
38
|
+
non-default region by supplying
|
|
39
|
+
`host: 'email-smtp.<region>.amazonaws.com'`. Fixed-host presets
|
|
40
|
+
(Resend / Gmail / SendGrid / Mailgun) deliberately ignore host
|
|
41
|
+
overrides to prevent "changed host, kept the API key" footguns.
|
|
42
|
+
- **`Channel.canSend(payload)` pre-flight hook (optional).** Channels
|
|
43
|
+
can return a `SendResult` (typically `{ status: 'skipped' }`) before
|
|
44
|
+
the service consumes a rate-limit token. Built-in `EmailChannel`,
|
|
45
|
+
`SmsChannel`, and `PushChannel` implement it to skip when the
|
|
46
|
+
recipient field for that channel is missing — preventing a mixed-
|
|
47
|
+
channel batch from burning, say, email quota on a payload that was
|
|
48
|
+
never going to deliver email. Channels that omit `canSend` keep
|
|
49
|
+
working exactly as before.
|
|
50
|
+
- **`queueFailureMode` config knob** on `NotificationService`. Controls
|
|
51
|
+
how the queue processor signals failure to the queue adapter:
|
|
52
|
+
- `'throw-on-total-failure'` (new default) — when
|
|
53
|
+
`sent === 0 && failed > 0`, the processor throws so the queue
|
|
54
|
+
marks the job failed and its retry policy kicks in. Partial
|
|
55
|
+
successes resolve normally so a retry can't double-send the
|
|
56
|
+
channels that already delivered.
|
|
57
|
+
- `'always-complete'` — legacy behavior preserved for hosts whose
|
|
58
|
+
delivery log is the source of truth for failures.
|
|
59
|
+
|
|
60
|
+
### Changed
|
|
61
|
+
|
|
62
|
+
- **Queue jobs no longer silently complete on total dispatch failure.**
|
|
63
|
+
Previously, the queue processor swallowed `DispatchResult` and
|
|
64
|
+
resolved every job, so `MemoryQueue` (or a BullMQ adapter) would
|
|
65
|
+
mark a job completed even when every channel raised. The processor
|
|
66
|
+
now propagates total failure under the default `queueFailureMode`.
|
|
67
|
+
Opt back into the old behavior with
|
|
68
|
+
`queueFailureMode: 'always-complete'`.
|
|
69
|
+
- **Rate-limit tokens are no longer consumed for deterministic skips.**
|
|
70
|
+
`sendToChannel` calls `channel.canSend?.(payload)` before
|
|
71
|
+
`rateLimitStore.consume()`. This fixes a quota-exhaustion footgun
|
|
72
|
+
where a payload addressing an email recipient with no `phone` would
|
|
73
|
+
still decrement the SMS channel's quota.
|
|
74
|
+
- `package.json` adds a `typesVersions` map so node10-style resolvers
|
|
75
|
+
find subpath declarations (`./channels`, `./providers`, `./utils`).
|
|
76
|
+
|
|
77
|
+
### Test infrastructure
|
|
78
|
+
|
|
79
|
+
- Live network tests now live behind a dedicated
|
|
80
|
+
`vitest.live.config.ts` and the `npm run test:live` script. The
|
|
81
|
+
default `npm test` glob no longer includes `*.live.test.ts`, so a
|
|
82
|
+
fresh checkout — even with the workspace `.env.dev` mounted —
|
|
83
|
+
cannot accidentally trigger real SMTP sends.
|
|
84
|
+
- `prepublishOnly` and `release` now run `npm test` (unit suite) in
|
|
85
|
+
addition to the build + typecheck.
|
|
86
|
+
- New live "send" suite (`EMAIL_LIVE_SEND_TO=<inbox>`) actually invokes
|
|
87
|
+
`nodemailer.sendMail` for each provider with creds in the
|
|
88
|
+
environment, so deliverability can be smoke-tested before publish.
|
|
89
|
+
The send gate is intentionally NOT placed in shared env files —
|
|
90
|
+
export it per-shell.
|
|
91
|
+
- `tests/setup-env.ts` auto-loads workspace `../.env.dev` plus
|
|
92
|
+
package-local `.env` / `.env.test` / `.env.test.local`; shell vars
|
|
93
|
+
always win.
|
|
94
|
+
|
|
95
|
+
### Dependencies
|
|
96
|
+
|
|
97
|
+
- `nodemailer >=6` remains the only optional peer dependency.
|
|
98
|
+
|
|
5
99
|
## [2.0.0] - 2026-03-24
|
|
6
100
|
|
|
7
101
|
### Added
|
package/README.md
CHANGED
|
@@ -31,6 +31,23 @@ npm install @classytic/notifications
|
|
|
31
31
|
npm install nodemailer
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
+
### Module Format
|
|
35
|
+
|
|
36
|
+
This package is **ESM-only** (`"type": "module"`, Node 18+, no CJS build).
|
|
37
|
+
That means:
|
|
38
|
+
|
|
39
|
+
- ✅ ESM consumers — `import { ... } from '@classytic/notifications'` just works.
|
|
40
|
+
- ⚠️ CommonJS consumers — you must use a dynamic import:
|
|
41
|
+
```js
|
|
42
|
+
const { NotificationService } = await import('@classytic/notifications');
|
|
43
|
+
```
|
|
44
|
+
A top-level `require('@classytic/notifications')` will fail with
|
|
45
|
+
`ERR_REQUIRE_ESM`. If you're starting a new project, prefer ESM
|
|
46
|
+
(`"type": "module"` in your `package.json`) or use a bundler/runtime
|
|
47
|
+
that handles ESM natively (Vite, Next.js, Bun, modern Node).
|
|
48
|
+
- TypeScript declarations are emitted as `.d.mts`. `typesVersions` is
|
|
49
|
+
configured so node10-style resolvers still resolve subpaths.
|
|
50
|
+
|
|
34
51
|
## Quick Start
|
|
35
52
|
|
|
36
53
|
```typescript
|
|
@@ -112,6 +129,75 @@ const email = new EmailChannel({
|
|
|
112
129
|
});
|
|
113
130
|
```
|
|
114
131
|
|
|
132
|
+
### Email Providers (`/providers`)
|
|
133
|
+
|
|
134
|
+
For multi-tenant apps where each org brings its own email provider, use the
|
|
135
|
+
`/providers` surface to render a credential form, validate the connection,
|
|
136
|
+
and build a transporter from the stored blob — no per-provider branching
|
|
137
|
+
in your host code.
|
|
138
|
+
|
|
139
|
+
```typescript
|
|
140
|
+
import {
|
|
141
|
+
EMAIL_PRESETS,
|
|
142
|
+
EMAIL_PROVIDER_OPTIONS,
|
|
143
|
+
buildEmailTransport,
|
|
144
|
+
buildFromHeader,
|
|
145
|
+
getEmailCredentialSchema,
|
|
146
|
+
testEmailCredential,
|
|
147
|
+
type EmailCredentialData,
|
|
148
|
+
type EmailProviderName,
|
|
149
|
+
} from '@classytic/notifications/providers';
|
|
150
|
+
import { EmailChannel } from '@classytic/notifications/channels';
|
|
151
|
+
|
|
152
|
+
// 1. Render a dynamic form from the schema (provider select + the union
|
|
153
|
+
// of all provider-specific fields — UI hides what's not relevant).
|
|
154
|
+
const fields = getEmailCredentialSchema();
|
|
155
|
+
|
|
156
|
+
// 2. "Test Connection" — opens an SMTP connection and runs `verify()`.
|
|
157
|
+
// Returns `{ status: 'OK' | 'Error', message }` instead of throwing.
|
|
158
|
+
const result = await testEmailCredential({
|
|
159
|
+
provider: 'resend',
|
|
160
|
+
fromEmail: 'hello@yourdomain.com',
|
|
161
|
+
fromName: 'Your Brand',
|
|
162
|
+
apiKey: 're_xxx',
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
// 3. At send time, turn the encrypted DB blob into a transporter and
|
|
166
|
+
// plug it straight into EmailChannel.
|
|
167
|
+
const data: EmailCredentialData = /* decrypted from DB */;
|
|
168
|
+
const transporter = await buildEmailTransport(data);
|
|
169
|
+
const channel = new EmailChannel({
|
|
170
|
+
from: buildFromHeader(data), // '"Brand" <hello@…>' or bare email
|
|
171
|
+
transporter,
|
|
172
|
+
});
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
**Supported providers** — every one is SMTP under the hood:
|
|
176
|
+
|
|
177
|
+
| `provider` | Host | Auth fields | Notes |
|
|
178
|
+
|---|---|---|---|
|
|
179
|
+
| `resend` | `smtp.resend.com:465` | `apiKey` | User is the literal `resend` |
|
|
180
|
+
| `gmail` | `smtp.gmail.com:465` | `user`, `password` | App Password, NOT account password |
|
|
181
|
+
| `sendgrid` | `smtp.sendgrid.net:587` | `apiKey` | User is the literal `apikey` |
|
|
182
|
+
| `mailgun` | `smtp.mailgun.org:465` | `user`, `password` | Per-domain SMTP creds |
|
|
183
|
+
| `ses` | `email-smtp.us-east-1.amazonaws.com:465` | `user`, `password` | SES IAM SMTP creds. Override `host` for other regions |
|
|
184
|
+
| `smtp` | user-supplied | `host`, `port`, `secure`, `user`, `password` | Any auth-SMTP server |
|
|
185
|
+
|
|
186
|
+
Host override is allowed only for `smtp` and `ses` (regional). Other
|
|
187
|
+
presets pin the host to prevent footguns like "I changed the host but
|
|
188
|
+
kept the Resend API key".
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
// SES in eu-west-1
|
|
192
|
+
await buildEmailTransport({
|
|
193
|
+
provider: 'ses',
|
|
194
|
+
fromEmail: 'support@yourdomain.com',
|
|
195
|
+
user: 'AKIAxxxx',
|
|
196
|
+
password: 'BFxxxx',
|
|
197
|
+
host: 'email-smtp.eu-west-1.amazonaws.com',
|
|
198
|
+
});
|
|
199
|
+
```
|
|
200
|
+
|
|
115
201
|
### SmsChannel (BYOP)
|
|
116
202
|
|
|
117
203
|
Zero dependencies — bring your own SMS SDK.
|
|
@@ -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-
|
|
1
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-CeUVeVfB.mjs";
|
|
2
2
|
export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, WebhookChannel };
|
package/dist/channels/index.mjs
CHANGED
|
@@ -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-
|
|
1
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-DI6BNBZ4.mjs";
|
|
2
2
|
|
|
3
3
|
export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, WebhookChannel };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { A as TemplateResult, B as DeliveryLogQuery, C as RetryConfig, D as SmsProvider, E as SmsChannelConfig, F as QueueJob, G as MemoryRateLimitStore, H as IDEMPOTENCY_DEFAULT_TTL, I as QueueJobStatus, K as RateLimitConfig, L as QueueProcessor, M as MemoryQueue, N as QueueAdapter, O as SmtpTransportOptions, P as QueueEnqueueOptions, R as DeliveryLog, S as ResolvedRetryConfig, T as ServiceEvent, U as IdempotencyStore, V as MemoryDeliveryLog, W as MemoryIdempotencyStore, _ as NotificationServiceConfig, a as ChannelConfig, b as PushProvider, c as EmailChannelConfig, d as HookMap, f as Logger, g as NotificationPreferences, h as NotificationPayload, i as Channel, j as WebhookChannelConfig, k as TemplateResolver, l as EventHandler, m as NotificationHookConfig, n as BatchProgress, o as DispatchResult, p as NodemailerTransporter, q as RateLimitStore, r as BatchResult, s as EmailAttachment, t as BatchOptions, u as HookHandler, v as PreferenceResolver, w as SendResult, x as Recipient, y as PushChannelConfig, z as DeliveryLogEntry } from "./types-
|
|
2
|
-
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-
|
|
3
|
-
import { S as mergeHooks, _ as
|
|
1
|
+
import { A as TemplateResult, B as DeliveryLogQuery, C as RetryConfig, D as SmsProvider, E as SmsChannelConfig, F as QueueJob, G as MemoryRateLimitStore, H as IDEMPOTENCY_DEFAULT_TTL, I as QueueJobStatus, K as RateLimitConfig, L as QueueProcessor, M as MemoryQueue, N as QueueAdapter, O as SmtpTransportOptions, P as QueueEnqueueOptions, R as DeliveryLog, S as ResolvedRetryConfig, T as ServiceEvent, U as IdempotencyStore, V as MemoryDeliveryLog, W as MemoryIdempotencyStore, _ as NotificationServiceConfig, a as ChannelConfig, b as PushProvider, c as EmailChannelConfig, d as HookMap, f as Logger, g as NotificationPreferences, h as NotificationPayload, i as Channel, j as WebhookChannelConfig, k as TemplateResolver, l as EventHandler, m as NotificationHookConfig, n as BatchProgress, o as DispatchResult, p as NodemailerTransporter, q as RateLimitStore, r as BatchResult, s as EmailAttachment, t as BatchOptions, u as HookHandler, v as PreferenceResolver, w as SendResult, x as Recipient, y as PushChannelConfig, z as DeliveryLogEntry } from "./types-QIV0Th2F.mjs";
|
|
2
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-CeUVeVfB.mjs";
|
|
3
|
+
import { C as resolveRetryConfig, S as calculateDelay, T as mergeHooks, _ as isQuietHours, a as createStatusHandler, b as ProviderNotInstalledError, c as InterpolateOptions, d as TemplateMap, f as createSimpleResolver, g as QuietHoursConfig, h as pMap, i as StatusUpdate, l as SimpleResolverOptions, m as PMapOptions, n as StatusHandler, o as FallbackOptions, p as interpolateHtml, r as StatusHandlerConfig, s as withFallback, t as DeliveryStatus, u as TemplateDefinition, v as ChannelError, w as withRetry, x as Emitter, y as NotificationError } from "./status-webhook-DxCdp0c_.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/NotificationService.d.ts
|
|
6
6
|
declare class NotificationService {
|
|
@@ -15,6 +15,7 @@ declare class NotificationService {
|
|
|
15
15
|
private deliveryLog?;
|
|
16
16
|
private rateLimitStore?;
|
|
17
17
|
private queueAdapter?;
|
|
18
|
+
private queueFailureMode;
|
|
18
19
|
constructor(config?: NotificationServiceConfig);
|
|
19
20
|
/** Add a channel at runtime */
|
|
20
21
|
addChannel(channel: Channel): this;
|
|
@@ -133,4 +134,57 @@ declare class NotificationService {
|
|
|
133
134
|
off(event: ServiceEvent, handler: EventHandler): this;
|
|
134
135
|
}
|
|
135
136
|
//#endregion
|
|
136
|
-
|
|
137
|
+
//#region src/index.d.ts
|
|
138
|
+
/**
|
|
139
|
+
* @classytic/notifications
|
|
140
|
+
* Multi-Channel Notification System
|
|
141
|
+
*
|
|
142
|
+
* Pluggable channels, templates, retry, and preferences.
|
|
143
|
+
* Zero required dependencies - bring your own providers.
|
|
144
|
+
*
|
|
145
|
+
* v2: Rate limiting, delivery tracking, queue adapter,
|
|
146
|
+
* BCC batching, template engines, SMS & push channels.
|
|
147
|
+
*
|
|
148
|
+
* @module @classytic/notifications
|
|
149
|
+
* @author Classytic (https://github.com/classytic)
|
|
150
|
+
* @license MIT
|
|
151
|
+
*
|
|
152
|
+
* @example
|
|
153
|
+
* ```typescript
|
|
154
|
+
* import { NotificationService } from '@classytic/notifications';
|
|
155
|
+
* import { EmailChannel, SmsChannel, PushChannel } from '@classytic/notifications/channels';
|
|
156
|
+
* import { MemoryDeliveryLog, createSimpleResolver } from '@classytic/notifications/utils';
|
|
157
|
+
*
|
|
158
|
+
* const notifications = new NotificationService({
|
|
159
|
+
* channels: [
|
|
160
|
+
* new EmailChannel({
|
|
161
|
+
* from: 'App <noreply@app.com>',
|
|
162
|
+
* transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
|
|
163
|
+
* rateLimit: { maxPerWindow: 500, windowMs: 86_400_000 }, // Gmail 500/day
|
|
164
|
+
* }),
|
|
165
|
+
* new SmsChannel({
|
|
166
|
+
* from: '+15551234567',
|
|
167
|
+
* provider: { send: async ({ to, from, body }) => ({ sid: 'custom' }) },
|
|
168
|
+
* }),
|
|
169
|
+
* new PushChannel({
|
|
170
|
+
* provider: { send: async ({ token, title, body }) => ({ messageId: 'custom' }) },
|
|
171
|
+
* }),
|
|
172
|
+
* ],
|
|
173
|
+
* templates: createSimpleResolver({
|
|
174
|
+
* welcome: { subject: 'Welcome ${name}!', html: '<p>Hi ${name}</p>' },
|
|
175
|
+
* }),
|
|
176
|
+
* retry: { maxAttempts: 3, backoff: 'exponential' },
|
|
177
|
+
* deliveryLog: new MemoryDeliveryLog(),
|
|
178
|
+
* });
|
|
179
|
+
*
|
|
180
|
+
* await notifications.send({
|
|
181
|
+
* event: 'user.created',
|
|
182
|
+
* recipient: { email: 'user@example.com', phone: '+15559876543', name: 'John' },
|
|
183
|
+
* data: { name: 'John' },
|
|
184
|
+
* template: 'welcome',
|
|
185
|
+
* });
|
|
186
|
+
* ```
|
|
187
|
+
*/
|
|
188
|
+
|
|
189
|
+
//#endregion
|
|
190
|
+
export { BaseChannel, type BatchOptions, type BatchProgress, type BatchResult, type Channel, type ChannelConfig, ChannelError, ConsoleChannel, type DeliveryLog, type DeliveryLogEntry, type DeliveryLogQuery, type DeliveryStatus, type DispatchResult, type EmailAttachment, EmailChannel, type EmailChannelConfig, Emitter, type EventHandler, type FallbackOptions, type HookHandler, type HookMap, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, type InterpolateOptions, type Logger, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, type NodemailerTransporter, NotificationError, type NotificationHookConfig, type NotificationPayload, type NotificationPreferences, NotificationService, type NotificationServiceConfig, type PMapOptions, type PreferenceResolver, ProviderNotInstalledError, PushChannel, type PushChannelConfig, type PushProvider, type QueueAdapter, type QueueEnqueueOptions, type QueueJob, type QueueJobStatus, type QueueProcessor, type QuietHoursConfig, type RateLimitConfig, type RateLimitStore, type Recipient, type ResolvedRetryConfig, type RetryConfig, type SendResult, type ServiceEvent, type SimpleResolverOptions, SmsChannel, type SmsChannelConfig, type SmsProvider, type SmtpTransportOptions, type StatusHandler, type StatusHandlerConfig, type StatusUpdate, type TemplateDefinition, type TemplateMap, type TemplateResolver, type TemplateResult, WebhookChannel, type WebhookChannelConfig, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "./errors-
|
|
3
|
-
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-
|
|
1
|
+
import { a as MemoryQueue, c as pMap, d as MemoryIdempotencyStore, f as isQuietHours, g as Emitter, h as withRetry, i as interpolateHtml, l as MemoryRateLimitStore, m as resolveRetryConfig, n as withFallback, o as MemoryDeliveryLog, p as calculateDelay, r as createSimpleResolver, s as mergeHooks, t as createStatusHandler, u as IDEMPOTENCY_DEFAULT_TTL } from "./status-webhook-C69Vrc2v.mjs";
|
|
2
|
+
import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "./errors-BxRjct-E.mjs";
|
|
3
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-DI6BNBZ4.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/NotificationService.ts
|
|
6
6
|
/**
|
|
@@ -69,6 +69,7 @@ var NotificationService = class {
|
|
|
69
69
|
deliveryLog;
|
|
70
70
|
rateLimitStore;
|
|
71
71
|
queueAdapter;
|
|
72
|
+
queueFailureMode;
|
|
72
73
|
constructor(config = {}) {
|
|
73
74
|
this.channels = config.channels ?? [];
|
|
74
75
|
this.templateResolver = config.templates;
|
|
@@ -82,10 +83,15 @@ var NotificationService = class {
|
|
|
82
83
|
this.deliveryLog = config.deliveryLog;
|
|
83
84
|
if (config.rateLimitStore) this.rateLimitStore = config.rateLimitStore;
|
|
84
85
|
else if (this.channels.some((ch) => this.getChannelRateLimit(ch))) this.rateLimitStore = new MemoryRateLimitStore();
|
|
86
|
+
this.queueFailureMode = config.queueFailureMode ?? "throw-on-total-failure";
|
|
85
87
|
if (config.queue) {
|
|
86
88
|
this.queueAdapter = config.queue;
|
|
87
89
|
this.queueAdapter.process(async (payload) => {
|
|
88
|
-
await this.sendDirect(payload);
|
|
90
|
+
const dispatch = await this.sendDirect(payload);
|
|
91
|
+
if (this.queueFailureMode === "throw-on-total-failure" && dispatch.sent === 0 && dispatch.failed > 0) {
|
|
92
|
+
const summary = dispatch.results.filter((r) => r.status === "failed").map((r) => `${r.channel}: ${r.error ?? "unknown error"}`).join("; ");
|
|
93
|
+
throw new NotificationError(`Queued dispatch for "${dispatch.event}" failed on every channel: ${summary || "no detail"}`, { code: "QUEUE_DISPATCH_FAILED" });
|
|
94
|
+
}
|
|
89
95
|
});
|
|
90
96
|
}
|
|
91
97
|
}
|
|
@@ -268,6 +274,12 @@ var NotificationService = class {
|
|
|
268
274
|
}
|
|
269
275
|
/** Send to a single channel with rate limiting and retry */
|
|
270
276
|
async sendToChannel(channel, payload) {
|
|
277
|
+
if (typeof channel.canSend === "function") try {
|
|
278
|
+
const preflight = channel.canSend(payload);
|
|
279
|
+
if (preflight) return preflight;
|
|
280
|
+
} catch (err) {
|
|
281
|
+
this.logger.warn(`[${channel.name}] canSend() threw, falling through to send(): ${err instanceof Error ? err.message : err}`);
|
|
282
|
+
}
|
|
271
283
|
const rateLimit = this.getChannelRateLimit(channel);
|
|
272
284
|
if (rateLimit && this.rateLimitStore) {
|
|
273
285
|
if (!await this.rateLimitStore.consume(channel.name, rateLimit)) {
|
|
@@ -285,12 +297,16 @@ var NotificationService = class {
|
|
|
285
297
|
};
|
|
286
298
|
}
|
|
287
299
|
}
|
|
288
|
-
const
|
|
289
|
-
const retryConfig = channelRetryRaw ? resolveRetryConfig(channelRetryRaw) : this.retryConfig;
|
|
300
|
+
const retryConfig = channel.retry ? resolveRetryConfig(channel.retry) : this.retryConfig;
|
|
290
301
|
const start = Date.now();
|
|
302
|
+
const NON_RETRYABLE = Symbol("non_retryable");
|
|
291
303
|
try {
|
|
292
304
|
return {
|
|
293
|
-
...await withRetry(
|
|
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) => {
|
|
294
310
|
this.logger.warn(`[${channel.name}] Retry ${attempt}/${retryConfig.maxAttempts}: ${error.message}`);
|
|
295
311
|
this.emitter.emit("send:retry", {
|
|
296
312
|
channel: channel.name,
|
|
@@ -303,6 +319,10 @@ var NotificationService = class {
|
|
|
303
319
|
duration: Date.now() - start
|
|
304
320
|
};
|
|
305
321
|
} catch (err) {
|
|
322
|
+
if (err instanceof Error && NON_RETRYABLE in err) return {
|
|
323
|
+
...err[NON_RETRYABLE],
|
|
324
|
+
duration: Date.now() - start
|
|
325
|
+
};
|
|
306
326
|
const message = err instanceof Error ? err.message : String(err);
|
|
307
327
|
this.logger.error(`[${channel.name}] Failed: ${message}`);
|
|
308
328
|
return {
|
|
@@ -315,7 +335,7 @@ var NotificationService = class {
|
|
|
315
335
|
}
|
|
316
336
|
/** Extract rate limit config from a channel */
|
|
317
337
|
getChannelRateLimit(channel) {
|
|
318
|
-
return channel.
|
|
338
|
+
return channel.rateLimit;
|
|
319
339
|
}
|
|
320
340
|
/**
|
|
321
341
|
* Send multiple notifications with controlled concurrency.
|
|
@@ -455,4 +475,57 @@ var NotificationService = class {
|
|
|
455
475
|
};
|
|
456
476
|
|
|
457
477
|
//#endregion
|
|
458
|
-
|
|
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 };
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { Transporter } from "nodemailer";
|
|
2
|
+
|
|
3
|
+
//#region src/providers/email/presets.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Email provider presets — Resend, Gmail, SendGrid, Mailgun, custom SMTP.
|
|
6
|
+
*
|
|
7
|
+
* Every provider that ships today exposes an SMTP gateway, so the table
|
|
8
|
+
* here captures the constants (host / port / secure / user-source /
|
|
9
|
+
* pass-source) and leaves the variable bits (api key, app password) to
|
|
10
|
+
* the credential's `data` blob. `buildEmailTransport` reads the preset,
|
|
11
|
+
* fills in the auth tuple, and builds a `nodemailer` transport.
|
|
12
|
+
*
|
|
13
|
+
* Adding a new SMTP-based provider is one entry below. Non-SMTP API
|
|
14
|
+
* providers (Postmark API, SES API) would branch in `buildEmailTransport`
|
|
15
|
+
* BEFORE the SMTP fallback — none are shipped yet.
|
|
16
|
+
*/
|
|
17
|
+
type EmailProviderName = 'resend' | 'gmail' | 'sendgrid' | 'mailgun' | 'ses' | 'smtp';
|
|
18
|
+
interface EmailPreset {
|
|
19
|
+
/** Display label for the credential card / dropdown. */
|
|
20
|
+
displayName: string;
|
|
21
|
+
/** One-line description shown next to the option. */
|
|
22
|
+
description: string;
|
|
23
|
+
/** SMTP host. `null` ⇒ user-supplied (custom SMTP). */
|
|
24
|
+
host: string | null;
|
|
25
|
+
/** SMTP port. */
|
|
26
|
+
port: number;
|
|
27
|
+
/** TLS — `true` = implicit TLS, `false` = STARTTLS. */
|
|
28
|
+
secure: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Where the SMTP `user` comes from:
|
|
31
|
+
* - `literal:<value>` — fixed for this provider (Resend → `resend`, SendGrid → `apikey`)
|
|
32
|
+
* - `user` — read `credential.data.user` (Gmail, Mailgun, custom SMTP)
|
|
33
|
+
*/
|
|
34
|
+
userSource: string;
|
|
35
|
+
/**
|
|
36
|
+
* Where the SMTP `pass` comes from:
|
|
37
|
+
* - `apiKey` — read `credential.data.apiKey` (Resend, SendGrid)
|
|
38
|
+
* - `password` — read `credential.data.password` (Gmail, Mailgun, SMTP)
|
|
39
|
+
*/
|
|
40
|
+
passSource: 'apiKey' | 'password';
|
|
41
|
+
/**
|
|
42
|
+
* Allow user-supplied `data.host` / `data.port` / `data.secure` to
|
|
43
|
+
* override the preset defaults. `true` for providers like SES where
|
|
44
|
+
* the region picks the host (`email-smtp.{region}.amazonaws.com`).
|
|
45
|
+
* `false` for fixed-host providers (Resend, Gmail, SendGrid, Mailgun)
|
|
46
|
+
* — prevents "changed host, kept the Resend key" footguns.
|
|
47
|
+
*/
|
|
48
|
+
allowHostOverride?: boolean;
|
|
49
|
+
/** Setup instructions surfaced in the Integrations UI. */
|
|
50
|
+
setupHint: string;
|
|
51
|
+
}
|
|
52
|
+
declare const EMAIL_PRESETS: Record<EmailProviderName, EmailPreset>;
|
|
53
|
+
/** Convenience dropdown options for the credential UI. */
|
|
54
|
+
declare const EMAIL_PROVIDER_OPTIONS: {
|
|
55
|
+
value: EmailProviderName;
|
|
56
|
+
label: string;
|
|
57
|
+
}[];
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region src/providers/email/transport.d.ts
|
|
60
|
+
/**
|
|
61
|
+
* Per-org credential blob — what the host stores (encrypted) and passes
|
|
62
|
+
* back into `buildEmailTransport()` at send time.
|
|
63
|
+
*
|
|
64
|
+
* Only the fields matching `provider` are read; the rest are ignored so
|
|
65
|
+
* a host can store the union shape (a single form with conditionally
|
|
66
|
+
* relevant fields) without leaking unused values into the auth tuple.
|
|
67
|
+
*/
|
|
68
|
+
interface EmailCredentialData {
|
|
69
|
+
provider: EmailProviderName;
|
|
70
|
+
fromEmail: string;
|
|
71
|
+
fromName?: string;
|
|
72
|
+
apiKey?: string;
|
|
73
|
+
user?: string;
|
|
74
|
+
password?: string;
|
|
75
|
+
host?: string;
|
|
76
|
+
port?: string | number;
|
|
77
|
+
secure?: string | boolean;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Build a `nodemailer` `Transporter` from the credential blob.
|
|
81
|
+
*
|
|
82
|
+
* @throws `Error` when required fields are missing for the chosen provider.
|
|
83
|
+
* @throws `Error` when `nodemailer` is not installed (optional peer).
|
|
84
|
+
*/
|
|
85
|
+
declare function buildEmailTransport(data: EmailCredentialData): Promise<Transporter>;
|
|
86
|
+
/**
|
|
87
|
+
* Compose the RFC-5322 `From` header value from the credential blob.
|
|
88
|
+
* Returns `"Display Name" <email@example.com>` when `fromName` is set,
|
|
89
|
+
* otherwise just `email@example.com`.
|
|
90
|
+
*/
|
|
91
|
+
declare function buildFromHeader(data: EmailCredentialData): string;
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/providers/email/schema.d.ts
|
|
94
|
+
/**
|
|
95
|
+
* Credential field schema for the email provider.
|
|
96
|
+
*
|
|
97
|
+
* Hosts that ship a dynamic credential form (driven by a provider's
|
|
98
|
+
* `getCredentialSchema()`-style method) read this to render the right
|
|
99
|
+
* fields. Returning the UNION of all provider-specific fields keeps the
|
|
100
|
+
* form generic — the UI hides irrelevant fields based on the chosen
|
|
101
|
+
* `provider`. Only relevant fields get saved into the encrypted blob.
|
|
102
|
+
*
|
|
103
|
+
* Shape is host-agnostic (no `@classytic/social` import). Hosts that
|
|
104
|
+
* use the social registry's `CredentialField` type can structurally cast.
|
|
105
|
+
*/
|
|
106
|
+
type EmailCredentialFieldType = 'text' | 'password' | 'url' | 'select' | 'textarea';
|
|
107
|
+
interface EmailCredentialField {
|
|
108
|
+
name: string;
|
|
109
|
+
displayName: string;
|
|
110
|
+
type: EmailCredentialFieldType;
|
|
111
|
+
required: boolean;
|
|
112
|
+
placeholder?: string;
|
|
113
|
+
description?: string;
|
|
114
|
+
options?: {
|
|
115
|
+
label: string;
|
|
116
|
+
value: string;
|
|
117
|
+
}[];
|
|
118
|
+
}
|
|
119
|
+
/** Union-of-fields schema — every field appears; the UI hides what's
|
|
120
|
+
* not relevant for the chosen `provider`. */
|
|
121
|
+
declare function getEmailCredentialSchema(): EmailCredentialField[];
|
|
122
|
+
//#endregion
|
|
123
|
+
//#region src/providers/email/test.d.ts
|
|
124
|
+
type EmailTestStatus = 'OK' | 'Error';
|
|
125
|
+
interface EmailTestResult {
|
|
126
|
+
status: EmailTestStatus;
|
|
127
|
+
message: string;
|
|
128
|
+
/** Set when status === 'OK'. */
|
|
129
|
+
data?: {
|
|
130
|
+
provider: EmailCredentialData['provider'];
|
|
131
|
+
fromEmail: string;
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
declare function testEmailCredential(data: EmailCredentialData): Promise<EmailTestResult>;
|
|
135
|
+
//#endregion
|
|
136
|
+
export { EMAIL_PRESETS, EMAIL_PROVIDER_OPTIONS, type EmailCredentialData, type EmailCredentialField, type EmailCredentialFieldType, type EmailPreset, type EmailProviderName, type EmailTestResult, type EmailTestStatus, buildEmailTransport, buildFromHeader, getEmailCredentialSchema, testEmailCredential };
|