@hogsend/engine 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +9 -6
- package/src/container.ts +76 -21
- package/src/env.ts +23 -1
- package/src/index.ts +21 -6
- package/src/lib/email-provider-registry.ts +45 -0
- package/src/lib/email-providers-from-env.ts +94 -0
- package/src/lib/email-service-types.ts +40 -4
- package/src/lib/headers.ts +13 -0
- package/src/lib/mailer.ts +120 -70
- package/src/lib/outbound.ts +11 -2
- package/src/lib/tracked.ts +34 -29
- package/src/lib/tracking-events.ts +26 -11
- package/src/routes/admin/emails.ts +5 -1
- package/src/routes/tracking/click.ts +1 -1
- package/src/routes/tracking/open.ts +1 -1
- package/src/routes/webhooks/email-provider.ts +124 -0
- package/src/routes/webhooks/index.ts +7 -0
- package/src/routes/webhooks/resend.ts +14 -29
- package/src/routes/webhooks/sources.ts +15 -4
- package/src/workflows/send-email.ts +2 -1
package/src/lib/mailer.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
BatchEmailItem,
|
|
3
|
+
EmailEvent,
|
|
4
|
+
EmailEventType,
|
|
3
5
|
EmailProvider,
|
|
4
|
-
WebhookEvent,
|
|
5
|
-
WebhookEventType,
|
|
6
6
|
WebhookHandlerMap,
|
|
7
7
|
} from "@hogsend/core";
|
|
8
8
|
import type { Database } from "@hogsend/db";
|
|
@@ -13,23 +13,23 @@ import type {
|
|
|
13
13
|
TemplateName,
|
|
14
14
|
} from "@hogsend/email";
|
|
15
15
|
import { getTemplate, renderToHtml, renderToPlainText } from "@hogsend/email";
|
|
16
|
-
import { eq, sql } from "drizzle-orm";
|
|
17
|
-
import
|
|
18
|
-
EmailService,
|
|
19
|
-
EmailServiceConfig,
|
|
20
|
-
EmailServiceSendOptions,
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
16
|
+
import { eq, inArray, sql } from "drizzle-orm";
|
|
17
|
+
import {
|
|
18
|
+
type EmailService,
|
|
19
|
+
type EmailServiceConfig,
|
|
20
|
+
type EmailServiceSendOptions,
|
|
21
|
+
type EmailServiceWebhookResult,
|
|
22
|
+
type SendRawOptions,
|
|
23
|
+
type SendResult,
|
|
24
|
+
type TrackedSendResult,
|
|
25
|
+
trackedSendResult,
|
|
26
26
|
} from "./email-service-types.js";
|
|
27
27
|
import { hatchet } from "./hatchet.js";
|
|
28
28
|
import { createLogger } from "./logger.js";
|
|
29
29
|
import { emitOutbound } from "./outbound.js";
|
|
30
30
|
import type { PrepareTrackedHtmlFn } from "./tracked.js";
|
|
31
31
|
import { sendTrackedEmail } from "./tracked.js";
|
|
32
|
-
import {
|
|
32
|
+
import { resolveEmailSendContextByMessageId } from "./tracking-events.js";
|
|
33
33
|
|
|
34
34
|
// Fallback logger for the provider-webhook outbound emit — `config.logger` is
|
|
35
35
|
// optional, but `emitOutbound` requires one. Mirrors the engine-lib singleton
|
|
@@ -37,7 +37,7 @@ import { resolveEmailSendContextByResendId } from "./tracking-events.js";
|
|
|
37
37
|
const emitLogger = createLogger(process.env.LOG_LEVEL);
|
|
38
38
|
|
|
39
39
|
const WEBHOOK_TO_STATUS_FIELD: Partial<
|
|
40
|
-
Record<
|
|
40
|
+
Record<EmailEventType, keyof typeof emailSends.$inferSelect>
|
|
41
41
|
> = {
|
|
42
42
|
"email.sent": "sentAt",
|
|
43
43
|
"email.delivered": "deliveredAt",
|
|
@@ -47,7 +47,7 @@ const WEBHOOK_TO_STATUS_FIELD: Partial<
|
|
|
47
47
|
"email.complained": "complainedAt",
|
|
48
48
|
};
|
|
49
49
|
|
|
50
|
-
const WEBHOOK_TO_STATUS: Partial<Record<
|
|
50
|
+
const WEBHOOK_TO_STATUS: Partial<Record<EmailEventType, string>> = {
|
|
51
51
|
"email.sent": "sent",
|
|
52
52
|
"email.delivered": "delivered",
|
|
53
53
|
"email.opened": "opened",
|
|
@@ -56,6 +56,10 @@ const WEBHOOK_TO_STATUS: Partial<Record<WebhookEventType, string>> = {
|
|
|
56
56
|
"email.complained": "complained",
|
|
57
57
|
};
|
|
58
58
|
|
|
59
|
+
/** Max recipients we will iterate on a bounce/complaint, to avoid a fan-out
|
|
60
|
+
* webhook mass-suppressing addresses. Above this we log + skip suppression. */
|
|
61
|
+
const MAX_SUPPRESSION_RECIPIENTS = 100;
|
|
62
|
+
|
|
59
63
|
/**
|
|
60
64
|
* The engine-owned high-level mailer. It owns the full send pipeline —
|
|
61
65
|
* render → preference/suppression check → tracked-html rewrite → `email_sends`
|
|
@@ -78,6 +82,27 @@ export function createTrackedMailer(
|
|
|
78
82
|
return overrideFrom ?? config.defaultFrom;
|
|
79
83
|
}
|
|
80
84
|
|
|
85
|
+
/**
|
|
86
|
+
* Drop `scheduledAt` unless the active provider declares
|
|
87
|
+
* `capabilities.scheduledSend`. A provider that can't natively schedule (e.g.
|
|
88
|
+
* Postmark/SES) would silently ignore it — so the engine strips it and logs a
|
|
89
|
+
* WARN pointing at the durable alternative (`ctx.sleepUntil`).
|
|
90
|
+
*/
|
|
91
|
+
function applyScheduledAtGate<T extends { scheduledAt?: string }>(
|
|
92
|
+
opts: T,
|
|
93
|
+
): T {
|
|
94
|
+
if (opts.scheduledAt && provider.capabilities?.scheduledSend !== true) {
|
|
95
|
+
(config.logger ?? emitLogger).warn(
|
|
96
|
+
`scheduledAt ignored: provider ${
|
|
97
|
+
provider.meta?.id ?? "resend"
|
|
98
|
+
} has no native scheduled send; use ctx.sleepUntil`,
|
|
99
|
+
);
|
|
100
|
+
const { scheduledAt: _dropped, ...rest } = opts;
|
|
101
|
+
return rest as T;
|
|
102
|
+
}
|
|
103
|
+
return opts;
|
|
104
|
+
}
|
|
105
|
+
|
|
81
106
|
const service: EmailService = {
|
|
82
107
|
async send<K extends TemplateName>(
|
|
83
108
|
options: EmailServiceSendOptions<K>,
|
|
@@ -118,25 +143,30 @@ export function createTrackedMailer(
|
|
|
118
143
|
props: options.props,
|
|
119
144
|
registry,
|
|
120
145
|
});
|
|
146
|
+
// HTML-ONLY wire — the engine ALWAYS renders React → HTML itself before
|
|
147
|
+
// the provider. React Email stays first-class for authoring/Studio; it
|
|
148
|
+
// never crosses the provider boundary.
|
|
149
|
+
const html = await renderToHtml(element);
|
|
121
150
|
const result = await provider.send({
|
|
122
151
|
from,
|
|
123
152
|
to: options.to,
|
|
124
153
|
subject: options.subject ?? defaultSubject,
|
|
125
|
-
|
|
154
|
+
html,
|
|
126
155
|
tags: options.tags,
|
|
127
156
|
headers: options.headers,
|
|
128
157
|
replyTo: options.replyTo,
|
|
129
158
|
});
|
|
130
159
|
|
|
131
|
-
return {
|
|
160
|
+
return trackedSendResult({
|
|
132
161
|
emailSendId: "",
|
|
133
|
-
|
|
162
|
+
messageId: result.id,
|
|
134
163
|
status: "sent",
|
|
135
|
-
};
|
|
164
|
+
});
|
|
136
165
|
},
|
|
137
166
|
|
|
138
167
|
async sendRaw(options: SendRawOptions): Promise<SendResult> {
|
|
139
|
-
|
|
168
|
+
const gated = applyScheduledAtGate(options);
|
|
169
|
+
return provider.send({ ...gated, from: resolveFrom(options.from) });
|
|
140
170
|
},
|
|
141
171
|
|
|
142
172
|
async sendBatch(options: {
|
|
@@ -167,23 +197,14 @@ export function createTrackedMailer(
|
|
|
167
197
|
},
|
|
168
198
|
|
|
169
199
|
async handleWebhook(
|
|
170
|
-
|
|
200
|
+
event: EmailEvent,
|
|
201
|
+
_providerId?: string,
|
|
171
202
|
): Promise<EmailServiceWebhookResult> {
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
);
|
|
176
|
-
}
|
|
177
|
-
|
|
203
|
+
// The route owns provider resolution + signature verification and hands us
|
|
204
|
+
// an already-verified, provider-neutral EmailEvent. No secret gate here —
|
|
205
|
+
// each provider owns its own webhook secret at construction time.
|
|
178
206
|
const userHandlers: WebhookHandlerMap = config.webhookHandlers ?? {};
|
|
179
|
-
|
|
180
|
-
const event = provider.verifyWebhook({
|
|
181
|
-
payload: options.payload,
|
|
182
|
-
headers: options.headers,
|
|
183
|
-
});
|
|
184
|
-
|
|
185
207
|
const handled = await dispatchWebhook(event, userHandlers);
|
|
186
|
-
|
|
187
208
|
return { type: event.type, handled };
|
|
188
209
|
},
|
|
189
210
|
};
|
|
@@ -191,7 +212,7 @@ export function createTrackedMailer(
|
|
|
191
212
|
const bounceThreshold = config.bounceThreshold ?? 3;
|
|
192
213
|
|
|
193
214
|
async function dispatchWebhook(
|
|
194
|
-
event:
|
|
215
|
+
event: EmailEvent,
|
|
195
216
|
userHandlers: WebhookHandlerMap,
|
|
196
217
|
): Promise<boolean> {
|
|
197
218
|
switch (event.type) {
|
|
@@ -199,13 +220,13 @@ export function createTrackedMailer(
|
|
|
199
220
|
// `email.sent` is emitted FIRST-PARTY from the tracked mailer's
|
|
200
221
|
// provider-accepted branch (lib/tracked.ts) with the rich payload — the
|
|
201
222
|
// provider-webhook echo only updates the DB status, it does NOT emit.
|
|
202
|
-
await updateEmailStatus(event.type, event.
|
|
223
|
+
await updateEmailStatus(event.type, event.messageId);
|
|
203
224
|
break;
|
|
204
225
|
case "email.delivered":
|
|
205
|
-
await updateEmailStatus(event.type, event.
|
|
226
|
+
await updateEmailStatus(event.type, event.messageId);
|
|
206
227
|
// OUTBOUND `email.delivered` — the provider webhook is the SINGLE source
|
|
207
228
|
// for delivered/bounced (these have no first-party signal).
|
|
208
|
-
await emitProviderEmailEvent("email.delivered", event.
|
|
229
|
+
await emitProviderEmailEvent("email.delivered", event.messageId);
|
|
209
230
|
break;
|
|
210
231
|
case "email.opened":
|
|
211
232
|
case "email.clicked":
|
|
@@ -213,34 +234,45 @@ export function createTrackedMailer(
|
|
|
213
234
|
// open/click — it now fires PER-HIT (every open/click → a delivery to
|
|
214
235
|
// every destination, owner decision 1). The provider-webhook echo is
|
|
215
236
|
// SUPPRESSED here: it only updates the DB status, it does NOT emit
|
|
216
|
-
// outbound (no double-source).
|
|
217
|
-
|
|
237
|
+
// outbound (no double-source). This is the outbound-echo defence for a
|
|
238
|
+
// provider with native tracking left ON.
|
|
239
|
+
await updateEmailStatus(event.type, event.messageId);
|
|
218
240
|
break;
|
|
219
241
|
case "email.bounced":
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
242
|
+
// `bounce.class` is stored in `bounceType`, the human reason in
|
|
243
|
+
// `bounceReason`. Soft/transient bounces are recorded here too (status
|
|
244
|
+
// `bounced`, `class:'transient'`) — the old transient →
|
|
245
|
+
// `email.delivery_delayed` no-op is gone.
|
|
246
|
+
await updateEmailStatus(event.type, event.messageId, {
|
|
247
|
+
bounceType: event.bounce?.class,
|
|
248
|
+
bounceReason: event.bounce?.reason,
|
|
223
249
|
});
|
|
224
|
-
// OUTBOUND `email.bounced` with the bounce detail.
|
|
225
|
-
await emitProviderEmailEvent("email.bounced", event.
|
|
226
|
-
bounceType: event.
|
|
227
|
-
bounceReason: event.
|
|
250
|
+
// OUTBOUND `email.bounced` with the bounce detail (class + reason).
|
|
251
|
+
await emitProviderEmailEvent("email.bounced", event.messageId, {
|
|
252
|
+
bounceType: event.bounce?.class,
|
|
253
|
+
bounceReason: event.bounce?.reason,
|
|
228
254
|
});
|
|
229
|
-
|
|
255
|
+
// Suppress (increment bounceCount toward threshold) ONLY on a permanent
|
|
256
|
+
// bounce. Transient/unknown are recorded but never auto-suppress.
|
|
257
|
+
if (event.bounce?.class === "permanent") {
|
|
258
|
+
await handleBounce(event.recipients);
|
|
259
|
+
}
|
|
230
260
|
break;
|
|
231
261
|
case "email.complained":
|
|
232
|
-
await updateEmailStatus(event.type, event.
|
|
262
|
+
await updateEmailStatus(event.type, event.messageId);
|
|
233
263
|
// OUTBOUND `email.complained` — the provider webhook is the SINGLE
|
|
234
264
|
// source for complaints (no first-party signal exists).
|
|
235
|
-
await emitProviderEmailEvent("email.complained", event.
|
|
236
|
-
await handleComplaint(event.
|
|
265
|
+
await emitProviderEmailEvent("email.complained", event.messageId);
|
|
266
|
+
await handleComplaint(event.recipients);
|
|
237
267
|
break;
|
|
238
268
|
case "email.delivery_delayed":
|
|
269
|
+
// No-op: providers now map transient bounces to `email.bounced` with
|
|
270
|
+
// `class:'transient'`, so soft bounces are recorded there instead.
|
|
239
271
|
break;
|
|
240
272
|
}
|
|
241
273
|
|
|
242
274
|
const userHandler = userHandlers[event.type] as
|
|
243
|
-
| ((e:
|
|
275
|
+
| ((e: EmailEvent) => void | Promise<void>)
|
|
244
276
|
| undefined;
|
|
245
277
|
if (userHandler) {
|
|
246
278
|
await userHandler(event);
|
|
@@ -250,11 +282,28 @@ export function createTrackedMailer(
|
|
|
250
282
|
return false;
|
|
251
283
|
}
|
|
252
284
|
|
|
253
|
-
|
|
285
|
+
/** Recipients to actually act on: de-duped, falsy-stripped, count-capped. A
|
|
286
|
+
* fan-out webhook over the cap is logged + skipped to avoid mass-suppression. */
|
|
287
|
+
function validRecipients(recipients: string[]): string[] {
|
|
288
|
+
const unique = [...new Set(recipients.filter(Boolean))];
|
|
289
|
+
if (unique.length > MAX_SUPPRESSION_RECIPIENTS) {
|
|
290
|
+
(config.logger ?? emitLogger).warn(
|
|
291
|
+
"suppression skipped: recipient count exceeds cap",
|
|
292
|
+
{ count: unique.length, cap: MAX_SUPPRESSION_RECIPIENTS },
|
|
293
|
+
);
|
|
294
|
+
return [];
|
|
295
|
+
}
|
|
296
|
+
return unique;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
async function handleBounce(recipients: string[]): Promise<void> {
|
|
254
300
|
if (!db) return;
|
|
255
|
-
const
|
|
256
|
-
if (
|
|
301
|
+
const emails = validRecipients(recipients);
|
|
302
|
+
if (emails.length === 0) return;
|
|
257
303
|
|
|
304
|
+
// ONE statement for all recipients. The CASE-WHEN auto-suppress at threshold
|
|
305
|
+
// is evaluated PER ROW inside the single UPDATE, so semantics match the old
|
|
306
|
+
// per-email loop exactly.
|
|
258
307
|
await db
|
|
259
308
|
.update(emailPreferences)
|
|
260
309
|
.set({
|
|
@@ -264,14 +313,15 @@ export function createTrackedMailer(
|
|
|
264
313
|
suppressedAt: sql`CASE WHEN ${emailPreferences.bounceCount} + 1 >= ${bounceThreshold} THEN NOW() ELSE ${emailPreferences.suppressedAt} END`,
|
|
265
314
|
updatedAt: new Date(),
|
|
266
315
|
})
|
|
267
|
-
.where(
|
|
316
|
+
.where(inArray(emailPreferences.email, emails));
|
|
268
317
|
}
|
|
269
318
|
|
|
270
|
-
async function handleComplaint(
|
|
319
|
+
async function handleComplaint(recipients: string[]): Promise<void> {
|
|
271
320
|
if (!db) return;
|
|
272
|
-
const
|
|
273
|
-
if (
|
|
321
|
+
const emails = validRecipients(recipients);
|
|
322
|
+
if (emails.length === 0) return;
|
|
274
323
|
|
|
324
|
+
// ONE statement for all recipients (same semantics as the old per-email loop).
|
|
275
325
|
await db
|
|
276
326
|
.update(emailPreferences)
|
|
277
327
|
.set({
|
|
@@ -279,15 +329,15 @@ export function createTrackedMailer(
|
|
|
279
329
|
suppressedAt: new Date(),
|
|
280
330
|
updatedAt: new Date(),
|
|
281
331
|
})
|
|
282
|
-
.where(
|
|
332
|
+
.where(inArray(emailPreferences.email, emails));
|
|
283
333
|
}
|
|
284
334
|
|
|
285
335
|
/**
|
|
286
336
|
* Emit the provider-funnel outbound event (`email.delivered` /
|
|
287
|
-
* `email.bounced` / `email.complained`) for a
|
|
337
|
+
* `email.bounced` / `email.complained`) for a provider `messageId`. These three
|
|
288
338
|
* have no first-party signal — the provider webhook is their single source.
|
|
289
|
-
* Enriches via {@link
|
|
290
|
-
* (the only handle a provider webhook holds is the
|
|
339
|
+
* Enriches via {@link resolveEmailSendContextByMessageId}
|
|
340
|
+
* (the only handle a provider webhook holds is the message id). Fire-and-forget:
|
|
291
341
|
* a missing context (webhook racing the send-row commit) or a transient outbound
|
|
292
342
|
* error is logged and swallowed — never failing the webhook handler. No
|
|
293
343
|
* `dedupeKey`: the provider path is not a Hatchet-retryable producer, and the
|
|
@@ -295,18 +345,18 @@ export function createTrackedMailer(
|
|
|
295
345
|
*/
|
|
296
346
|
function emitProviderEmailEvent(
|
|
297
347
|
event: "email.delivered" | "email.bounced" | "email.complained",
|
|
298
|
-
|
|
348
|
+
messageId: string,
|
|
299
349
|
bounce?: { bounceType?: string; bounceReason?: string },
|
|
300
350
|
): void {
|
|
301
351
|
if (!db) return;
|
|
302
352
|
const log = config.logger ?? emitLogger;
|
|
303
353
|
const database = db;
|
|
304
|
-
void
|
|
354
|
+
void resolveEmailSendContextByMessageId(database, messageId)
|
|
305
355
|
.then((ctx) => {
|
|
306
356
|
if (!ctx) return;
|
|
307
357
|
const base = {
|
|
308
358
|
emailSendId: ctx.emailSendId,
|
|
309
|
-
|
|
359
|
+
messageId,
|
|
310
360
|
templateKey: ctx.templateKey,
|
|
311
361
|
userId: ctx.userId,
|
|
312
362
|
to: ctx.to,
|
|
@@ -346,15 +396,15 @@ export function createTrackedMailer(
|
|
|
346
396
|
})
|
|
347
397
|
.catch((err: unknown) => {
|
|
348
398
|
log.warn(`emitOutbound ${event} failed`, {
|
|
349
|
-
|
|
399
|
+
messageId,
|
|
350
400
|
error: err instanceof Error ? err.message : String(err),
|
|
351
401
|
});
|
|
352
402
|
});
|
|
353
403
|
}
|
|
354
404
|
|
|
355
405
|
async function updateEmailStatus(
|
|
356
|
-
eventType:
|
|
357
|
-
|
|
406
|
+
eventType: EmailEventType,
|
|
407
|
+
messageId: string,
|
|
358
408
|
extra?: { bounceType?: string; bounceReason?: string },
|
|
359
409
|
): Promise<void> {
|
|
360
410
|
if (!db) return;
|
|
@@ -372,7 +422,7 @@ export function createTrackedMailer(
|
|
|
372
422
|
...(extra?.bounceReason ? { bounceReason: extra.bounceReason } : {}),
|
|
373
423
|
updatedAt: new Date(),
|
|
374
424
|
})
|
|
375
|
-
.where(eq(emailSends.
|
|
425
|
+
.where(eq(emailSends.messageId, messageId));
|
|
376
426
|
}
|
|
377
427
|
|
|
378
428
|
return service;
|
package/src/lib/outbound.ts
CHANGED
|
@@ -15,7 +15,16 @@ import {
|
|
|
15
15
|
} from "./webhook-signing.js";
|
|
16
16
|
|
|
17
17
|
export {
|
|
18
|
+
type EmailSendContextByMessageId,
|
|
19
|
+
/**
|
|
20
|
+
* @deprecated Kept for one minor; use {@link EmailSendContextByMessageId}.
|
|
21
|
+
*/
|
|
18
22
|
type ResendEmailSendContext,
|
|
23
|
+
resolveEmailSendContextByMessageId,
|
|
24
|
+
/**
|
|
25
|
+
* @deprecated Kept for one minor; use
|
|
26
|
+
* {@link resolveEmailSendContextByMessageId}.
|
|
27
|
+
*/
|
|
19
28
|
resolveEmailSendContextByResendId,
|
|
20
29
|
} from "./tracking-events.js";
|
|
21
30
|
|
|
@@ -28,7 +37,7 @@ export type OutboundEventName = WebhookEventType;
|
|
|
28
37
|
|
|
29
38
|
interface EmailEventPayload {
|
|
30
39
|
emailSendId: string;
|
|
31
|
-
|
|
40
|
+
messageId: string | null;
|
|
32
41
|
templateKey: string | null;
|
|
33
42
|
userId: string | null;
|
|
34
43
|
to: string;
|
|
@@ -69,7 +78,7 @@ export interface OutboundPayloads {
|
|
|
69
78
|
};
|
|
70
79
|
"email.sent": {
|
|
71
80
|
emailSendId: string;
|
|
72
|
-
|
|
81
|
+
messageId: string;
|
|
73
82
|
templateKey: string | null;
|
|
74
83
|
to: string;
|
|
75
84
|
userId: string | null;
|
package/src/lib/tracked.ts
CHANGED
|
@@ -14,10 +14,11 @@ import {
|
|
|
14
14
|
} from "@hogsend/email";
|
|
15
15
|
import { eq } from "drizzle-orm";
|
|
16
16
|
import { getListRegistry } from "../lists/registry-singleton.js";
|
|
17
|
-
import
|
|
18
|
-
FrequencyCapConfig,
|
|
19
|
-
SendTrackedEmailOptions,
|
|
20
|
-
TrackedSendResult,
|
|
17
|
+
import {
|
|
18
|
+
type FrequencyCapConfig,
|
|
19
|
+
type SendTrackedEmailOptions,
|
|
20
|
+
type TrackedSendResult,
|
|
21
|
+
trackedSendResult,
|
|
21
22
|
} from "./email-service-types.js";
|
|
22
23
|
import { isFrequencyCapped } from "./frequency-cap.js";
|
|
23
24
|
import { hatchet } from "./hatchet.js";
|
|
@@ -71,12 +72,12 @@ export async function sendTrackedEmail<K extends TemplateName>(
|
|
|
71
72
|
id: string;
|
|
72
73
|
status: string;
|
|
73
74
|
}): TrackedSendResult =>
|
|
74
|
-
({
|
|
75
|
+
trackedSendResult({
|
|
75
76
|
emailSendId: prior.id,
|
|
76
|
-
|
|
77
|
+
messageId: "",
|
|
77
78
|
status: prior.status === "sent" ? "sent" : "skipped",
|
|
78
79
|
...(prior.status === "sent" ? {} : { reason: "frequency_capped" }),
|
|
79
|
-
}
|
|
80
|
+
} as Omit<TrackedSendResult, "resendId">);
|
|
80
81
|
|
|
81
82
|
// Idempotency short-circuit (POST /v1/emails): a retry with the same key
|
|
82
83
|
// returns the prior send instead of dispatching a duplicate provider call /
|
|
@@ -135,15 +136,15 @@ export async function sendTrackedEmail<K extends TemplateName>(
|
|
|
135
136
|
const suppressedRow = rows[0];
|
|
136
137
|
if (!suppressedRow) throw new Error("Failed to insert email_sends row");
|
|
137
138
|
|
|
138
|
-
return {
|
|
139
|
+
return trackedSendResult({
|
|
139
140
|
emailSendId: suppressedRow.id,
|
|
140
|
-
|
|
141
|
+
messageId: "",
|
|
141
142
|
status:
|
|
142
143
|
suppression === "unsubscribed" ||
|
|
143
144
|
suppression === "category_unsubscribed"
|
|
144
145
|
? "unsubscribed"
|
|
145
146
|
: "suppressed",
|
|
146
|
-
};
|
|
147
|
+
});
|
|
147
148
|
}
|
|
148
149
|
|
|
149
150
|
// Frequency cap — consulted only for non-system sends (system mail sets
|
|
@@ -165,12 +166,12 @@ export async function sendTrackedEmail<K extends TemplateName>(
|
|
|
165
166
|
to: options.to,
|
|
166
167
|
category: options.category,
|
|
167
168
|
});
|
|
168
|
-
return {
|
|
169
|
+
return trackedSendResult({
|
|
169
170
|
emailSendId: "",
|
|
170
|
-
|
|
171
|
+
messageId: "",
|
|
171
172
|
status: "skipped",
|
|
172
173
|
reason: "frequency_capped",
|
|
173
|
-
};
|
|
174
|
+
});
|
|
174
175
|
}
|
|
175
176
|
}
|
|
176
177
|
}
|
|
@@ -257,22 +258,26 @@ export async function sendTrackedEmail<K extends TemplateName>(
|
|
|
257
258
|
const emailSendId = insertedRow.id;
|
|
258
259
|
|
|
259
260
|
try {
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
261
|
+
// HTML-ONLY wire — the engine ALWAYS renders React → HTML itself. When
|
|
262
|
+
// tracking is on (baseUrl + prepareTrackedHtml) we render then rewrite
|
|
263
|
+
// links/inject the open pixel; otherwise we render plain HTML. React Email
|
|
264
|
+
// stays first-class for authoring/Studio; it never crosses the wire.
|
|
265
|
+
const rawHtml = await renderToHtml(sendElement);
|
|
266
|
+
const html =
|
|
267
|
+
options.baseUrl && prepareTrackedHtml
|
|
268
|
+
? await prepareTrackedHtml({
|
|
269
|
+
html: rawHtml,
|
|
270
|
+
emailSendId,
|
|
271
|
+
baseUrl: options.baseUrl,
|
|
272
|
+
db,
|
|
273
|
+
})
|
|
274
|
+
: rawHtml;
|
|
270
275
|
|
|
271
276
|
const result = await provider.send({
|
|
272
277
|
from: options.from,
|
|
273
278
|
to: options.to,
|
|
274
279
|
subject,
|
|
275
|
-
|
|
280
|
+
html,
|
|
276
281
|
tags: options.tags,
|
|
277
282
|
headers: sendHeaders,
|
|
278
283
|
replyTo: options.replyTo,
|
|
@@ -282,7 +287,7 @@ export async function sendTrackedEmail<K extends TemplateName>(
|
|
|
282
287
|
await db
|
|
283
288
|
.update(emailSends)
|
|
284
289
|
.set({
|
|
285
|
-
|
|
290
|
+
messageId: result.id,
|
|
286
291
|
status: "sent",
|
|
287
292
|
sentAt,
|
|
288
293
|
updatedAt: sentAt,
|
|
@@ -306,7 +311,7 @@ export async function sendTrackedEmail<K extends TemplateName>(
|
|
|
306
311
|
dedupeKey: `email.sent:${emailSendId}`,
|
|
307
312
|
payload: {
|
|
308
313
|
emailSendId,
|
|
309
|
-
|
|
314
|
+
messageId: result.id,
|
|
310
315
|
templateKey: options.templateKey,
|
|
311
316
|
to: options.to,
|
|
312
317
|
userId: options.userId ?? null,
|
|
@@ -322,11 +327,11 @@ export async function sendTrackedEmail<K extends TemplateName>(
|
|
|
322
327
|
});
|
|
323
328
|
});
|
|
324
329
|
|
|
325
|
-
return {
|
|
330
|
+
return trackedSendResult({
|
|
326
331
|
emailSendId,
|
|
327
|
-
|
|
332
|
+
messageId: result.id,
|
|
328
333
|
status: "sent",
|
|
329
|
-
};
|
|
334
|
+
});
|
|
330
335
|
} catch (error) {
|
|
331
336
|
// A provider send failed (transient SMTP/network/429). Stamp `failed` AND
|
|
332
337
|
// RELEASE the idempotency key (set it null), exactly like the suppression
|
|
@@ -9,7 +9,7 @@ interface EmailSendContext {
|
|
|
9
9
|
userId: string;
|
|
10
10
|
userEmail: string;
|
|
11
11
|
templateKey: string | null;
|
|
12
|
-
|
|
12
|
+
messageId: string | null;
|
|
13
13
|
to: string;
|
|
14
14
|
}
|
|
15
15
|
|
|
@@ -21,7 +21,7 @@ export async function resolveEmailSendContext(
|
|
|
21
21
|
.select({
|
|
22
22
|
toEmail: emailSends.toEmail,
|
|
23
23
|
templateKey: emailSends.templateKey,
|
|
24
|
-
|
|
24
|
+
messageId: emailSends.messageId,
|
|
25
25
|
userId: journeyStates.userId,
|
|
26
26
|
userEmail: journeyStates.userEmail,
|
|
27
27
|
})
|
|
@@ -37,12 +37,12 @@ export async function resolveEmailSendContext(
|
|
|
37
37
|
userId: row.userId ?? row.toEmail,
|
|
38
38
|
userEmail: row.userEmail ?? row.toEmail,
|
|
39
39
|
templateKey: row.templateKey,
|
|
40
|
-
|
|
40
|
+
messageId: row.messageId,
|
|
41
41
|
to: row.toEmail,
|
|
42
42
|
};
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
-
export interface
|
|
45
|
+
export interface EmailSendContextByMessageId {
|
|
46
46
|
emailSendId: string;
|
|
47
47
|
userId: string;
|
|
48
48
|
userEmail: string;
|
|
@@ -50,21 +50,28 @@ export interface ResendEmailSendContext {
|
|
|
50
50
|
to: string;
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
+
/**
|
|
54
|
+
* @deprecated Renamed to {@link EmailSendContextByMessageId} as part of the
|
|
55
|
+
* provider-neutral `resendId` → `messageId` rename. Kept as an alias for one
|
|
56
|
+
* minor; removed the following minor.
|
|
57
|
+
*/
|
|
58
|
+
export type ResendEmailSendContext = EmailSendContextByMessageId;
|
|
59
|
+
|
|
53
60
|
/**
|
|
54
61
|
* Mirror of {@link resolveEmailSendContext} that resolves by the provider's
|
|
55
|
-
* `
|
|
62
|
+
* `messageId` instead of the internal `email_sends.id`. Used by the
|
|
56
63
|
* provider-webhook enrichment path (`email.delivered`/`email.bounced`) where the
|
|
57
|
-
* only handle we hold is the
|
|
64
|
+
* only handle we hold is the provider message id.
|
|
58
65
|
*
|
|
59
66
|
* Returns the internal `emailSendId` plus the same denormalized identity
|
|
60
67
|
* (`userId`/`userEmail` fall back to the recipient address, exactly like the
|
|
61
68
|
* id-keyed resolver) and `to` recipient. Returns null when no send row carries
|
|
62
|
-
* that `
|
|
69
|
+
* that `messageId` yet (e.g. a webhook arriving before the send row is committed).
|
|
63
70
|
*/
|
|
64
|
-
export async function
|
|
71
|
+
export async function resolveEmailSendContextByMessageId(
|
|
65
72
|
db: Database,
|
|
66
|
-
|
|
67
|
-
): Promise<
|
|
73
|
+
messageId: string,
|
|
74
|
+
): Promise<EmailSendContextByMessageId | null> {
|
|
68
75
|
const rows = await db
|
|
69
76
|
.select({
|
|
70
77
|
emailSendId: emailSends.id,
|
|
@@ -77,7 +84,7 @@ export async function resolveEmailSendContextByResendId(
|
|
|
77
84
|
})
|
|
78
85
|
.from(emailSends)
|
|
79
86
|
.leftJoin(journeyStates, eq(emailSends.journeyStateId, journeyStates.id))
|
|
80
|
-
.where(eq(emailSends.
|
|
87
|
+
.where(eq(emailSends.messageId, messageId))
|
|
81
88
|
.limit(1);
|
|
82
89
|
|
|
83
90
|
const row = rows[0];
|
|
@@ -92,6 +99,14 @@ export async function resolveEmailSendContextByResendId(
|
|
|
92
99
|
};
|
|
93
100
|
}
|
|
94
101
|
|
|
102
|
+
/**
|
|
103
|
+
* @deprecated Renamed to {@link resolveEmailSendContextByMessageId} as part of
|
|
104
|
+
* the provider-neutral `resendId` → `messageId` rename. Kept as an alias for one
|
|
105
|
+
* minor; removed the following minor.
|
|
106
|
+
*/
|
|
107
|
+
export const resolveEmailSendContextByResendId =
|
|
108
|
+
resolveEmailSendContextByMessageId;
|
|
109
|
+
|
|
95
110
|
export interface PushTrackingEventOpts {
|
|
96
111
|
db: Database;
|
|
97
112
|
hatchet: HatchetClient;
|
|
@@ -26,6 +26,8 @@ const emailSchema = z.object({
|
|
|
26
26
|
id: z.string(),
|
|
27
27
|
journeyStateId: z.string().nullable(),
|
|
28
28
|
templateKey: z.string().nullable(),
|
|
29
|
+
messageId: z.string().nullable(),
|
|
30
|
+
/** @deprecated Mirrors `messageId`; kept for one minor, removed thereafter. */
|
|
29
31
|
resendId: z.string().nullable(),
|
|
30
32
|
fromEmail: z.string(),
|
|
31
33
|
toEmail: z.string(),
|
|
@@ -88,7 +90,9 @@ function serializeEmail(
|
|
|
88
90
|
id: row.id,
|
|
89
91
|
journeyStateId: row.journeyStateId,
|
|
90
92
|
templateKey: row.templateKey,
|
|
91
|
-
|
|
93
|
+
messageId: row.messageId,
|
|
94
|
+
// @deprecated Mirror of `messageId` for one minor (back-compat).
|
|
95
|
+
resendId: row.messageId,
|
|
92
96
|
fromEmail: row.fromEmail,
|
|
93
97
|
toEmail: row.toEmail,
|
|
94
98
|
subject: row.subject,
|
|
@@ -121,7 +121,7 @@ export const clickRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
|
121
121
|
event: "email.clicked",
|
|
122
122
|
payload: {
|
|
123
123
|
emailSendId,
|
|
124
|
-
|
|
124
|
+
messageId: ctx.messageId ?? null,
|
|
125
125
|
templateKey: ctx.templateKey ?? null,
|
|
126
126
|
userId: ctx.userId ?? null,
|
|
127
127
|
to: ctx.to ?? ctx.userEmail ?? "",
|
|
@@ -81,7 +81,7 @@ export const openRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
|
81
81
|
event: "email.opened",
|
|
82
82
|
payload: {
|
|
83
83
|
emailSendId: id,
|
|
84
|
-
|
|
84
|
+
messageId: ctx.messageId ?? null,
|
|
85
85
|
templateKey: ctx.templateKey ?? null,
|
|
86
86
|
userId: ctx.userId ?? null,
|
|
87
87
|
to: ctx.to ?? ctx.userEmail ?? "",
|