@hogsend/engine 0.40.0 → 0.42.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 (69) hide show
  1. package/package.json +11 -8
  2. package/src/buckets/check-membership.ts +6 -1
  3. package/src/campaigns/cohort-sql.ts +198 -0
  4. package/src/campaigns/define-campaign.ts +207 -28
  5. package/src/campaigns/reconcile.ts +105 -11
  6. package/src/campaigns/steps.ts +48 -0
  7. package/src/connectors/define-action.ts +70 -0
  8. package/src/container.ts +124 -42
  9. package/src/destinations/presets/posthog.ts +7 -1
  10. package/src/index.ts +96 -2
  11. package/src/journeys/constants.ts +10 -0
  12. package/src/journeys/define-journey.ts +14 -405
  13. package/src/journeys/execute-journey-run.ts +641 -0
  14. package/src/journeys/graph/build-graph.ts +212 -56
  15. package/src/journeys/journey-boundary.ts +54 -0
  16. package/src/journeys/journey-context.ts +406 -59
  17. package/src/journeys/record-once.ts +110 -0
  18. package/src/lib/blueprint-lock.ts +21 -0
  19. package/src/lib/blueprints.ts +803 -0
  20. package/src/lib/campaign-send-key.ts +58 -0
  21. package/src/lib/connector-actions.ts +203 -19
  22. package/src/lib/contacts.ts +54 -0
  23. package/src/lib/email-service-types.ts +4 -1
  24. package/src/lib/email.ts +13 -2
  25. package/src/lib/event-names.ts +143 -0
  26. package/src/lib/feed.ts +77 -57
  27. package/src/lib/frequency-cap.ts +45 -15
  28. package/src/lib/hatchet-duration.ts +22 -0
  29. package/src/lib/html.ts +1 -0
  30. package/src/lib/ingestion.ts +145 -4
  31. package/src/lib/journey-suppress.ts +87 -0
  32. package/src/lib/links.ts +204 -18
  33. package/src/lib/outbound.ts +20 -0
  34. package/src/lib/preferences.ts +80 -1
  35. package/src/lib/tracked.ts +44 -29
  36. package/src/lib/tracking-event-names.ts +8 -0
  37. package/src/lib/tracking.ts +1 -5
  38. package/src/lib/webhook-signing.ts +6 -1
  39. package/src/lists/channels.ts +75 -0
  40. package/src/lists/define-list.ts +34 -0
  41. package/src/lists/registry.ts +29 -2
  42. package/src/mcp/authoring-guide.ts +160 -0
  43. package/src/mcp/blueprint-tools.ts +390 -0
  44. package/src/middleware/require-admin.ts +13 -0
  45. package/src/routes/admin/api-keys.ts +72 -0
  46. package/src/routes/admin/blueprints.ts +795 -0
  47. package/src/routes/admin/campaigns.ts +179 -3
  48. package/src/routes/admin/emails.ts +13 -0
  49. package/src/routes/admin/events.ts +55 -0
  50. package/src/routes/admin/index.ts +4 -0
  51. package/src/routes/admin/journeys.ts +4 -2
  52. package/src/routes/admin/links.ts +303 -36
  53. package/src/routes/admin/lists.ts +51 -0
  54. package/src/routes/campaigns/index.ts +44 -6
  55. package/src/routes/email/preferences.ts +50 -13
  56. package/src/routes/feed/recipient.ts +2 -43
  57. package/src/routes/index.ts +6 -0
  58. package/src/routes/lists/index.ts +138 -18
  59. package/src/routes/tracking/arrive.ts +260 -0
  60. package/src/routes/tracking/click-pipeline.ts +329 -0
  61. package/src/routes/tracking/click.ts +5 -270
  62. package/src/routes/tracking/index.ts +2 -0
  63. package/src/routes/tracking/vanity.ts +64 -0
  64. package/src/worker.ts +5 -0
  65. package/src/workflows/bucket-backfill.ts +4 -2
  66. package/src/workflows/bucket-reconcile.ts +11 -4
  67. package/src/workflows/check-alerts.ts +130 -1
  68. package/src/workflows/journey-blueprint-interpreter.ts +656 -0
  69. package/src/workflows/send-campaign.ts +574 -180
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hogsend/engine",
3
- "version": "0.40.0",
3
+ "version": "0.42.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -15,6 +15,7 @@
15
15
  "./worker": "./src/worker.ts",
16
16
  "./auth": "./src/lib/auth.ts",
17
17
  "./create-admin": "./src/lib/create-admin.ts",
18
+ "./mcp/authoring-guide": "./src/mcp/authoring-guide.ts",
18
19
  "./package.json": "./package.json"
19
20
  },
20
21
  "files": [
@@ -31,6 +32,8 @@
31
32
  "@openrouter/ai-sdk-provider": "^2.9.1",
32
33
  "@scalar/hono-api-reference": "^0.10.19",
33
34
  "@t3-oss/env-core": "^0.13.11",
35
+ "@types/papaparse": "^5.5.2",
36
+ "@types/qrcode": "^1.5.6",
34
37
  "acorn": "^8.17.0",
35
38
  "acorn-walk": "^8.3.5",
36
39
  "ai": "^6.0.209",
@@ -41,22 +44,22 @@
41
44
  "launch-editor": "^2.14.1",
42
45
  "papaparse": "^5.5.3",
43
46
  "picocolors": "^1.1.1",
47
+ "qrcode": "^1.5.4",
44
48
  "resend": "^6.12.3",
45
49
  "svix": "^1.95.1",
46
50
  "winston": "^3.19.0",
47
51
  "zod": "^4.4.3",
48
- "@hogsend/core": "^0.40.0",
49
- "@hogsend/db": "^0.40.0",
50
- "@hogsend/email": "^0.40.0",
51
- "@hogsend/plugin-posthog": "^0.40.0",
52
- "@hogsend/plugin-resend": "^0.40.0"
52
+ "@hogsend/core": "^0.42.0",
53
+ "@hogsend/db": "^0.42.0",
54
+ "@hogsend/email": "^0.42.0",
55
+ "@hogsend/plugin-posthog": "^0.42.0",
56
+ "@hogsend/plugin-resend": "^0.42.0"
53
57
  },
54
58
  "optionalDependencies": {
55
- "@hogsend/plugin-postmark": "^0.40.0"
59
+ "@hogsend/plugin-postmark": "^0.42.0"
56
60
  },
57
61
  "devDependencies": {
58
62
  "@types/node": "^22.15.3",
59
- "@types/papaparse": "^5.5.2",
60
63
  "tsx": "^4.22.3",
61
64
  "@repo/typescript-config": "0.0.0"
62
65
  },
@@ -9,6 +9,7 @@ import type { JourneyRegistry } from "@hogsend/core/registry";
9
9
  import { bucketMemberships, contacts, type Database } from "@hogsend/db";
10
10
  import { and, desc, eq, isNotNull, isNull } from "drizzle-orm";
11
11
  import { emitBucketTransition } from "../lib/bucket-emit.js";
12
+ import { normalizeEmailOrNull } from "../lib/contacts.js";
12
13
  import type { Logger } from "../lib/logger.js";
13
14
  import {
14
15
  BUCKET_EVENT_PREFIX,
@@ -70,11 +71,15 @@ export async function checkBucketMembership(opts: {
70
71
  hatchet,
71
72
  logger,
72
73
  userId,
73
- userEmail,
74
74
  event,
75
75
  eventProperties,
76
76
  contactProperties: contactPropertiesPatch,
77
77
  } = opts;
78
+ // The caller's email comes verbatim from the raw event payload — normalize
79
+ // ONCE here so the membership row, the emitted bucket:* transition events,
80
+ // and the arm-expiry payload all carry the same normalized address the
81
+ // `email_preferences` keyspace (and every other email write) uses.
82
+ const userEmail = normalizeEmailOrNull(opts.userEmail);
78
83
 
79
84
  // (1) Recursion guard — MUST be first. bucket:-prefixed events are transition
80
85
  // rows (still written to userEvents / pushed to Hatchet / run through
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Bulk condition → SQL for the campaign wave runtime. Waves after the first
3
+ * qualify recipients FROM the anchored cohort (`campaign_recipients`) with one
4
+ * indexed query per page — the per-user `evaluateCondition()` path is never
5
+ * used on the wave hot path. Each supported `ConditionEval` compiles to a
6
+ * single [NOT] EXISTS predicate correlated against the outer
7
+ * `campaign_recipients` row; a step's condition array is AND-composed by the
8
+ * caller (OR is deferred — core's `composite` type is the seam, so composites
9
+ * THROW here rather than half-work).
10
+ *
11
+ * v1 supports exactly the cohort-builder vocabulary: `email_engagement`
12
+ * (opened/clicked over THIS campaign's prior sends), `event` (a `user_events`
13
+ * row since the campaign's `startedAt`), and `channel_identity` (a linked
14
+ * connector identity). `property` has no bulk source on this path and throws.
15
+ */
16
+ import {
17
+ type ChannelIdentityCondition,
18
+ type ConditionEval,
19
+ durationToMs,
20
+ type EmailEngagementCondition,
21
+ type EventCondition,
22
+ } from "@hogsend/core";
23
+ import {
24
+ campaignRecipients,
25
+ contacts,
26
+ emailPreferences,
27
+ emailSends,
28
+ userEvents,
29
+ } from "@hogsend/db";
30
+ import { type SQL, sql } from "drizzle-orm";
31
+ import type { PgColumn } from "drizzle-orm/pg-core";
32
+ import { campaignSendKeyPattern } from "../lib/campaign-send-key.js";
33
+
34
+ /**
35
+ * The v1 linked-identity map: connector id → the `contacts` column that holds
36
+ * the linked identity. `contact_aliases` is deliberately NOT consulted — it is
37
+ * the stale-key merge table, not the linked-identity store. `defineCampaign`
38
+ * already rejects unknown connectors at authoring time; the throw below is the
39
+ * runtime backstop (a hand-written steps blob bypasses authoring validation).
40
+ */
41
+ const CONNECTOR_IDENTITY_COLUMNS: Record<string, PgColumn | undefined> = {
42
+ discord: contacts.discordId,
43
+ };
44
+
45
+ /**
46
+ * Fresh suppression/unsubscribe re-check for a cohort wave — suppression is
47
+ * never snapshotted (GDPR/CAN-SPAM): a member who unsubscribes between waves
48
+ * is excluded from every subsequent wave automatically. Mirrors the bucket
49
+ * resolver's correlated NOT EXISTS exactly (an EXISTS subquery, NOT a JOIN,
50
+ * so an email with two prefs rows is not fanned out; an absent prefs row
51
+ * matches nothing → included, subscribed-by-default). `campaign_recipients.
52
+ * email` is normalized at write, so only the prefs side needs `lower()`. The
53
+ * mailer's per-send category check remains the authoritative backstop.
54
+ *
55
+ * The second NOT EXISTS covers the erasure path the prefs check misses: an
56
+ * admin contact delete (a GDPR erasure) sets ONLY `contacts.deletedAt` and
57
+ * writes nothing to `email_preferences`, so an erased wave-0 recipient would
58
+ * otherwise keep qualifying for every later wave (the mailer's per-send check
59
+ * reads only prefs, too). Matched on the same identity binding the anchor
60
+ * wrote (`userId = externalId ?? contactId` — see channelIdentitySql), and
61
+ * deliberately NOT on email: merge-loser rows are also soft-deleted and share
62
+ * their email with a live survivor, so an email leg would wrongly drop merged
63
+ * members. Failure direction here is under-delivery, never over-delivery.
64
+ */
65
+ export function cohortSuppressionSql(): SQL {
66
+ return sql`not exists (
67
+ select 1 from ${emailPreferences}
68
+ where lower(${emailPreferences.email}) = ${campaignRecipients.email}
69
+ and (${emailPreferences.unsubscribedAll} = true
70
+ or ${emailPreferences.suppressed} = true)
71
+ ) and not exists (
72
+ select 1 from ${contacts}
73
+ where (${contacts.externalId} = ${campaignRecipients.userId}
74
+ or ${contacts.id}::text = ${campaignRecipients.userId})
75
+ and ${contacts.deletedAt} is not null
76
+ )`;
77
+ }
78
+
79
+ /**
80
+ * Compile one wave `where` condition to its correlated [NOT] EXISTS predicate.
81
+ * `startedAt` is the claimed row's `startedAt` — the anchor `event` conditions
82
+ * scope to ("since the campaign started"), which is why the claim CAS must
83
+ * never reset it.
84
+ *
85
+ * @throws on `composite`/`property` conditions (not supported on the wave
86
+ * path in v1), an `event` count check, or an unknown `channel_identity`
87
+ * connector.
88
+ */
89
+ export function waveConditionSql(opts: {
90
+ condition: ConditionEval;
91
+ campaignId: string;
92
+ startedAt: Date;
93
+ }): SQL {
94
+ const { condition, campaignId, startedAt } = opts;
95
+ switch (condition.type) {
96
+ case "email_engagement":
97
+ return engagementSql(condition, campaignId);
98
+ case "event":
99
+ return eventSql(condition, startedAt);
100
+ case "channel_identity":
101
+ return channelIdentitySql(condition);
102
+ default:
103
+ throw new Error(
104
+ `Campaign wave \`where\` does not support "${condition.type}" conditions in v1 — only email_engagement, event, and channel_identity (the cohort-builder vocabulary).`,
105
+ );
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Engagement over THIS campaign's prior deliveries. The campaign-level LIKE
111
+ * (`campaign:<escaped-id>:%`) is a correct superset of BOTH key formats
112
+ * (legacy and step-scoped), so an absent `templateKey` — "any prior send of
113
+ * this campaign" — and a template-filtered check both anchor on it. Negative
114
+ * checks are NOT EXISTS of the same positive-engagement subquery, so
115
+ * `notOpened()` reads "no opened send of this campaign", including members
116
+ * who received nothing (e.g. suppressed on the prior wave).
117
+ */
118
+ function engagementSql(
119
+ condition: EmailEngagementCondition,
120
+ campaignId: string,
121
+ ): SQL {
122
+ const engagedAt =
123
+ condition.check === "opened" || condition.check === "not_opened"
124
+ ? emailSends.openedAt
125
+ : emailSends.clickedAt;
126
+ const templateFilter =
127
+ condition.templateKey !== undefined
128
+ ? sql` and ${emailSends.templateKey} = ${condition.templateKey}`
129
+ : sql.empty();
130
+ const positive = sql`exists (
131
+ select 1 from ${emailSends}
132
+ where ${emailSends.idempotencyKey} like ${campaignSendKeyPattern(campaignId)}
133
+ and ${emailSends.toEmail} = ${campaignRecipients.email}
134
+ and ${engagedAt} is not null${templateFilter}
135
+ )`;
136
+ return condition.check === "not_opened" || condition.check === "not_clicked"
137
+ ? sql`not ${positive}`
138
+ : positive;
139
+ }
140
+
141
+ /**
142
+ * A `user_events` row for this member since the campaign's `startedAt` (plus
143
+ * the condition's own `within` window when set — both bounds apply, which is
144
+ * the natural reading of "fired within N days of a campaign that started
145
+ * later"). `campaign_recipients.user_id` may be NULL (an email-only list
146
+ * member with no behavioral identity): SQL NULL comparison makes the EXISTS
147
+ * false — so `firedEvent` never matches such a member and `notFiredEvent`
148
+ * always does. That is the correct stance: with no identity there is no
149
+ * evidence the event fired.
150
+ */
151
+ function eventSql(condition: EventCondition, startedAt: Date): SQL {
152
+ if (condition.check === "count") {
153
+ throw new Error(
154
+ 'Campaign wave `where` does not support event "count" checks in v1 — only exists/not_exists (c.firedEvent / c.notFiredEvent).',
155
+ );
156
+ }
157
+ // Both time bounds are passed as ISO strings + an explicit ::timestamptz
158
+ // cast — a raw sql`` template does NOT map a JS Date param (postgres-js
159
+ // throws ERR_INVALID_ARG_TYPE), unlike the composable gt()/lt() helpers.
160
+ const windowFilter = condition.within
161
+ ? sql` and ${userEvents.occurredAt} >= ${new Date(
162
+ Date.now() - durationToMs(condition.within),
163
+ ).toISOString()}::timestamptz`
164
+ : sql.empty();
165
+ const positive = sql`exists (
166
+ select 1 from ${userEvents}
167
+ where ${userEvents.userId} = ${campaignRecipients.userId}
168
+ and ${userEvents.event} = ${condition.eventName}
169
+ and ${userEvents.occurredAt} >= ${startedAt.toISOString()}::timestamptz${windowFilter}
170
+ )`;
171
+ return condition.check === "not_exists" ? sql`not ${positive}` : positive;
172
+ }
173
+
174
+ /**
175
+ * The member has/lacks a linked identity for the connector (v1: `"discord"` →
176
+ * `contacts.discordId`, live rows only). The OR-join mirrors the opt-out list
177
+ * resolver's recipient identity fallback (`userId = externalId ?? contactId`):
178
+ * a cohort member's `user_id` may hold either the contact's external id or,
179
+ * for a contact without one, the contact row's own uuid — so the lookup must
180
+ * accept both spellings. A NULL `user_id` matches nothing → `linked` false,
181
+ * `notLinked` true (no identity, no link).
182
+ */
183
+ function channelIdentitySql(condition: ChannelIdentityCondition): SQL {
184
+ const column = CONNECTOR_IDENTITY_COLUMNS[condition.connector];
185
+ if (!column) {
186
+ throw new Error(
187
+ `Campaign wave \`where\`: channel_identity connector "${condition.connector}" has no linked-identity source in v1 — only "discord" is supported.`,
188
+ );
189
+ }
190
+ const positive = sql`exists (
191
+ select 1 from ${contacts}
192
+ where (${contacts.externalId} = ${campaignRecipients.userId}
193
+ or ${contacts.id}::text = ${campaignRecipients.userId})
194
+ and ${column} is not null
195
+ and ${contacts.deletedAt} is null
196
+ )`;
197
+ return condition.check === "not_linked" ? sql`not ${positive}` : positive;
198
+ }
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Code-defined campaigns (broadcasts) — a one-shot scheduled send committed to
3
- * the repo, mirroring `defineJourney()` / `defineList()`: write a file, deploy,
2
+ * Code-defined campaigns (broadcasts) — a scheduled send committed to the
3
+ * repo, mirroring `defineJourney()` / `defineList()`: write a file, deploy,
4
4
  * and the worker's boot reconciler schedules it; once sent it is retired
5
5
  * (redeploys no-op via the campaign's definition idempotency key).
6
6
  *
@@ -8,12 +8,29 @@
8
8
  * `campaigns` row + durable `send-campaign` task the `POST /v1/campaigns`
9
9
  * data-plane uses, so scheduling, cancel, counts, and Studio visibility are
10
10
  * identical regardless of how the campaign was created.
11
+ *
12
+ * A campaign is one or more `steps` — email waves separated by durable waits
13
+ * (`step.send` / `step.wait`), each wave a SET operation over the audience,
14
+ * never per-user code (that's `defineJourney`). The legacy single-template
15
+ * form stays supported forever and compiles to one send step.
11
16
  */
17
+ import {
18
+ type CampaignSendStep,
19
+ type CampaignStep,
20
+ type ConditionEval,
21
+ durationToMs,
22
+ } from "@hogsend/core";
12
23
  import type { TemplateName } from "@hogsend/email";
13
24
 
14
25
  /** Allowed campaign-id shape (mirrors list ids): alnum, dash, underscore. */
15
26
  const CAMPAIGN_ID_PATTERN = /^[a-z0-9_-]+$/i;
16
27
 
28
+ /** Steps per campaign, inclusive. A longer sequence belongs in a journey. */
29
+ const MAX_STEPS = 10;
30
+
31
+ /** Floor on `step.wait` — below the scheduling grace windows is a footgun. */
32
+ const MIN_WAIT_MS = 5 * 60_000;
33
+
17
34
  /**
18
35
  * The `campaigns.idempotency_key` namespace for code-defined campaigns. A
19
36
  * definition's row key is `campaign-def:<id>` — the reconciler resolves the
@@ -26,9 +43,12 @@ export const DEFINED_CAMPAIGN_KEY_PREFIX = "campaign-def:";
26
43
  export type CampaignAudience = { list: string } | { bucket: string };
27
44
 
28
45
  /**
29
- * The validated, fully-defaulted campaign metadata. `sendAt` is always a
30
- * `Date` after `defineCampaign` (authoring input also accepts an ISO string);
31
- * `enabled` defaults to `true`, `name` to the id.
46
+ * The validated, fully-defaulted campaign metadata. `steps` is the canonical
47
+ * form (always populated — the legacy single-template form compiles to one
48
+ * send step); `template`/`props`/`subject`/`from` mirror the FIRST send step
49
+ * so the reconciler and every single-send consumer keep working unchanged.
50
+ * `sendAt` is always a `Date` after `defineCampaign` (authoring input also
51
+ * accepts an ISO string); `enabled` defaults to `true`, `name` to the id.
32
52
  */
33
53
  export interface CampaignMeta {
34
54
  id: string;
@@ -38,6 +58,7 @@ export interface CampaignMeta {
38
58
  props?: Record<string, unknown>;
39
59
  subject?: string;
40
60
  from?: string;
61
+ steps: CampaignStep[];
41
62
  sendAt: Date;
42
63
  enabled: boolean;
43
64
  }
@@ -49,27 +70,53 @@ export interface DefinedCampaign<Id extends string = string> {
49
70
  }
50
71
 
51
72
  /**
52
- * Define a one-shot campaign (broadcast) in code. Validates the id shape, the
53
- * audience XOR (exactly one of `list` / `bucket`), and that `sendAt` parses to
54
- * a real instant. Whether `sendAt` is still in the future is deliberately NOT
55
- * checked here — that is a deploy-time question the reconciler answers (a
56
- * definition whose `sendAt` is already stale at first reconcile becomes
57
- * `expired`, never a surprise blast).
73
+ * Define a campaign (broadcast) in code — a single send, or multi-step waves
74
+ * via `steps: [step.send(…), step.wait(…), …]`. Exactly one of the two forms
75
+ * (top-level `template` fields XOR `steps`) must be provided. Validates the
76
+ * id shape, the audience XOR (exactly one of `list` / `bucket`), that
77
+ * `sendAt` parses to a real instant, and the step sequence: 1–10 steps, the
78
+ * FIRST must be a send (`sendAt` is the timing — a leading wait is redundant;
79
+ * announcement steps are phase 2), the LAST must not be a wait, `where` only
80
+ * on send steps after the first (the cohort must exist before it can be
81
+ * filtered), every wait >= 5 minutes, and every `where` condition is one the
82
+ * wave runtime can compile to bulk SQL — email_engagement, event
83
+ * exists/not_exists, channel_identity targeting `"discord"` (the only
84
+ * linked-identity connector in v1); `property`/`composite`/event-`count`
85
+ * conditions are rejected HERE so they fail at deploy, not mid-campaign.
86
+ * Whether
87
+ * `sendAt` is still in the future is deliberately NOT checked here — that is
88
+ * a deploy-time question the reconciler answers (a definition whose `sendAt`
89
+ * is already stale at first reconcile becomes `expired`, never a surprise
90
+ * blast).
58
91
  *
59
- * @throws if `id` is empty/malformed, the audience is not exactly one of
60
- * list/bucket, or `sendAt` does not parse.
92
+ * @throws if `id` is empty/malformed, both/neither of `template`/`steps` are
93
+ * given, the step sequence breaks any rule above, the audience is not exactly
94
+ * one of list/bucket, or `sendAt` does not parse.
61
95
  */
62
- export function defineCampaign<const Id extends string>(meta: {
63
- id: Id;
64
- name?: string;
65
- audience: CampaignAudience;
66
- template: TemplateName;
67
- props?: Record<string, unknown>;
68
- subject?: string;
69
- from?: string;
70
- sendAt: Date | string;
71
- enabled?: boolean;
72
- }): DefinedCampaign<Id> {
96
+ export function defineCampaign<const Id extends string>(
97
+ meta: {
98
+ id: Id;
99
+ name?: string;
100
+ audience: CampaignAudience;
101
+ sendAt: Date | string;
102
+ enabled?: boolean;
103
+ } & (
104
+ | {
105
+ template: TemplateName;
106
+ props?: Record<string, unknown>;
107
+ subject?: string;
108
+ from?: string;
109
+ steps?: undefined;
110
+ }
111
+ | {
112
+ steps: CampaignStep[];
113
+ template?: undefined;
114
+ props?: undefined;
115
+ subject?: undefined;
116
+ from?: undefined;
117
+ }
118
+ ),
119
+ ): DefinedCampaign<Id> {
73
120
  const { id } = meta;
74
121
 
75
122
  if (!id || !CAMPAIGN_ID_PATTERN.test(id)) {
@@ -78,6 +125,47 @@ export function defineCampaign<const Id extends string>(meta: {
78
125
  );
79
126
  }
80
127
 
128
+ // Same widening trick as `audience` below: the XOR is re-validated at
129
+ // runtime regardless of what the compile-time union already enforces.
130
+ const input = meta as {
131
+ template?: TemplateName;
132
+ props?: Record<string, unknown>;
133
+ subject?: string;
134
+ from?: string;
135
+ steps?: CampaignStep[];
136
+ };
137
+
138
+ let steps: CampaignStep[];
139
+ if (input.steps !== undefined) {
140
+ if (
141
+ input.template !== undefined ||
142
+ input.props !== undefined ||
143
+ input.subject !== undefined ||
144
+ input.from !== undefined
145
+ ) {
146
+ throw new Error(
147
+ `Campaign "${id}": provide either the single-template form (template/props/subject/from) or steps — not both.`,
148
+ );
149
+ }
150
+ steps = input.steps;
151
+ } else if (input.template !== undefined) {
152
+ steps = [
153
+ {
154
+ kind: "send",
155
+ template: input.template,
156
+ ...(input.props !== undefined ? { props: input.props } : {}),
157
+ ...(input.subject !== undefined ? { subject: input.subject } : {}),
158
+ ...(input.from !== undefined ? { from: input.from } : {}),
159
+ },
160
+ ];
161
+ } else {
162
+ throw new Error(
163
+ `Campaign "${id}": provide a template (single send) or a steps array.`,
164
+ );
165
+ }
166
+
167
+ const firstSend = validateSteps(id, steps);
168
+
81
169
  const audience = meta.audience as { list?: string; bucket?: string };
82
170
  const selectors = (audience.list ? 1 : 0) + (audience.bucket ? 1 : 0);
83
171
  if (selectors !== 1) {
@@ -99,10 +187,15 @@ export function defineCampaign<const Id extends string>(meta: {
99
187
  id,
100
188
  name: meta.name ?? id,
101
189
  audience: meta.audience,
102
- template: meta.template,
103
- ...(meta.props !== undefined ? { props: meta.props } : {}),
104
- ...(meta.subject !== undefined ? { subject: meta.subject } : {}),
105
- ...(meta.from !== undefined ? { from: meta.from } : {}),
190
+ // The stored step form keeps a plain string; authored via `step.send`
191
+ // it was a registry-checked TemplateName.
192
+ template: firstSend.template as TemplateName,
193
+ ...(firstSend.props !== undefined ? { props: firstSend.props } : {}),
194
+ ...(firstSend.subject !== undefined
195
+ ? { subject: firstSend.subject }
196
+ : {}),
197
+ ...(firstSend.from !== undefined ? { from: firstSend.from } : {}),
198
+ steps,
106
199
  sendAt,
107
200
  enabled: meta.enabled ?? true,
108
201
  },
@@ -110,6 +203,92 @@ export function defineCampaign<const Id extends string>(meta: {
110
203
  };
111
204
  }
112
205
 
206
+ /**
207
+ * Enforce the step-sequence invariants (see {@link defineCampaign}). Returns
208
+ * the FIRST send step — guaranteed to be `steps[0]` — which seeds the
209
+ * mirrored top-level `template`/`props`/`subject`/`from` on the meta.
210
+ */
211
+ function validateSteps(id: string, steps: CampaignStep[]): CampaignSendStep {
212
+ // The [0] read doubles as the non-empty check (noUncheckedIndexedAccess).
213
+ const first = steps[0];
214
+ if (first === undefined || steps.length > MAX_STEPS) {
215
+ throw new Error(
216
+ `Campaign "${id}": steps must contain 1–${MAX_STEPS} steps (got ${steps.length}).`,
217
+ );
218
+ }
219
+ if (first.kind !== "send") {
220
+ throw new Error(
221
+ `Campaign "${id}": the first step must be a send — sendAt is the campaign's timing, so a leading wait is redundant (announcement steps are phase 2).`,
222
+ );
223
+ }
224
+ if (steps[steps.length - 1]?.kind === "wait") {
225
+ throw new Error(
226
+ `Campaign "${id}": the last step must not be a wait — a trailing wait does nothing.`,
227
+ );
228
+ }
229
+
230
+ steps.forEach((step, index) => {
231
+ if (step.kind === "wait") {
232
+ if (durationToMs(step.duration) < MIN_WAIT_MS) {
233
+ throw new Error(
234
+ `Campaign "${id}": step ${index} wait is shorter than 5 minutes — below the scheduling grace windows.`,
235
+ );
236
+ }
237
+ return;
238
+ }
239
+ if (step.where !== undefined && index === 0) {
240
+ throw new Error(
241
+ `Campaign "${id}": \`where\` is not allowed on the first step — the cohort must exist before it can be filtered.`,
242
+ );
243
+ }
244
+ for (const condition of step.where ?? []) {
245
+ validateWaveCondition(id, index, condition);
246
+ }
247
+ });
248
+
249
+ return first;
250
+ }
251
+
252
+ /**
253
+ * Reject any `where` condition the wave runtime cannot compile to bulk SQL —
254
+ * at DEFINITION time, not wave time. `CampaignWhere` accepts raw declarative
255
+ * `ConditionEval`, so without this check a `property`/`composite`/event
256
+ * `count` condition would pass `defineCampaign` AND the reconciler (which
257
+ * re-checks templates, not conditions), then throw on every attempt of wave k
258
+ * — a mid-campaign poison wave silently under-delivering every step after
259
+ * the wait, the exact deploy-time-vs-send-time failure the reconciler exists
260
+ * to front-run. Must mirror the runtime switch in `cohort-sql.ts`
261
+ * `waveConditionSql` exactly.
262
+ */
263
+ function validateWaveCondition(
264
+ id: string,
265
+ index: number,
266
+ condition: ConditionEval,
267
+ ): void {
268
+ switch (condition.type) {
269
+ case "email_engagement":
270
+ return;
271
+ case "event":
272
+ if (condition.check === "count") {
273
+ throw new Error(
274
+ `Campaign "${id}": step ${index} \`where\` does not support event "count" checks in v1 — only exists/not_exists (c.firedEvent / c.notFiredEvent).`,
275
+ );
276
+ }
277
+ return;
278
+ case "channel_identity":
279
+ if (condition.connector !== "discord") {
280
+ throw new Error(
281
+ `Campaign "${id}": step ${index} channel_identity connector "${condition.connector}" is not supported — only "discord" has a linked-identity source in v1.`,
282
+ );
283
+ }
284
+ return;
285
+ default:
286
+ throw new Error(
287
+ `Campaign "${id}": step ${index} \`where\` does not support "${condition.type}" conditions in v1 — only email_engagement, event (exists/not_exists), and channel_identity (the cohort-builder vocabulary).`,
288
+ );
289
+ }
290
+ }
291
+
113
292
  /** Narrowing helper: the audience kind + id as stored on the campaigns row. */
114
293
  export function audienceOf(meta: CampaignMeta): {
115
294
  audienceKind: "list" | "bucket";