@classytic/notifications 2.8.0 → 2.10.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,95 @@
2
2
 
3
3
  All notable changes to `@classytic/notifications` will be documented in this file.
4
4
 
5
+ ## [2.10.0] - 2026-11-23
6
+
7
+ Implements gaps G3 and G4 of arc-notifications' `docs/push-gaps-2026-11.md` (ADR 0001 in
8
+ arc-ecosystem, `docs/adr/0001-notifications-and-push.md`).
9
+
10
+ ### Added: provider retry floors and retry planning (G4)
11
+
12
+ - `TransientPushError.retryFloorMs`: the provider's documented minimum wait, filled by the constructor
13
+ from `pushRetryFloorMs(provider, status)`: FCM 10 s (5xx, network, timeout), FCM 429 60 s, APNs 5xx
14
+ 15 min, APNs 429 60 s, network / unknown 10 s. Throw sites may pass their own.
15
+ - `PUSH_RETRY_DEFAULTS`, `pushRetryDelay(err, attempt)` (`max(Retry-After, floor) x 2^(n-1)`, growth
16
+ capped at 60 min, 0 to 20 % jitter that only adds), `planPushRetry({ error, attempt, firstFailureAt,
17
+ now, expiresAt?, maxAttempts? = 5, giveUpAfterMs? })` returning `{ retry: true, delayMs, at }` or
18
+ `{ retry: false, reason: 'permanent' | 'attempts' | 'expired' | 'gave-up' }` (FCM: 60 min window).
19
+ Pure functions: nothing sleeps; schedule the next attempt on a job queue.
20
+ - `retryFloorHint(err)` (root and `/utils`), the floor counterpart of `retryAfterHint`.
21
+
22
+ ### Added: per-channel idempotency (G3)
23
+
24
+ - `idempotency.scope: 'channel' | 'payload'`. `'channel'` (new default) claims and records
25
+ `${idempotencyKey}:${channel.name}` per channel, only for channels that sent; a redelivery skips the
26
+ done channels (`skipped`, `duplicate (idempotency)`) and retries the rest. A fully duplicated payload
27
+ keeps the 2.9 shape (`results: []`, `skipped: 1`). With a queue (`throw-on-total-failure`), a
28
+ dispatch with a retryable failed channel now throws so the queue re-runs it; only the unfinished
29
+ channels send. `'payload'` is the 2.9 behaviour.
30
+
31
+ ### Changed (migration)
32
+
33
+ - **Idempotency keys** now carry a `:<channel>` suffix by default. A key written by 2.9 does not
34
+ dedupe an event redelivered within its 24 h TTL after the upgrade. Deploy outside a redelivery
35
+ window, or set `idempotency: { scope: 'payload' }` and switch later. Code that reads the store by
36
+ key must append `:<channel>`.
37
+ - **`withRetry` honours `retryFloorMs`** like `Retry-After`: a push `TransientPushError` is never
38
+ retried in process sooner than its floor, and not in process at all when the floor exceeds
39
+ `maxDelay` (default 30 s; so APNs 5xx always goes to the queue). An FCM 5xx through `PushChannel`
40
+ with the default retry config now waits 10 s instead of about 0.5 s. Custom errors without the field
41
+ are unaffected.
42
+
43
+ ## [2.9.0] - 2026-11-23
44
+
45
+ ### Added: `@classytic/notifications/push`, FCM HTTP v1 and APNs HTTP/2 with no SDK
46
+
47
+ Generalised from the push stack of a production incident-management app (FCM through
48
+ `firebase-admin` there; here straight HTTP v1). Node built-ins only (`node:crypto`, `node:http2`,
49
+ `fetch`), so the "zero required dependencies" promise holds. A new subpath and tsdown entry: the root
50
+ entry never loads `node:http2`.
51
+
52
+ - `fcmProvider(options)`: service-account JWT (RS256) exchanged for an OAuth2 access token, cached
53
+ until 60 s before expiry, ONE shared refresh for concurrent sends; a 401 refreshes and retries once.
54
+ - `apnsProvider(options)`: ES256 provider token reused for `tokenTtlMs` (default 50 min, validated to
55
+ Apple's 20 to 60 min window), one HTTP/2 session per host reused and reopened after GOAWAY / close /
56
+ error, ref'd only while streams are in flight; sandbox / production host from
57
+ `credentials.environment`; `apns-push-type`, `apns-priority`, `apns-topic`, `apns-expiration`,
58
+ `apns-collapse-id`; interruption levels with `critical` only when `allowCriticalAlerts`.
59
+ - `pushRouter({ android, ios, web, defaultPlatform })`: dispatch on `message.platform`; a platform
60
+ with no provider is a `PushRejectedError` (`platform-disabled`), never a dead token.
61
+ - Dead tokens: FCM `UNREGISTERED` / `INVALID_ARGUMENT` naming the token and APNs 410 /
62
+ `BadDeviceToken` throw `InvalidPushTokenError` (`reason`) after calling `onInvalidToken(token, reason)`.
63
+ `SENDER_ID_MISMATCH` and `DeviceTokenNotForTopic` are `PushRejectedError` and keep the device (a
64
+ configuration mix-up must not wipe every device row).
65
+ - Transient errors (429, 5xx, timeout, network) are `TransientPushError` with `retryAfterMs` from
66
+ `Retry-After`; a provider-wide 429 / 503 with `Retry-After` pauses that provider instance (fails fast)
67
+ until the time passes; a per-device 429 does not.
68
+ - `PushCredentialsError` for missing / malformed / refused credentials, naming fields only.
69
+ - Credentials as a value or a function (`CredentialsSource`), re-resolved per send; a changed `version`
70
+ (or field fingerprint) re-imports the key and drops cached tokens. `parseFcmServiceAccount`,
71
+ `validateFcmCredentials`, `validateApnsCredentials`.
72
+ - Content-free pushes: `createContentFreeBuilder` and the `contentFreeOnly` provider guard.
73
+ - `onDelivery` structured events (`PushDeliveryEvent`): token suffix + hash, status, reason, latency.
74
+ - `maxConcurrency` per provider instance (FCM 100, APNs 500 by default).
75
+
76
+ ### Added: delivery hints and data-only pushes on the root `PushProvider`
77
+
78
+ - `PushProviderMessage` (named, exported) gains optional `platform`, `priority`, `ttlSeconds`,
79
+ `interruptionLevel`, `contentAvailable`, `sound`, `channelId`, `category`; `PushProvider` gains an
80
+ optional `close()`. `PushChannel` forwards each from `payload.data`.
81
+ - `PushChannel` sends a data-only push (no title, no body) only when `data.contentAvailable` or
82
+ `data.dataOnly` is `true`; without the flag such a send is still skipped, as before.
83
+
84
+ ### Added: `Retry-After` in `withRetry`
85
+
86
+ `withRetry` (and so `NotificationService`) waits at least an error's `retryAfterMs` (found on the error
87
+ or its `cause` chain, `retryAfterHint`); a hint above `maxDelay` stops retrying instead of shortening the
88
+ wait. Errors without the field back off exactly as before.
89
+
90
+ Pinned by `tests/push-fcm.test.ts`, `tests/push-apns.test.ts` (local fake FCM over HTTP and APNs over
91
+ h2c, generated keys, no network), `tests/push-router-payload.test.ts`, `tests/types/push-contract.ts`.
92
+ Design notes: `DESIGN.md`.
93
+
5
94
  ## [2.8.0] — 2026-11-09
6
95
 
7
96
  ### Added: custom SMTP without authentication, and `requireTLS`
package/README.md CHANGED
@@ -314,6 +314,74 @@ const expoPush = new PushChannel({
314
314
  });
315
315
  ```
316
316
 
317
+ ### Built-in push transports (`/push`): FCM HTTP v1 and APNs, no SDK
318
+
319
+ `@classytic/notifications/push` ships production push providers on node built-ins only
320
+ (`node:crypto`, `node:http2`, `fetch`): no `firebase-admin`, no `apn`. Each is a plain `PushProvider`,
321
+ so it drops into `PushChannel`.
322
+
323
+ ```typescript
324
+ import { PushChannel } from '@classytic/notifications/channels';
325
+ import { apnsProvider, fcmProvider, pushRouter } from '@classytic/notifications/push';
326
+
327
+ const dropToken = (token: string) => devices.deleteOne({ token });
328
+
329
+ const push = new PushChannel({
330
+ provider: pushRouter({
331
+ // Credentials are a value or a FUNCTION, re-read per send: rotate without restarting.
332
+ android: fcmProvider({ credentials: () => vault.fcm(), onInvalidToken: dropToken }),
333
+ ios: apnsProvider({
334
+ credentials: () => vault.apns(), // { keyId, teamId, privateKey (.p8), bundleId, environment }
335
+ onInvalidToken: dropToken,
336
+ allowCriticalAlerts: false, // true only if the iOS build has Apple's critical-alerts entitlement
337
+ }),
338
+ }),
339
+ });
340
+
341
+ await service.send({
342
+ event: 'task.offered',
343
+ recipient: { id: userId, deviceToken },
344
+ data: {
345
+ title: 'New task',
346
+ platform: 'ios', // pushRouter dispatches on it
347
+ pushData: { type: 'task_offer', offerId: 'o_1' },
348
+ collapseKey: 'offer-o_1',
349
+ interruptionLevel: 'time-sensitive',
350
+ ttlSeconds: 300,
351
+ },
352
+ });
353
+ ```
354
+
355
+ | Provider answer | Result | Retried |
356
+ |---|---|---|
357
+ | FCM `UNREGISTERED`, `INVALID_ARGUMENT` naming the token; APNs 410, `BadDeviceToken` | `InvalidPushTokenError` + `onInvalidToken(token, reason)` | no |
358
+ | Payload / topic / sender problems, a platform without a provider | `PushRejectedError` (device kept) | no |
359
+ | Credentials missing, malformed, or refused after one refresh | `PushCredentialsError` | no |
360
+ | 429, 5xx, timeout, network | `TransientPushError` with `retryAfterMs` and `retryFloorMs` | yes, never sooner than `Retry-After` or the provider floor |
361
+
362
+ **Retry timing (2.10).** Every `TransientPushError` carries `retryFloorMs`, the provider's documented
363
+ minimum: FCM 10 s (60 s on 429), APNs 15 min on 5xx and 60 s on 429, 10 s for network errors
364
+ (`PUSH_RETRY_DEFAULTS`). `pushRetryDelay(err, attempt)` is `max(Retry-After, floor) x 2^(attempt-1)`
365
+ with upward-only jitter; `planPushRetry({ error, attempt, firstFailureAt, now, expiresAt })` adds at
366
+ most 5 attempts, FCM's 60 min give-up window and the notification's expiry, and returns
367
+ `{ retry: true, delayMs }` or `{ retry: false, reason }`. Both are pure: schedule the next attempt on
368
+ your job queue (arc-notifications' `push.device` job does). `withRetry` never retries sooner than a
369
+ floor, and stops in process when the floor exceeds `maxDelay`.
370
+
371
+ - **Tokens**: FCM OAuth2 access tokens are cached until 60 s before expiry with one shared refresh
372
+ for concurrent sends; APNs ES256 provider tokens are reused for 50 minutes (Apple allows 20 to 60).
373
+ - **Connections**: one HTTP/2 session per APNs host, reused, reopened after GOAWAY; it never holds
374
+ the process open while idle. `close()` ends it on shutdown.
375
+ - **Data-only pushes**: `data.contentAvailable: true` (or `dataOnly: true`) with no title/body sends a
376
+ background push. `createContentFreeBuilder` / `contentFreeOnly` keep pushes to a type and opaque ids
377
+ for apps whose data may not leave a jurisdiction.
378
+ - **Observability**: `onDelivery(event)` gets one redacted record per send (token suffix and hash,
379
+ status, reason, latency; never the token or the text).
380
+ - `withRetry` (and so the service) honours `retryAfterMs` and `retryFloorMs` on an error or its `cause`.
381
+
382
+ Arc apps: `@classytic/arc-notifications/push` adds device registration, credentials from env or an
383
+ encrypted admin integration, and a device fan-out channel on top of these providers.
384
+
317
385
  ### WebhookChannel
318
386
 
319
387
  Zero dependencies — uses native `fetch`.
@@ -652,6 +720,19 @@ A custom `IdempotencyStore` gets the same guarantee by implementing the optional
652
720
  `claim(key, leaseMs)` / `release(key)` pair; stores with only `has` / `set` keep the
653
721
  previous check-then-record behaviour (fine in one process, racy across several).
654
722
 
723
+ **Per-channel keys (2.10 default).** The key is claimed and recorded per channel as
724
+ `${idempotencyKey}:${channel}`, and recorded only for channels that sent. With
725
+ `channels: ['in-app', 'push']`, an in-app write that succeeded beside a push that failed
726
+ leaves `key:push` free: a redelivery (or the queue's retry) sends the push and skips the
727
+ in-app channel (`skipped`, error `duplicate (idempotency)`). With a queue, a dispatch with a
728
+ retryable failed channel now throws so the queue re-runs it; without a key the old "partial
729
+ success completes" rule stays. `idempotency: { scope: 'payload' }` restores the 2.9
730
+ single key (a failed channel beside a successful one is then never retried).
731
+
732
+ Upgrading from 2.9: keys written by 2.9 have no `:<channel>` suffix, so an event redelivered
733
+ within 24 h of the upgrade is not recognised as a duplicate. Deploy outside a redelivery
734
+ window, or keep `scope: 'payload'` until old keys have expired.
735
+
655
736
  ## Batch Sending
656
737
 
657
738
  Send thousands of notifications with controlled concurrency:
@@ -679,6 +760,9 @@ const notifications = new NotificationService({
679
760
  ```
680
761
 
681
762
  Jitter (+-25%) is applied automatically to prevent thundering herd. Per-channel overrides are supported.
763
+ An error that carries `retryAfterMs` (HTTP `Retry-After`) or `retryFloorMs` (a provider's minimum, set
764
+ on every push `TransientPushError`) is never retried sooner; when that wait exceeds `maxDelay` the
765
+ in-process loop stops and the failure is left to your queue.
682
766
 
683
767
  ## Lifecycle Events
684
768
 
@@ -761,6 +845,18 @@ import {
761
845
  NotificationError, ChannelError, ProviderNotInstalledError,
762
846
  } from '@classytic/notifications/utils';
763
847
 
848
+ // Push transports (FCM HTTP v1, APNs HTTP/2), zero dependencies
849
+ import {
850
+ fcmProvider, apnsProvider, pushRouter,
851
+ createContentFreeBuilder, contentFreeOnly,
852
+ parseFcmServiceAccount, validateFcmCredentials, validateApnsCredentials,
853
+ InvalidPushTokenError, PushRejectedError, PushCredentialsError, TransientPushError,
854
+ isInvalidPushTokenError, tokenSuffix, tokenHash,
855
+ } from '@classytic/notifications/push';
856
+ import type {
857
+ FcmCredentials, ApnsCredentials, CredentialsSource, PushDeliveryEvent, InvalidTokenReason,
858
+ } from '@classytic/notifications/push';
859
+
764
860
  // Types
765
861
  import type {
766
862
  SmsProvider, PushProvider, DeliveryLog, DeliveryStatus,
@@ -1,2 +1,2 @@
1
- import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "../telegram.channel-CzQH7Wa8.mjs";
1
+ import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "../telegram.channel-DcqdfWmV.mjs";
2
2
  export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, TelegramChannel, WebhookChannel };
@@ -1,3 +1,3 @@
1
- import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "../telegram.channel-DnVdyq8_.mjs";
1
+ import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "../telegram.channel-0XRkIXmt.mjs";
2
2
 
3
3
  export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, TelegramChannel, WebhookChannel };
@@ -0,0 +1,37 @@
1
+ //#region src/utils/errors.d.ts
2
+ /**
3
+ * Notification Errors
4
+ * @module @classytic/notifications
5
+ */
6
+ declare class NotificationError extends Error {
7
+ readonly code: string;
8
+ readonly channel?: string;
9
+ readonly cause?: Error;
10
+ constructor(message: string, options?: {
11
+ code?: string;
12
+ channel?: string;
13
+ cause?: Error;
14
+ });
15
+ }
16
+ declare class ChannelError extends NotificationError {
17
+ constructor(channel: string, message: string, cause?: Error);
18
+ }
19
+ /**
20
+ * Thrown by a provider for a failure no retry can fix (unregistered device token, invalid
21
+ * recipient). Channels that honour it (PushChannel) return `failed` with `retryable: false`, so
22
+ * the service does not retry. Detected structurally (`retryable === false`), so a provider may
23
+ * also throw any error carrying that flag.
24
+ */
25
+ declare class PermanentDeliveryError extends NotificationError {
26
+ readonly retryable: false;
27
+ constructor(message: string, options?: {
28
+ code?: string;
29
+ channel?: string;
30
+ cause?: Error;
31
+ });
32
+ }
33
+ declare class ProviderNotInstalledError extends NotificationError {
34
+ constructor(provider: string, installCmd: string);
35
+ }
36
+ //#endregion
37
+ export { ProviderNotInstalledError as i, NotificationError as n, PermanentDeliveryError as r, ChannelError as t };
package/dist/index.d.mts CHANGED
@@ -1,6 +1,7 @@
1
- import { A as TemplateResolver, B as DeliveryLogEntry, C as RetryConfig, D as SmsProvider, E as SmsChannelConfig, F as QueueEnqueueOptions, G as IdempotencyStore, H as MemoryDeliveryLog, I as QueueJob, J as RedisIdempotencyStore, K as MemoryIdempotencyStore, L as QueueJobStatus, M as WebhookChannelConfig, N as MemoryQueue, O as SmtpTransportOptions, P as QueueAdapter, R as QueueProcessor, S as ResolvedRetryConfig, T as ServiceEvent, U as IDEMPOTENCY_DEFAULT_LEASE, V as DeliveryLogQuery, W as IDEMPOTENCY_DEFAULT_TTL, X as RateLimitConfig, Y as MemoryRateLimitStore, Z as RateLimitStore, _ 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 TemplateResult, k as TelegramChannelConfig, l as EventHandler, m as NotificationHookConfig, n as BatchProgress, o as DispatchResult, p as NodemailerTransporter, q as RedisIdempotencyClient, 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 DeliveryLog } from "./types-DyUMfkyr.mjs";
2
- import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "./telegram.channel-CzQH7Wa8.mjs";
3
- import { C as calculateDelay, E as mergeHooks, S as Emitter, T as withRetry, _ as isQuietHours, a as createStatusHandler, b as PermanentDeliveryError, 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 resolveRetryConfig, x as ProviderNotInstalledError, y as NotificationError } from "./status-webhook-BlhPvRnD.mjs";
1
+ import { $ as RateLimitConfig, A as SmsProvider, B as QueueJobStatus, C as PushProviderMessage, D as SendResult, E as RetryConfig, F as WebhookChannelConfig, G as MemoryDeliveryLog, H as DeliveryLog, I as MemoryQueue, J as IdempotencyStore, K as IDEMPOTENCY_DEFAULT_LEASE, L as QueueAdapter, M as TelegramChannelConfig, N as TemplateResolver, O as ServiceEvent, P as TemplateResult, Q as MemoryRateLimitStore, R as QueueEnqueueOptions, S as PushProvider, T as ResolvedRetryConfig, U as DeliveryLogEntry, V as QueueProcessor, W as DeliveryLogQuery, X as RedisIdempotencyClient, Y as MemoryIdempotencyStore, Z as RedisIdempotencyStore, _ as NotificationServiceConfig, a as ChannelConfig, b as PushInterruptionLevel, c as EmailChannelConfig, d as HookMap, et as RateLimitStore, f as Logger, g as NotificationPreferences, h as NotificationPayload, i as Channel, j as SmtpTransportOptions, k as SmsChannelConfig, l as EventHandler, m as NotificationHookConfig, n as BatchProgress, o as DispatchResult, p as NodemailerTransporter, q as IDEMPOTENCY_DEFAULT_TTL, r as BatchResult, s as EmailAttachment, t as BatchOptions, u as HookHandler, v as PreferenceResolver, w as Recipient, x as PushPlatform, y as PushChannelConfig, z as QueueJob } from "./types-D3g8xK2h.mjs";
2
+ import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "./telegram.channel-DcqdfWmV.mjs";
3
+ import { C as withRetry, S as retryFloorHint, _ as isQuietHours, a as createStatusHandler, b as resolveRetryConfig, 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 Emitter, w as mergeHooks, x as retryAfterHint, y as calculateDelay } from "./status-webhook-DCU8KQLR.mjs";
4
+ import { i as ProviderNotInstalledError, n as NotificationError, r as PermanentDeliveryError, t as ChannelError } from "./errors-DCOaQvhV.mjs";
4
5
  //#region src/NotificationService.d.ts
5
6
  export declare class NotificationService {
6
7
  private channels;
@@ -12,6 +13,7 @@ export declare class NotificationService {
12
13
  private idempotencyStore?;
13
14
  private idempotencyTtl;
14
15
  private idempotencyLease;
16
+ private idempotencyScope;
15
17
  private deliveryLog?;
16
18
  private rateLimitStore?;
17
19
  private queueAdapter?;
@@ -53,6 +55,18 @@ export declare class NotificationService {
53
55
  * lifecycle events are always emitted.
54
56
  */
55
57
  private sendDirect;
58
+ /** Per-channel keys apply: a key, a store, and `scope: 'channel'` (the default). */
59
+ private perChannelIdempotency;
60
+ /**
61
+ * Per-channel idempotency (G3 in arc-notifications' `docs/push-gaps-2026-11.md`; ADR 0001
62
+ * section 2 item 4 applied at the channel level). Each target channel is claimed under
63
+ * `${key}:${channel}` BEFORE the template is rendered, so a full duplicate stays as cheap as in
64
+ * 2.9. Channels already done are skipped (reported as `skipped`, error `duplicate`); the rest
65
+ * deliver. After delivery a channel that SENT records its key for the TTL; every other claim is
66
+ * released, so a redelivery (or the queue's retry) sends that channel, and only that channel,
67
+ * again. A pipeline error releases every claim it holds.
68
+ */
69
+ private deliverPerChannel;
56
70
  /** Drop a claimed idempotency key so a later retry can deliver. Never throws. */
57
71
  private releaseIdempotency;
58
72
  /** Steps 2-5 of the send pipeline: template, channel filter, preferences, delivery. */
@@ -138,4 +152,4 @@ export declare class NotificationService {
138
152
  off(event: ServiceEvent, handler: EventHandler): this;
139
153
  }
140
154
  //#endregion
141
- 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_LEASE, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, type InterpolateOptions, type Logger, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, type NodemailerTransporter, NotificationError, type NotificationHookConfig, type NotificationPayload, type NotificationPreferences, type NotificationServiceConfig, type PMapOptions, PermanentDeliveryError, 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 RedisIdempotencyClient, RedisIdempotencyStore, type ResolvedRetryConfig, type RetryConfig, type SendResult, type ServiceEvent, type SimpleResolverOptions, SmsChannel, type SmsChannelConfig, type SmsProvider, type SmtpTransportOptions, type StatusHandler, type StatusHandlerConfig, type StatusUpdate, TelegramChannel, type TelegramChannelConfig, type TemplateDefinition, type TemplateMap, type TemplateResolver, type TemplateResult, WebhookChannel, type WebhookChannelConfig, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
155
+ 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_LEASE, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, type InterpolateOptions, type Logger, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, type NodemailerTransporter, NotificationError, type NotificationHookConfig, type NotificationPayload, type NotificationPreferences, type NotificationServiceConfig, type PMapOptions, PermanentDeliveryError, type PreferenceResolver, ProviderNotInstalledError, PushChannel, type PushChannelConfig, type PushInterruptionLevel, type PushPlatform, type PushProvider, type PushProviderMessage, type QueueAdapter, type QueueEnqueueOptions, type QueueJob, type QueueJobStatus, type QueueProcessor, type QuietHoursConfig, type RateLimitConfig, type RateLimitStore, type Recipient, type RedisIdempotencyClient, RedisIdempotencyStore, type ResolvedRetryConfig, type RetryConfig, type SendResult, type ServiceEvent, type SimpleResolverOptions, SmsChannel, type SmsChannelConfig, type SmsProvider, type SmtpTransportOptions, type StatusHandler, type StatusHandlerConfig, type StatusUpdate, TelegramChannel, type TelegramChannelConfig, type TemplateDefinition, type TemplateMap, type TemplateResolver, type TemplateResult, WebhookChannel, type WebhookChannelConfig, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, retryAfterHint, retryFloorHint, withFallback, withRetry };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { _ as withRetry, a as MemoryQueue, c as pMap, d as IDEMPOTENCY_DEFAULT_TTL, f as MemoryIdempotencyStore, g as resolveRetryConfig, h as calculateDelay, i as interpolateHtml, l as MemoryRateLimitStore, m as isQuietHours, n as withFallback, o as MemoryDeliveryLog, p as RedisIdempotencyStore, r as createSimpleResolver, s as mergeHooks, t as createStatusHandler, u as IDEMPOTENCY_DEFAULT_LEASE, v as Emitter } from "./status-webhook-D7Hrr71A.mjs";
1
+ import { _ as retryAfterHint, a as MemoryQueue, b as Emitter, c as pMap, d as IDEMPOTENCY_DEFAULT_TTL, f as MemoryIdempotencyStore, g as resolveRetryConfig, h as calculateDelay, i as interpolateHtml, l as MemoryRateLimitStore, m as isQuietHours, n as withFallback, o as MemoryDeliveryLog, p as RedisIdempotencyStore, r as createSimpleResolver, s as mergeHooks, t as createStatusHandler, u as IDEMPOTENCY_DEFAULT_LEASE, v as retryFloorHint, y as withRetry } from "./status-webhook-DN3bdqKs.mjs";
2
2
  import { i as ProviderNotInstalledError, n as NotificationError, r as PermanentDeliveryError, t as ChannelError } from "./errors-CsQZKfec.mjs";
3
- import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "./telegram.channel-DnVdyq8_.mjs";
3
+ import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "./telegram.channel-0XRkIXmt.mjs";
4
4
 
5
5
  //#region src/NotificationService.ts
6
6
  /**
@@ -67,6 +67,7 @@ var NotificationService = class {
67
67
  idempotencyStore;
68
68
  idempotencyTtl;
69
69
  idempotencyLease;
70
+ idempotencyScope;
70
71
  deliveryLog;
71
72
  rateLimitStore;
72
73
  queueAdapter;
@@ -82,6 +83,7 @@ var NotificationService = class {
82
83
  this.idempotencyTtl = config.idempotency.ttl ?? 864e5;
83
84
  } else this.idempotencyTtl = IDEMPOTENCY_DEFAULT_TTL;
84
85
  this.idempotencyLease = config.idempotency?.leaseMs ?? 3e5;
86
+ this.idempotencyScope = config.idempotency?.scope ?? "channel";
85
87
  this.deliveryLog = config.deliveryLog;
86
88
  if (config.rateLimitStore) this.rateLimitStore = config.rateLimitStore;
87
89
  else if (this.channels.some((ch) => this.getChannelRateLimit(ch))) this.rateLimitStore = new MemoryRateLimitStore();
@@ -90,9 +92,12 @@ var NotificationService = class {
90
92
  this.queueAdapter = config.queue;
91
93
  this.queueAdapter.process(async (payload) => {
92
94
  const dispatch = await this.sendDirect(payload);
93
- if (this.queueFailureMode === "throw-on-total-failure" && dispatch.sent === 0 && dispatch.failed > 0) {
95
+ const perChannel = this.perChannelIdempotency(payload);
96
+ const retryableFailed = dispatch.results.filter((r) => r.status === "failed" && r.retryable !== false);
97
+ const totalFailure = dispatch.sent === 0 && dispatch.failed > 0;
98
+ if (this.queueFailureMode === "throw-on-total-failure" && (totalFailure || perChannel && retryableFailed.length > 0)) {
94
99
  const summary = dispatch.results.filter((r) => r.status === "failed").map((r) => `${r.channel}: ${r.error ?? "unknown error"}`).join("; ");
95
- throw new NotificationError(`Queued dispatch for "${dispatch.event}" failed on every channel: ${summary || "no detail"}`, { code: "QUEUE_DISPATCH_FAILED" });
100
+ throw new NotificationError(totalFailure ? `Queued dispatch for "${dispatch.event}" failed on every channel: ${summary || "no detail"}` : `Queued dispatch for "${dispatch.event}" failed on some channels (retrying those only): ${summary}`, { code: "QUEUE_DISPATCH_FAILED" });
96
101
  }
97
102
  });
98
103
  }
@@ -171,6 +176,7 @@ var NotificationService = class {
171
176
  async sendDirect(payload) {
172
177
  const start = Date.now();
173
178
  await this.emitter.emit("before:send", payload);
179
+ if (this.perChannelIdempotency(payload)) return this.deliverPerChannel(payload, start, payload.idempotencyKey, this.idempotencyStore);
174
180
  let claimed = false;
175
181
  if (payload.idempotencyKey && this.idempotencyStore) {
176
182
  const store = this.idempotencyStore;
@@ -195,6 +201,78 @@ var NotificationService = class {
195
201
  if (!delivered || delivered.sent === 0) await this.releaseIdempotency(payload.idempotencyKey);
196
202
  }
197
203
  }
204
+ /** Per-channel keys apply: a key, a store, and `scope: 'channel'` (the default). */
205
+ perChannelIdempotency(payload) {
206
+ return Boolean(payload.idempotencyKey && this.idempotencyStore && this.idempotencyScope === "channel");
207
+ }
208
+ /**
209
+ * Per-channel idempotency (G3 in arc-notifications' `docs/push-gaps-2026-11.md`; ADR 0001
210
+ * section 2 item 4 applied at the channel level). Each target channel is claimed under
211
+ * `${key}:${channel}` BEFORE the template is rendered, so a full duplicate stays as cheap as in
212
+ * 2.9. Channels already done are skipped (reported as `skipped`, error `duplicate`); the rest
213
+ * deliver. After delivery a channel that SENT records its key for the TTL; every other claim is
214
+ * released, so a redelivery (or the queue's retry) sends that channel, and only that channel,
215
+ * again. A pipeline error releases every claim it holds.
216
+ */
217
+ async deliverPerChannel(payload, start, key, store) {
218
+ let candidates = this.channels.filter((ch) => ch.shouldHandle(payload.event));
219
+ if (payload.channels?.length) {
220
+ const targetSet = new Set(payload.channels);
221
+ candidates = candidates.filter((ch) => targetSet.has(ch.name));
222
+ }
223
+ const keyOf = (name) => `${key}:${name}`;
224
+ const fresh = [];
225
+ const duplicates = [];
226
+ const held = /* @__PURE__ */ new Set();
227
+ const done = /* @__PURE__ */ new Set();
228
+ const releaseHeld = async () => {
229
+ for (const name of held) if (!done.has(name)) await this.releaseIdempotency(keyOf(name));
230
+ };
231
+ try {
232
+ for (const channel of candidates) {
233
+ const k = keyOf(channel.name);
234
+ if (store.claim ? !await store.claim(k, this.idempotencyLease) : await store.has(k)) {
235
+ duplicates.push(channel);
236
+ continue;
237
+ }
238
+ fresh.push(channel);
239
+ if (store.claim) held.add(channel.name);
240
+ }
241
+ } catch (err) {
242
+ await releaseHeld();
243
+ throw err;
244
+ }
245
+ if (candidates.length > 0 && fresh.length === 0) {
246
+ this.logger.debug?.(`Duplicate notification skipped (key: ${key})`);
247
+ return this.finalize(payload, {
248
+ event: payload.event,
249
+ results: [],
250
+ sent: 0,
251
+ failed: 0,
252
+ skipped: 1,
253
+ duration: Date.now() - start
254
+ });
255
+ }
256
+ try {
257
+ return await this.deliver(payload, start, {
258
+ channels: fresh,
259
+ duplicates,
260
+ settle: async (results) => {
261
+ for (const r of results) {
262
+ if (r.status !== "sent") continue;
263
+ done.add(r.channel);
264
+ try {
265
+ await store.set(keyOf(r.channel), this.idempotencyTtl);
266
+ } catch (err) {
267
+ this.logger.warn(`Idempotency store error: ${err instanceof Error ? err.message : err}`);
268
+ }
269
+ }
270
+ }
271
+ });
272
+ } finally {
273
+ await releaseHeld();
274
+ }
275
+ }
198
276
  /** Drop a claimed idempotency key so a later retry can deliver. Never throws. */
199
277
  async releaseIdempotency(key) {
200
278
  try {
@@ -204,7 +282,7 @@ var NotificationService = class {
204
282
  }
205
283
  }
206
284
  /** Steps 2-5 of the send pipeline: template, channel filter, preferences, delivery. */
207
- async deliver(payload, start) {
285
+ async deliver(payload, start, perChannel) {
208
286
  let enrichedPayload = payload;
209
287
  if (payload.template && this.templateResolver) try {
210
288
  const rendered = await this.templateResolver(payload.template, payload.data);
@@ -219,10 +297,14 @@ var NotificationService = class {
219
297
  this.logger.error(`Template resolution failed for "${payload.template}"`, err);
220
298
  throw new NotificationError(`Template "${payload.template}" failed: ${err instanceof Error ? err.message : err}`, { code: "TEMPLATE_ERROR" });
221
299
  }
222
- let activeChannels = this.channels.filter((ch) => ch.shouldHandle(payload.event));
223
- if (payload.channels?.length) {
224
- const targetSet = new Set(payload.channels);
225
- activeChannels = activeChannels.filter((ch) => targetSet.has(ch.name));
300
+ let activeChannels;
301
+ if (perChannel) activeChannels = perChannel.channels;
302
+ else {
303
+ activeChannels = this.channels.filter((ch) => ch.shouldHandle(payload.event));
304
+ if (payload.channels?.length) {
305
+ const targetSet = new Set(payload.channels);
306
+ activeChannels = activeChannels.filter((ch) => targetSet.has(ch.name));
307
+ }
226
308
  }
227
309
  if (enrichedPayload.recipient.id && this.preferenceResolver) try {
228
310
  const prefs = await this.preferenceResolver(enrichedPayload.recipient.id, enrichedPayload.event);
@@ -259,7 +341,16 @@ var NotificationService = class {
259
341
  skipped: 0,
260
342
  duration: Date.now() - start
261
343
  });
262
- const results = await Promise.all(activeChannels.map((channel) => this.sendToChannel(channel, enrichedPayload)));
344
+ const sentResults = await Promise.all(activeChannels.map((channel) => this.sendToChannel(channel, enrichedPayload)));
345
+ let results = sentResults;
346
+ if (perChannel) {
347
+ await perChannel.settle(sentResults);
348
+ results = [...sentResults, ...perChannel.duplicates.map((ch) => ({
349
+ status: "skipped",
350
+ channel: ch.name,
351
+ error: "duplicate (idempotency)"
352
+ }))];
353
+ }
263
354
  const dispatch = {
264
355
  event: enrichedPayload.event,
265
356
  results,
@@ -268,7 +359,7 @@ var NotificationService = class {
268
359
  skipped: results.filter((r) => r.status === "skipped").length,
269
360
  duration: Date.now() - start
270
361
  };
271
- if (payload.idempotencyKey && this.idempotencyStore && dispatch.sent > 0) try {
362
+ if (!perChannel && payload.idempotencyKey && this.idempotencyStore && dispatch.sent > 0) try {
272
363
  await this.idempotencyStore.set(payload.idempotencyKey, this.idempotencyTtl);
273
364
  } catch (err) {
274
365
  this.logger.warn(`Idempotency store error: ${err instanceof Error ? err.message : err}`);
@@ -575,4 +666,4 @@ var NotificationService = class {
575
666
  */
576
667
 
577
668
  //#endregion
578
- export { BaseChannel, ChannelError, ConsoleChannel, EmailChannel, Emitter, IDEMPOTENCY_DEFAULT_LEASE, IDEMPOTENCY_DEFAULT_TTL, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, NotificationService, PermanentDeliveryError, ProviderNotInstalledError, PushChannel, RedisIdempotencyStore, SmsChannel, TelegramChannel, WebhookChannel, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
669
+ export { BaseChannel, ChannelError, ConsoleChannel, EmailChannel, Emitter, IDEMPOTENCY_DEFAULT_LEASE, IDEMPOTENCY_DEFAULT_TTL, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, NotificationService, PermanentDeliveryError, ProviderNotInstalledError, PushChannel, RedisIdempotencyStore, SmsChannel, TelegramChannel, WebhookChannel, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, retryAfterHint, retryFloorHint, withFallback, withRetry };