@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.
- package/package.json +9 -7
- package/src/container.ts +192 -4
- package/src/env.ts +28 -0
- package/src/index.ts +39 -0
- package/src/journeys/journey-boundary.ts +5 -1
- package/src/journeys/journey-context.ts +26 -0
- package/src/lib/journey-suppress.ts +33 -2
- package/src/lib/outbound.ts +58 -0
- package/src/lib/phone.ts +19 -0
- package/src/lib/preferences.ts +32 -0
- package/src/lib/sms-frequency-cap.ts +47 -0
- package/src/lib/sms-inbound.ts +200 -0
- package/src/lib/sms-link-tracking.ts +160 -0
- package/src/lib/sms-mailer.ts +338 -0
- package/src/lib/sms-provider-registry.ts +35 -0
- package/src/lib/sms-providers-from-env.ts +100 -0
- package/src/lib/sms-service-types.ts +169 -0
- package/src/lib/sms-tracked.ts +590 -0
- package/src/lib/sms.ts +117 -0
- package/src/lib/tracking-event-names.ts +6 -0
- package/src/lib/tracking-events.ts +107 -1
- package/src/lib/tracking.ts +2 -1
- package/src/lib/webhook-signing.ts +17 -1
- package/src/lists/channels.ts +21 -0
- package/src/routes/email/unsubscribe.ts +1 -0
- package/src/routes/index.ts +6 -0
- package/src/routes/lists/index.ts +54 -7
- package/src/routes/tracking/click-pipeline.ts +83 -2
- package/src/routes/tracking/short.ts +61 -0
- package/src/routes/webhooks/index.ts +5 -1
- package/src/routes/webhooks/sms-provider.ts +110 -0
- package/src/workflows/import-contacts.ts +61 -4
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hogsend/engine",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.43.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -49,14 +49,16 @@
|
|
|
49
49
|
"svix": "^1.95.1",
|
|
50
50
|
"winston": "^3.19.0",
|
|
51
51
|
"zod": "^4.4.3",
|
|
52
|
-
"@hogsend/core": "^0.
|
|
53
|
-
"@hogsend/db": "^0.
|
|
54
|
-
"@hogsend/email": "^0.
|
|
55
|
-
"@hogsend/plugin-posthog": "^0.
|
|
56
|
-
"@hogsend/plugin-resend": "^0.
|
|
52
|
+
"@hogsend/core": "^0.43.0",
|
|
53
|
+
"@hogsend/db": "^0.43.0",
|
|
54
|
+
"@hogsend/email": "^0.43.0",
|
|
55
|
+
"@hogsend/plugin-posthog": "^0.43.0",
|
|
56
|
+
"@hogsend/plugin-resend": "^0.43.0",
|
|
57
|
+
"@hogsend/sms": "^0.43.0"
|
|
57
58
|
},
|
|
58
59
|
"optionalDependencies": {
|
|
59
|
-
"@hogsend/plugin-postmark": "^0.
|
|
60
|
+
"@hogsend/plugin-postmark": "^0.43.0",
|
|
61
|
+
"@hogsend/plugin-twilio": "^0.43.0"
|
|
60
62
|
},
|
|
61
63
|
"devDependencies": {
|
|
62
64
|
"@types/node": "^22.15.3",
|
package/src/container.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type {
|
|
|
5
5
|
EmailProvider,
|
|
6
6
|
JourneySourceLocation,
|
|
7
7
|
PostHogService,
|
|
8
|
+
SmsProvider,
|
|
8
9
|
TimeZone,
|
|
9
10
|
} from "@hogsend/core";
|
|
10
11
|
import type { BucketRegistry, JourneyRegistry } from "@hogsend/core/registry";
|
|
@@ -16,6 +17,7 @@ import {
|
|
|
16
17
|
type JournalShape,
|
|
17
18
|
} from "@hogsend/db";
|
|
18
19
|
import type { TemplateDefinition, TemplateRegistry } from "@hogsend/email";
|
|
20
|
+
import type { SmsTemplateDefinition, SmsTemplateRegistry } from "@hogsend/sms";
|
|
19
21
|
import { createBucketAccessor } from "./buckets/bucket-access.js";
|
|
20
22
|
import type { DefinedBucket } from "./buckets/define-bucket.js";
|
|
21
23
|
import {
|
|
@@ -78,6 +80,11 @@ import { createTrackedMailer } from "./lib/mailer.js";
|
|
|
78
80
|
import { createRedisSecondaryStorage, getRedis } from "./lib/redis.js";
|
|
79
81
|
import { sendResetPasswordEmail } from "./lib/reset-email.js";
|
|
80
82
|
import { seedPostHogDestination } from "./lib/seed-posthog-destination.js";
|
|
83
|
+
import { setSmsService } from "./lib/sms.js";
|
|
84
|
+
import { createTrackedSmsSender } from "./lib/sms-mailer.js";
|
|
85
|
+
import { SmsProviderRegistry } from "./lib/sms-provider-registry.js";
|
|
86
|
+
import { smsProvidersFromEnv } from "./lib/sms-providers-from-env.js";
|
|
87
|
+
import type { SmsService } from "./lib/sms-service-types.js";
|
|
81
88
|
import { prepareTrackedHtml } from "./lib/tracking.js";
|
|
82
89
|
import { synthesizeChannelLists } from "./lists/channels.js";
|
|
83
90
|
import {
|
|
@@ -134,6 +141,23 @@ export interface HogsendClient {
|
|
|
134
141
|
* templates without going through a send. Empty when no templates are wired.
|
|
135
142
|
*/
|
|
136
143
|
templates: TemplateRegistry;
|
|
144
|
+
/**
|
|
145
|
+
* The engine-owned tracked SMS sender (the SMS sibling of {@link emailService}).
|
|
146
|
+
* When no SMS provider is configured this is an inert stub whose `send` throws
|
|
147
|
+
* an actionable error — so an existing deploy without Twilio creds boots clean.
|
|
148
|
+
*/
|
|
149
|
+
smsService: SmsService;
|
|
150
|
+
/**
|
|
151
|
+
* The container-held registry of SMS providers, keyed by `meta.id`. The
|
|
152
|
+
* `POST /v1/webhooks/sms/:providerId` route resolves the verifying provider
|
|
153
|
+
* out of this. Empty when no SMS provider is configured.
|
|
154
|
+
*/
|
|
155
|
+
smsProviders: SmsProviderRegistry;
|
|
156
|
+
/**
|
|
157
|
+
* The single resolved active SMS provider the tracked sender delivers through.
|
|
158
|
+
* Undefined when no SMS provider is configured.
|
|
159
|
+
*/
|
|
160
|
+
smsProvider?: SmsProvider;
|
|
137
161
|
/**
|
|
138
162
|
* The container-held registry of analytics providers, keyed by `meta.id` —
|
|
139
163
|
* the analytics sibling of {@link emailProviders}. Built from env presets
|
|
@@ -274,6 +298,46 @@ export interface HogsendClientOptions {
|
|
|
274
298
|
defaultProvider?: string;
|
|
275
299
|
templates?: TemplateRegistry;
|
|
276
300
|
};
|
|
301
|
+
/**
|
|
302
|
+
* SMS is a first-class channel (the SMS sibling of {@link email}). Its config
|
|
303
|
+
* is grouped here; the engine owns the cohesive SMS pipeline (templates →
|
|
304
|
+
* render → preference/suppression checks → `sms_sends` write → STOP handling),
|
|
305
|
+
* and the {@link SmsProvider} (Twilio, …) is only the swappable wire.
|
|
306
|
+
*
|
|
307
|
+
* - `provider` — a single SMS provider. Merged LAST (after env presets and
|
|
308
|
+
* `providers`), so it wins on id collision.
|
|
309
|
+
* - `providers` — register MANY providers into the {@link SmsProviderRegistry}
|
|
310
|
+
* so `POST /v1/webhooks/sms/:providerId` can verify each one's webhooks.
|
|
311
|
+
* - `defaultProvider` — the active provider id the tracked sender delivers
|
|
312
|
+
* through. Resolves as `defaultProvider ?? SMS_PROVIDER ?? "twilio"`. If it
|
|
313
|
+
* names an unregistered provider, the container throws at boot.
|
|
314
|
+
* - `templates` — the app's SMS template registry (key → component +
|
|
315
|
+
* category), threaded into the tracked SMS sender.
|
|
316
|
+
* - `from` — the E.164 default sender (overrides env `SMS_FROM`).
|
|
317
|
+
* - `stopFooter` — the compliance footer appended to non-transactional
|
|
318
|
+
* bodies; `false` disables it, a string overrides the default text.
|
|
319
|
+
* - `optOutReplies` — send STOP/START/HELP confirmation replies (default off;
|
|
320
|
+
* the carrier already replies and a post-STOP send is blocked).
|
|
321
|
+
* - `linkTracking` — rewrite bare URLs in rendered bodies to first-party
|
|
322
|
+
* short tracked links (`/s/:code`). Default true (overrides env
|
|
323
|
+
* `SMS_LINK_TRACKING`).
|
|
324
|
+
* - `linkHost` — the full origin short links are minted under (overrides
|
|
325
|
+
* env `SMS_LINK_HOST`; falls back to `API_PUBLIC_URL`).
|
|
326
|
+
*
|
|
327
|
+
* Omitting `sms` entirely (or configuring no provider) installs an inert stub
|
|
328
|
+
* SMS service — an existing deploy without Twilio creds boots unchanged.
|
|
329
|
+
*/
|
|
330
|
+
sms?: {
|
|
331
|
+
provider?: SmsProvider;
|
|
332
|
+
providers?: SmsProvider[];
|
|
333
|
+
defaultProvider?: string;
|
|
334
|
+
templates?: SmsTemplateRegistry;
|
|
335
|
+
from?: string;
|
|
336
|
+
stopFooter?: string | false;
|
|
337
|
+
optOutReplies?: boolean;
|
|
338
|
+
linkTracking?: boolean;
|
|
339
|
+
linkHost?: string;
|
|
340
|
+
};
|
|
277
341
|
/**
|
|
278
342
|
* The analytics provider(s) — provider-neutral since the
|
|
279
343
|
* `AnalyticsProvider` contract (the analytics sibling of `EmailProvider`;
|
|
@@ -498,6 +562,33 @@ function validateListCategory(opts: {
|
|
|
498
562
|
);
|
|
499
563
|
}
|
|
500
564
|
|
|
565
|
+
/**
|
|
566
|
+
* The inert SMS service installed when no SMS provider is configured. `render`
|
|
567
|
+
* still works (templates need no provider); `send` throws an actionable error;
|
|
568
|
+
* `handleWebhook` is a no-op (a stray webhook can't dispatch without a provider).
|
|
569
|
+
*/
|
|
570
|
+
function createStubSmsService(): SmsService {
|
|
571
|
+
const notConfigured = () => {
|
|
572
|
+
throw new Error(
|
|
573
|
+
"No SMS provider configured. Set TWILIO_ACCOUNT_SID/TWILIO_AUTH_TOKEN and SMS_FROM, or pass sms.provider to createHogsendClient.",
|
|
574
|
+
);
|
|
575
|
+
};
|
|
576
|
+
return {
|
|
577
|
+
async send() {
|
|
578
|
+
return notConfigured();
|
|
579
|
+
},
|
|
580
|
+
async sendRaw() {
|
|
581
|
+
return notConfigured();
|
|
582
|
+
},
|
|
583
|
+
async render() {
|
|
584
|
+
return notConfigured();
|
|
585
|
+
},
|
|
586
|
+
async handleWebhook(event) {
|
|
587
|
+
return { type: event.type, handled: false };
|
|
588
|
+
},
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
|
|
501
592
|
export function createHogsendClient(
|
|
502
593
|
opts: HogsendClientOptions = {},
|
|
503
594
|
): HogsendClient {
|
|
@@ -563,7 +654,20 @@ export function createHogsendClient(
|
|
|
563
654
|
// is available here before the connector-action registry is built, and is
|
|
564
655
|
// identical in both the API and worker processes — then registered
|
|
565
656
|
// unconditionally (bypassing ENABLED_LISTS) after the user lists.
|
|
566
|
-
|
|
657
|
+
// Build the SMS provider registry early (before channel synthesis) so the
|
|
658
|
+
// `sms` opt-out channel is minted iff an SMS provider is actually configured.
|
|
659
|
+
// Same merge order as email: env presets FIRST, then `providers`, then the
|
|
660
|
+
// single `provider` LAST (last-writer-wins).
|
|
661
|
+
const smsProviders = new SmsProviderRegistry([
|
|
662
|
+
...smsProvidersFromEnv(env),
|
|
663
|
+
...(opts.sms?.providers ?? []),
|
|
664
|
+
...(opts.sms?.provider ? [opts.sms.provider] : []),
|
|
665
|
+
]);
|
|
666
|
+
const smsConfigured = smsProviders.count() > 0;
|
|
667
|
+
|
|
668
|
+
const channelLists = synthesizeChannelLists(opts.connectorActions ?? [], {
|
|
669
|
+
sms: smsConfigured,
|
|
670
|
+
});
|
|
567
671
|
const listRegistry = buildListRegistry(
|
|
568
672
|
opts.lists ?? [],
|
|
569
673
|
opts.enabledLists ?? env.ENABLED_LISTS,
|
|
@@ -724,6 +828,86 @@ export function createHogsendClient(
|
|
|
724
828
|
|
|
725
829
|
setEmailService(emailService);
|
|
726
830
|
|
|
831
|
+
// --- SMS channel (parallel to the email pipeline above) -------------------
|
|
832
|
+
// Resolve the active SMS provider: `defaultProvider ?? SMS_PROVIDER ?? "twilio"`.
|
|
833
|
+
// An EXPLICITLY-requested id that isn't registered throws (mirrors email's
|
|
834
|
+
// "never silently fall back"). When nothing is configured the registry is
|
|
835
|
+
// empty and `smsProvider` stays undefined — the tracked sender below becomes
|
|
836
|
+
// an inert stub so an existing deploy without Twilio creds boots unchanged.
|
|
837
|
+
const smsTemplates = opts.sms?.templates ?? ({} as SmsTemplateRegistry);
|
|
838
|
+
const smsActiveId = opts.sms?.defaultProvider ?? env.SMS_PROVIDER ?? "twilio";
|
|
839
|
+
const smsExplicit = Boolean(opts.sms?.defaultProvider ?? env.SMS_PROVIDER);
|
|
840
|
+
let smsProvider = smsProviders.get(smsActiveId);
|
|
841
|
+
// DX: when the active id wasn't explicitly requested and the default "twilio"
|
|
842
|
+
// isn't registered but EXACTLY ONE provider is, use that one — so a consumer
|
|
843
|
+
// passing a single `sms.provider` (any id) never has to also set
|
|
844
|
+
// `defaultProvider`. An explicit id that misses still throws below.
|
|
845
|
+
if (!smsProvider && !smsExplicit && smsProviders.count() === 1) {
|
|
846
|
+
smsProvider = smsProviders.getAll()[0];
|
|
847
|
+
}
|
|
848
|
+
if (smsExplicit && !smsProvider) {
|
|
849
|
+
throw new Error(
|
|
850
|
+
`SMS provider "${smsActiveId}" is not registered (registered: ${
|
|
851
|
+
smsProviders
|
|
852
|
+
.getAll()
|
|
853
|
+
.map((p) => p.meta.id)
|
|
854
|
+
.join(", ") || "none"
|
|
855
|
+
}). Set TWILIO_ACCOUNT_SID/TWILIO_AUTH_TOKEN and SMS_FROM, or pass sms.provider.`,
|
|
856
|
+
);
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// Boot-validate SMS template categories through the SAME fail-closed helper as
|
|
860
|
+
// email templates (a channel/typo/consent-flip category is as dangerous here).
|
|
861
|
+
for (const [templateKey, def] of Object.entries(smsTemplates)) {
|
|
862
|
+
const category = (def as SmsTemplateDefinition | undefined)?.category;
|
|
863
|
+
if (!category) continue;
|
|
864
|
+
validateListCategory({
|
|
865
|
+
owner: `SMS template "${templateKey}"`,
|
|
866
|
+
category,
|
|
867
|
+
listRegistry,
|
|
868
|
+
definedLists,
|
|
869
|
+
logger,
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
const smsService: SmsService = smsProvider
|
|
874
|
+
? createTrackedSmsSender(
|
|
875
|
+
{
|
|
876
|
+
defaultFrom: opts.sms?.from ?? env.SMS_FROM,
|
|
877
|
+
templates: smsTemplates,
|
|
878
|
+
db,
|
|
879
|
+
frequencyCap: defaults.frequencyCap,
|
|
880
|
+
logger,
|
|
881
|
+
stopFooter: opts.sms?.stopFooter,
|
|
882
|
+
optOutReplies: opts.sms?.optOutReplies,
|
|
883
|
+
// Deploy-wide test-mode coherence: HOGSEND_TEST_MODE is channel-
|
|
884
|
+
// neutral. "true" forces SMS test mode directly; "auto" arms it
|
|
885
|
+
// whenever the EMAIL side's test mode is armed (unverified domain),
|
|
886
|
+
// so a staging deploy that redirects email never live-texts real
|
|
887
|
+
// numbers. SMS has no domain-verification analog of its own, so
|
|
888
|
+
// "auto" with email test mode off keeps live sends (PR behavior).
|
|
889
|
+
testMode: () =>
|
|
890
|
+
env.HOGSEND_TEST_MODE === "true" ||
|
|
891
|
+
(env.HOGSEND_TEST_MODE === "auto" &&
|
|
892
|
+
domainStatus.testModeCached().active),
|
|
893
|
+
testPhone: env.HOGSEND_TEST_PHONE,
|
|
894
|
+
// First-party short-link rewriting (ON by default, mirrors email's
|
|
895
|
+
// always-on tracking). SMS_LINK_HOST swaps in a branded short
|
|
896
|
+
// domain; API_PUBLIC_URL serves out of the box.
|
|
897
|
+
linkTracking:
|
|
898
|
+
opts.sms?.linkTracking ?? env.SMS_LINK_TRACKING !== "false",
|
|
899
|
+
linkHost: (
|
|
900
|
+
opts.sms?.linkHost ??
|
|
901
|
+
env.SMS_LINK_HOST ??
|
|
902
|
+
env.API_PUBLIC_URL
|
|
903
|
+
).replace(/\/+$/, ""),
|
|
904
|
+
},
|
|
905
|
+
{ provider: smsProvider },
|
|
906
|
+
)
|
|
907
|
+
: createStubSmsService();
|
|
908
|
+
|
|
909
|
+
setSmsService(smsService);
|
|
910
|
+
|
|
727
911
|
// Wire better-auth's secondary storage to the SHARED engine Redis (the same
|
|
728
912
|
// singleton backing the PostHog cache + worker heartbeat — never a second
|
|
729
913
|
// pool). Passing `secondaryStorage` flips better-auth's rate-limit store from
|
|
@@ -929,11 +1113,12 @@ export function createHogsendClient(
|
|
|
929
1113
|
for (const connector of connectorList) {
|
|
930
1114
|
if (
|
|
931
1115
|
(connector.meta.transport ?? "webhook") === "webhook" &&
|
|
932
|
-
connector.meta.id === "email"
|
|
1116
|
+
(connector.meta.id === "email" || connector.meta.id === "sms")
|
|
933
1117
|
) {
|
|
934
1118
|
throw new Error(
|
|
935
|
-
|
|
936
|
-
"(POST /v1/webhooks/email/:providerId).
|
|
1119
|
+
`Connector id "${connector.meta.id}" is reserved for the ` +
|
|
1120
|
+
"email/SMS-provider routes (POST /v1/webhooks/{email,sms}/:providerId). " +
|
|
1121
|
+
"Rename the connector.",
|
|
937
1122
|
);
|
|
938
1123
|
}
|
|
939
1124
|
}
|
|
@@ -991,6 +1176,9 @@ export function createHogsendClient(
|
|
|
991
1176
|
emailProvider: provider,
|
|
992
1177
|
domainStatus,
|
|
993
1178
|
templates,
|
|
1179
|
+
smsService,
|
|
1180
|
+
smsProviders,
|
|
1181
|
+
smsProvider,
|
|
994
1182
|
analyticsProviders,
|
|
995
1183
|
analytics,
|
|
996
1184
|
identity,
|
package/src/env.ts
CHANGED
|
@@ -121,6 +121,34 @@ export const env = createEnv({
|
|
|
121
121
|
POSTMARK_MESSAGE_STREAM: z.string().min(1).optional(),
|
|
122
122
|
POSTMARK_WEBHOOK_USER: z.string().min(1).optional(),
|
|
123
123
|
POSTMARK_WEBHOOK_PASS: z.string().min(1).optional(),
|
|
124
|
+
// --- SMS channel (provider-neutral, BYO SMS provider) ---
|
|
125
|
+
// The active SMS provider id the container resolves from the
|
|
126
|
+
// SmsProviderRegistry. Absent → "twilio" when a provider is registered;
|
|
127
|
+
// with no provider configured the SMS service is an inert throwing stub.
|
|
128
|
+
SMS_PROVIDER: z.string().optional(),
|
|
129
|
+
// Neutral E.164 default-from number the tracked SMS sender uses when a send
|
|
130
|
+
// omits `from` and no messaging-service is pinned.
|
|
131
|
+
SMS_FROM: z.string().optional(),
|
|
132
|
+
// The safe phone every redirected SMS is delivered to under
|
|
133
|
+
// HOGSEND_TEST_MODE=true. When unset while test mode is active, the send is
|
|
134
|
+
// BLOCKED (recorded, never delivered to the real recipient).
|
|
135
|
+
HOGSEND_TEST_PHONE: z.string().optional(),
|
|
136
|
+
// SMS link shortening/tracking is ON by default when SMS is configured.
|
|
137
|
+
// An enum, NOT z.coerce.boolean — an explicit "false" must actually
|
|
138
|
+
// disable (coerce treats the string "false" as true; HOGSEND_TEST_MODE
|
|
139
|
+
// precedent).
|
|
140
|
+
SMS_LINK_TRACKING: z.enum(["true", "false"]).default("true"),
|
|
141
|
+
// Full origin short links are minted under (e.g. https://hs.example.com —
|
|
142
|
+
// a branded short domain routed to this app). Falls back to
|
|
143
|
+
// API_PUBLIC_URL; the /s/:code route serves either way.
|
|
144
|
+
SMS_LINK_HOST: z.string().url().optional(),
|
|
145
|
+
// --- Twilio (default SMS provider, opt-in) ---
|
|
146
|
+
// A preset provider is built only when BOTH SID + token are present (the
|
|
147
|
+
// guarded dynamic import in sms-providers-from-env.ts). One of SMS_FROM /
|
|
148
|
+
// TWILIO_MESSAGING_SERVICE_SID must also be set for sends to succeed.
|
|
149
|
+
TWILIO_ACCOUNT_SID: z.string().min(1).optional(),
|
|
150
|
+
TWILIO_AUTH_TOKEN: z.string().min(1).optional(),
|
|
151
|
+
TWILIO_MESSAGING_SERVICE_SID: z.string().min(1).optional(),
|
|
124
152
|
// Hatchet connection contract. The @hatchet-dev SDK also reads these straight
|
|
125
153
|
// from process.env via its own config-loader, so this schema is a presence /
|
|
126
154
|
// shape check that keeps the contract in one place — the values still flow to
|
package/src/index.ts
CHANGED
|
@@ -483,6 +483,7 @@ export {
|
|
|
483
483
|
type OutboundEventName,
|
|
484
484
|
type OutboundPayloads,
|
|
485
485
|
} from "./lib/outbound.js";
|
|
486
|
+
export { isE164, normalizePhone } from "./lib/phone.js";
|
|
486
487
|
export { getPostHog } from "./lib/posthog.js";
|
|
487
488
|
// --- PostHog OAuth scopes (front-loaded set; gap-detector source of truth) ---
|
|
488
489
|
export { EXPECTED_POSTHOG_SCOPES } from "./lib/posthog-scopes.js";
|
|
@@ -524,6 +525,42 @@ export {
|
|
|
524
525
|
SEMANTIC_BURST_DISTINCT_LINKS,
|
|
525
526
|
SEMANTIC_BURST_WINDOW_MS,
|
|
526
527
|
} from "./lib/semantic-click.js";
|
|
528
|
+
// --- SMS ---
|
|
529
|
+
export {
|
|
530
|
+
getSmsService,
|
|
531
|
+
type SendSmsOptions as SendSmsJourneyOptions,
|
|
532
|
+
type SendSmsResult,
|
|
533
|
+
sendSms,
|
|
534
|
+
setSmsService,
|
|
535
|
+
} from "./lib/sms.js";
|
|
536
|
+
// --- SMS inbound consent helpers (phone-track grant/opt-out) ---
|
|
537
|
+
export {
|
|
538
|
+
grantPhoneConsent,
|
|
539
|
+
recordPhoneOptOut,
|
|
540
|
+
} from "./lib/sms-inbound.js";
|
|
541
|
+
// --- SMS link shortening (pure rewriter; the insert rides the send txn) ---
|
|
542
|
+
export {
|
|
543
|
+
generateShortCode,
|
|
544
|
+
isShortCodeCollision,
|
|
545
|
+
type PendingSmsLink,
|
|
546
|
+
planSmsLinkRewrite,
|
|
547
|
+
SHORT_CODE_ALPHABET,
|
|
548
|
+
SHORT_CODE_LENGTH,
|
|
549
|
+
type SmsLinkRewritePlan,
|
|
550
|
+
} from "./lib/sms-link-tracking.js";
|
|
551
|
+
// --- SMS mailer factory (the engine-owned tracked sender; mirrors createTrackedMailer) ---
|
|
552
|
+
export { createTrackedSmsSender } from "./lib/sms-mailer.js";
|
|
553
|
+
// --- SMS provider registry (container-held, keyed by meta.id) ---
|
|
554
|
+
export { SmsProviderRegistry } from "./lib/sms-provider-registry.js";
|
|
555
|
+
// --- SMS service (engine-owned tracked SMS sender) ---
|
|
556
|
+
export type {
|
|
557
|
+
SmsService,
|
|
558
|
+
SmsServiceConfig,
|
|
559
|
+
SmsServiceSendOptions,
|
|
560
|
+
SmsServiceWebhookResult,
|
|
561
|
+
SmsTrackedSendResult,
|
|
562
|
+
} from "./lib/sms-service-types.js";
|
|
563
|
+
export { SMS_CHANNEL_ID } from "./lib/sms-tracked.js";
|
|
527
564
|
export { type MountStudioResult, mountStudio } from "./lib/studio.js";
|
|
528
565
|
// --- In-app survey/rating (sendSurvey — producer sugar over sendFeedItem) ---
|
|
529
566
|
export { type SendSurveyOptions, sendSurvey } from "./lib/survey.js";
|
|
@@ -547,6 +584,7 @@ export {
|
|
|
547
584
|
rewriteLinks,
|
|
548
585
|
} from "./lib/tracking.js";
|
|
549
586
|
export {
|
|
587
|
+
pushSmsTrackingEvent,
|
|
550
588
|
pushTrackingEvent,
|
|
551
589
|
resolveEmailSendContext,
|
|
552
590
|
resolveEmailSendContextByMessageId,
|
|
@@ -555,6 +593,7 @@ export {
|
|
|
555
593
|
* {@link resolveEmailSendContextByMessageId}.
|
|
556
594
|
*/
|
|
557
595
|
resolveEmailSendContextByResendId,
|
|
596
|
+
resolveSmsSendContext,
|
|
558
597
|
} from "./lib/tracking-events.js";
|
|
559
598
|
/**
|
|
560
599
|
* Publishable-key `userToken` mint/verify helpers.
|
|
@@ -146,10 +146,14 @@ export function supportsEviction(hatchetCtx: unknown): boolean {
|
|
|
146
146
|
}
|
|
147
147
|
|
|
148
148
|
/** The kind of side effect a key is derived for — keeps the namespaces apart. */
|
|
149
|
-
export type JourneyKeyKind = "send" | "trigger" | "connector";
|
|
149
|
+
export type JourneyKeyKind = "send" | "smsSend" | "trigger" | "connector";
|
|
150
150
|
|
|
151
151
|
const KEY_PREFIX: Record<JourneyKeyKind, string> = {
|
|
152
152
|
send: "journeySend",
|
|
153
|
+
// Disjoint from `send` so a `sendEmail("x")` and a `sendSms("x")` under the
|
|
154
|
+
// SAME nearest wait label derive DIFFERENT keys and never collide in
|
|
155
|
+
// registerKey — email + SMS of the same template on one branch is legitimate.
|
|
156
|
+
smsSend: "journeySmsSend",
|
|
153
157
|
trigger: "journeyTrigger",
|
|
154
158
|
connector: "journeyConnector",
|
|
155
159
|
};
|
|
@@ -42,6 +42,7 @@ import {
|
|
|
42
42
|
type Database,
|
|
43
43
|
emailSends,
|
|
44
44
|
journeyStates,
|
|
45
|
+
smsSends,
|
|
45
46
|
userEvents,
|
|
46
47
|
} from "@hogsend/db";
|
|
47
48
|
import {
|
|
@@ -1212,6 +1213,31 @@ export function createJourneyContext(
|
|
|
1212
1213
|
};
|
|
1213
1214
|
},
|
|
1214
1215
|
|
|
1216
|
+
async sms({ phone, template }) {
|
|
1217
|
+
const [result] = await db
|
|
1218
|
+
.select({
|
|
1219
|
+
count: count(),
|
|
1220
|
+
lastSentAt: max(smsSends.sentAt),
|
|
1221
|
+
})
|
|
1222
|
+
.from(smsSends)
|
|
1223
|
+
.where(
|
|
1224
|
+
and(
|
|
1225
|
+
eq(smsSends.toPhone, phone),
|
|
1226
|
+
eq(smsSends.templateKey, template),
|
|
1227
|
+
),
|
|
1228
|
+
);
|
|
1229
|
+
|
|
1230
|
+
const total = result?.count ?? 0;
|
|
1231
|
+
return {
|
|
1232
|
+
sent: total > 0,
|
|
1233
|
+
lastSentAt:
|
|
1234
|
+
result?.lastSentAt instanceof Date
|
|
1235
|
+
? result.lastSentAt.toISOString()
|
|
1236
|
+
: null,
|
|
1237
|
+
count: total,
|
|
1238
|
+
};
|
|
1239
|
+
},
|
|
1240
|
+
|
|
1215
1241
|
async events({
|
|
1216
1242
|
userId: targetUserId,
|
|
1217
1243
|
event,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Database } from "@hogsend/db";
|
|
2
|
-
import { emailSends, journeyStates } from "@hogsend/db";
|
|
2
|
+
import { emailSends, journeyStates, smsSends } from "@hogsend/db";
|
|
3
3
|
import { and, eq, gte, ne } from "drizzle-orm";
|
|
4
4
|
import type { JourneyBoundary } from "../journeys/journey-boundary.js";
|
|
5
5
|
import { recordOnce } from "../journeys/record-once.js";
|
|
@@ -36,6 +36,33 @@ export async function hasRecentJourneySend(opts: {
|
|
|
36
36
|
return rows.length > 0;
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
/**
|
|
40
|
+
* The SMS leg of {@link hasRecentJourneySend}: same cross-enrollment EXISTS
|
|
41
|
+
* over `sms_sends` keyed by recipient phone. `meta.suppress` is a per-journey,
|
|
42
|
+
* per-recipient min-gap — it must gap SMS exactly as it gaps email.
|
|
43
|
+
*/
|
|
44
|
+
export async function hasRecentJourneySmsSend(opts: {
|
|
45
|
+
db: Database;
|
|
46
|
+
journeyId: string;
|
|
47
|
+
to: string;
|
|
48
|
+
since: Date;
|
|
49
|
+
}): Promise<boolean> {
|
|
50
|
+
const rows = await opts.db
|
|
51
|
+
.select({ id: smsSends.id })
|
|
52
|
+
.from(smsSends)
|
|
53
|
+
.innerJoin(journeyStates, eq(smsSends.journeyStateId, journeyStates.id))
|
|
54
|
+
.where(
|
|
55
|
+
and(
|
|
56
|
+
eq(journeyStates.journeyId, opts.journeyId),
|
|
57
|
+
eq(smsSends.toPhone, opts.to),
|
|
58
|
+
gte(smsSends.createdAt, opts.since),
|
|
59
|
+
ne(smsSends.status, "failed"),
|
|
60
|
+
),
|
|
61
|
+
)
|
|
62
|
+
.limit(1);
|
|
63
|
+
return rows.length > 0;
|
|
64
|
+
}
|
|
65
|
+
|
|
39
66
|
/**
|
|
40
67
|
* The RECORDED-once journey-suppress verdict for a boundary send. Returns
|
|
41
68
|
* `{ suppressed }` — `true` means the tracked mailer must skip the send
|
|
@@ -58,6 +85,8 @@ export async function checkJourneySuppress(opts: {
|
|
|
58
85
|
boundary: JourneyBoundary | undefined;
|
|
59
86
|
to: string;
|
|
60
87
|
idempotencyKey: string | undefined;
|
|
88
|
+
/** Which channel's send history the min-gap EXISTS runs against. */
|
|
89
|
+
channel?: "email" | "sms";
|
|
61
90
|
/** Injectable clock for tests; defaults to the live wall clock. */
|
|
62
91
|
now?: number;
|
|
63
92
|
}): Promise<{ suppressed: boolean }> {
|
|
@@ -79,8 +108,10 @@ export async function checkJourneySuppress(opts: {
|
|
|
79
108
|
key: `suppress:${idempotencyKey}`,
|
|
80
109
|
compute: async () => {
|
|
81
110
|
const since = new Date((opts.now ?? Date.now()) - suppressMs);
|
|
111
|
+
const hasRecent =
|
|
112
|
+
opts.channel === "sms" ? hasRecentJourneySmsSend : hasRecentJourneySend;
|
|
82
113
|
return {
|
|
83
|
-
suppressed: await
|
|
114
|
+
suppressed: await hasRecent({ db, journeyId, to, since }),
|
|
84
115
|
};
|
|
85
116
|
},
|
|
86
117
|
});
|
package/src/lib/outbound.ts
CHANGED
|
@@ -76,6 +76,19 @@ export interface OutboundPayloads {
|
|
|
76
76
|
category: string | null;
|
|
77
77
|
scope: "all" | "category";
|
|
78
78
|
};
|
|
79
|
+
/**
|
|
80
|
+
* A genuine opt-IN (resubscribe-all or a category/channel grant) — the
|
|
81
|
+
* mirror of `contact.unsubscribed`, emitted from the same preference-write
|
|
82
|
+
* choke. `source` is the grant provenance: `"api"` (default),
|
|
83
|
+
* `"preference_center"`, `"started_keyword"`, `"import"`.
|
|
84
|
+
*/
|
|
85
|
+
"contact.subscribed": {
|
|
86
|
+
externalId: string | null;
|
|
87
|
+
email: string | null;
|
|
88
|
+
category: string | null;
|
|
89
|
+
scope: "all" | "category";
|
|
90
|
+
source: string;
|
|
91
|
+
};
|
|
79
92
|
"email.sent": {
|
|
80
93
|
emailSendId: string;
|
|
81
94
|
messageId: string;
|
|
@@ -152,6 +165,51 @@ export interface OutboundPayloads {
|
|
|
152
165
|
complaintType?: string;
|
|
153
166
|
reason?: string;
|
|
154
167
|
};
|
|
168
|
+
"sms.sent": {
|
|
169
|
+
smsSendId: string;
|
|
170
|
+
messageId: string;
|
|
171
|
+
templateKey: string | null;
|
|
172
|
+
to: string;
|
|
173
|
+
userId: string | null;
|
|
174
|
+
category: string | null;
|
|
175
|
+
journeyStateId: string | null;
|
|
176
|
+
segments: number | null;
|
|
177
|
+
sentAt: string;
|
|
178
|
+
};
|
|
179
|
+
"sms.delivered": {
|
|
180
|
+
smsSendId: string;
|
|
181
|
+
messageId: string;
|
|
182
|
+
templateKey: string | null;
|
|
183
|
+
userId: string | null;
|
|
184
|
+
to: string;
|
|
185
|
+
at: string;
|
|
186
|
+
};
|
|
187
|
+
"sms.failed": {
|
|
188
|
+
smsSendId: string;
|
|
189
|
+
messageId: string;
|
|
190
|
+
templateKey: string | null;
|
|
191
|
+
userId: string | null;
|
|
192
|
+
to: string;
|
|
193
|
+
at: string;
|
|
194
|
+
errorCode?: string;
|
|
195
|
+
errorReason?: string;
|
|
196
|
+
};
|
|
197
|
+
/**
|
|
198
|
+
* A tracked SMS short link was clicked (first-party, PER-HIT — the SMS
|
|
199
|
+
* sibling of `email.clicked`). `linkId` is the `tracked_links.id`,
|
|
200
|
+
* `linkUrl` the original destination. `userId` is null for a raw send with
|
|
201
|
+
* no resolvable contact.
|
|
202
|
+
*/
|
|
203
|
+
"sms.clicked": {
|
|
204
|
+
smsSendId: string;
|
|
205
|
+
messageId: string | null;
|
|
206
|
+
templateKey: string | null;
|
|
207
|
+
userId: string | null;
|
|
208
|
+
to: string;
|
|
209
|
+
at: string;
|
|
210
|
+
linkUrl: string;
|
|
211
|
+
linkId: string;
|
|
212
|
+
};
|
|
155
213
|
"journey.completed": {
|
|
156
214
|
journeyId: string;
|
|
157
215
|
journeyName: string;
|
package/src/lib/phone.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strict E.164 normalization. Strips common human separators (spaces, dashes,
|
|
3
|
+
* parens, dots) then requires a leading `+`, a non-zero country digit, and
|
|
4
|
+
* 7–15 total digits (the E.164 max is 15). Fail-closed: anything that doesn't
|
|
5
|
+
* match returns `null` — the caller rejects it rather than guessing a country
|
|
6
|
+
* code (no libphonenumber dependency, no implicit `+1`).
|
|
7
|
+
*/
|
|
8
|
+
export function normalizePhone(
|
|
9
|
+
input: string | null | undefined,
|
|
10
|
+
): string | null {
|
|
11
|
+
if (!input) return null;
|
|
12
|
+
const stripped = input.trim().replace(/[\s\-().]/g, "");
|
|
13
|
+
return /^\+[1-9]\d{6,14}$/.test(stripped) ? stripped : null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Whether `input` is already a valid E.164 number (post-normalization). */
|
|
17
|
+
export function isE164(input: string | null | undefined): boolean {
|
|
18
|
+
return normalizePhone(input) !== null;
|
|
19
|
+
}
|
package/src/lib/preferences.ts
CHANGED
|
@@ -43,6 +43,12 @@ export async function upsertEmailPreference(opts: {
|
|
|
43
43
|
categoryValue?: boolean;
|
|
44
44
|
};
|
|
45
45
|
emitOutbound?: boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Grant provenance carried on the `contact.subscribed` emit: `"api"`
|
|
48
|
+
* (default), `"preference_center"`, `"started_keyword"`, `"import"`.
|
|
49
|
+
* TCPA record-keeping is the "how" as much as the "when".
|
|
50
|
+
*/
|
|
51
|
+
source?: string;
|
|
46
52
|
}): Promise<void> {
|
|
47
53
|
const { db, externalId, email, update } = opts;
|
|
48
54
|
|
|
@@ -119,6 +125,32 @@ export async function upsertEmailPreference(opts: {
|
|
|
119
125
|
},
|
|
120
126
|
}).catch(logger.warn);
|
|
121
127
|
}
|
|
128
|
+
|
|
129
|
+
// The opt-IN mirror: `contact.subscribed` on a genuine grant (resubscribe-all
|
|
130
|
+
// or a category flip to true) — the consent audit signal for opt-in channels
|
|
131
|
+
// (the explicit-consent `sms` channel above all). Same choke, same
|
|
132
|
+
// fire-and-forget semantics, same `emitOutbound: false` escape for bulk
|
|
133
|
+
// imports. A redundant re-grant re-emits, identical to the opt-out side.
|
|
134
|
+
const isSubscribe =
|
|
135
|
+
!isUnsubscribe &&
|
|
136
|
+
(update.unsubscribedAll === false || update.categoryValue === true);
|
|
137
|
+
if (isSubscribe && (opts.emitOutbound ?? true)) {
|
|
138
|
+
const scope: "all" | "category" =
|
|
139
|
+
update.categoryKey !== undefined ? "category" : "all";
|
|
140
|
+
void emitOutbound({
|
|
141
|
+
db,
|
|
142
|
+
hatchet,
|
|
143
|
+
logger,
|
|
144
|
+
event: "contact.subscribed",
|
|
145
|
+
payload: {
|
|
146
|
+
externalId,
|
|
147
|
+
email,
|
|
148
|
+
category: update.categoryKey ?? null,
|
|
149
|
+
scope,
|
|
150
|
+
source: opts.source ?? "api",
|
|
151
|
+
},
|
|
152
|
+
}).catch(logger.warn);
|
|
153
|
+
}
|
|
122
154
|
}
|
|
123
155
|
|
|
124
156
|
/**
|