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