@hogsend/engine 0.42.0 → 0.44.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.
Files changed (75) hide show
  1. package/package.json +10 -7
  2. package/src/container.ts +419 -4
  3. package/src/destinations/define-destination.ts +7 -3
  4. package/src/destinations/presets/posthog.ts +31 -0
  5. package/src/env.ts +28 -0
  6. package/src/index.ts +138 -0
  7. package/src/journeys/execute-journey-run.ts +93 -0
  8. package/src/journeys/journey-boundary.ts +5 -1
  9. package/src/journeys/journey-context.ts +30 -0
  10. package/src/lib/attribution-backfill.ts +285 -0
  11. package/src/lib/attribution.ts +239 -0
  12. package/src/lib/contacts.ts +71 -0
  13. package/src/lib/conversion-dispatch.ts +326 -0
  14. package/src/lib/conversions.ts +197 -0
  15. package/src/lib/crm-deals.ts +320 -0
  16. package/src/lib/crm-ingest.ts +341 -0
  17. package/src/lib/crm-provider-registry.ts +41 -0
  18. package/src/lib/crm-registry-singleton.ts +22 -0
  19. package/src/lib/deal-money-events.ts +85 -0
  20. package/src/lib/email-service-types.ts +16 -1
  21. package/src/lib/event-names.ts +1 -1
  22. package/src/lib/funnel-progress.ts +76 -0
  23. package/src/lib/funnel-registry.ts +108 -0
  24. package/src/lib/funnel-transitions.ts +280 -0
  25. package/src/lib/holdout.ts +62 -0
  26. package/src/lib/ingestion.ts +218 -9
  27. package/src/lib/journey-suppress.ts +33 -2
  28. package/src/lib/lift-stats.ts +125 -0
  29. package/src/lib/mailer.ts +1 -0
  30. package/src/lib/operator.ts +31 -0
  31. package/src/lib/outbound.ts +109 -0
  32. package/src/lib/phone.ts +19 -0
  33. package/src/lib/preferences.ts +32 -0
  34. package/src/lib/revenue.ts +116 -0
  35. package/src/lib/sms-frequency-cap.ts +47 -0
  36. package/src/lib/sms-inbound.ts +200 -0
  37. package/src/lib/sms-link-tracking.ts +160 -0
  38. package/src/lib/sms-mailer.ts +338 -0
  39. package/src/lib/sms-provider-registry.ts +35 -0
  40. package/src/lib/sms-providers-from-env.ts +100 -0
  41. package/src/lib/sms-service-types.ts +175 -0
  42. package/src/lib/sms-tracked.ts +625 -0
  43. package/src/lib/sms.ts +117 -0
  44. package/src/lib/tracked.ts +40 -0
  45. package/src/lib/tracking-event-names.ts +6 -0
  46. package/src/lib/tracking-events.ts +133 -1
  47. package/src/lib/tracking.ts +2 -1
  48. package/src/lib/webhook-signing.ts +24 -1
  49. package/src/lists/channels.ts +21 -0
  50. package/src/routes/admin/attribution.ts +414 -0
  51. package/src/routes/admin/contacts.ts +71 -11
  52. package/src/routes/admin/conversions.ts +247 -0
  53. package/src/routes/admin/deals.ts +472 -0
  54. package/src/routes/admin/funnels.ts +228 -0
  55. package/src/routes/admin/index.ts +8 -0
  56. package/src/routes/admin/journeys.ts +158 -1
  57. package/src/routes/admin/readiness.ts +97 -2
  58. package/src/routes/admin/templates.ts +28 -1
  59. package/src/routes/email/unsubscribe.ts +1 -0
  60. package/src/routes/events/index.ts +12 -0
  61. package/src/routes/index.ts +6 -0
  62. package/src/routes/lists/index.ts +54 -7
  63. package/src/routes/tracking/click-pipeline.ts +105 -16
  64. package/src/routes/tracking/short.ts +61 -0
  65. package/src/routes/webhooks/crm-provider.ts +117 -0
  66. package/src/routes/webhooks/index.ts +9 -1
  67. package/src/routes/webhooks/sms-provider.ts +110 -0
  68. package/src/sources/define-contact-source.ts +159 -0
  69. package/src/sources/registry.ts +71 -0
  70. package/src/sources/webhook-source.ts +109 -0
  71. package/src/worker.ts +4 -0
  72. package/src/workflows/crm-reconcile.ts +129 -0
  73. package/src/workflows/dispatch-conversion.ts +31 -0
  74. package/src/workflows/import-contacts.ts +61 -4
  75. package/src/workflows/send-campaign.ts +5 -0
@@ -0,0 +1,625 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { SmsProvider } from "@hogsend/core";
3
+ import type { Database } from "@hogsend/db";
4
+ import { smsSends, smsSuppressions, trackedLinks } from "@hogsend/db";
5
+ import {
6
+ countSmsSegments,
7
+ getSmsTemplate,
8
+ renderSmsToText,
9
+ type SmsTemplateName,
10
+ type SmsTemplateRegistry,
11
+ } from "@hogsend/sms";
12
+ import { eq } from "drizzle-orm";
13
+ import {
14
+ deriveJourneyKey,
15
+ getJourneyBoundary,
16
+ registerKey,
17
+ } from "../journeys/journey-boundary.js";
18
+ import { logTransition } from "../journeys/journey-log.js";
19
+ import { getListRegistry } from "../lists/registry-singleton.js";
20
+ import type { FrequencyCapConfig } from "./email-service-types.js";
21
+ import { hatchet } from "./hatchet.js";
22
+ import { isGlobalControl } from "./holdout.js";
23
+ import { checkJourneySuppress } from "./journey-suppress.js";
24
+ import { createLogger, type Logger } from "./logger.js";
25
+ import { emitOutbound } from "./outbound.js";
26
+ import { readRecipientPreferences } from "./preferences.js";
27
+ import { isSmsFrequencyCapped } from "./sms-frequency-cap.js";
28
+ import {
29
+ isShortCodeCollision,
30
+ planSmsLinkRewrite,
31
+ type SmsLinkRewritePlan,
32
+ } from "./sms-link-tracking.js";
33
+ import type {
34
+ SendTrackedSmsOptions,
35
+ SmsTrackedSendResult,
36
+ } from "./sms-service-types.js";
37
+
38
+ const emitLogger = createLogger(process.env.LOG_LEVEL);
39
+
40
+ /** The engine-synthesized SMS channel list id (opt-out polarity). */
41
+ export const SMS_CHANNEL_ID = "sms";
42
+
43
+ interface TrackedSmsDeps {
44
+ db: Database;
45
+ provider: SmsProvider;
46
+ registry: SmsTemplateRegistry;
47
+ frequencyCap?: FrequencyCapConfig;
48
+ logger?: Logger;
49
+ /** `false` disables the STOP footer; a string overrides the default text. */
50
+ stopFooter?: string | false;
51
+ /** Container-wired test-mode resolver (validated env). Absent ⇒ never active. */
52
+ testMode?: () => boolean;
53
+ /** Redirect target while test mode is active (env.HOGSEND_TEST_PHONE). */
54
+ testPhone?: string;
55
+ /** Rewrite bare URLs to first-party short tracked links. Default true. */
56
+ linkTracking?: boolean;
57
+ /** Full origin short links are minted under; rewriting is skipped if absent. */
58
+ linkHost?: string;
59
+ }
60
+
61
+ /**
62
+ * Boundary-aware entry point mirroring {@link sendTrackedEmail}. A raw-service
63
+ * SMS send from INSIDE a journey (no idempotency key set) is auto-keyed with the
64
+ * `smsSend` kind so the engine's exactly-once guarantee covers it. Outside a
65
+ * journey, or with a key already set, this is a transparent pass-through.
66
+ */
67
+ export async function sendTrackedSms<K extends SmsTemplateName>(
68
+ opts: TrackedSmsDeps & { options: SendTrackedSmsOptions<K> },
69
+ ): Promise<SmsTrackedSendResult> {
70
+ const boundary = getJourneyBoundary();
71
+ if (!boundary) return sendTrackedSmsInner(opts);
72
+
73
+ // Inside a journey run the engine KNOWS the enrollment — default the
74
+ // attribution to the boundary's state id so authors never hand-thread it.
75
+ // An explicit journeyStateId (cross-enrollment sends) still wins. Without
76
+ // this, a forgotten journeyStateId silently blinds transition logs AND the
77
+ // meta.suppress min-gap guard.
78
+ const attributed = {
79
+ ...opts,
80
+ options: {
81
+ ...opts.options,
82
+ journeyStateId: opts.options.journeyStateId ?? boundary.stateId,
83
+ },
84
+ };
85
+ if (attributed.options.idempotencyKey) {
86
+ return sendTrackedSmsInner(attributed);
87
+ }
88
+
89
+ const site = boundary.currentLabel ?? String(opts.options.templateKey);
90
+ const key = deriveJourneyKey({
91
+ kind: "smsSend",
92
+ anchor: boundary.runAnchor,
93
+ site,
94
+ discriminant: String(opts.options.templateKey),
95
+ });
96
+ registerKey(boundary, key);
97
+ const keyed = {
98
+ ...attributed,
99
+ options: { ...attributed.options, idempotencyKey: key },
100
+ };
101
+ return boundary.memoize([key], () => sendTrackedSmsInner(keyed));
102
+ }
103
+
104
+ /**
105
+ * The result for a keyed send that found an already-DISPATCHED row under its
106
+ * key: `sent` (or `delivered` — the webhook advanced it) is a satisfied
107
+ * duplicate. Any other status is defensively skipped (a `failed` row releases
108
+ * its key, so it can't actually collide).
109
+ */
110
+ function duplicateResult(row: {
111
+ id: string;
112
+ status: string;
113
+ }): SmsTrackedSendResult {
114
+ return {
115
+ smsSendId: row.id,
116
+ messageId: "",
117
+ status:
118
+ row.status === "sent" || row.status === "delivered" ? "sent" : "skipped",
119
+ };
120
+ }
121
+
122
+ async function sendTrackedSmsInner<K extends SmsTemplateName>(
123
+ opts: TrackedSmsDeps & { options: SendTrackedSmsOptions<K> },
124
+ ): Promise<SmsTrackedSendResult> {
125
+ const {
126
+ db,
127
+ provider,
128
+ registry,
129
+ frequencyCap,
130
+ logger,
131
+ stopFooter,
132
+ linkTracking,
133
+ linkHost,
134
+ options,
135
+ } = opts;
136
+
137
+ // Idempotency short-circuit: a dispatched prior row is a satisfied
138
+ // duplicate; an orphaned `queued` row (crash before the provider returned) is
139
+ // REUSED and re-driven — with its STORED body (see below). A `failed` row
140
+ // released its key, so it never collides.
141
+ let reuseRow: { id: string; body: string; toPhone: string } | undefined;
142
+ if (options.idempotencyKey) {
143
+ const existing = await db
144
+ .select({
145
+ id: smsSends.id,
146
+ status: smsSends.status,
147
+ body: smsSends.body,
148
+ toPhone: smsSends.toPhone,
149
+ })
150
+ .from(smsSends)
151
+ .where(eq(smsSends.idempotencyKey, options.idempotencyKey))
152
+ .limit(1);
153
+ const prior = existing[0];
154
+ if (prior) {
155
+ if (prior.status === "queued") {
156
+ reuseRow = prior;
157
+ } else {
158
+ return duplicateResult(prior);
159
+ }
160
+ }
161
+ }
162
+
163
+ const { element, category: templateCategory } = getSmsTemplate({
164
+ key: options.templateKey,
165
+ props: options.props,
166
+ registry,
167
+ });
168
+ const effectiveCategory = options.category ?? templateCategory;
169
+
170
+ // The suppression/consent gate runs UNCONDITIONALLY: `exempt` (transactional
171
+ // or skipPreferenceCheck) bypasses only the consent + topic gates inside it —
172
+ // never the phone STOP list or unsubscribed_all. Twilio 21610 enforces STOP
173
+ // at the carrier anyway; bypassing it first-party would only produce failed
174
+ // provider calls and compliance exposure.
175
+ const exempt =
176
+ options.skipPreferenceCheck === true ||
177
+ effectiveCategory === "transactional";
178
+ {
179
+ const suppression = await checkSmsSuppression(db, {
180
+ phone: options.to,
181
+ userId: options.userId,
182
+ category: effectiveCategory,
183
+ exempt,
184
+ });
185
+ if (suppression) {
186
+ const rows = await db
187
+ .insert(smsSends)
188
+ .values({
189
+ templateKey: options.templateKey,
190
+ fromPhone: options.from,
191
+ toPhone: options.to,
192
+ body: "",
193
+ category: effectiveCategory,
194
+ journeyStateId: options.journeyStateId,
195
+ userId: options.userId,
196
+ status: "failed",
197
+ metadata: { suppressionReason: suppression },
198
+ // A suppressed send does NOT consume the idempotency key — a later
199
+ // retry (after re-subscribe / a consent grant) can then actually
200
+ // attempt the send.
201
+ })
202
+ .returning({ id: smsSends.id });
203
+ const row = rows[0];
204
+ if (!row) throw new Error("Failed to insert sms_sends row");
205
+ return {
206
+ smsSendId: row.id,
207
+ messageId: "",
208
+ status:
209
+ suppression === "no_consent"
210
+ ? "no_consent"
211
+ : suppression === "unsubscribed" || suppression === "channel_off"
212
+ ? "unsubscribed"
213
+ : "suppressed",
214
+ };
215
+ }
216
+ }
217
+
218
+ if (!options.skipPreferenceCheck) {
219
+ // Global control group (impact plan §4.3) — the SMS leg of the email
220
+ // gate in tracked.ts: same deterministic bucket, same key precedence
221
+ // (userId when known, else the recipient address), same marker emit
222
+ // (per-endpoint deduped on the contact key), so a contact with a stable
223
+ // userId is controlled consistently across channels.
224
+ if (effectiveCategory !== "transactional") {
225
+ const controlKey = options.userId ?? options.to;
226
+ if (isGlobalControl(controlKey)) {
227
+ logger?.info("sms skipped: control_group", { to: options.to });
228
+ void emitOutbound({
229
+ db,
230
+ hatchet,
231
+ logger: logger ?? emitLogger,
232
+ event: "contact.control_group",
233
+ dedupeKey: `contact.control_group:${controlKey.toLowerCase()}`,
234
+ payload: {
235
+ userId: options.userId ?? null,
236
+ email: null,
237
+ at: new Date().toISOString(),
238
+ },
239
+ }).catch((err: unknown) => {
240
+ (logger ?? emitLogger).warn("control_group marker emit failed", {
241
+ error: err instanceof Error ? err.message : String(err),
242
+ });
243
+ });
244
+ return {
245
+ smsSendId: "",
246
+ messageId: "",
247
+ status: "skipped",
248
+ reason: "control_group",
249
+ };
250
+ }
251
+ }
252
+
253
+ if (frequencyCap) {
254
+ const capped = await isSmsFrequencyCapped({
255
+ db,
256
+ to: options.to,
257
+ category: options.category,
258
+ config: frequencyCap,
259
+ });
260
+ if (capped) {
261
+ logger?.info("sms skipped: frequency_capped", { to: options.to });
262
+ return {
263
+ smsSendId: "",
264
+ messageId: "",
265
+ status: "skipped",
266
+ reason: "frequency_capped",
267
+ };
268
+ }
269
+ }
270
+
271
+ // Journey suppress (`meta.suppress`) — the same per-recipient min-gap
272
+ // flooding guard the email pipeline enforces (tracked.ts), running against
273
+ // SMS send history. Placed after the idempotency short-circuit (a replayed
274
+ // already-dispatched send must return its dup first) and recorded set-once
275
+ // so the verdict is replay-stable. Inert outside a journey boundary.
276
+ const boundary = getJourneyBoundary();
277
+ const suppress = await checkJourneySuppress({
278
+ db,
279
+ boundary,
280
+ to: options.to,
281
+ idempotencyKey: options.idempotencyKey,
282
+ channel: "sms",
283
+ });
284
+ if (suppress.suppressed) {
285
+ logger?.info("sms skipped: journey_suppressed", {
286
+ to: options.to,
287
+ journeyId: boundary?.journeyId,
288
+ });
289
+ return {
290
+ smsSendId: "",
291
+ messageId: "",
292
+ status: "skipped",
293
+ reason: "journey_suppressed",
294
+ };
295
+ }
296
+ }
297
+
298
+ // Test mode: redirect to HOGSEND_TEST_PHONE (block when unset). Preference
299
+ // checks above stayed keyed to the ORIGINAL recipient. The resolver is
300
+ // container-wired (validated env + email-side auto-arm coherence) — never a
301
+ // raw process.env read here.
302
+ const testActive = opts.testMode?.() ?? false;
303
+ const testPhone = opts.testPhone;
304
+
305
+ let smsSendId: string;
306
+ let wireTo: string;
307
+ let wireBody: string;
308
+
309
+ if (reuseRow) {
310
+ // Re-drive of an orphaned queued row (crash replay): wire the STORED body
311
+ // verbatim — it already carries the rewritten short links, footer, and any
312
+ // test prefix from the first drive, and its tracked_links rows were
313
+ // committed atomically with it. Re-rendering + re-rewriting here would
314
+ // mint duplicate tracked rows with fresh codes on every replay.
315
+ if (testActive && !testPhone) {
316
+ (logger ?? emitLogger).error(
317
+ "SMS test mode active but HOGSEND_TEST_PHONE is unset; send blocked",
318
+ { originalTo: options.to, templateKey: options.templateKey },
319
+ );
320
+ return {
321
+ smsSendId: reuseRow.id,
322
+ messageId: "",
323
+ status: "skipped",
324
+ reason: "test_mode_blocked",
325
+ };
326
+ }
327
+ smsSendId = reuseRow.id;
328
+ wireTo = testActive && testPhone ? testPhone : reuseRow.toPhone;
329
+ wireBody = reuseRow.body;
330
+ } else {
331
+ // Render React → text, rewrite bare URLs to first-party short links, then
332
+ // append the compliance STOP footer. The rewrite sits BEFORE the footer +
333
+ // test prefix (neither carries URLs) so ONE final string flows to the
334
+ // stored row, the segment count, and the provider wire. `derive` is
335
+ // re-runnable — a short-code unique collision rolls the transaction back
336
+ // and replans with fresh codes.
337
+ const rawBody = await renderSmsToText(element);
338
+ const rewriteEnabled = linkTracking !== false && Boolean(linkHost);
339
+ const derive = (): { plan: SmsLinkRewritePlan; body: string } => {
340
+ const plan: SmsLinkRewritePlan = rewriteEnabled
341
+ ? planSmsLinkRewrite({ body: rawBody, linkHost: linkHost as string })
342
+ : { body: rawBody, links: [] };
343
+ return {
344
+ plan,
345
+ body: applyStopFooter({
346
+ body: plan.body,
347
+ category: effectiveCategory,
348
+ skipPreferenceCheck: options.skipPreferenceCheck,
349
+ stopFooter,
350
+ }),
351
+ };
352
+ };
353
+ let attempt = derive();
354
+
355
+ if (testActive && !testPhone) {
356
+ (logger ?? emitLogger).error(
357
+ "SMS test mode active but HOGSEND_TEST_PHONE is unset; send blocked",
358
+ { originalTo: options.to, templateKey: options.templateKey },
359
+ );
360
+ const rows = await db
361
+ .insert(smsSends)
362
+ .values({
363
+ templateKey: options.templateKey,
364
+ fromPhone: options.from,
365
+ toPhone: options.to,
366
+ body: attempt.body,
367
+ category: effectiveCategory,
368
+ journeyStateId: options.journeyStateId,
369
+ userId: options.userId,
370
+ status: "failed",
371
+ metadata: { testMode: true, originalTo: options.to },
372
+ })
373
+ .returning({ id: smsSends.id });
374
+ const row = rows[0];
375
+ if (!row) throw new Error("Failed to insert sms_sends row");
376
+ return {
377
+ smsSendId: row.id,
378
+ messageId: "",
379
+ status: "skipped",
380
+ reason: "test_mode_blocked",
381
+ };
382
+ }
383
+
384
+ const applyTestPrefix = (body: string): string =>
385
+ testActive && testPhone ? `[TEST → ${options.to}] ${body}` : body;
386
+ wireTo = testActive && testPhone ? testPhone : options.to;
387
+ wireBody = applyTestPrefix(attempt.body);
388
+
389
+ // Insert the queued row AND its tracked_links in ONE transaction: the FK
390
+ // forces the order, and atomicity means no queued row ever exists whose
391
+ // short codes have no tracked rows (a crash window that would send dead
392
+ // links), while a code collision rolls back cleanly for a full replan.
393
+ // The concurrent idempotency-key LOSER adopts the winner's stored
394
+ // body/toPhone — its own rewritten codes were rolled back with the losing
395
+ // insert.
396
+ let resolvedId: string | undefined;
397
+ for (let tries = 0; tries < 3 && resolvedId === undefined; tries++) {
398
+ const rowId = randomUUID();
399
+ const pending = attempt.plan.links;
400
+ let inserted = false;
401
+ try {
402
+ inserted = await db.transaction(async (tx) => {
403
+ const baseInsert = tx.insert(smsSends).values({
404
+ id: rowId,
405
+ templateKey: options.templateKey,
406
+ fromPhone: options.from,
407
+ toPhone: wireTo,
408
+ body: wireBody,
409
+ category: effectiveCategory,
410
+ journeyStateId: options.journeyStateId,
411
+ userId: options.userId,
412
+ status: "queued",
413
+ idempotencyKey: options.idempotencyKey,
414
+ ...(testActive && testPhone
415
+ ? { metadata: { testMode: true, originalTo: options.to } }
416
+ : {}),
417
+ });
418
+ const insertRows = options.idempotencyKey
419
+ ? await baseInsert
420
+ .onConflictDoNothing({ target: smsSends.idempotencyKey })
421
+ .returning({ id: smsSends.id })
422
+ : await baseInsert.returning({ id: smsSends.id });
423
+ if (!insertRows[0]) return false;
424
+ if (pending.length > 0) {
425
+ await tx.insert(trackedLinks).values(
426
+ pending.map((link) => ({
427
+ smsSendId: rowId,
428
+ source: "sms",
429
+ originalUrl: link.originalUrl,
430
+ shortCode: link.shortCode,
431
+ })),
432
+ );
433
+ }
434
+ return true;
435
+ });
436
+ } catch (err) {
437
+ if (!isShortCodeCollision(err) || tries === 2) throw err;
438
+ attempt = derive();
439
+ wireBody = applyTestPrefix(attempt.body);
440
+ continue;
441
+ }
442
+
443
+ if (inserted) {
444
+ resolvedId = rowId;
445
+ break;
446
+ }
447
+ // Idempotency-key loser: adopt the winner (nothing of ours committed).
448
+ const winner = await db
449
+ .select({
450
+ id: smsSends.id,
451
+ status: smsSends.status,
452
+ body: smsSends.body,
453
+ toPhone: smsSends.toPhone,
454
+ })
455
+ .from(smsSends)
456
+ .where(eq(smsSends.idempotencyKey, options.idempotencyKey ?? ""))
457
+ .limit(1);
458
+ const won = winner[0];
459
+ if (!won) throw new Error("Failed to insert sms_sends row");
460
+ if (won.status !== "queued") return duplicateResult(won);
461
+ resolvedId = won.id;
462
+ wireBody = won.body;
463
+ wireTo = testActive && testPhone ? testPhone : won.toPhone;
464
+ }
465
+ if (resolvedId === undefined) {
466
+ throw new Error("Failed to insert sms_sends row");
467
+ }
468
+ smsSendId = resolvedId;
469
+ }
470
+
471
+ try {
472
+ const segments = countSmsSegments(wireBody).segments;
473
+ const result = await provider.send({
474
+ from: options.from,
475
+ to: wireTo,
476
+ body: wireBody,
477
+ });
478
+
479
+ const sentAt = new Date();
480
+ await db
481
+ .update(smsSends)
482
+ .set({
483
+ messageId: result.id,
484
+ status: "sent",
485
+ segments,
486
+ sentAt,
487
+ updatedAt: sentAt,
488
+ })
489
+ .where(eq(smsSends.id, smsSendId));
490
+
491
+ if (options.journeyStateId) {
492
+ logTransition({
493
+ db,
494
+ journeyStateId: options.journeyStateId,
495
+ to: `sms:${String(options.templateKey)}`,
496
+ action: "send",
497
+ detail: { template: String(options.templateKey), smsSendId },
498
+ });
499
+ }
500
+
501
+ void emitOutbound({
502
+ db,
503
+ hatchet,
504
+ logger: logger ?? emitLogger,
505
+ event: "sms.sent",
506
+ dedupeKey: `sms.sent:${smsSendId}`,
507
+ payload: {
508
+ smsSendId,
509
+ messageId: result.id,
510
+ templateKey: String(options.templateKey),
511
+ to: options.to,
512
+ userId: options.userId ?? null,
513
+ category: effectiveCategory ?? null,
514
+ journeyStateId: options.journeyStateId ?? null,
515
+ segments,
516
+ sentAt: sentAt.toISOString(),
517
+ },
518
+ }).catch((err: unknown) => {
519
+ (logger ?? emitLogger).warn("emitOutbound sms.sent failed", {
520
+ smsSendId,
521
+ error: err instanceof Error ? err.message : String(err),
522
+ });
523
+ });
524
+
525
+ return { smsSendId, messageId: result.id, status: "sent" };
526
+ } catch (error) {
527
+ // Provider send failed. Stamp `failed` AND release the idempotency key so a
528
+ // retry genuinely re-attempts (mirrors the email pipeline).
529
+ await db
530
+ .update(smsSends)
531
+ .set({ status: "failed", idempotencyKey: null, updatedAt: new Date() })
532
+ .where(eq(smsSends.id, smsSendId));
533
+ throw error;
534
+ }
535
+ }
536
+
537
+ type SmsSuppressionReason =
538
+ | "suppressed"
539
+ | "unsubscribed"
540
+ | "channel_off"
541
+ | "no_consent"
542
+ | null;
543
+
544
+ /**
545
+ * Resolve whether an SMS send to `phone` must be suppressed. The consent model
546
+ * is EXPLICIT OPT-IN (TCPA prior-express-consent):
547
+ *
548
+ * 1. Phone track (`sms_suppressions`, tri-state, checked UNCONDITIONALLY —
549
+ * `exempt` never bypasses it): an ACTIVE row (`resubscribed_at IS NULL`,
550
+ * STOP / permanent carrier fail) blocks everything; a RESUBSCRIBED row
551
+ * (`resubscribed_at` set — an inbound START or an API grant for a
552
+ * phone-only contact) is express phone-level consent; no row is neither.
553
+ * 2. `unsubscribed_all` on the contact's `email_preferences` — the master
554
+ * opt-out, also never bypassed.
555
+ * 3. `exempt` (transactional / skipPreferenceCheck) short-circuits ONLY the
556
+ * consent + topic gates below this point.
557
+ * 4. The `sms` channel gate: an explicit `categories.sms === false` (STOP /
558
+ * preference-center off) blocks even with phone consent; otherwise the
559
+ * send needs an explicit grant — `categories.sms === true` (the channel
560
+ * registers `defaultOptIn: false`) OR phone-track consent. A send with no
561
+ * resolvable `userId` and no phone consent fails CLOSED (`no_consent`).
562
+ * 5. The topic-category gate (unchanged; topic lists keep their own polarity).
563
+ *
564
+ * The email-transport `suppressed` flag is NOT consumed (hard-bounce /
565
+ * complaint is email-specific).
566
+ */
567
+ async function checkSmsSuppression(
568
+ db: Database,
569
+ opts: {
570
+ phone: string;
571
+ userId?: string;
572
+ category?: string;
573
+ exempt?: boolean;
574
+ },
575
+ ): Promise<SmsSuppressionReason> {
576
+ const phoneRows = await db
577
+ .select({ resubscribedAt: smsSuppressions.resubscribedAt })
578
+ .from(smsSuppressions)
579
+ .where(eq(smsSuppressions.phone, opts.phone))
580
+ .limit(1);
581
+ const phoneRow = phoneRows[0];
582
+ if (phoneRow && phoneRow.resubscribedAt === null) return "suppressed";
583
+ const phoneConsent = phoneRow != null;
584
+
585
+ const prefs = opts.userId
586
+ ? await readRecipientPreferences(db, { userId: opts.userId })
587
+ : null;
588
+ if (prefs?.unsubscribedAll) return "unsubscribed";
589
+
590
+ if (opts.exempt) return null;
591
+
592
+ const registry = getListRegistry();
593
+ if (prefs?.categories[SMS_CHANNEL_ID] === false) return "channel_off";
594
+ const granted =
595
+ (prefs != null &&
596
+ registry.isSubscribed(prefs.categories, SMS_CHANNEL_ID)) ||
597
+ phoneConsent;
598
+ if (!granted) return "no_consent";
599
+
600
+ if (
601
+ opts.category &&
602
+ prefs &&
603
+ !registry.isSubscribed(prefs.categories, opts.category)
604
+ ) {
605
+ return "unsubscribed";
606
+ }
607
+ return null;
608
+ }
609
+
610
+ function applyStopFooter(opts: {
611
+ body: string;
612
+ category?: string;
613
+ skipPreferenceCheck?: boolean;
614
+ stopFooter?: string | false;
615
+ }): string {
616
+ if (opts.stopFooter === false) return opts.body;
617
+ if (opts.skipPreferenceCheck) return opts.body;
618
+ if (opts.category === "transactional") return opts.body;
619
+ // Skip only when the body already carries an opt-out INSTRUCTION ("Reply
620
+ // STOP…", "Text STOP…"), not when prose merely contains the word "stop" —
621
+ // "Don't stop now!" must still get the compliance footer.
622
+ if (/\b(?:reply|text|send)\s+stop\b/i.test(opts.body)) return opts.body;
623
+ const footer = opts.stopFooter ?? "Reply STOP to opt out";
624
+ return `${opts.body}\n\n${footer}`;
625
+ }