@aglyn/shared-util-email 1.0.0-beta.143

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 (72) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +104 -0
  3. package/package.json +37 -0
  4. package/src/index.d.ts +37 -0
  5. package/src/index.js +46 -0
  6. package/src/index.js.map +1 -0
  7. package/src/lib/email-delivery-events.d.ts +198 -0
  8. package/src/lib/email-delivery-events.js +310 -0
  9. package/src/lib/email-delivery-events.js.map +1 -0
  10. package/src/lib/email-health.d.ts +154 -0
  11. package/src/lib/email-health.js +264 -0
  12. package/src/lib/email-health.js.map +1 -0
  13. package/src/lib/email-media-src.d.ts +33 -0
  14. package/src/lib/email-media-src.js +113 -0
  15. package/src/lib/email-media-src.js.map +1 -0
  16. package/src/lib/email-merge.d.ts +31 -0
  17. package/src/lib/email-merge.js +36 -0
  18. package/src/lib/email-merge.js.map +1 -0
  19. package/src/lib/email-render.d.ts +114 -0
  20. package/src/lib/email-render.js +293 -0
  21. package/src/lib/email-render.js.map +1 -0
  22. package/src/lib/email-revenue-window.d.ts +55 -0
  23. package/src/lib/email-revenue-window.js +58 -0
  24. package/src/lib/email-revenue-window.js.map +1 -0
  25. package/src/lib/host-email-render.d.ts +99 -0
  26. package/src/lib/host-email-render.js +126 -0
  27. package/src/lib/host-email-render.js.map +1 -0
  28. package/src/lib/host-sender.d.ts +86 -0
  29. package/src/lib/host-sender.js +131 -0
  30. package/src/lib/host-sender.js.map +1 -0
  31. package/src/lib/marketing-send.d.ts +466 -0
  32. package/src/lib/marketing-send.js +459 -0
  33. package/src/lib/marketing-send.js.map +1 -0
  34. package/src/lib/platform-sending-domain.d.ts +362 -0
  35. package/src/lib/platform-sending-domain.js +697 -0
  36. package/src/lib/platform-sending-domain.js.map +1 -0
  37. package/src/lib/received-email.d.ts +86 -0
  38. package/src/lib/received-email.js +124 -0
  39. package/src/lib/received-email.js.map +1 -0
  40. package/src/lib/send-ceilings.d.ts +394 -0
  41. package/src/lib/send-ceilings.js +341 -0
  42. package/src/lib/send-ceilings.js.map +1 -0
  43. package/src/lib/send-email.d.ts +385 -0
  44. package/src/lib/send-email.js +586 -0
  45. package/src/lib/send-email.js.map +1 -0
  46. package/src/lib/send-rate.d.ts +298 -0
  47. package/src/lib/send-rate.js +310 -0
  48. package/src/lib/send-rate.js.map +1 -0
  49. package/src/lib/sender-reputation.d.ts +357 -0
  50. package/src/lib/sender-reputation.js +392 -0
  51. package/src/lib/sender-reputation.js.map +1 -0
  52. package/src/lib/sending-domain.d.ts +744 -0
  53. package/src/lib/sending-domain.js +798 -0
  54. package/src/lib/sending-domain.js.map +1 -0
  55. package/src/lib/sending-mailbox.d.ts +132 -0
  56. package/src/lib/sending-mailbox.js +192 -0
  57. package/src/lib/sending-mailbox.js.map +1 -0
  58. package/src/lib/stored-email-nodes.d.ts +38 -0
  59. package/src/lib/stored-email-nodes.js +78 -0
  60. package/src/lib/stored-email-nodes.js.map +1 -0
  61. package/src/lib/svix-signature.d.ts +38 -0
  62. package/src/lib/svix-signature.js +55 -0
  63. package/src/lib/svix-signature.js.map +1 -0
  64. package/src/lib/system-email-catalog.d.ts +170 -0
  65. package/src/lib/system-email-catalog.js +828 -0
  66. package/src/lib/system-email-catalog.js.map +1 -0
  67. package/src/lib/tenant-email-catalog.d.ts +78 -0
  68. package/src/lib/tenant-email-catalog.js +452 -0
  69. package/src/lib/tenant-email-catalog.js.map +1 -0
  70. package/src/lib/text-email-html.d.ts +32 -0
  71. package/src/lib/text-email-html.js +119 -0
  72. package/src/lib/text-email-html.js.map +1 -0
@@ -0,0 +1,310 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /**
17
+ * WHAT HAPPENED TO A MESSAGE, IN OUR OWN VOCABULARY.
18
+ *
19
+ * ## The seam
20
+ *
21
+ * A staff answer to "did they get the invite, and did they open it?" must not
22
+ * be a question about Resend. Two things follow from that, and this module is
23
+ * both of them:
24
+ *
25
+ * 1. **The stored shape is ours.** Nothing downstream — the delivery log, the
26
+ * staff card, a future export — reads a provider's field names or its event
27
+ * strings. Swapping the sender changes exactly one function in this file
28
+ * and nothing else in the tree.
29
+ * 2. **The history is ours.** The log is written into our own Firestore and
30
+ * read from there, never from the provider on render. A provider's list
31
+ * endpoint is a different shape per vendor, has its own retention window,
32
+ * and disappears entirely with the account; a record we keep survives the
33
+ * migration that the seam exists to make possible.
34
+ *
35
+ * That is a rule about the READ PATH, not a rule against ever reading the
36
+ * provider. The event feed only knows mail sent after it was connected, so
37
+ * a log fed by events alone is empty for all existing history — which is
38
+ * precisely the mail a support question is about. The second half of this
39
+ * module (see THE READ SIDE OF THE SEAM below) imports that history
40
+ * through the same neutral vocabulary, once, into the same store.
41
+ *
42
+ * ## Pure on purpose
43
+ *
44
+ * No Firestore and no admin SDK. `system-email-catalog` is imported by console
45
+ * CLIENT components through this library's barrel, so anything reachable from
46
+ * it that touched `firebase-admin` would drag the admin SDK into a browser
47
+ * bundle. Normalisation is a pure function of a payload; the writing lives in
48
+ * `@aglyn/tenant-data-admin/server/email-delivery-log`.
49
+ *
50
+ * The one `fetch` is `resendDeliveryHistorySource`, which is a function that
51
+ * must be CALLED with a key to do anything — it holds no module state and is
52
+ * unreachable from a client component, unlike an admin-SDK import, which
53
+ * executes on load.
54
+ */ /**
55
+ * The lifecycle of one message, in the order it normally happens.
56
+ *
57
+ * Chosen to be the intersection every ESP can report rather than the union of
58
+ * what any one of them does: a vendor with no equivalent for a state simply
59
+ * never produces it, and a vendor with a richer taxonomy folds into the
60
+ * nearest of these rather than widening the type. `delayed` is retryable and
61
+ * `failed` is not, which is the distinction a staffer actually needs.
62
+ */ /** Lifecycle states ordered worst-last, for {@link worstDeliveryStatus}. */ const STATUS_SEVERITY = {
63
+ sent: 1,
64
+ delivered: 2,
65
+ opened: 3,
66
+ clicked: 4,
67
+ delayed: 5,
68
+ complained: 6,
69
+ bounced: 7,
70
+ failed: 8
71
+ };
72
+ /** The later of two statuses on the lifecycle, worst winning a tie. */ export function worstDeliveryStatus(current, next) {
73
+ if (!current) return next;
74
+ return STATUS_SEVERITY[next] >= STATUS_SEVERITY[current] ? next : current;
75
+ }
76
+ /** Tags arrive as an array of `{name, value}` or a plain map — accept both. */ export function normalizeEventTags(raw) {
77
+ if (Array.isArray(raw)) {
78
+ const map = {};
79
+ for (const tag of raw){
80
+ var _tag_value;
81
+ if (tag == null ? void 0 : tag.name) map[String(tag.name)] = String((_tag_value = tag.value) != null ? _tag_value : '');
82
+ }
83
+ return map;
84
+ }
85
+ if (raw && typeof raw === 'object') {
86
+ return Object.fromEntries(Object.entries(raw).map(([key, value])=>[
87
+ key,
88
+ String(value != null ? value : '')
89
+ ]));
90
+ }
91
+ return {};
92
+ }
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;
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
+ return recipients.map((to)=>{
148
+ var _ref, _ref1, _ref2;
149
+ var _data_click, _data_bounce, _data_bounce1, _data_failed;
150
+ return {
151
+ type,
152
+ at,
153
+ provider: 'resend',
154
+ providerMessageId,
155
+ to,
156
+ subject,
157
+ context: tags['context'] || null,
158
+ tags,
159
+ link: type === 'clicked' ? String((_ref = (_data_click = data.click) == null ? void 0 : _data_click.link) != null ? _ref : '') || null : null,
160
+ bounceType: type === 'bounced' ? normalizeBounceType((_data_bounce = data.bounce) == null ? void 0 : _data_bounce.type) : null,
161
+ 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
162
+ };
163
+ });
164
+ }
165
+ /**
166
+ * A provider's `last_event` string, mapped onto our lifecycle.
167
+ *
168
+ * Deliberately the bare state names rather than the `email.*` event names:
169
+ * the list endpoint reports `"delivered"`, the webhook reports
170
+ * `"email.delivered"`, and they are two different vocabularies for one
171
+ * concept. Both are accepted here so a provider that unifies them later
172
+ * needs no change.
173
+ */ const RESEND_LAST_EVENTS = {
174
+ sent: 'sent',
175
+ delivered: 'delivered',
176
+ delivery_delayed: 'delayed',
177
+ opened: 'opened',
178
+ clicked: 'clicked',
179
+ bounced: 'bounced',
180
+ complained: 'complained',
181
+ failed: 'failed',
182
+ canceled: 'failed',
183
+ queued: 'sent',
184
+ scheduled: 'sent'
185
+ };
186
+ /**
187
+ * Turns one entry from Resend's `GET /emails` list into zero or more
188
+ * snapshots — one per recipient, for the same reason the event adapter fans
189
+ * out: the staff view is keyed on a person.
190
+ *
191
+ * An unrecognised `last_event` falls back to `sent` rather than being
192
+ * dropped. The message demonstrably exists and was addressed to somebody, and
193
+ * "we sent this and cannot characterise what happened next" is a far more
194
+ * useful row than no row — which is the state that sent a staffer to the
195
+ * vendor dashboard in the first place.
196
+ */ export function normalizeResendSentEmails(raw) {
197
+ var _record_id, _record_created_at, _RESEND_LAST_EVENTS_String_trim_toLowerCase, _record_last_event;
198
+ const record = raw != null ? raw : {};
199
+ const providerMessageId = String((_record_id = record.id) != null ? _record_id : '').trim();
200
+ if (!providerMessageId) return [];
201
+ const recipients = (Array.isArray(record.to) ? record.to : [
202
+ record.to
203
+ ]).map((address)=>String(address != null ? address : '').trim().toLowerCase()).filter((address)=>address.includes('@'));
204
+ if (!recipients.length) return [];
205
+ const parsed = Date.parse(String((_record_created_at = record.created_at) != null ? _record_created_at : ''));
206
+ const sentAt = Number.isFinite(parsed) ? parsed : 0;
207
+ // A snapshot with no timestamp cannot be ordered, and the log's read drops
208
+ // any document missing its sort key — so it is refused rather than written
209
+ // somewhere nothing will look for it.
210
+ if (!sentAt) return [];
211
+ 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';
212
+ return recipients.map((to)=>{
213
+ var _record_subject;
214
+ return {
215
+ provider: 'resend',
216
+ providerMessageId,
217
+ to,
218
+ subject: String((_record_subject = record.subject) != null ? _record_subject : '').trim() || null,
219
+ sentAt,
220
+ status
221
+ };
222
+ });
223
+ }
224
+ /** Resend's list endpoint. Paginates with `after=<id>`; caps at 100. */ export const RESEND_EMAILS_ENDPOINT = 'https://api.resend.com/emails';
225
+ /**
226
+ * {@link EmailDeliveryHistorySource} for Resend.
227
+ *
228
+ * Needs a FULL-ACCESS key: a sending-scoped key answers every read on this
229
+ * endpoint with `401 restricted_api_key`, which is the correct posture for
230
+ * the key that sends mail and the reason this takes its own.
231
+ */ export function resendDeliveryHistorySource(apiKey) {
232
+ return async ({ cursor, limit } = {})=>{
233
+ var _ref;
234
+ var _entries_;
235
+ const params = new URLSearchParams({
236
+ limit: String(Math.min(Math.max(1, limit != null ? limit : 100), 100))
237
+ });
238
+ if (cursor) params.set('after', cursor);
239
+ const response = await fetch(`${RESEND_EMAILS_ENDPOINT}?${params}`, {
240
+ headers: {
241
+ Authorization: `Bearer ${apiKey}`
242
+ }
243
+ });
244
+ if (!response.ok) {
245
+ const detail = await response.text().catch(()=>'');
246
+ throw new Error(`email history read failed: HTTP ${response.status} ${detail.slice(0, 200)}`);
247
+ }
248
+ const body = await response.json();
249
+ const entries = Array.isArray(body == null ? void 0 : body.data) ? body.data : [];
250
+ const snapshots = entries.flatMap((entry)=>normalizeResendSentEmails(entry));
251
+ // The cursor is the LAST RAW entry's id, not the last snapshot's: a page
252
+ // whose final entry fanned out to zero snapshots (no recipient, no
253
+ // timestamp) would otherwise rewind the cursor to an earlier message and
254
+ // loop over the same page forever.
255
+ const lastId = String((_ref = (_entries_ = entries[entries.length - 1]) == null ? void 0 : _entries_.id) != null ? _ref : '').trim();
256
+ return {
257
+ snapshots,
258
+ nextCursor: (body == null ? void 0 : body.has_more) && lastId ? lastId : null
259
+ };
260
+ };
261
+ }
262
+ function addressList(raw) {
263
+ return (Array.isArray(raw) ? raw : raw == null ? [] : [
264
+ raw
265
+ ]).map((address)=>String(address != null ? address : '').trim()).filter(Boolean);
266
+ }
267
+ /** Resend's `GET /emails/:id` payload, in our vocabulary. */ export function normalizeResendMessage(raw) {
268
+ var _record_id, _record_created_at, _record_from, _record_subject, _RESEND_LAST_EVENTS_String_trim_toLowerCase, _record_last_event;
269
+ const record = raw != null ? raw : {};
270
+ const providerMessageId = String((_record_id = record.id) != null ? _record_id : '').trim();
271
+ if (!providerMessageId) return null;
272
+ const parsed = Date.parse(String((_record_created_at = record.created_at) != null ? _record_created_at : ''));
273
+ return {
274
+ provider: 'resend',
275
+ providerMessageId,
276
+ to: addressList(record.to),
277
+ cc: addressList(record.cc),
278
+ bcc: addressList(record.bcc),
279
+ from: String((_record_from = record.from) != null ? _record_from : '').trim() || null,
280
+ replyTo: addressList(record.reply_to).length ? addressList(record.reply_to) : null,
281
+ subject: String((_record_subject = record.subject) != null ? _record_subject : '').trim() || null,
282
+ // Empty string is NOT null here, and the difference is the point: a
283
+ // message that went out text-only really does have an empty HTML part,
284
+ // and a reader has to be able to tell that from "we could not fetch it".
285
+ html: typeof record.html === 'string' ? record.html : null,
286
+ text: typeof record.text === 'string' ? record.text : null,
287
+ sentAt: Number.isFinite(parsed) ? parsed : null,
288
+ 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
289
+ };
290
+ }
291
+ /** Resend's single-message endpoint. Needs the same full-access key. */ export function resendDeliveryMessageSource(apiKey) {
292
+ return async (providerMessageId)=>{
293
+ const response = await fetch(`${RESEND_EMAILS_ENDPOINT}/${encodeURIComponent(providerMessageId)}`, {
294
+ headers: {
295
+ Authorization: `Bearer ${apiKey}`
296
+ }
297
+ });
298
+ // A message the provider has aged out is a 404, and that is an ANSWER —
299
+ // "we know this was sent and the body is gone" — not a failure to report
300
+ // as an error the staffer must act on.
301
+ if (response.status === 404) return null;
302
+ if (!response.ok) {
303
+ const detail = await response.text().catch(()=>'');
304
+ throw new Error(`message read failed: HTTP ${response.status} ${detail.slice(0, 200)}`);
305
+ }
306
+ return normalizeResendMessage(await response.json());
307
+ };
308
+ }
309
+
310
+ //# sourceMappingURL=email-delivery-events.js.map
@@ -0,0 +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\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\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\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 }))\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":["STATUS_SEVERITY","sent","delivered","opened","clicked","delayed","complained","bounced","failed","worstDeliveryStatus","current","next","normalizeEventTags","raw","Array","isArray","map","tag","name","String","value","Object","fromEntries","entries","key","eventTimeMs","Number","isFinite","parsed","Date","parse","normalizeBounceType","lowered","trim","toLowerCase","RESEND_EVENT_TYPES","normalizeResendDeliveryEvents","payload","receivedAtMs","event","data","type","providerMessageId","email_id","id","recipients","to","address","filter","includes","length","at","click","timestamp","open","created_at","subject","tags","provider","context","link","bounceType","bounce","detail","message","reason","RESEND_LAST_EVENTS","delivery_delayed","canceled","queued","scheduled","normalizeResendSentEmails","record","sentAt","status","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","from","replyTo","reply_to","html","resendDeliveryMessageSource","encodeURIComponent"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCC,GAED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,EAAEZ,QAAQ;YAAC;QAAE;QAEnD,wEAAwE;QACxE,yEAAyE;QACzE,uCAAuC;QACvC,IAAIS,SAASb,MAAM,KAAK,KAAK,OAAO;QACpC,IAAI,CAACa,SAASI,EAAE,EAAE;YAChB,MAAM5B,SAAS,MAAMwB,SAASK,IAAI,GAAGC,KAAK,CAAC,IAAM;YACjD,MAAM,IAAIC,MACR,CAAC,0BAA0B,EAAEP,SAASb,MAAM,CAAC,CAAC,EAAEX,OAAOgC,KAAK,CAAC,GAAG,MAAM;QAE1E;QACA,OAAOW,uBAAuB,MAAMnB,SAASU,IAAI;IACnD;AACF"}
@@ -0,0 +1,154 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
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";
28
+ export interface EmailConfigReport {
29
+ /** Both env vars present — mail will at least be attempted. */
30
+ configured: boolean;
31
+ hasApiKey: boolean;
32
+ hasFrom: boolean;
33
+ /**
34
+ * The configured sender, e.g. `Aglyn <noreply@aglyn.com>`. Not a secret —
35
+ * it appears in the headers of every message we send.
36
+ */
37
+ from: string | null;
38
+ /** Domain part of the sender, which is what must be verified in Resend. */
39
+ fromDomain: string | null;
40
+ }
41
+ /**
42
+ * Describes the email configuration without revealing the API key.
43
+ *
44
+ * Answers "is this environment able to send mail?" — the question that is
45
+ * otherwise only answerable by emailing a real person and waiting.
46
+ */
47
+ export declare function describeEmailConfig(): EmailConfigReport;
48
+ export type EmailCredentialStatus = 'ok' | 'unconfigured' | 'invalid-key' | 'unknown';
49
+ export interface EmailCredentialReport {
50
+ status: EmailCredentialStatus;
51
+ /** HTTP status Resend answered the probe with, when it answered. */
52
+ probeStatus?: number;
53
+ detail?: string;
54
+ }
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`
72
+ *
73
+ * An unrecognized rejection is `unknown`, never `invalid-key`: this feeds a
74
+ * 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.
77
+ *
78
+ * It cannot confirm that *domain verification* has completed — only a real
79
+ * send does that.
80
+ */
81
+ export declare function checkEmailCredentials(): Promise<EmailCredentialReport>;
82
+ /** One pool member, as the provider reports it. */
83
+ export interface SharedPoolDomainReport {
84
+ domain: string;
85
+ /** `verified` when the provider will accept mail on it. */
86
+ status: string;
87
+ /** False when the provider has never heard of it. */
88
+ present: boolean;
89
+ /**
90
+ * Whether the provider will rewrite links on this domain to measure clicks.
91
+ *
92
+ * Reported because the symptom of it being off is INVISIBLE. A provider
93
+ * counts a click by rewriting every `<a href>` to a tracking host, so a
94
+ * domain without one produces a click rate of exactly 0% — which reads on a
95
+ * dashboard as an audience that does not click, not as a domain that cannot
96
+ * count. The last time this was wrong nobody found it by looking at the
97
+ * numbers; it was found by reading a delivered message's source.
98
+ *
99
+ * `null` when the provider's listing does not say, so "it did not tell us"
100
+ * is never reported as "it is off".
101
+ */
102
+ clickTracking: boolean | null;
103
+ /** The same, for the open pixel. */
104
+ openTracking: boolean | null;
105
+ }
106
+ export type SharedPoolStatus =
107
+ /** No platform pool applies to this deployment. */
108
+ 'not-applicable'
109
+ /** No read credential, so the pool cannot be inspected. */
110
+ | 'unreadable' | 'ok' | 'degraded';
111
+ export interface SharedPoolReport {
112
+ status: SharedPoolStatus;
113
+ domains: SharedPoolDomainReport[];
114
+ /** Members the provider will not accept mail on right now. */
115
+ unusable: string[];
116
+ /**
117
+ * Members that will carry mail but cannot measure a click on it.
118
+ *
119
+ * Reported APART from {@link unusable} because the two are different
120
+ * severities and conflating them would be wrong in both directions: a
121
+ * member here is delivering perfectly, and a member in `unusable` is not
122
+ * delivering at all. This one does not degrade the pool — see
123
+ * {@link SharedPoolReport.status} — it is a measurement fault, and stopping
124
+ * mail over it would be the control causing the outage.
125
+ */
126
+ untracked: string[];
127
+ detail?: string;
128
+ }
129
+ /**
130
+ * Whether the shared platform pool can actually carry mail.
131
+ *
132
+ * The pool is the delivery floor: a site with no domain of its own sends its
133
+ * receipts, password resets and booking confirmations from a member of it. So
134
+ * a degraded pool is not a warning about a future problem, it is every such
135
+ * site's transactional mail already failing — which is why the caller treats
136
+ * this as a blocker rather than a note.
137
+ *
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".
145
+ *
146
+ * `not-applicable` covers the self-host shape. The pool is a property of the
147
+ * Aglyn platform; an operator running their own deployment sends from their
148
+ * own domain and has no pool to be degraded.
149
+ */
150
+ export declare function checkSharedSendingPool(options: {
151
+ pool: string[];
152
+ readApiKey?: string;
153
+ endpoint?: string;
154
+ }): Promise<SharedPoolReport>;