@aglyn/shared-util-email 1.0.0-beta.217 → 1.0.0-beta.219

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.
Files changed (46) hide show
  1. package/README.md +58 -19
  2. package/package.json +3 -3
  3. package/src/index.d.ts +2 -0
  4. package/src/index.js +9 -1
  5. package/src/index.js.map +1 -1
  6. package/src/lib/email-deliverability.d.ts +9 -2
  7. package/src/lib/email-deliverability.js.map +1 -1
  8. package/src/lib/email-delivery-events.d.ts +41 -48
  9. package/src/lib/email-delivery-events.js +18 -247
  10. package/src/lib/email-delivery-events.js.map +1 -1
  11. package/src/lib/email-health.d.ts +30 -43
  12. package/src/lib/email-health.js +45 -141
  13. package/src/lib/email-health.js.map +1 -1
  14. package/src/lib/mail-provider-resend.d.ts +194 -0
  15. package/src/lib/mail-provider-resend.js +649 -0
  16. package/src/lib/mail-provider-resend.js.map +1 -0
  17. package/src/lib/mail-provider-webhook.d.ts +80 -0
  18. package/src/lib/mail-provider-webhook.js +156 -0
  19. package/src/lib/mail-provider-webhook.js.map +1 -0
  20. package/src/lib/mail-provider.d.ts +148 -0
  21. package/src/lib/mail-provider.js +84 -0
  22. package/src/lib/mail-provider.js.map +1 -0
  23. package/src/lib/mail-providers.d.ts +99 -0
  24. package/src/lib/mail-providers.js +182 -0
  25. package/src/lib/mail-providers.js.map +1 -0
  26. package/src/lib/received-email.d.ts +7 -44
  27. package/src/lib/received-email.js +8 -104
  28. package/src/lib/received-email.js.map +1 -1
  29. package/src/lib/risk-notice-catalog.js +7 -1
  30. package/src/lib/risk-notice-catalog.js.map +1 -1
  31. package/src/lib/send-ceilings.d.ts +0 -57
  32. package/src/lib/send-ceilings.js +0 -47
  33. package/src/lib/send-ceilings.js.map +1 -1
  34. package/src/lib/send-email.d.ts +36 -58
  35. package/src/lib/send-email.js +102 -133
  36. package/src/lib/send-email.js.map +1 -1
  37. package/src/lib/send-rate.js +4 -3
  38. package/src/lib/send-rate.js.map +1 -1
  39. package/src/lib/system-email-catalog.js +3 -3
  40. package/src/lib/system-email-catalog.js.map +1 -1
  41. package/src/lib/tenant-email-catalog.d.ts +7 -0
  42. package/src/lib/tenant-email-catalog.js +10 -591
  43. package/src/lib/tenant-email-catalog.js.map +1 -1
  44. package/src/lib/tenant-emails.generated.d.ts +11 -0
  45. package/src/lib/tenant-emails.generated.js +594 -0
  46. package/src/lib/tenant-emails.generated.js.map +1 -0
@@ -1,4 +1,3 @@
1
- import { _ as _extends } from "@swc/helpers/_/_extends";
2
1
  /**
3
2
  * @license
4
3
  * Copyright 2026 Aglyn LLC
@@ -20,13 +19,14 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
20
19
  * ## The seam
21
20
  *
22
21
  * A staff answer to "did they get the invite, and did they open it?" must not
23
- * be a question about Resend. Two things follow from that, and this module is
24
- * both of them:
22
+ * be a question about one sending vendor. Two things follow from that, and
23
+ * this module is both of them:
25
24
  *
26
25
  * 1. **The stored shape is ours.** Nothing downstream — the delivery log, the
27
26
  * staff card, a future export — reads a provider's field names or its event
28
- * strings. Swapping the sender changes exactly one function in this file
29
- * and nothing else in the tree.
27
+ * strings. A provider turns its own wire format into these types (its
28
+ * `deliveryEvents` and `reads`, see `mail-provider.ts`), and swapping the
29
+ * sender changes that provider and nothing else in the tree.
30
30
  * 2. **The history is ours.** The log is written into our own Firestore and
31
31
  * read from there, never from the provider on render. A provider's list
32
32
  * endpoint is a different shape per vendor, has its own retention window,
@@ -37,8 +37,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
37
37
  * provider. The event feed only knows mail sent after it was connected, so
38
38
  * a log fed by events alone is empty for all existing history — which is
39
39
  * precisely the mail a support question is about. The second half of this
40
- * module (see THE READ SIDE OF THE SEAM below) imports that history
41
- * through the same neutral vocabulary, once, into the same store.
40
+ * module (see THE READ SIDE OF THE SEAM below) is the vocabulary that
41
+ * history is imported through, once, into the same store.
42
42
  *
43
43
  * ## Pure on purpose
44
44
  *
@@ -46,14 +46,17 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
46
46
  * CLIENT components through this library's barrel, so anything reachable from
47
47
  * it that touched `firebase-admin` would drag the admin SDK into a browser
48
48
  * bundle. Normalisation is a pure function of a payload; the writing lives in
49
- * `@aglyn/tenant-data-admin/server/email-delivery-log`.
50
- *
51
- * The one `fetch` is `resendDeliveryHistorySource`, which is a function that
52
- * must be CALLED with a key to do anything — it holds no module state and is
53
- * unreachable from a client component, unlike an admin-SDK import, which
54
- * executes on load.
55
- */ import { readBounceText } from "./mail-bounce.js";
56
- /** Lifecycle states ordered worst-last, for {@link worstDeliveryStatus}. */ const STATUS_SEVERITY = {
49
+ * `@aglyn/tenant-data-admin/server/email-delivery-log`, and the reading
50
+ * of a provider's payloads in that provider.
51
+ */ /**
52
+ * The lifecycle of one message, in the order it normally happens.
53
+ *
54
+ * Chosen to be the intersection every ESP can report rather than the union of
55
+ * what any one of them does: a vendor with no equivalent for a state simply
56
+ * never produces it, and a vendor with a richer taxonomy folds into the
57
+ * nearest of these rather than widening the type. `delayed` is retryable and
58
+ * `failed` is not, which is the distinction a staffer actually needs.
59
+ */ /** Lifecycle states ordered worst-last, for {@link worstDeliveryStatus}. */ const STATUS_SEVERITY = {
57
60
  sent: 1,
58
61
  delivered: 2,
59
62
  opened: 3,
@@ -90,237 +93,5 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
90
93
  }
91
94
  return {};
92
95
  }
93
- /** Epoch ms from an ISO string or a number, or `null` when unreadable. */ function eventTimeMs(value) {
94
- if (typeof value === 'number' && Number.isFinite(value)) return value;
95
- const parsed = Date.parse(String(value != null ? value : ''));
96
- return Number.isFinite(parsed) ? parsed : null;
97
- }
98
- function normalizeBounceType(value) {
99
- const lowered = String(value != null ? value : '').trim().toLowerCase();
100
- if (lowered === 'permanent') return 'permanent';
101
- if (lowered === 'transient') return 'transient';
102
- return lowered ? 'undetermined' : null;
103
- }
104
- /** The Resend event names we understand, mapped onto ours. */ const RESEND_EVENT_TYPES = {
105
- 'email.sent': 'sent',
106
- 'email.delivered': 'delivered',
107
- 'email.delivery_delayed': 'delayed',
108
- 'email.opened': 'opened',
109
- 'email.clicked': 'clicked',
110
- 'email.bounced': 'bounced',
111
- 'email.complained': 'complained',
112
- 'email.failed': 'failed'
113
- };
114
- /**
115
- * Turns one Resend webhook payload into zero or more of our events — **the
116
- * only function in the tree that knows Resend's wire format.**
117
- *
118
- * One event per recipient, not per message: a send addressed to three people
119
- * produces one webhook, and a staff view keyed on a person has to be able to
120
- * find it under each of them.
121
- *
122
- * Returns an empty array for anything unrecognised — a contact or domain
123
- * event, an inbound `email.received`, a type added after this was written.
124
- * Silence rather than a throw, because a webhook handler that 500s on an
125
- * unfamiliar event teaches the provider to retry it forever.
126
- *
127
- * @param payload The parsed webhook body.
128
- * @param receivedAtMs Fallback timestamp for a payload that carries none.
129
- */ export function normalizeResendDeliveryEvents(payload, receivedAtMs) {
130
- var _event_type, _event_data, _ref, _data_email_id, _ref1, _ref2, _ref3, _eventTimeMs, _data_subject;
131
- var _data_click, _data_open, _data_bounce, _data_bounce1, _data_bounce2, _data_bounce3, _data_bounce4;
132
- const event = payload != null ? payload : {};
133
- const type = RESEND_EVENT_TYPES[String((_event_type = event.type) != null ? _event_type : '')];
134
- if (!type) return [];
135
- const data = (_event_data = event.data) != null ? _event_data : {};
136
- const providerMessageId = String((_ref = (_data_email_id = data.email_id) != null ? _data_email_id : data.id) != null ? _ref : '').trim();
137
- if (!providerMessageId) return [];
138
- const recipients = (Array.isArray(data.to) ? data.to : [
139
- data.to
140
- ]).map((address)=>String(address != null ? address : '').trim().toLowerCase()).filter((address)=>address.includes('@'));
141
- if (!recipients.length) return [];
142
- // The per-state timestamp when the provider gives one, because an open
143
- // three days after the send is the whole point of recording an open.
144
- const at = (_ref1 = (_ref2 = (_ref3 = (_eventTimeMs = eventTimeMs((_data_click = data.click) == null ? void 0 : _data_click.timestamp)) != null ? _eventTimeMs : eventTimeMs((_data_open = data.open) == null ? void 0 : _data_open.timestamp)) != null ? _ref3 : eventTimeMs(event.created_at)) != null ? _ref2 : eventTimeMs(data.created_at)) != null ? _ref1 : receivedAtMs;
145
- const subject = String((_data_subject = data.subject) != null ? _data_subject : '').trim() || null;
146
- const tags = normalizeEventTags(data.tags);
147
- const from = bareSenderAddress(data.from);
148
- // The provider folds a DSN's fields into one sentence; the structured
149
- // ones are read first where a payload carries them.
150
- const bounceText = type === 'bounced' ? readBounceText([
151
- (_data_bounce = data.bounce) == null ? void 0 : _data_bounce.diagnosticCode,
152
- (_data_bounce1 = data.bounce) == null ? void 0 : _data_bounce1.diagnostic_code,
153
- (_data_bounce2 = data.bounce) == null ? void 0 : _data_bounce2.remoteMta,
154
- (_data_bounce3 = data.bounce) == null ? void 0 : _data_bounce3.remote_mta,
155
- (_data_bounce4 = data.bounce) == null ? void 0 : _data_bounce4.message
156
- ].filter((part)=>typeof part === 'string' && part.trim()).join(' ')) : null;
157
- return recipients.map((to)=>{
158
- var _ref, _ref1, _ref2;
159
- var _data_click, _data_bounce, _data_bounce1, _data_failed;
160
- return _extends({
161
- type,
162
- at,
163
- provider: 'resend',
164
- providerMessageId,
165
- to,
166
- subject,
167
- context: tags['context'] || null,
168
- tags,
169
- link: type === 'clicked' ? String((_ref = (_data_click = data.click) == null ? void 0 : _data_click.link) != null ? _ref : '') || null : null,
170
- bounceType: type === 'bounced' ? normalizeBounceType((_data_bounce = data.bounce) == null ? void 0 : _data_bounce.type) : null,
171
- detail: String((_ref1 = (_ref2 = (_data_bounce1 = data.bounce) == null ? void 0 : _data_bounce1.message) != null ? _ref2 : (_data_failed = data.failed) == null ? void 0 : _data_failed.reason) != null ? _ref1 : '').trim() || null
172
- }, from ? {
173
- from
174
- } : {}, (bounceText == null ? void 0 : bounceText.status) ? {
175
- bounceStatus: bounceText.status
176
- } : {}, (bounceText == null ? void 0 : bounceText.remoteMta) ? {
177
- remoteMta: bounceText.remoteMta
178
- } : {});
179
- });
180
- }
181
- /**
182
- * A provider's `last_event` string, mapped onto our lifecycle.
183
- *
184
- * Deliberately the bare state names rather than the `email.*` event names:
185
- * the list endpoint reports `"delivered"`, the webhook reports
186
- * `"email.delivered"`, and they are two different vocabularies for one
187
- * concept. Both are accepted here so a provider that unifies them later
188
- * needs no change.
189
- */ const RESEND_LAST_EVENTS = {
190
- sent: 'sent',
191
- delivered: 'delivered',
192
- delivery_delayed: 'delayed',
193
- opened: 'opened',
194
- clicked: 'clicked',
195
- bounced: 'bounced',
196
- complained: 'complained',
197
- failed: 'failed',
198
- canceled: 'failed',
199
- queued: 'sent',
200
- scheduled: 'sent'
201
- };
202
- /**
203
- * Turns one entry from Resend's `GET /emails` list into zero or more
204
- * snapshots — one per recipient, for the same reason the event adapter fans
205
- * out: the staff view is keyed on a person.
206
- *
207
- * An unrecognised `last_event` falls back to `sent` rather than being
208
- * dropped. The message demonstrably exists and was addressed to somebody, and
209
- * "we sent this and cannot characterise what happened next" is a far more
210
- * useful row than no row — which is the state that sent a staffer to the
211
- * vendor dashboard in the first place.
212
- */ export function normalizeResendSentEmails(raw) {
213
- var _record_id, _record_created_at, _RESEND_LAST_EVENTS_String_trim_toLowerCase, _record_last_event;
214
- const record = raw != null ? raw : {};
215
- const providerMessageId = String((_record_id = record.id) != null ? _record_id : '').trim();
216
- if (!providerMessageId) return [];
217
- const recipients = (Array.isArray(record.to) ? record.to : [
218
- record.to
219
- ]).map((address)=>String(address != null ? address : '').trim().toLowerCase()).filter((address)=>address.includes('@'));
220
- if (!recipients.length) return [];
221
- const parsed = Date.parse(String((_record_created_at = record.created_at) != null ? _record_created_at : ''));
222
- const sentAt = Number.isFinite(parsed) ? parsed : 0;
223
- // A snapshot with no timestamp cannot be ordered, and the log's read drops
224
- // any document missing its sort key — so it is refused rather than written
225
- // somewhere nothing will look for it.
226
- if (!sentAt) return [];
227
- const status = (_RESEND_LAST_EVENTS_String_trim_toLowerCase = RESEND_LAST_EVENTS[String((_record_last_event = record.last_event) != null ? _record_last_event : '').trim().toLowerCase()]) != null ? _RESEND_LAST_EVENTS_String_trim_toLowerCase : 'sent';
228
- return recipients.map((to)=>{
229
- var _record_subject;
230
- return {
231
- provider: 'resend',
232
- providerMessageId,
233
- to,
234
- subject: String((_record_subject = record.subject) != null ? _record_subject : '').trim() || null,
235
- sentAt,
236
- status
237
- };
238
- });
239
- }
240
- /** Resend's list endpoint. Paginates with `after=<id>`; caps at 100. */ export const RESEND_EMAILS_ENDPOINT = 'https://api.resend.com/emails';
241
- /**
242
- * {@link EmailDeliveryHistorySource} for Resend.
243
- *
244
- * Needs a FULL-ACCESS key: a sending-scoped key answers every read on this
245
- * endpoint with `401 restricted_api_key`, which is the correct posture for
246
- * the key that sends mail and the reason this takes its own.
247
- */ export function resendDeliveryHistorySource(apiKey) {
248
- return async ({ cursor, limit } = {})=>{
249
- var _ref;
250
- var _entries_;
251
- const params = new URLSearchParams({
252
- limit: String(Math.min(Math.max(1, limit != null ? limit : 100), 100))
253
- });
254
- if (cursor) params.set('after', cursor);
255
- const response = await fetch(`${RESEND_EMAILS_ENDPOINT}?${params}`, {
256
- headers: {
257
- Authorization: `Bearer ${apiKey}`
258
- }
259
- });
260
- if (!response.ok) {
261
- const detail = await response.text().catch(()=>'');
262
- throw new Error(`email history read failed: HTTP ${response.status} ${detail.slice(0, 200)}`);
263
- }
264
- const body = await response.json();
265
- const entries = Array.isArray(body == null ? void 0 : body.data) ? body.data : [];
266
- const snapshots = entries.flatMap((entry)=>normalizeResendSentEmails(entry));
267
- // The cursor is the LAST RAW entry's id, not the last snapshot's: a page
268
- // whose final entry fanned out to zero snapshots (no recipient, no
269
- // timestamp) would otherwise rewind the cursor to an earlier message and
270
- // loop over the same page forever.
271
- const lastId = String((_ref = (_entries_ = entries[entries.length - 1]) == null ? void 0 : _entries_.id) != null ? _ref : '').trim();
272
- return {
273
- snapshots,
274
- nextCursor: (body == null ? void 0 : body.has_more) && lastId ? lastId : null
275
- };
276
- };
277
- }
278
- function addressList(raw) {
279
- return (Array.isArray(raw) ? raw : raw == null ? [] : [
280
- raw
281
- ]).map((address)=>String(address != null ? address : '').trim()).filter(Boolean);
282
- }
283
- /** Resend's `GET /emails/:id` payload, in our vocabulary. */ export function normalizeResendMessage(raw) {
284
- var _record_id, _record_created_at, _record_from, _record_subject, _RESEND_LAST_EVENTS_String_trim_toLowerCase, _record_last_event;
285
- const record = raw != null ? raw : {};
286
- const providerMessageId = String((_record_id = record.id) != null ? _record_id : '').trim();
287
- if (!providerMessageId) return null;
288
- const parsed = Date.parse(String((_record_created_at = record.created_at) != null ? _record_created_at : ''));
289
- return {
290
- provider: 'resend',
291
- providerMessageId,
292
- to: addressList(record.to),
293
- cc: addressList(record.cc),
294
- bcc: addressList(record.bcc),
295
- from: String((_record_from = record.from) != null ? _record_from : '').trim() || null,
296
- replyTo: addressList(record.reply_to).length ? addressList(record.reply_to) : null,
297
- subject: String((_record_subject = record.subject) != null ? _record_subject : '').trim() || null,
298
- // Empty string is NOT null here, and the difference is the point: a
299
- // message that went out text-only really does have an empty HTML part,
300
- // and a reader has to be able to tell that from "we could not fetch it".
301
- html: typeof record.html === 'string' ? record.html : null,
302
- text: typeof record.text === 'string' ? record.text : null,
303
- sentAt: Number.isFinite(parsed) ? parsed : null,
304
- status: (_RESEND_LAST_EVENTS_String_trim_toLowerCase = RESEND_LAST_EVENTS[String((_record_last_event = record.last_event) != null ? _record_last_event : '').trim().toLowerCase()]) != null ? _RESEND_LAST_EVENTS_String_trim_toLowerCase : null
305
- };
306
- }
307
- /** Resend's single-message endpoint. Needs the same full-access key. */ export function resendDeliveryMessageSource(apiKey) {
308
- return async (providerMessageId)=>{
309
- const response = await fetch(`${RESEND_EMAILS_ENDPOINT}/${encodeURIComponent(providerMessageId)}`, {
310
- headers: {
311
- Authorization: `Bearer ${apiKey}`
312
- }
313
- });
314
- // A message the provider has aged out is a 404, and that is an ANSWER —
315
- // "we know this was sent and the body is gone" — not a failure to report
316
- // as an error the staffer must act on.
317
- if (response.status === 404) return null;
318
- if (!response.ok) {
319
- const detail = await response.text().catch(()=>'');
320
- throw new Error(`message read failed: HTTP ${response.status} ${detail.slice(0, 200)}`);
321
- }
322
- return normalizeResendMessage(await response.json());
323
- };
324
- }
325
96
 
326
97
  //# sourceMappingURL=email-delivery-events.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/shared/util/email/src/lib/email-delivery-events.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * WHAT HAPPENED TO A MESSAGE, IN OUR OWN VOCABULARY.\n *\n * ## The seam\n *\n * A staff answer to \"did they get the invite, and did they open it?\" must not\n * be a question about Resend. Two things follow from that, and this module is\n * both of them:\n *\n * 1. **The stored shape is ours.** Nothing downstream — the delivery log, the\n * staff card, a future export — reads a provider's field names or its event\n * strings. Swapping the sender changes exactly one function in this file\n * and nothing else in the tree.\n * 2. **The history is ours.** The log is written into our own Firestore and\n * read from there, never from the provider on render. A provider's list\n * endpoint is a different shape per vendor, has its own retention window,\n * and disappears entirely with the account; a record we keep survives the\n * migration that the seam exists to make possible.\n *\n * That is a rule about the READ PATH, not a rule against ever reading the\n * provider. The event feed only knows mail sent after it was connected, so\n * a log fed by events alone is empty for all existing history — which is\n * precisely the mail a support question is about. The second half of this\n * module (see THE READ SIDE OF THE SEAM below) imports that history\n * through the same neutral vocabulary, once, into the same store.\n *\n * ## Pure on purpose\n *\n * No Firestore and no admin SDK. `system-email-catalog` is imported by console\n * CLIENT components through this library's barrel, so anything reachable from\n * it that touched `firebase-admin` would drag the admin SDK into a browser\n * bundle. Normalisation is a pure function of a payload; the writing lives in\n * `@aglyn/tenant-data-admin/server/email-delivery-log`.\n *\n * The one `fetch` is `resendDeliveryHistorySource`, which is a function that\n * must be CALLED with a key to do anything — it holds no module state and is\n * unreachable from a client component, unlike an admin-SDK import, which\n * executes on load.\n */\n\nimport { readBounceText } from './mail-bounce'\n\n/**\n * The lifecycle of one message, in the order it normally happens.\n *\n * Chosen to be the intersection every ESP can report rather than the union of\n * what any one of them does: a vendor with no equivalent for a state simply\n * never produces it, and a vendor with a richer taxonomy folds into the\n * nearest of these rather than widening the type. `delayed` is retryable and\n * `failed` is not, which is the distinction a staffer actually needs.\n */\nexport type EmailDeliveryEventType =\n | 'sent'\n | 'delivered'\n | 'delayed'\n | 'opened'\n | 'clicked'\n | 'bounced'\n | 'complained'\n | 'failed'\n\n/** Lifecycle states ordered worst-last, for {@link worstDeliveryStatus}. */\nconst STATUS_SEVERITY: Record<EmailDeliveryEventType, number> = {\n sent: 1,\n delivered: 2,\n opened: 3,\n clicked: 4,\n delayed: 5,\n complained: 6,\n bounced: 7,\n failed: 8,\n}\n\n/**\n * One normalized delivery event.\n *\n * `at` is epoch milliseconds rather than a Firestore timestamp so this type\n * stays usable in a browser, in a test, and in whatever writes it next.\n */\nexport interface EmailDeliveryEvent {\n type: EmailDeliveryEventType\n /** When the PROVIDER says it happened, falling back to receipt time. */\n at: number\n /** Slug of the sending provider, e.g. `'resend'`. */\n provider: string\n /** The provider's id for the message. Our per-message document key. */\n providerMessageId: string\n /** Recipient, lowercased. One address per record even on a multi-recipient send. */\n to: string\n subject: string | null\n /**\n * The sender label `sendEmail` stamps on every message (`'invite'`,\n * `'password-reset'`, `'campaign'`, …). This is what makes the staff view\n * legible: without it a row says only that *an* email was sent.\n */\n context: string | null\n /** Everything else the send was tagged with, e.g. `hostId`, `campaignId`. */\n tags: Record<string, string>\n /** `clicked` only: the destination the recipient followed. */\n link: string | null\n /**\n * `bounced` only: whether the mailbox is gone (`permanent`) or the failure\n * was temporary. Lowercased, because providers disagree on capitalisation\n * and a staff filter must not depend on which one is in use.\n */\n bounceType: 'permanent' | 'transient' | 'undetermined' | null\n /** Provider-supplied explanation, for the states that carry one. */\n detail: string | null\n /**\n * The bare sender address, lowercased: the domain it names is the sending\n * domain a gateway's verdict is filed against (AGL-3328). Absent from\n * events normalized before it existed, and `null` when the provider sent\n * none.\n */\n from?: string | null\n /**\n * `bounced` only: the enhanced status code (`5.7.1`) and the receiving\n * server the provider's bounce message names, read by `readBounceText` —\n * what a Gmail DSN hands over as `Status` and `Remote-MTA` (AGL-3328).\n */\n bounceStatus?: string | null\n remoteMta?: string | null\n}\n\n/** The bare address of a `From:` value (`\"Acme\" <hi@acme.com>` → `hi@acme.com`), lowercased. */\nexport function bareSenderAddress(value: unknown): string | null {\n const raw = String(value ?? '').trim()\n const angle = raw.match(/<([^>]+)>/)\n const address = (angle ? angle[1] : raw).trim().toLowerCase()\n return /^[^\\s@<>]+@[^\\s@<>]+\\.[^\\s@<>]+$/.test(address) ? address : null\n}\n\n/** The later of two statuses on the lifecycle, worst winning a tie. */\nexport function worstDeliveryStatus(\n current: EmailDeliveryEventType | null | undefined,\n next: EmailDeliveryEventType,\n): EmailDeliveryEventType {\n if (!current) return next\n return STATUS_SEVERITY[next] >= STATUS_SEVERITY[current] ? next : current\n}\n\n/** Tags arrive as an array of `{name, value}` or a plain map — accept both. */\nexport function normalizeEventTags(raw: unknown): Record<string, string> {\n if (Array.isArray(raw)) {\n const map: Record<string, string> = {}\n for (const tag of raw) {\n if (tag?.name) map[String(tag.name)] = String(tag.value ?? '')\n }\n return map\n }\n if (raw && typeof raw === 'object') {\n return Object.fromEntries(\n Object.entries(raw as Record<string, unknown>).map(([key, value]) => [\n key,\n String(value ?? ''),\n ]),\n )\n }\n return {}\n}\n\n/** Epoch ms from an ISO string or a number, or `null` when unreadable. */\nfunction eventTimeMs(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n const parsed = Date.parse(String(value ?? ''))\n return Number.isFinite(parsed) ? parsed : null\n}\n\nfunction normalizeBounceType(\n value: unknown,\n): EmailDeliveryEvent['bounceType'] {\n const lowered = String(value ?? '')\n .trim()\n .toLowerCase()\n if (lowered === 'permanent') return 'permanent'\n if (lowered === 'transient') return 'transient'\n return lowered ? 'undetermined' : null\n}\n\n/** The Resend event names we understand, mapped onto ours. */\nconst RESEND_EVENT_TYPES: Record<string, EmailDeliveryEventType> = {\n 'email.sent': 'sent',\n 'email.delivered': 'delivered',\n 'email.delivery_delayed': 'delayed',\n 'email.opened': 'opened',\n 'email.clicked': 'clicked',\n 'email.bounced': 'bounced',\n 'email.complained': 'complained',\n 'email.failed': 'failed',\n}\n\n/**\n * Turns one Resend webhook payload into zero or more of our events — **the\n * only function in the tree that knows Resend's wire format.**\n *\n * One event per recipient, not per message: a send addressed to three people\n * produces one webhook, and a staff view keyed on a person has to be able to\n * find it under each of them.\n *\n * Returns an empty array for anything unrecognised — a contact or domain\n * event, an inbound `email.received`, a type added after this was written.\n * Silence rather than a throw, because a webhook handler that 500s on an\n * unfamiliar event teaches the provider to retry it forever.\n *\n * @param payload The parsed webhook body.\n * @param receivedAtMs Fallback timestamp for a payload that carries none.\n */\nexport function normalizeResendDeliveryEvents(\n payload: unknown,\n receivedAtMs: number,\n): EmailDeliveryEvent[] {\n const event = (payload ?? {}) as Record<string, any>\n const type = RESEND_EVENT_TYPES[String(event.type ?? '')]\n if (!type) return []\n\n const data = (event.data ?? {}) as Record<string, any>\n const providerMessageId = String(data.email_id ?? data.id ?? '').trim()\n if (!providerMessageId) return []\n\n const recipients = (Array.isArray(data.to) ? data.to : [data.to])\n .map((address: unknown) => String(address ?? '').trim().toLowerCase())\n .filter((address: string) => address.includes('@'))\n if (!recipients.length) return []\n\n // The per-state timestamp when the provider gives one, because an open\n // three days after the send is the whole point of recording an open.\n const at =\n eventTimeMs(data.click?.timestamp) ??\n eventTimeMs(data.open?.timestamp) ??\n eventTimeMs(event.created_at) ??\n eventTimeMs(data.created_at) ??\n receivedAtMs\n\n const subject = String(data.subject ?? '').trim() || null\n const tags = normalizeEventTags(data.tags)\n const from = bareSenderAddress(data.from)\n // The provider folds a DSN's fields into one sentence; the structured\n // ones are read first where a payload carries them.\n const bounceText =\n type === 'bounced'\n ? readBounceText(\n [data.bounce?.diagnosticCode, data.bounce?.diagnostic_code, data.bounce?.remoteMta, data.bounce?.remote_mta, data.bounce?.message]\n .filter((part: unknown) => typeof part === 'string' && part.trim())\n .join(' '),\n )\n : null\n\n return recipients.map((to: string) => ({\n type,\n at,\n provider: 'resend',\n providerMessageId,\n to,\n subject,\n context: tags['context'] || null,\n tags,\n link: type === 'clicked' ? String(data.click?.link ?? '') || null : null,\n bounceType: type === 'bounced' ? normalizeBounceType(data.bounce?.type) : null,\n detail:\n String(data.bounce?.message ?? data.failed?.reason ?? '').trim() || null,\n ...(from ? { from } : {}),\n ...(bounceText?.status ? { bounceStatus: bounceText.status } : {}),\n ...(bounceText?.remoteMta ? { remoteMta: bounceText.remoteMta } : {}),\n }))\n}\n\n/*==========================================\n * THE READ SIDE OF THE SEAM.\n *\n * The event feed above only ever knows about mail sent AFTER it was\n * connected. That is correct for the steady state and useless for the\n * question the staff card exists to answer, which is asked about mail that\n * has already gone out — so a delivery log fed only by events is empty\n * exactly when somebody needs it.\n *\n * A provider also holds the history, and reading it is not lock-in as long as\n * it happens through an interface. {@link EmailDeliverySnapshot} is that\n * interface: one message as the provider currently sees it, in our\n * vocabulary. `normalizeResendSentEmails` is the Resend implementation and\n * the second (and last) function in the tree that knows Resend's wire format.\n *\n * WHAT A SNAPSHOT DELIBERATELY DOES NOT CARRY\n *\n * Open and click COUNTS. Resend's list endpoint reports a single\n * `last_event` per message and no engagement detail, so a snapshot can say\n * \"this was opened at least once\" and can never say \"three times\". The\n * writer therefore treats a snapshot as a floor, never as truth that\n * overwrites what the event feed recorded — see `recordEmailDeliverySnapshot`.\n *=========================================*/\n\n/** One message as the provider currently reports it, in our vocabulary. */\nexport interface EmailDeliverySnapshot {\n provider: string\n providerMessageId: string\n to: string\n subject: string | null\n /** Epoch ms the provider says the message was created. */\n sentAt: number\n /** Furthest state the provider reports. Never richer than the event feed. */\n status: EmailDeliveryEventType\n}\n\n/**\n * A provider's `last_event` string, mapped onto our lifecycle.\n *\n * Deliberately the bare state names rather than the `email.*` event names:\n * the list endpoint reports `\"delivered\"`, the webhook reports\n * `\"email.delivered\"`, and they are two different vocabularies for one\n * concept. Both are accepted here so a provider that unifies them later\n * needs no change.\n */\nconst RESEND_LAST_EVENTS: Record<string, EmailDeliveryEventType> = {\n sent: 'sent',\n delivered: 'delivered',\n delivery_delayed: 'delayed',\n opened: 'opened',\n clicked: 'clicked',\n bounced: 'bounced',\n complained: 'complained',\n failed: 'failed',\n canceled: 'failed',\n queued: 'sent',\n scheduled: 'sent',\n}\n\n/**\n * Turns one entry from Resend's `GET /emails` list into zero or more\n * snapshots — one per recipient, for the same reason the event adapter fans\n * out: the staff view is keyed on a person.\n *\n * An unrecognised `last_event` falls back to `sent` rather than being\n * dropped. The message demonstrably exists and was addressed to somebody, and\n * \"we sent this and cannot characterise what happened next\" is a far more\n * useful row than no row — which is the state that sent a staffer to the\n * vendor dashboard in the first place.\n */\nexport function normalizeResendSentEmails(\n raw: unknown,\n): EmailDeliverySnapshot[] {\n const record = (raw ?? {}) as Record<string, any>\n const providerMessageId = String(record.id ?? '').trim()\n if (!providerMessageId) return []\n\n const recipients = (Array.isArray(record.to) ? record.to : [record.to])\n .map((address: unknown) => String(address ?? '').trim().toLowerCase())\n .filter((address: string) => address.includes('@'))\n if (!recipients.length) return []\n\n const parsed = Date.parse(String(record.created_at ?? ''))\n const sentAt = Number.isFinite(parsed) ? parsed : 0\n // A snapshot with no timestamp cannot be ordered, and the log's read drops\n // any document missing its sort key — so it is refused rather than written\n // somewhere nothing will look for it.\n if (!sentAt) return []\n\n const status =\n RESEND_LAST_EVENTS[\n String(record.last_event ?? '')\n .trim()\n .toLowerCase()\n ] ?? 'sent'\n\n return recipients.map((to: string) => ({\n provider: 'resend',\n providerMessageId,\n to,\n subject: String(record.subject ?? '').trim() || null,\n sentAt,\n status,\n }))\n}\n\n/** One page of provider history, in our vocabulary. */\nexport interface EmailDeliveryHistoryPage {\n snapshots: EmailDeliverySnapshot[]\n /** Cursor for the next page, or null at the end. */\n nextCursor: string | null\n}\n\n/**\n * Reads one page of already-sent mail from a provider.\n *\n * The shape a second provider would implement. Cursor-based rather than\n * offset- or date-based because that is the lowest common denominator, and\n * NOT filtered by recipient: Resend's list endpoint has no recipient\n * parameter, so filtering is the caller's job and the import is a sweep\n * rather than a per-person lookup. That is the right shape regardless — a\n * staff page must not fan out to a third party on render.\n */\nexport type EmailDeliveryHistorySource = (options: {\n cursor?: string | null\n limit?: number\n}) => Promise<EmailDeliveryHistoryPage>\n\n/** Resend's list endpoint. Paginates with `after=<id>`; caps at 100. */\nexport const RESEND_EMAILS_ENDPOINT = 'https://api.resend.com/emails'\n\n/**\n * {@link EmailDeliveryHistorySource} for Resend.\n *\n * Needs a FULL-ACCESS key: a sending-scoped key answers every read on this\n * endpoint with `401 restricted_api_key`, which is the correct posture for\n * the key that sends mail and the reason this takes its own.\n */\nexport function resendDeliveryHistorySource(\n apiKey: string,\n): EmailDeliveryHistorySource {\n return async ({ cursor, limit } = {}) => {\n const params = new URLSearchParams({\n limit: String(Math.min(Math.max(1, limit ?? 100), 100)),\n })\n if (cursor) params.set('after', cursor)\n const response = await fetch(`${RESEND_EMAILS_ENDPOINT}?${params}`, {\n headers: { Authorization: `Bearer ${apiKey}` },\n })\n if (!response.ok) {\n const detail = await response.text().catch(() => '')\n throw new Error(\n `email history read failed: HTTP ${response.status} ${detail.slice(0, 200)}`,\n )\n }\n const body = (await response.json()) as {\n data?: unknown[]\n has_more?: boolean\n }\n const entries = Array.isArray(body?.data) ? body.data : []\n const snapshots = entries.flatMap((entry) => normalizeResendSentEmails(entry))\n // The cursor is the LAST RAW entry's id, not the last snapshot's: a page\n // whose final entry fanned out to zero snapshots (no recipient, no\n // timestamp) would otherwise rewind the cursor to an earlier message and\n // loop over the same page forever.\n const lastId = String(\n (entries[entries.length - 1] as { id?: unknown })?.id ?? '',\n ).trim()\n return {\n snapshots,\n nextCursor: body?.has_more && lastId ? lastId : null,\n }\n }\n}\n\n/*==========================================\n * ONE MESSAGE, RENDERED.\n *\n * The log records what HAPPENED to a message; it does not keep the message.\n * Storing every body would put an unbounded copy of every email we have ever\n * sent — including reset links and receipts — into our own database, to\n * duplicate something the provider already holds.\n *\n * So a body is fetched when a staffer explicitly opens one row. That is a\n * deliberate single lookup, not the per-render fan-out the read path refuses:\n * one message, on one click, by id.\n *=========================================*/\n\n/** One message's content and envelope, in our vocabulary. */\nexport interface EmailDeliveryMessage {\n provider: string\n providerMessageId: string\n to: string[]\n cc: string[]\n bcc: string[]\n from: string | null\n replyTo: string[] | null\n subject: string | null\n /** The HTML part, or null when the message was sent as text only. */\n html: string | null\n /** The plain-text part, or null. */\n text: string | null\n sentAt: number | null\n status: EmailDeliveryEventType | null\n}\n\n/** A single message by id. The shape a second provider would implement. */\nexport type EmailDeliveryMessageSource = (\n providerMessageId: string,\n) => Promise<EmailDeliveryMessage | null>\n\nfunction addressList(raw: unknown): string[] {\n return (Array.isArray(raw) ? raw : raw == null ? [] : [raw])\n .map((address) => String(address ?? '').trim())\n .filter(Boolean)\n}\n\n/** Resend's `GET /emails/:id` payload, in our vocabulary. */\nexport function normalizeResendMessage(raw: unknown): EmailDeliveryMessage | null {\n const record = (raw ?? {}) as Record<string, any>\n const providerMessageId = String(record.id ?? '').trim()\n if (!providerMessageId) return null\n const parsed = Date.parse(String(record.created_at ?? ''))\n return {\n provider: 'resend',\n providerMessageId,\n to: addressList(record.to),\n cc: addressList(record.cc),\n bcc: addressList(record.bcc),\n from: String(record.from ?? '').trim() || null,\n replyTo: addressList(record.reply_to).length\n ? addressList(record.reply_to)\n : null,\n subject: String(record.subject ?? '').trim() || null,\n // Empty string is NOT null here, and the difference is the point: a\n // message that went out text-only really does have an empty HTML part,\n // and a reader has to be able to tell that from \"we could not fetch it\".\n html: typeof record.html === 'string' ? record.html : null,\n text: typeof record.text === 'string' ? record.text : null,\n sentAt: Number.isFinite(parsed) ? parsed : null,\n status:\n RESEND_LAST_EVENTS[\n String(record.last_event ?? '')\n .trim()\n .toLowerCase()\n ] ?? null,\n }\n}\n\n/** Resend's single-message endpoint. Needs the same full-access key. */\nexport function resendDeliveryMessageSource(\n apiKey: string,\n): EmailDeliveryMessageSource {\n return async (providerMessageId: string) => {\n const response = await fetch(\n `${RESEND_EMAILS_ENDPOINT}/${encodeURIComponent(providerMessageId)}`,\n { headers: { Authorization: `Bearer ${apiKey}` } },\n )\n // A message the provider has aged out is a 404, and that is an ANSWER —\n // \"we know this was sent and the body is gone\" — not a failure to report\n // as an error the staffer must act on.\n if (response.status === 404) return null\n if (!response.ok) {\n const detail = await response.text().catch(() => '')\n throw new Error(\n `message read failed: HTTP ${response.status} ${detail.slice(0, 200)}`,\n )\n }\n return normalizeResendMessage(await response.json())\n }\n}\n"],"names":["readBounceText","STATUS_SEVERITY","sent","delivered","opened","clicked","delayed","complained","bounced","failed","bareSenderAddress","value","raw","String","trim","angle","match","address","toLowerCase","test","worstDeliveryStatus","current","next","normalizeEventTags","Array","isArray","map","tag","name","Object","fromEntries","entries","key","eventTimeMs","Number","isFinite","parsed","Date","parse","normalizeBounceType","lowered","RESEND_EVENT_TYPES","normalizeResendDeliveryEvents","payload","receivedAtMs","event","data","type","providerMessageId","email_id","id","recipients","to","filter","includes","length","at","click","timestamp","open","created_at","subject","tags","from","bounceText","bounce","diagnosticCode","diagnostic_code","remoteMta","remote_mta","message","part","join","provider","context","link","bounceType","detail","reason","status","bounceStatus","RESEND_LAST_EVENTS","delivery_delayed","canceled","queued","scheduled","normalizeResendSentEmails","record","sentAt","last_event","RESEND_EMAILS_ENDPOINT","resendDeliveryHistorySource","apiKey","cursor","limit","params","URLSearchParams","Math","min","max","set","response","fetch","headers","Authorization","ok","text","catch","Error","slice","body","json","snapshots","flatMap","entry","lastId","nextCursor","has_more","addressList","Boolean","normalizeResendMessage","cc","bcc","replyTo","reply_to","html","resendDeliveryMessageSource","encodeURIComponent"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCC,GAED,SAASA,cAAc,QAAQ,mBAAe;AAqB9C,0EAA0E,GAC1E,MAAMC,kBAA0D;IAC9DC,MAAM;IACNC,WAAW;IACXC,QAAQ;IACRC,SAAS;IACTC,SAAS;IACTC,YAAY;IACZC,SAAS;IACTC,QAAQ;AACV;AAqDA,8FAA8F,GAC9F,OAAO,SAASC,kBAAkBC,KAAc;IAC9C,MAAMC,MAAMC,OAAOF,gBAAAA,QAAS,IAAIG,IAAI;IACpC,MAAMC,QAAQH,IAAII,KAAK,CAAC;IACxB,MAAMC,UAAU,AAACF,CAAAA,QAAQA,KAAK,CAAC,EAAE,GAAGH,GAAE,EAAGE,IAAI,GAAGI,WAAW;IAC3D,OAAO,mCAAmCC,IAAI,CAACF,WAAWA,UAAU;AACtE;AAEA,qEAAqE,GACrE,OAAO,SAASG,oBACdC,OAAkD,EAClDC,IAA4B;IAE5B,IAAI,CAACD,SAAS,OAAOC;IACrB,OAAOrB,eAAe,CAACqB,KAAK,IAAIrB,eAAe,CAACoB,QAAQ,GAAGC,OAAOD;AACpE;AAEA,6EAA6E,GAC7E,OAAO,SAASE,mBAAmBX,GAAY;IAC7C,IAAIY,MAAMC,OAAO,CAACb,MAAM;QACtB,MAAMc,MAA8B,CAAC;QACrC,KAAK,MAAMC,OAAOf,IAAK;gBACyBe;YAA9C,IAAIA,uBAAAA,IAAKC,IAAI,EAAEF,GAAG,CAACb,OAAOc,IAAIC,IAAI,EAAE,GAAGf,QAAOc,aAAAA,IAAIhB,KAAK,YAATgB,aAAa;QAC7D;QACA,OAAOD;IACT;IACA,IAAId,OAAO,OAAOA,QAAQ,UAAU;QAClC,OAAOiB,OAAOC,WAAW,CACvBD,OAAOE,OAAO,CAACnB,KA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eAAe,CAAC,OAAO,EAAEZ,QAAQ;YAAC;QAAE;QAEnD,wEAAwE;QACxE,yEAAyE;QACzE,uCAAuC;QACvC,IAAIS,SAAStB,MAAM,KAAK,KAAK,OAAO;QACpC,IAAI,CAACsB,SAASI,EAAE,EAAE;YAChB,MAAM5B,SAAS,MAAMwB,SAASK,IAAI,GAAGC,KAAK,CAAC,IAAM;YACjD,MAAM,IAAIC,MACR,CAAC,0BAA0B,EAAEP,SAAStB,MAAM,CAAC,CAAC,EAAEF,OAAOgC,KAAK,CAAC,GAAG,MAAM;QAE1E;QACA,OAAOW,uBAAuB,MAAMnB,SAASU,IAAI;IACnD;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/shared/util/email/src/lib/email-delivery-events.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * WHAT HAPPENED TO A MESSAGE, IN OUR OWN VOCABULARY.\n *\n * ## The seam\n *\n * A staff answer to \"did they get the invite, and did they open it?\" must not\n * be a question about one sending vendor. Two things follow from that, and\n * this module is both of them:\n *\n * 1. **The stored shape is ours.** Nothing downstream — the delivery log, the\n * staff card, a future export — reads a provider's field names or its event\n * strings. A provider turns its own wire format into these types (its\n * `deliveryEvents` and `reads`, see `mail-provider.ts`), and swapping the\n * sender changes that provider and nothing else in the tree.\n * 2. **The history is ours.** The log is written into our own Firestore and\n * read from there, never from the provider on render. A provider's list\n * endpoint is a different shape per vendor, has its own retention window,\n * and disappears entirely with the account; a record we keep survives the\n * migration that the seam exists to make possible.\n *\n * That is a rule about the READ PATH, not a rule against ever reading the\n * provider. The event feed only knows mail sent after it was connected, so\n * a log fed by events alone is empty for all existing history — which is\n * precisely the mail a support question is about. The second half of this\n * module (see THE READ SIDE OF THE SEAM below) is the vocabulary that\n * history is imported through, once, into the same store.\n *\n * ## Pure on purpose\n *\n * No Firestore and no admin SDK. `system-email-catalog` is imported by console\n * CLIENT components through this library's barrel, so anything reachable from\n * it that touched `firebase-admin` would drag the admin SDK into a browser\n * bundle. Normalisation is a pure function of a payload; the writing lives in\n * `@aglyn/tenant-data-admin/server/email-delivery-log`, and the reading\n * of a provider's payloads in that provider.\n */\n\n/**\n * The lifecycle of one message, in the order it normally happens.\n *\n * Chosen to be the intersection every ESP can report rather than the union of\n * what any one of them does: a vendor with no equivalent for a state simply\n * never produces it, and a vendor with a richer taxonomy folds into the\n * nearest of these rather than widening the type. `delayed` is retryable and\n * `failed` is not, which is the distinction a staffer actually needs.\n */\nexport type EmailDeliveryEventType =\n | 'sent'\n | 'delivered'\n | 'delayed'\n | 'opened'\n | 'clicked'\n | 'bounced'\n | 'complained'\n | 'failed'\n\n/** Lifecycle states ordered worst-last, for {@link worstDeliveryStatus}. */\nconst STATUS_SEVERITY: Record<EmailDeliveryEventType, number> = {\n sent: 1,\n delivered: 2,\n opened: 3,\n clicked: 4,\n delayed: 5,\n complained: 6,\n bounced: 7,\n failed: 8,\n}\n\n/**\n * One normalized delivery event.\n *\n * `at` is epoch milliseconds rather than a Firestore timestamp so this type\n * stays usable in a browser, in a test, and in whatever writes it next.\n */\nexport interface EmailDeliveryEvent {\n type: EmailDeliveryEventType\n /** When the PROVIDER says it happened, falling back to receipt time. */\n at: number\n /** Slug of the sending provider — the `id` of the provider that carried it. */\n provider: string\n /** The provider's id for the message. Our per-message document key. */\n providerMessageId: string\n /** Recipient, lowercased. One address per record even on a multi-recipient send. */\n to: string\n subject: string | null\n /**\n * The sender label `sendEmail` stamps on every message (`'invite'`,\n * `'password-reset'`, `'campaign'`, …). This is what makes the staff view\n * legible: without it a row says only that *an* email was sent.\n */\n context: string | null\n /** Everything else the send was tagged with, e.g. `hostId`, `campaignId`. */\n tags: Record<string, string>\n /** `clicked` only: the destination the recipient followed. */\n link: string | null\n /**\n * `bounced` only: whether the mailbox is gone (`permanent`) or the failure\n * was temporary. Lowercased, because providers disagree on capitalisation\n * and a staff filter must not depend on which one is in use.\n */\n bounceType: 'permanent' | 'transient' | 'undetermined' | null\n /** Provider-supplied explanation, for the states that carry one. */\n detail: string | null\n /**\n * The bare sender address, lowercased: the domain it names is the sending\n * domain a gateway's verdict is filed against (AGL-3328). Absent from\n * events normalized before it existed, and `null` when the provider sent\n * none.\n */\n from?: string | null\n /**\n * `bounced` only: the enhanced status code (`5.7.1`) and the receiving\n * server the provider's bounce message names, read by `readBounceText` —\n * what a Gmail DSN hands over as `Status` and `Remote-MTA` (AGL-3328).\n */\n bounceStatus?: string | null\n remoteMta?: string | null\n}\n\n/** The bare address of a `From:` value (`\"Acme\" <hi@acme.com>` → `hi@acme.com`), lowercased. */\nexport function bareSenderAddress(value: unknown): string | null {\n const raw = String(value ?? '').trim()\n const angle = raw.match(/<([^>]+)>/)\n const address = (angle ? angle[1] : raw).trim().toLowerCase()\n return /^[^\\s@<>]+@[^\\s@<>]+\\.[^\\s@<>]+$/.test(address) ? address : null\n}\n\n/** The later of two statuses on the lifecycle, worst winning a tie. */\nexport function worstDeliveryStatus(\n current: EmailDeliveryEventType | null | undefined,\n next: EmailDeliveryEventType,\n): EmailDeliveryEventType {\n if (!current) return next\n return STATUS_SEVERITY[next] >= STATUS_SEVERITY[current] ? next : current\n}\n\n/** Tags arrive as an array of `{name, value}` or a plain map — accept both. */\nexport function normalizeEventTags(raw: unknown): Record<string, string> {\n if (Array.isArray(raw)) {\n const map: Record<string, string> = {}\n for (const tag of raw) {\n if (tag?.name) map[String(tag.name)] = String(tag.value ?? '')\n }\n return map\n }\n if (raw && typeof raw === 'object') {\n return Object.fromEntries(\n Object.entries(raw as Record<string, unknown>).map(([key, value]) => [\n key,\n String(value ?? ''),\n ]),\n )\n }\n return {}\n}\n\n/*==========================================\n * THE READ SIDE OF THE SEAM.\n *\n * The event feed above only ever knows about mail sent AFTER it was\n * connected. That is correct for the steady state and useless for the\n * question the staff card exists to answer, which is asked about mail that\n * has already gone out — so a delivery log fed only by events is empty\n * exactly when somebody needs it.\n *\n * A provider also holds the history, and reading it is not lock-in as long as\n * it happens through an interface. {@link EmailDeliverySnapshot} is that\n * interface: one message as the provider currently sees it, in our\n * vocabulary, read through the provider's `reads.history`.\n *\n * WHAT A SNAPSHOT DELIBERATELY DOES NOT CARRY\n *\n * Open and click COUNTS. A provider's list typically reports one latest\n * state per message and no engagement detail, so a snapshot can say \"this\n * was opened at least once\" and can never say \"three times\". The writer\n * therefore treats a snapshot as a floor, never as truth that overwrites\n * what the event feed recorded — see `recordEmailDeliverySnapshot`.\n *=========================================*/\n\n/** One message as the provider currently reports it, in our vocabulary. */\nexport interface EmailDeliverySnapshot {\n provider: string\n providerMessageId: string\n to: string\n subject: string | null\n /** Epoch ms the provider says the message was created. */\n sentAt: number\n /** Furthest state the provider reports. Never richer than the event feed. */\n status: EmailDeliveryEventType\n}\n\n/** One page of provider history, in our vocabulary. */\nexport interface EmailDeliveryHistoryPage {\n snapshots: EmailDeliverySnapshot[]\n /** Cursor for the next page, or null at the end. */\n nextCursor: string | null\n}\n\n/**\n * Reads one page of already-sent mail from a provider.\n *\n * The shape a second provider would implement. Cursor-based rather than\n * offset- or date-based because that is the lowest common denominator, and\n * NOT filtered by recipient: a provider's list endpoint need not take one,\n * so filtering is the caller's job and the import is a sweep rather than a\n * per-person lookup. That is the right shape regardless — a staff page must\n * not fan out to a third party on render.\n */\nexport type EmailDeliveryHistorySource = (options: {\n cursor?: string | null\n limit?: number\n}) => Promise<EmailDeliveryHistoryPage>\n\n/*==========================================\n * ONE MESSAGE, RENDERED.\n *\n * The log records what HAPPENED to a message; it does not keep the message.\n * Storing every body would put an unbounded copy of every email we have ever\n * sent — including reset links and receipts — into our own database, to\n * duplicate something the provider already holds.\n *\n * So a body is fetched when a staffer explicitly opens one row. That is a\n * deliberate single lookup, not the per-render fan-out the read path refuses:\n * one message, on one click, by id.\n *=========================================*/\n\n/** One message's content and envelope, in our vocabulary. */\nexport interface EmailDeliveryMessage {\n provider: string\n providerMessageId: string\n to: string[]\n cc: string[]\n bcc: string[]\n from: string | null\n replyTo: string[] | null\n subject: string | null\n /** The HTML part, or null when the message was sent as text only. */\n html: string | null\n /** The plain-text part, or null. */\n text: string | null\n sentAt: number | null\n status: EmailDeliveryEventType | null\n}\n\n/** A single message by id. The shape a second provider would implement. */\nexport type EmailDeliveryMessageSource = (\n providerMessageId: string,\n) => Promise<EmailDeliveryMessage | null>\n"],"names":["STATUS_SEVERITY","sent","delivered","opened","clicked","delayed","complained","bounced","failed","bareSenderAddress","value","raw","String","trim","angle","match","address","toLowerCase","test","worstDeliveryStatus","current","next","normalizeEventTags","Array","isArray","map","tag","name","Object","fromEntries","entries","key"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCC,GAED;;;;;;;;CAQC,GAWD,0EAA0E,GAC1E,MAAMA,kBAA0D;IAC9DC,MAAM;IACNC,WAAW;IACXC,QAAQ;IACRC,SAAS;IACTC,SAAS;IACTC,YAAY;IACZC,SAAS;IACTC,QAAQ;AACV;AAqDA,8FAA8F,GAC9F,OAAO,SAASC,kBAAkBC,KAAc;IAC9C,MAAMC,MAAMC,OAAOF,gBAAAA,QAAS,IAAIG,IAAI;IACpC,MAAMC,QAAQH,IAAII,KAAK,CAAC;IACxB,MAAMC,UAAU,AAACF,CAAAA,QAAQA,KAAK,CAAC,EAAE,GAAGH,GAAE,EAAGE,IAAI,GAAGI,WAAW;IAC3D,OAAO,mCAAmCC,IAAI,CAACF,WAAWA,UAAU;AACtE;AAEA,qEAAqE,GACrE,OAAO,SAASG,oBACdC,OAAkD,EAClDC,IAA4B;IAE5B,IAAI,CAACD,SAAS,OAAOC;IACrB,OAAOrB,eAAe,CAACqB,KAAK,IAAIrB,eAAe,CAACoB,QAAQ,GAAGC,OAAOD;AACpE;AAEA,6EAA6E,GAC7E,OAAO,SAASE,mBAAmBX,GAAY;IAC7C,IAAIY,MAAMC,OAAO,CAACb,MAAM;QACtB,MAAMc,MAA8B,CAAC;QACrC,KAAK,MAAMC,OAAOf,IAAK;gBACyBe;YAA9C,IAAIA,uBAAAA,IAAKC,IAAI,EAAEF,GAAG,CAACb,OAAOc,IAAIC,IAAI,EAAE,GAAGf,QAAOc,aAAAA,IAAIhB,KAAK,YAATgB,aAAa;QAC7D;QACA,OAAOD;IACT;IACA,IAAId,OAAO,OAAOA,QAAQ,UAAU;QAClC,OAAOiB,OAAOC,WAAW,CACvBD,OAAOE,OAAO,CAACnB,KAAgCc,GAAG,CAAC,CAAC,CAACM,KAAKrB,MAAM,GAAK;gBACnEqB;gBACAnB,OAAOF,gBAAAA,QAAS;aACjB;IAEL;IACA,OAAO,CAAC;AACV"}
@@ -14,20 +14,20 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- /**
18
- * Where the credential probe asks its question.
19
- *
20
- * Deliberately NOT the send endpoint. A probe aimed at `/emails` is a send
21
- * attempt however empty its body is: it consumes an API call, and Resend
22
- * records it in the account's logs as a `422` on `POST /emails` with no
23
- * recipient, no subject and nothing identifying the caller — a line an
24
- * operator reading that dashboard has to treat as failed mail. A domain read
25
- * cannot create a message and cannot be mistaken for one.
26
- */
27
- export declare const RESEND_DOMAINS_ENDPOINT = "https://api.resend.com/domains";
17
+ import type { MailProvider } from './mail-provider';
28
18
  export interface EmailConfigReport {
29
- /** Both env vars present — mail will at least be attempted. */
19
+ /** The provider has its settings and a sender is set — mail will at least be attempted. */
30
20
  configured: boolean;
21
+ /** The id of the provider mail is handed to — see `mail-providers.ts`. */
22
+ provider: string;
23
+ /** Settings that provider still needs before it can send, as an operator names them. */
24
+ missingSettings: string[];
25
+ /**
26
+ * Set when the operator chose a provider this process does not have: why
27
+ * no mail is sent. Not the same as a missing key — see `mailProviderProblem`.
28
+ */
29
+ providerProblem: string | null;
30
+ /** The provider has what it needs to send. */
31
31
  hasApiKey: boolean;
32
32
  hasFrom: boolean;
33
33
  /**
@@ -35,7 +35,7 @@ export interface EmailConfigReport {
35
35
  * it appears in the headers of every message we send.
36
36
  */
37
37
  from: string | null;
38
- /** Domain part of the sender, which is what must be verified in Resend. */
38
+ /** Domain part of the sender, which is what must be verified with the provider. */
39
39
  fromDomain: string | null;
40
40
  }
41
41
  /**
@@ -48,37 +48,24 @@ export declare function describeEmailConfig(): EmailConfigReport;
48
48
  export type EmailCredentialStatus = 'ok' | 'unconfigured' | 'invalid-key' | 'unknown';
49
49
  export interface EmailCredentialReport {
50
50
  status: EmailCredentialStatus;
51
- /** HTTP status Resend answered the probe with, when it answered. */
51
+ /** HTTP status the provider answered the probe with, when it answered. */
52
52
  probeStatus?: number;
53
53
  detail?: string;
54
54
  }
55
55
  /**
56
- * Checks whether `RESEND_API_KEY` is actually accepted by Resend — without
57
- * sending anything to anybody, and without leaving anything behind that reads
58
- * as failed mail.
59
- *
60
- * How: a `GET` of the domains collection. The question is only ever "does
61
- * Resend recognize this credential", so the probe reads the ERROR NAME rather
62
- * than the status, because `401` and `403` each carry both meanings:
63
- *
64
- * - `2xx` — the key is accepted and has read scope → `ok`
65
- * - `restricted_api_key` / `invalid_permission` — Resend authenticated the
66
- * key and then denied it this read. A sending-scoped key, which is what
67
- * Aglyn provisions, always answers this way, and getting the answer proves
68
- * the credential works → `ok`
69
- * - `missing_api_key` / `validation_error` / `suspended_api_key` — the key
70
- * itself was refused → `invalid-key`
71
- * - anything else → `unknown`
56
+ * Whether the provider accepts this deployment's credential — asked without
57
+ * sending anything to anybody, and without leaving anything behind that
58
+ * reads as failed mail. How it asks is the provider's own (see its
59
+ * `checkCredentials`).
72
60
  *
73
- * An unrecognized rejection is `unknown`, never `invalid-key`: this feeds a
61
+ * An answer this cannot get is `unknown`, never `invalid-key`: this feeds a
74
62
  * staff diagnostics screen whose whole value is that a red line means
75
- * something, and a shape we have not seen before is not evidence that a
76
- * working key is broken.
63
+ * something. A provider with no probe is `unknown` for the same reason.
77
64
  *
78
65
  * It cannot confirm that *domain verification* has completed — only a real
79
66
  * send does that.
80
67
  */
81
- export declare function checkEmailCredentials(): Promise<EmailCredentialReport>;
68
+ export declare function checkEmailCredentials(provider?: MailProvider): Promise<EmailCredentialReport>;
82
69
  /** One pool member, as the provider reports it. */
83
70
  export interface SharedPoolDomainReport {
84
71
  domain: string;
@@ -135,13 +122,13 @@ export interface SharedPoolReport {
135
122
  * site's transactional mail already failing — which is why the caller treats
136
123
  * this as a blocker rather than a note.
137
124
  *
138
- * Read with `RESEND_READ_API_KEY`, deliberately, and never with the sending
139
- * key. A sending-scoped key has no read permission, so asking it about domains
140
- * yields an authorization error that says nothing about the domains — which is
141
- * exactly how a pool the key could not send from reported healthy. Without a
142
- * read key this answers `unreadable`, which is the honest answer and not a
143
- * pass: the caller must not treat "I could not look" as "I looked and it was
144
- * fine".
125
+ * Read through the provider's READS, deliberately, and never with the
126
+ * sending credential. A sending-scoped key has no read permission, so asking
127
+ * it about domains yields an authorization error that says nothing about the
128
+ * domains — which is exactly how a pool the key could not send from reported
129
+ * healthy. A provider that cannot read answers `unreadable`, which is the
130
+ * honest answer and not a pass: the caller must not treat "I could not look"
131
+ * as "I looked and it was fine".
145
132
  *
146
133
  * `not-applicable` covers the self-host shape. The pool is a property of the
147
134
  * Aglyn platform; an operator running their own deployment sends from their
@@ -149,6 +136,6 @@ export interface SharedPoolReport {
149
136
  */
150
137
  export declare function checkSharedSendingPool(options: {
151
138
  pool: string[];
152
- readApiKey?: string;
153
- endpoint?: string;
139
+ /** The provider to ask; the deployment's own by default. */
140
+ provider?: MailProvider;
154
141
  }): Promise<SharedPoolReport>;