@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
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
+ }
@@ -30,6 +30,7 @@ import {
30
30
  } from "./email-service-types.js";
31
31
  import { isFrequencyCapped } from "./frequency-cap.js";
32
32
  import { hatchet } from "./hatchet.js";
33
+ import { isGlobalControl } from "./holdout.js";
33
34
  import { checkJourneySuppress } from "./journey-suppress.js";
34
35
  import { createLogger, type Logger } from "./logger.js";
35
36
  import { emitOutbound } from "./outbound.js";
@@ -209,6 +210,7 @@ async function sendTrackedEmailInner<K extends TemplateName>(
209
210
  subject: options.subject ?? "",
210
211
  category: effectiveCategory,
211
212
  journeyStateId: options.journeyStateId,
213
+ campaignId: options.campaignId,
212
214
  userId: options.userId,
213
215
  userEmail: options.userEmail ?? options.to,
214
216
  status: "failed",
@@ -232,6 +234,42 @@ async function sendTrackedEmailInner<K extends TemplateName>(
232
234
  });
233
235
  }
234
236
 
237
+ // Global control group (impact plan §4.3) — a deterministic contact-level
238
+ // bucket excluded from every non-transactional send so program-level lift
239
+ // is measurable. Runs INSIDE the non-system branch and additionally
240
+ // exempts the transactional category (control contacts still get
241
+ // receipts/resets). No provider call, no row — mirrors the frequency-cap
242
+ // skip. The outbound marker is per-endpoint deduped on the contact key,
243
+ // so the first suppressed send publishes membership exactly once.
244
+ if (effectiveCategory !== "transactional") {
245
+ const controlKey = options.userId ?? options.to;
246
+ if (isGlobalControl(controlKey)) {
247
+ logger?.info("send skipped: control_group", { to: options.to });
248
+ void emitOutbound({
249
+ db,
250
+ hatchet,
251
+ logger: logger ?? emitLogger,
252
+ event: "contact.control_group",
253
+ dedupeKey: `contact.control_group:${controlKey.toLowerCase()}`,
254
+ payload: {
255
+ userId: options.userId ?? null,
256
+ email: options.to,
257
+ at: new Date().toISOString(),
258
+ },
259
+ }).catch((err: unknown) => {
260
+ (logger ?? emitLogger).warn("control_group marker emit failed", {
261
+ error: err instanceof Error ? err.message : String(err),
262
+ });
263
+ });
264
+ return trackedSendResult({
265
+ emailSendId: "",
266
+ messageId: "",
267
+ status: "skipped",
268
+ reason: "control_group",
269
+ });
270
+ }
271
+ }
272
+
235
273
  // Frequency cap — consulted only for non-system sends (system mail sets
236
274
  // skipPreferenceCheck and bypasses both suppression and the cap). On a cap
237
275
  // hit: no provider call, no row inserted, no throw — the journey continues.
@@ -357,6 +395,7 @@ async function sendTrackedEmailInner<K extends TemplateName>(
357
395
  subject: options.subject ?? "",
358
396
  category: effectiveCategory,
359
397
  journeyStateId: options.journeyStateId,
398
+ campaignId: options.campaignId,
360
399
  userId: options.userId,
361
400
  userEmail: options.userEmail ?? options.to,
362
401
  status: "failed",
@@ -411,6 +450,7 @@ async function sendTrackedEmailInner<K extends TemplateName>(
411
450
  subject: wireSubject,
412
451
  category: effectiveCategory,
413
452
  journeyStateId: options.journeyStateId,
453
+ campaignId: options.campaignId,
414
454
  userId: options.userId,
415
455
  userEmail: options.userEmail ?? options.to,
416
456
  status: "queued",
@@ -20,3 +20,9 @@ export const LINK_CLICKED = "link.clicked" as const;
20
20
  // "did a known user scan this QR?". Bus + outbound both define `linkId` as the
21
21
  // managed `links.id` and carry `trackedLinkId` separately (no legacy split).
22
22
  export const LINK_ARRIVED = "link.arrived" as const;
23
+
24
+ // First-party BUS event for an SMS short-link click (`/s/:code`) — the SMS
25
+ // sibling of `email.link_clicked`, re-ingested through `ingestEvent` so
26
+ // journeys can trigger / `ctx.waitForEvent` on a click of a link texted to
27
+ // THIS user. The per-hit OUTBOUND counterpart is `sms.clicked`.
28
+ export const SMS_LINK_CLICKED = "sms.link_clicked" as const;
@@ -1,6 +1,11 @@
1
1
  import type { HatchetClient } from "@hatchet-dev/typescript-sdk/v1/index.js";
2
2
  import type { JourneyRegistry } from "@hogsend/core/registry";
3
- import { type Database, emailSends, journeyStates } from "@hogsend/db";
3
+ import {
4
+ type Database,
5
+ emailSends,
6
+ journeyStates,
7
+ smsSends,
8
+ } from "@hogsend/db";
4
9
  import { eq } from "drizzle-orm";
5
10
  import { type IngestResult, ingestEvent } from "./ingestion.js";
6
11
  import type { Logger } from "./logger.js";
@@ -12,6 +17,14 @@ interface EmailSendContext {
12
17
  templateKey: string | null;
13
18
  messageId: string | null;
14
19
  to: string;
20
+ /**
21
+ * Attribution scope (plan §1.2): the enrollment's journey id and the send's
22
+ * campaign id, stamped into every tracking event's properties so the credit
23
+ * ledger can slice by journey/campaign without a join back through
24
+ * email_sends. Null for transactional/raw sends.
25
+ */
26
+ journeyId: string | null;
27
+ campaignId: string | null;
15
28
  }
16
29
 
17
30
  export async function resolveEmailSendContext(
@@ -27,8 +40,10 @@ export async function resolveEmailSendContext(
27
40
  toEmail: emailSends.toEmail,
28
41
  templateKey: emailSends.templateKey,
29
42
  messageId: emailSends.messageId,
43
+ campaignId: emailSends.campaignId,
30
44
  userId: journeyStates.userId,
31
45
  userEmail: journeyStates.userEmail,
46
+ journeyId: journeyStates.journeyId,
32
47
  })
33
48
  .from(emailSends)
34
49
  .leftJoin(journeyStates, eq(emailSends.journeyStateId, journeyStates.id))
@@ -44,6 +59,8 @@ export async function resolveEmailSendContext(
44
59
  templateKey: row.templateKey,
45
60
  messageId: row.messageId,
46
61
  to: row.toEmail,
62
+ journeyId: row.journeyId,
63
+ campaignId: row.campaignId,
47
64
  };
48
65
  }
49
66
 
@@ -160,6 +177,10 @@ export async function pushTrackingEvent(
160
177
  const properties: Record<string, unknown> = {
161
178
  emailSendId,
162
179
  templateKey: ctx.templateKey,
180
+ // Attribution scope (plan §1.2) — journey/campaign identity rides the
181
+ // spine on every touch event so credits can be sliced without re-joining.
182
+ journeyId: ctx.journeyId,
183
+ campaignId: ctx.campaignId,
163
184
  ...opts.properties,
164
185
  };
165
186
 
@@ -252,3 +273,114 @@ export async function pushLinkClickEvent(
252
273
  },
253
274
  });
254
275
  }
276
+
277
+ export interface SmsSendContext {
278
+ /**
279
+ * The resolved contact key: the enrollment's userId, else the send row's
280
+ * denormalized userId, else NULL. Deliberately NO phone fallback — phone is
281
+ * not a merge-participating contact `Kind`, so a phone-keyed ingest would
282
+ * fork an orphan contact.
283
+ */
284
+ userId: string | null;
285
+ userEmail: string | null;
286
+ templateKey: string | null;
287
+ messageId: string | null;
288
+ to: string;
289
+ /**
290
+ * Attribution scope (plan §1.2): the enrollment's journey id. No campaign
291
+ * leg — campaign steps are email-only today, so `sms_sends` carries no
292
+ * campaign column (plan §5 Q3).
293
+ */
294
+ journeyId: string | null;
295
+ }
296
+
297
+ /**
298
+ * The SMS sibling of {@link resolveEmailSendContext}: one LEFT JOIN from
299
+ * `sms_sends` to `journey_states` giving the click pipeline the identity +
300
+ * template context for the bus re-ingest and the `sms.clicked` outbound emit.
301
+ */
302
+ export async function resolveSmsSendContext(
303
+ db: Database,
304
+ smsSendId: string | null,
305
+ ): Promise<SmsSendContext | null> {
306
+ if (!smsSendId) return null;
307
+ const rows = await db
308
+ .select({
309
+ toPhone: smsSends.toPhone,
310
+ templateKey: smsSends.templateKey,
311
+ messageId: smsSends.messageId,
312
+ sendUserId: smsSends.userId,
313
+ userId: journeyStates.userId,
314
+ userEmail: journeyStates.userEmail,
315
+ journeyId: journeyStates.journeyId,
316
+ })
317
+ .from(smsSends)
318
+ .leftJoin(journeyStates, eq(smsSends.journeyStateId, journeyStates.id))
319
+ .where(eq(smsSends.id, smsSendId))
320
+ .limit(1);
321
+
322
+ const row = rows[0];
323
+ if (!row) return null;
324
+
325
+ return {
326
+ userId: row.userId ?? row.sendUserId ?? null,
327
+ userEmail: row.userEmail ?? null,
328
+ templateKey: row.templateKey,
329
+ messageId: row.messageId,
330
+ to: row.toPhone,
331
+ journeyId: row.journeyId,
332
+ };
333
+ }
334
+
335
+ export interface PushSmsTrackingEventOpts {
336
+ db: Database;
337
+ hatchet: HatchetClient;
338
+ registry: JourneyRegistry;
339
+ logger: Logger;
340
+ event: string;
341
+ smsSendId: string;
342
+ properties?: Record<string, unknown>;
343
+ /** Pre-resolved send context (including null) skips the duplicate read. */
344
+ resolvedContext?: SmsSendContext | null;
345
+ idempotencyKey?: string;
346
+ }
347
+
348
+ /**
349
+ * Re-push a first-party SMS tracking event (short-link click) onto the
350
+ * INTERNAL bus for journey routing + `userEvents` persistence — the SMS
351
+ * sibling of {@link pushTrackingEvent}. Returns undefined without ingesting
352
+ * when the send has no resolvable contact key (`ingestEvent` throws on a
353
+ * zero-key event, and phone is not a contact key).
354
+ */
355
+ export async function pushSmsTrackingEvent(
356
+ opts: PushSmsTrackingEventOpts,
357
+ ): Promise<IngestResult | undefined> {
358
+ const { db, hatchet, registry, logger, event, smsSendId } = opts;
359
+
360
+ const ctx =
361
+ opts.resolvedContext !== undefined
362
+ ? opts.resolvedContext
363
+ : await resolveSmsSendContext(db, smsSendId);
364
+ if (!ctx?.userId) return undefined;
365
+
366
+ return await ingestEvent({
367
+ db,
368
+ registry,
369
+ hatchet,
370
+ logger,
371
+ event: {
372
+ event,
373
+ userId: ctx.userId,
374
+ userEmail: ctx.userEmail ?? undefined,
375
+ eventProperties: {
376
+ smsSendId,
377
+ templateKey: ctx.templateKey,
378
+ // Attribution scope (plan §1.2) — see pushTrackingEvent.
379
+ journeyId: ctx.journeyId,
380
+ ...opts.properties,
381
+ },
382
+ source: "tracking",
383
+ idempotencyKey: opts.idempotencyKey,
384
+ },
385
+ });
386
+ }
@@ -30,7 +30,8 @@ const SKIP_PATTERNS = ["/v1/email/unsubscribe", "/v1/email/preferences"];
30
30
  // them small and scalar (non-scalars don't survive the Hatchet wire anyway).
31
31
  const MAX_PROPS_JSON_LENGTH = 2048;
32
32
 
33
- function shouldSkipUrl(url: string): boolean {
33
+ /** Never rewrite unsubscribe/preference URLs (shared with the SMS rewriter). */
34
+ export function shouldSkipUrl(url: string): boolean {
34
35
  return SKIP_PATTERNS.some((pattern) => url.includes(pattern));
35
36
  }
36
37
 
@@ -25,10 +25,21 @@ import { Webhook } from "svix";
25
25
  */
26
26
 
27
27
  /**
28
- * The 16-event catalog — the SINGLE source of truth (schema, routes, client,
28
+ * The 21-event catalog — the SINGLE source of truth (schema, routes, client,
29
29
  * CLI all derive from this). The `webhook.test` sentinel is intentionally NOT a
30
30
  * member (it is delivered out-of-band regardless of an endpoint's `eventTypes`).
31
31
  *
32
+ * `contact.subscribed` mirrors `contact.unsubscribed` for a genuine opt-IN
33
+ * (resubscribe-all or a category/channel grant), emitted from the single
34
+ * preference-write choke with `source` provenance — the consent audit signal
35
+ * for the explicit-opt-in SMS channel (grants were previously silent).
36
+ *
37
+ * The `sms.*` family mirrors the email lifecycle for the SMS channel:
38
+ * `sms.sent` (provider-accepted, first-party), `sms.delivered` / `sms.failed`
39
+ * (provider status webhook — the single source, no first-party signal), and
40
+ * `sms.clicked` (first-party, per-hit, from the `/s/:code` short-link
41
+ * redirect — the SMS sibling of `email.clicked`).
42
+ *
32
43
  * `link.clicked` is the NON-email click event: a click on a tracked link that
33
44
  * has no email send (Discord/referral/ad-hoc `createTrackedLink`). It is the
34
45
  * deliberate counterpart to `email.clicked` so a non-email click never fires a
@@ -43,6 +54,10 @@ export const WEBHOOK_EVENT_TYPES = [
43
54
  "contact.updated",
44
55
  "contact.deleted",
45
56
  "contact.unsubscribed",
57
+ "contact.subscribed",
58
+ // Global control group membership (impact plan §4.3) — emitted once per
59
+ // contact key on the first withheld send.
60
+ "contact.control_group",
46
61
  "email.sent",
47
62
  "email.delivered",
48
63
  "email.opened",
@@ -50,11 +65,19 @@ export const WEBHOOK_EVENT_TYPES = [
50
65
  "email.action",
51
66
  "email.bounced",
52
67
  "email.complained",
68
+ "sms.sent",
69
+ "sms.delivered",
70
+ "sms.failed",
71
+ "sms.clicked",
53
72
  "journey.completed",
73
+ "journey.heldout",
54
74
  "bucket.entered",
55
75
  "bucket.left",
56
76
  "link.clicked",
57
77
  "link.arrived",
78
+ "funnel.stage_changed",
79
+ "deal.quoted",
80
+ "deal.sold",
58
81
  ] as const;
59
82
 
60
83
  export type WebhookEventType = (typeof WEBHOOK_EVENT_TYPES)[number];
@@ -46,6 +46,7 @@ function capitalize(id: string): string {
46
46
  */
47
47
  export function synthesizeChannelLists(
48
48
  actions: DefinedConnectorAction[],
49
+ opts?: { sms?: boolean },
49
50
  ): ListMeta[] {
50
51
  const channels: ListMeta[] = [
51
52
  {
@@ -71,5 +72,25 @@ export function synthesizeChannelLists(
71
72
  });
72
73
  }
73
74
 
75
+ // The SMS channel is minted when an SMS provider is configured (SMS is NOT a
76
+ // connector). UNLIKE every other channel it is OPT-IN polarity
77
+ // (`defaultOptIn: false`, not configurable): TCPA/CASL/PECR all require prior
78
+ // EXPRESS consent for marketing SMS, so a contact is textable only with an
79
+ // explicit `categories.sms === true` grant (API/SDK/preference-center) or
80
+ // phone-track consent (an inbound START). The tracked SMS sender fails closed
81
+ // (`no_consent`) without one; transactional sends are exempt from the consent
82
+ // gate but never from the STOP list. De-duped via `seen` in case a connector
83
+ // also happened to use the id "sms".
84
+ if (opts?.sms && !seen.has("sms")) {
85
+ seen.add("sms");
86
+ channels.push({
87
+ id: "sms",
88
+ name: "SMS",
89
+ defaultOptIn: false,
90
+ enabled: true,
91
+ kind: "channel",
92
+ });
93
+ }
94
+
74
95
  return channels;
75
96
  }