@hogsend/engine 0.42.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.
@@ -0,0 +1,338 @@
1
+ import type {
2
+ SmsEvent,
3
+ SmsEventType,
4
+ SmsProvider,
5
+ SmsWebhookHandlerMap,
6
+ } from "@hogsend/core";
7
+ import type { Database } from "@hogsend/db";
8
+ import { smsSends, smsSuppressions } from "@hogsend/db";
9
+ import {
10
+ countSmsSegments,
11
+ getSmsTemplate,
12
+ renderSmsToText,
13
+ type SmsTemplateName,
14
+ } from "@hogsend/sms";
15
+ import { and, eq, inArray } from "drizzle-orm";
16
+ import { hatchet } from "./hatchet.js";
17
+ import { createLogger } from "./logger.js";
18
+ import { emitOutbound } from "./outbound.js";
19
+ import { handleInboundSms } from "./sms-inbound.js";
20
+ import type {
21
+ SmsService,
22
+ SmsServiceConfig,
23
+ SmsServiceRenderOptions,
24
+ SmsServiceRenderResult,
25
+ SmsServiceSendOptions,
26
+ SmsServiceWebhookResult,
27
+ SmsTrackedSendResult,
28
+ } from "./sms-service-types.js";
29
+ import { sendTrackedSms } from "./sms-tracked.js";
30
+
31
+ const emitLogger = createLogger(process.env.LOG_LEVEL);
32
+
33
+ type SmsSendStatus = "queued" | "sent" | "delivered" | "failed";
34
+
35
+ /**
36
+ * SMS event → the `sms_sends` timestamp column + status it sets, plus the
37
+ * statuses it may LEGALLY transition from. Twilio status callbacks are separate
38
+ * unordered HTTP requests (a delayed `sent` can land after `delivered`), so the
39
+ * update is guarded monotonic: a callback that does not ADVANCE the lifecycle
40
+ * matches zero rows and is dropped — which also makes duplicate callbacks
41
+ * emit-once (the atomic guarded UPDATE is the dedup).
42
+ */
43
+ const WEBHOOK_TO_SMS_STATUS: Partial<
44
+ Record<
45
+ SmsEventType,
46
+ {
47
+ field: "sentAt" | "deliveredAt" | "failedAt";
48
+ status: SmsSendStatus;
49
+ allowedFrom: SmsSendStatus[];
50
+ }
51
+ >
52
+ > = {
53
+ "sms.sent": { field: "sentAt", status: "sent", allowedFrom: ["queued"] },
54
+ "sms.delivered": {
55
+ field: "deliveredAt",
56
+ status: "delivered",
57
+ allowedFrom: ["queued", "sent"],
58
+ },
59
+ "sms.failed": {
60
+ field: "failedAt",
61
+ status: "failed",
62
+ allowedFrom: ["queued", "sent"],
63
+ },
64
+ };
65
+
66
+ /**
67
+ * The engine-owned high-level SMS sender. Owns the full pipeline — render →
68
+ * preference/suppression check → `sms_sends` insert → `provider.send` → status
69
+ * record — and delegates only raw delivery + webhook parse/verify to the
70
+ * injected {@link SmsProvider}. The SMS sibling of `createTrackedMailer`.
71
+ */
72
+ export function createTrackedSmsSender(
73
+ config: SmsServiceConfig,
74
+ deps: { provider: SmsProvider },
75
+ ): SmsService {
76
+ const { provider } = deps;
77
+ const db = config.db as Database | undefined;
78
+ const registry = config.templates;
79
+ const logger = config.logger ?? emitLogger;
80
+
81
+ function resolveFrom(overrideFrom?: string): string {
82
+ const from = overrideFrom ?? config.defaultFrom;
83
+ if (!from) {
84
+ throw new Error(
85
+ "SMS send requires a `from` number — set SMS_FROM / sms.from, or pin a Twilio messaging service.",
86
+ );
87
+ }
88
+ return from;
89
+ }
90
+
91
+ const service: SmsService = {
92
+ async send<K extends SmsTemplateName>(
93
+ options: SmsServiceSendOptions<K>,
94
+ ): Promise<SmsTrackedSendResult> {
95
+ const from = resolveFrom(options.from);
96
+ if (db) {
97
+ return sendTrackedSms({
98
+ db,
99
+ provider,
100
+ registry,
101
+ frequencyCap: config.frequencyCap,
102
+ logger: config.logger,
103
+ stopFooter: config.stopFooter,
104
+ testMode: config.testMode,
105
+ testPhone: config.testPhone,
106
+ linkTracking: config.linkTracking,
107
+ linkHost: config.linkHost,
108
+ options: {
109
+ templateKey: options.template,
110
+ props: options.props,
111
+ from,
112
+ to: options.to,
113
+ journeyStateId: options.journeyStateId,
114
+ userId: options.userId,
115
+ category: options.category,
116
+ skipPreferenceCheck: options.skipPreferenceCheck,
117
+ idempotencyKey: options.idempotencyKey,
118
+ },
119
+ });
120
+ }
121
+
122
+ // No-db fallback (tests / bare instance): render + send, no tracking row.
123
+ const { element } = getSmsTemplate({
124
+ key: options.template,
125
+ props: options.props,
126
+ registry,
127
+ });
128
+ const body = await renderSmsToText(element);
129
+ const result = await provider.send({ from, to: options.to, body });
130
+ return { smsSendId: "", messageId: result.id, status: "sent" };
131
+ },
132
+
133
+ async sendRaw(options): Promise<{ id: string }> {
134
+ return provider.send({ ...options, from: resolveFrom(options.from) });
135
+ },
136
+
137
+ async render<K extends SmsTemplateName>(
138
+ options: SmsServiceRenderOptions<K>,
139
+ ): Promise<SmsServiceRenderResult> {
140
+ const { element, category } = getSmsTemplate({
141
+ key: options.template,
142
+ props: options.props,
143
+ registry,
144
+ });
145
+ const text = await renderSmsToText(element);
146
+ return { text, category, segments: countSmsSegments(text).segments };
147
+ },
148
+
149
+ async handleWebhook(
150
+ event: SmsEvent,
151
+ _providerId?: string,
152
+ ): Promise<SmsServiceWebhookResult> {
153
+ const userHandlers: SmsWebhookHandlerMap = config.webhookHandlers ?? {};
154
+ const handled = await dispatchSmsWebhook(event, userHandlers);
155
+ return { type: event.type, handled };
156
+ },
157
+ };
158
+
159
+ async function dispatchSmsWebhook(
160
+ event: SmsEvent,
161
+ userHandlers: SmsWebhookHandlerMap,
162
+ ): Promise<boolean> {
163
+ switch (event.type) {
164
+ case "sms.sent":
165
+ // First-party `sms.sent` already emitted from the tracked sender — the
166
+ // provider echo only updates DB status (and only from `queued`).
167
+ await updateSmsStatus(event.type, event.messageId);
168
+ break;
169
+ case "sms.delivered": {
170
+ // Provider webhook is the SINGLE source for delivered (no first-party
171
+ // signal) — emit outbound, but only when the guarded UPDATE actually
172
+ // advanced the row (a duplicate/late callback emits nothing).
173
+ const ctx = await updateSmsStatus(event.type, event.messageId);
174
+ if (ctx) {
175
+ await emitProviderSmsEvent("sms.delivered", event.messageId, ctx);
176
+ }
177
+ break;
178
+ }
179
+ case "sms.failed": {
180
+ const ctx = await updateSmsStatus(event.type, event.messageId, {
181
+ errorCode: event.failure?.code,
182
+ errorReason: event.failure?.reason,
183
+ });
184
+ if (ctx) {
185
+ await emitProviderSmsEvent("sms.failed", event.messageId, ctx, {
186
+ errorCode: event.failure?.code,
187
+ errorReason: event.failure?.reason,
188
+ });
189
+ }
190
+ // A permanent carrier failure auto-suppresses the number (mirrors email
191
+ // permanent-bounce auto-suppress) so we stop paying to text a dead
192
+ // line. Independent of the status guard — the suppression signal holds
193
+ // even when callbacks arrive out of order.
194
+ if (event.failure?.class === "permanent") {
195
+ await suppressPermanent(event.phone);
196
+ }
197
+ break;
198
+ }
199
+ case "sms.inbound":
200
+ if (db) {
201
+ await handleInboundSms(event, {
202
+ db,
203
+ provider,
204
+ logger,
205
+ optOutReplies: config.optOutReplies,
206
+ from: config.defaultFrom,
207
+ });
208
+ }
209
+ break;
210
+ }
211
+
212
+ const userHandler = userHandlers[event.type] as
213
+ | ((e: SmsEvent) => void | Promise<void>)
214
+ | undefined;
215
+ if (userHandler) {
216
+ await userHandler(event);
217
+ return true;
218
+ }
219
+ return false;
220
+ }
221
+
222
+ /**
223
+ * Guarded-monotonic status update. Returns the advanced row's emit context,
224
+ * or null when the callback did not advance the lifecycle (duplicate,
225
+ * out-of-order, or unknown messageId) — the `.returning()` doubles as the
226
+ * single query the outbound emit needs, so there is no second lookup.
227
+ */
228
+ async function updateSmsStatus(
229
+ eventType: SmsEventType,
230
+ messageId: string,
231
+ extra?: { errorCode?: string; errorReason?: string },
232
+ ): Promise<SmsSendEmitContext | null> {
233
+ if (!db || !messageId) return null;
234
+ const mapping = WEBHOOK_TO_SMS_STATUS[eventType];
235
+ if (!mapping) return null;
236
+ const rows = await db
237
+ .update(smsSends)
238
+ .set({
239
+ status: mapping.status,
240
+ [mapping.field]: new Date(),
241
+ ...(extra?.errorCode ? { errorCode: extra.errorCode } : {}),
242
+ ...(extra?.errorReason ? { errorReason: extra.errorReason } : {}),
243
+ updatedAt: new Date(),
244
+ })
245
+ .where(
246
+ and(
247
+ eq(smsSends.messageId, messageId),
248
+ inArray(smsSends.status, mapping.allowedFrom),
249
+ ),
250
+ )
251
+ .returning({
252
+ smsSendId: smsSends.id,
253
+ templateKey: smsSends.templateKey,
254
+ userId: smsSends.userId,
255
+ toPhone: smsSends.toPhone,
256
+ });
257
+ return rows[0] ?? null;
258
+ }
259
+
260
+ async function suppressPermanent(phone: string): Promise<void> {
261
+ if (!db) return;
262
+ const now = new Date();
263
+ await db
264
+ .insert(smsSuppressions)
265
+ .values({ phone, reason: "carrier_permanent", suppressedAt: now })
266
+ .onConflictDoUpdate({
267
+ target: smsSuppressions.phone,
268
+ set: {
269
+ reason: "carrier_permanent",
270
+ suppressedAt: now,
271
+ resubscribedAt: null,
272
+ updatedAt: now,
273
+ },
274
+ });
275
+ }
276
+
277
+ /**
278
+ * Emit the single-source provider events. `sms.delivered`/`sms.failed` have
279
+ * no first-party signal, and Twilio aggressively retries callbacks — the
280
+ * guarded UPDATE upstream already makes this emit-once per transition, and
281
+ * the dedupeKey backstops any endpoint-level replay.
282
+ */
283
+ async function emitProviderSmsEvent(
284
+ event: "sms.delivered" | "sms.failed",
285
+ messageId: string,
286
+ ctx: SmsSendEmitContext,
287
+ extra?: { errorCode?: string; errorReason?: string },
288
+ ): Promise<void> {
289
+ if (!db) return;
290
+ const base = {
291
+ smsSendId: ctx.smsSendId,
292
+ messageId,
293
+ templateKey: ctx.templateKey,
294
+ userId: ctx.userId,
295
+ to: ctx.toPhone,
296
+ at: new Date().toISOString(),
297
+ };
298
+ try {
299
+ if (event === "sms.failed") {
300
+ await emitOutbound({
301
+ db,
302
+ hatchet,
303
+ logger,
304
+ event: "sms.failed",
305
+ dedupeKey: `sms.failed:${ctx.smsSendId}`,
306
+ payload: {
307
+ ...base,
308
+ ...(extra?.errorCode ? { errorCode: extra.errorCode } : {}),
309
+ ...(extra?.errorReason ? { errorReason: extra.errorReason } : {}),
310
+ },
311
+ });
312
+ } else {
313
+ await emitOutbound({
314
+ db,
315
+ hatchet,
316
+ logger,
317
+ event: "sms.delivered",
318
+ dedupeKey: `sms.delivered:${ctx.smsSendId}`,
319
+ payload: base,
320
+ });
321
+ }
322
+ } catch (err: unknown) {
323
+ logger.warn(`emitOutbound ${event} failed`, {
324
+ messageId,
325
+ error: err instanceof Error ? err.message : String(err),
326
+ });
327
+ }
328
+ }
329
+
330
+ return service;
331
+ }
332
+
333
+ interface SmsSendEmitContext {
334
+ smsSendId: string;
335
+ templateKey: string | null;
336
+ userId: string | null;
337
+ toPhone: string;
338
+ }
@@ -0,0 +1,35 @@
1
+ import type { SmsProvider } from "@hogsend/core";
2
+
3
+ /**
4
+ * Container-held registry of SMS providers, keyed by `provider.meta.id`. The
5
+ * webhook route (`POST /v1/webhooks/sms/:providerId`) resolves the verifying
6
+ * provider out of this via `c.get("container")`, and the container picks ONE
7
+ * active provider out of it for the tracked SMS sender.
8
+ *
9
+ * The SMS sibling of {@link EmailProviderRegistry}. Unlike email, `meta` is
10
+ * REQUIRED on the SMS contract (no pre-registry back-compat), so there is no
11
+ * fallback id — last-writer-wins on `meta.id`.
12
+ */
13
+ export class SmsProviderRegistry {
14
+ private byId = new Map<string, SmsProvider>();
15
+
16
+ constructor(providers: SmsProvider[] = []) {
17
+ for (const provider of providers) this.register(provider);
18
+ }
19
+
20
+ register(provider: SmsProvider): void {
21
+ this.byId.set(provider.meta.id, provider);
22
+ }
23
+
24
+ get(id: string): SmsProvider | undefined {
25
+ return this.byId.get(id);
26
+ }
27
+
28
+ getAll(): SmsProvider[] {
29
+ return [...this.byId.values()];
30
+ }
31
+
32
+ count(): number {
33
+ return this.byId.size;
34
+ }
35
+ }
@@ -0,0 +1,100 @@
1
+ import type { SmsProvider } from "@hogsend/core";
2
+ import type { env as envSchema } from "../env.js";
3
+
4
+ /**
5
+ * `@hogsend/plugin-twilio` is an OPT-IN, deferred-publish package — an engine
6
+ * `optionalDependency`, NOT a hard one. Mirroring the Postmark pattern in
7
+ * `email-providers-from-env.ts`, we MUST NOT statically import it: a static
8
+ * import would make the package mandatory at engine load and break
9
+ * `npm install @hogsend/engine` for every consumer without it.
10
+ *
11
+ * Instead we load it lazily, ONCE, behind a top-level guarded dynamic import
12
+ * gated on the Twilio credentials being present. The specifier is assembled at
13
+ * runtime (not a literal) so `tsc` never tries to resolve the module's types for
14
+ * a consumer that doesn't have the opt-in package installed.
15
+ */
16
+ type CreateTwilioProvider = (cfg: {
17
+ accountSid: string;
18
+ authToken: string;
19
+ from?: string;
20
+ messagingServiceSid?: string;
21
+ statusCallbackUrl?: string;
22
+ }) => SmsProvider;
23
+
24
+ const TWILIO_PACKAGE = ["@hogsend", "plugin-twilio"].join("/");
25
+
26
+ let createTwilioProvider: CreateTwilioProvider | null = null;
27
+ if (process.env.TWILIO_ACCOUNT_SID && process.env.TWILIO_AUTH_TOKEN) {
28
+ try {
29
+ ({ createTwilioProvider } = (await import(TWILIO_PACKAGE)) as {
30
+ createTwilioProvider: CreateTwilioProvider;
31
+ });
32
+ } catch {
33
+ // Credentials set but the opt-in package isn't installed. Leave the factory
34
+ // null — `smsProvidersFromEnv` skips the preset, and if Twilio was the
35
+ // resolved active provider the container throws a clear "not registered"
36
+ // error directing the operator to install `@hogsend/plugin-twilio`.
37
+ createTwilioProvider = null;
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Build the env-enabled SMS-provider presets. A preset is constructed ONLY when
43
+ * its credentials are present, so a deploy without Twilio creds contributes no
44
+ * provider (and the container installs an inert throwing-stub SMS service).
45
+ *
46
+ * These presets come FIRST in the container's merge — a consumer-supplied
47
+ * provider of the same id wins (last-writer-wins on the registry).
48
+ */
49
+ /**
50
+ * A non-public `API_PUBLIC_URL` (localhost / loopback) cannot receive Twilio's
51
+ * status callback, and Twilio REJECTS a localhost `statusCallback` outright
52
+ * (error 21609 — the send 400s). So we only auto-attach the callback when the
53
+ * public URL is genuinely reachable — local `pnpm dev` sends then succeed (with
54
+ * no delivery receipts, which localhost can't receive anyway), while a real
55
+ * deploy still wires the callback.
56
+ */
57
+ function isPubliclyReachable(url: string): boolean {
58
+ try {
59
+ const host = new URL(url).hostname.toLowerCase();
60
+ return !(
61
+ host === "localhost" ||
62
+ host === "127.0.0.1" ||
63
+ host === "0.0.0.0" ||
64
+ host === "::1" ||
65
+ host.endsWith(".local")
66
+ );
67
+ } catch {
68
+ return false;
69
+ }
70
+ }
71
+
72
+ export function smsProvidersFromEnv(env: typeof envSchema): SmsProvider[] {
73
+ const providers: SmsProvider[] = [];
74
+
75
+ if (
76
+ env.TWILIO_ACCOUNT_SID &&
77
+ env.TWILIO_AUTH_TOKEN &&
78
+ createTwilioProvider &&
79
+ // Twilio needs a sender to construct; skip the preset (rather than throw at
80
+ // boot) when neither a from-number nor a messaging service is configured.
81
+ (env.SMS_FROM || env.TWILIO_MESSAGING_SERVICE_SID)
82
+ ) {
83
+ const statusCallbackUrl = isPubliclyReachable(env.API_PUBLIC_URL)
84
+ ? `${env.API_PUBLIC_URL}/v1/webhooks/sms/twilio`
85
+ : undefined;
86
+ providers.push(
87
+ createTwilioProvider({
88
+ accountSid: env.TWILIO_ACCOUNT_SID,
89
+ authToken: env.TWILIO_AUTH_TOKEN,
90
+ ...(env.SMS_FROM ? { from: env.SMS_FROM } : {}),
91
+ ...(env.TWILIO_MESSAGING_SERVICE_SID
92
+ ? { messagingServiceSid: env.TWILIO_MESSAGING_SERVICE_SID }
93
+ : {}),
94
+ ...(statusCallbackUrl ? { statusCallbackUrl } : {}),
95
+ }),
96
+ );
97
+ }
98
+
99
+ return providers;
100
+ }
@@ -0,0 +1,169 @@
1
+ import type {
2
+ SendSmsOptions,
3
+ SmsEvent,
4
+ SmsEventType,
5
+ SmsProvider,
6
+ SmsWebhookHandlerMap,
7
+ } from "@hogsend/core";
8
+ import type {
9
+ SmsTemplateName,
10
+ SmsTemplateRegistry,
11
+ SmsTemplateRegistryMap,
12
+ } from "@hogsend/sms";
13
+ import type { FrequencyCapConfig } from "./email-service-types.js";
14
+ import type { Logger } from "./logger.js";
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // Tracked SMS (high-level API)
18
+ // ---------------------------------------------------------------------------
19
+
20
+ export interface SendTrackedSmsOptions<
21
+ K extends SmsTemplateName = SmsTemplateName,
22
+ > {
23
+ templateKey: K;
24
+ props: SmsTemplateRegistryMap[K];
25
+ from: string;
26
+ to: string;
27
+ journeyStateId?: string;
28
+ /** Denormalized recipient identity, persisted on the sms_sends row. */
29
+ userId?: string;
30
+ category?: string;
31
+ /**
32
+ * Skips the consent + topic gates and the frequency cap — NEVER the phone
33
+ * STOP list or the `unsubscribed_all` master opt-out, which are enforced
34
+ * unconditionally (system sends must still respect a STOP).
35
+ */
36
+ skipPreferenceCheck?: boolean;
37
+ /**
38
+ * Caller-supplied idempotency key. A retry with the same key short-circuits to
39
+ * the prior `sms_sends` row instead of dispatching a duplicate provider send.
40
+ */
41
+ idempotencyKey?: string;
42
+ }
43
+
44
+ export interface SmsTrackedSendResult {
45
+ smsSendId: string;
46
+ /** The provider's neutral message id (Twilio MessageSid). */
47
+ messageId: string;
48
+ /**
49
+ * `"no_consent"` — the recipient has no explicit SMS consent (no
50
+ * `categories.sms === true` grant and no phone-track consent, or no
51
+ * resolvable `userId` on a non-transactional send). The consent model is
52
+ * explicit opt-in; the sender fails closed.
53
+ */
54
+ status: "sent" | "suppressed" | "unsubscribed" | "no_consent" | "skipped";
55
+ /**
56
+ * Present only when `status === "skipped"`:
57
+ * - `"frequency_capped"` — the per-recipient frequency cap was hit.
58
+ * - `"journey_suppressed"` — the journey's `meta.suppress` min-gap found a
59
+ * recent SMS to this recipient from the same journey.
60
+ * - `"test_mode_blocked"` — test mode active but no `HOGSEND_TEST_PHONE`, so
61
+ * the send was blocked rather than delivered to the real recipient.
62
+ */
63
+ reason?: "frequency_capped" | "journey_suppressed" | "test_mode_blocked";
64
+ }
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // SMS service (high-level DX) — engine-owned tracked SMS sender
68
+ // ---------------------------------------------------------------------------
69
+
70
+ export interface SmsServiceConfig {
71
+ defaultFrom?: string;
72
+ /** The client app's SMS template registry (key → component + category). */
73
+ templates: SmsTemplateRegistry;
74
+ db?: unknown;
75
+ webhookHandlers?: SmsWebhookHandlerMap;
76
+ /** Optional per-client frequency cap; undefined disables capping. */
77
+ frequencyCap?: FrequencyCapConfig;
78
+ logger?: Logger;
79
+ /**
80
+ * The compliance footer appended to non-transactional bodies when it isn't
81
+ * already present. `false` disables it entirely; a string overrides the
82
+ * default `"Reply STOP to opt out"`.
83
+ */
84
+ stopFooter?: string | false;
85
+ /**
86
+ * Whether the engine sends STOP/START/HELP confirmation replies on inbound
87
+ * keywords. Default `false`: Twilio's carrier-level opt-out already replies,
88
+ * and a post-STOP send is blocked by error 21610 — a double reply is worse
89
+ * than none. Operators who disable Twilio's Advanced Opt-Out can enable this.
90
+ */
91
+ optOutReplies?: boolean;
92
+ /**
93
+ * Resolves whether SMS test mode is active per send (container-wired from the
94
+ * validated HOGSEND_TEST_MODE, coherent with the email side's auto-arm).
95
+ * Absent ⇒ never active.
96
+ */
97
+ testMode?: () => boolean;
98
+ /** The redirect target while test mode is active (env.HOGSEND_TEST_PHONE). */
99
+ testPhone?: string;
100
+ /**
101
+ * Rewrite bare URLs in rendered bodies to first-party short tracked links
102
+ * (`/s/:code`). Default true (mirrors email's always-on tracking).
103
+ */
104
+ linkTracking?: boolean;
105
+ /**
106
+ * Full origin the short links are minted under (no trailing slash). The
107
+ * container resolves `sms.linkHost ?? SMS_LINK_HOST ?? API_PUBLIC_URL`.
108
+ * Rewriting is skipped when absent.
109
+ */
110
+ linkHost?: string;
111
+ }
112
+
113
+ export interface SmsServiceSendOptions<
114
+ K extends SmsTemplateName = SmsTemplateName,
115
+ > {
116
+ template: K;
117
+ props: SmsTemplateRegistryMap[K];
118
+ to: string;
119
+ from?: string;
120
+ journeyStateId?: string;
121
+ userId?: string;
122
+ category?: string;
123
+ skipPreferenceCheck?: boolean;
124
+ idempotencyKey?: string;
125
+ }
126
+
127
+ export interface SmsServiceRenderOptions<
128
+ K extends SmsTemplateName = SmsTemplateName,
129
+ > {
130
+ template: K;
131
+ props: SmsTemplateRegistryMap[K];
132
+ }
133
+
134
+ export interface SmsServiceRenderResult {
135
+ text: string;
136
+ category?: string;
137
+ segments: number;
138
+ }
139
+
140
+ export interface SmsServiceWebhookResult {
141
+ type: SmsEventType;
142
+ handled: boolean;
143
+ }
144
+
145
+ export interface SmsService {
146
+ send<K extends SmsTemplateName>(
147
+ options: SmsServiceSendOptions<K>,
148
+ ): Promise<SmsTrackedSendResult>;
149
+
150
+ /** Deliver a raw text body (no template, no tracking) — used for confirmations. */
151
+ sendRaw(options: SendSmsOptions): Promise<{ id: string }>;
152
+
153
+ render<K extends SmsTemplateName>(
154
+ options: SmsServiceRenderOptions<K>,
155
+ ): Promise<SmsServiceRenderResult>;
156
+
157
+ /**
158
+ * Dispatch an already-verified, provider-neutral {@link SmsEvent} into the
159
+ * status/suppression/inbound pipeline. The webhook route owns provider
160
+ * resolution + signature verification.
161
+ */
162
+ handleWebhook(
163
+ event: SmsEvent,
164
+ providerId?: string,
165
+ ): Promise<SmsServiceWebhookResult>;
166
+ }
167
+
168
+ /** The active SMS provider a tracked sender delegates raw delivery to. */
169
+ export type { SmsProvider };