@hermeticacomms/sdk-node 0.0.0-stage → 0.4.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 (73) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +12 -2
  3. package/dist/contracts/analytics.d.ts +405 -0
  4. package/dist/contracts/analytics.js +77 -0
  5. package/dist/contracts/auth.d.ts +363 -0
  6. package/dist/contracts/auth.js +130 -0
  7. package/dist/contracts/billing.d.ts +143 -0
  8. package/dist/contracts/billing.js +32 -0
  9. package/dist/contracts/campaigns.d.ts +915 -0
  10. package/dist/contracts/campaigns.js +276 -0
  11. package/dist/contracts/common.d.ts +57 -0
  12. package/dist/contracts/common.js +35 -0
  13. package/dist/contracts/connectors.d.ts +179 -0
  14. package/dist/contracts/connectors.js +46 -0
  15. package/dist/contracts/consent.d.ts +628 -0
  16. package/dist/contracts/consent.js +194 -0
  17. package/dist/contracts/content-blocks.d.ts +165 -0
  18. package/dist/contracts/content-blocks.js +62 -0
  19. package/dist/contracts/content-library.d.ts +347 -0
  20. package/dist/contracts/content-library.js +52 -0
  21. package/dist/contracts/content.d.ts +955 -0
  22. package/dist/contracts/content.js +194 -0
  23. package/dist/contracts/delivery.d.ts +602 -0
  24. package/dist/contracts/delivery.js +220 -0
  25. package/dist/contracts/events.d.ts +514 -0
  26. package/dist/contracts/events.js +180 -0
  27. package/dist/contracts/experiments.d.ts +378 -0
  28. package/dist/contracts/experiments.js +140 -0
  29. package/dist/contracts/identity.d.ts +761 -0
  30. package/dist/contracts/identity.js +226 -0
  31. package/dist/contracts/index.d.ts +15 -0
  32. package/dist/contracts/index.js +15 -0
  33. package/dist/contracts/integrations.d.ts +445 -0
  34. package/dist/contracts/integrations.js +139 -0
  35. package/dist/contracts/leads.d.ts +733 -0
  36. package/dist/contracts/leads.js +125 -0
  37. package/dist/contracts/metrics.d.ts +465 -0
  38. package/dist/contracts/metrics.js +96 -0
  39. package/dist/contracts/outbound.d.ts +15535 -0
  40. package/dist/contracts/outbound.js +432 -0
  41. package/dist/contracts/pickers.d.ts +12 -0
  42. package/dist/contracts/pickers.js +20 -0
  43. package/dist/contracts/platform-admin.d.ts +244 -0
  44. package/dist/contracts/platform-admin.js +98 -0
  45. package/dist/contracts/postcards.d.ts +79 -0
  46. package/dist/contracts/postcards.js +29 -0
  47. package/dist/contracts/push.d.ts +530 -0
  48. package/dist/contracts/push.js +102 -0
  49. package/dist/contracts/rcs.d.ts +39 -0
  50. package/dist/contracts/rcs.js +19 -0
  51. package/dist/contracts/segments.d.ts +3187 -0
  52. package/dist/contracts/segments.js +421 -0
  53. package/dist/contracts/workflow-nodes.d.ts +2130 -0
  54. package/dist/contracts/workflow-nodes.js +346 -0
  55. package/dist/contracts/workflows.d.ts +46811 -0
  56. package/dist/contracts/workflows.js +350 -0
  57. package/dist/contracts/x10-platform.d.ts +2603 -0
  58. package/dist/contracts/x10-platform.js +129 -0
  59. package/dist/http.d.ts +30 -0
  60. package/dist/http.js +65 -0
  61. package/dist/index.d.ts +11631 -0
  62. package/dist/index.js +63 -0
  63. package/dist/platform.d.ts +163 -0
  64. package/dist/platform.js +40 -0
  65. package/dist/resources.d.ts +1338 -0
  66. package/dist/resources.js +56 -0
  67. package/dist/signature.d.ts +5 -0
  68. package/dist/signature.js +19 -0
  69. package/dist/x10.d.ts +1608 -0
  70. package/dist/x10.js +66 -0
  71. package/dist/z10.d.ts +256 -0
  72. package/dist/z10.js +46 -0
  73. package/package.json +40 -4
@@ -0,0 +1,350 @@
1
+ import { z } from 'zod';
2
+ import { AppSlug, Channel, DateTimeIn, Id, PageQuery, Purpose, Timestamp, pageResult } from './common.js';
3
+ import { PropertyCondition } from './metrics.js';
4
+ import { SegmentDefinition } from './segments.js';
5
+ import { SequenceSettings } from './outbound.js';
6
+ import { Duration, EventRef, FieldRef, GoalMatch, NodeId, TagRef, WorkflowNode, refId } from './workflow-nodes.js';
7
+ import { pick } from './pickers.js';
8
+ export * from './workflow-nodes.js';
9
+ export const MAX_NODES = 500;
10
+ export const MAX_SYNC_STEPS = 50;
11
+ export const WorkflowMode = z.enum(['journey', 'sequence']);
12
+ export const WorkflowStatus = z.enum(['draft', 'live', 'paused', 'archived']);
13
+ export const EnrollmentState = z.enum(['active', 'waiting', 'completed', 'exited', 'failed', 'paused']);
14
+ export const Edge = z.object({ id: z.string().min(1).max(64), source: NodeId, sourceHandle: z.string().min(1).max(64), target: NodeId });
15
+ /** Re-entry is per trigger (a workflow may have several). `never` and `once` both mean one enrollment per profile, ever. */
16
+ export const ReentryPolicy = z.discriminatedUnion('mode', [
17
+ z.object({ mode: z.literal('never') }),
18
+ z.object({ mode: z.literal('once') }),
19
+ z.object({ mode: z.literal('after_completion') }),
20
+ z.object({ mode: z.literal('after_cooldown'), cooldown: Duration }),
21
+ z.object({ mode: z.literal('concurrent'), dedupeKeyTemplate: z.string().min(1).max(200) }),
22
+ ]);
23
+ const re = { reentry: ReentryPolicy.default({ mode: 'after_completion' }) };
24
+ const t = (type, shape) => z.object({ type: z.literal(type), ...shape, ...re });
25
+ export const Trigger = z.discriminatedUnion('type', [
26
+ t('profile_created', {}),
27
+ /** `where` is checked against the profile's current value after the change; `from` is the recorded previous value of the `where` field. */
28
+ t('profile_updated', { keys: z.array(pick(z.string(), 'field')).optional(), from: z.unknown().optional(), where: z.object({ field: FieldRef, op: z.enum(['eq', 'ne', 'gt', 'gte', 'lt', 'lte', 'contains', 'exists', 'not_exists']), value: z.unknown().optional() }).optional() }),
29
+ /** The lifecycle stage changed; `to` / `from` narrow it to a stage name (case-insensitive). */
30
+ t('lifecycle_changed', { to: pick(z.string().max(64), 'lifecycle_stage').optional(), from: pick(z.string().max(64), 'lifecycle_stage').optional() }),
31
+ t('list_added', { listId: refId('list') }),
32
+ t('list_removed', { listId: refId('list') }),
33
+ /** `enrollExisting`: when this trigger is first published, also enroll everyone already in the segment (batched, honours re-entry rules). */
34
+ t('segment_entered', { segmentId: refId('segment'), enrollExisting: z.boolean().optional() }),
35
+ t('segment_exited', { segmentId: refId('segment') }),
36
+ t('tag_added', { name: TagRef }),
37
+ t('tag_removed', { name: TagRef }),
38
+ t('consent_changed', { channel: Channel, status: z.enum(['granted', 'revoked']) }),
39
+ /** `filter` is equality only; `conditions` add operators (neq, gt, lt, contains, exists, ...) over the event properties. `app`: only events sent with that app. */
40
+ t('event', { name: EventRef, app: AppSlug.optional(), filter: z.record(z.string(), z.unknown()).optional(), conditions: z.array(PropertyCondition).max(10).optional() }),
41
+ /** Custom-object records: fires for every profile linked to the record. `object_updated` can require property conditions on the record. */
42
+ t('object_created', { objectType: pick(z.string().min(1).max(64), 'object_type') }),
43
+ t('object_updated', { objectType: pick(z.string().min(1).max(64), 'object_type'), conditions: z.array(PropertyCondition).max(10).optional() }),
44
+ t('object_linked', { objectType: pick(z.string().min(1).max(64), 'object_type') }),
45
+ /** A relationship between two records was added; fires for profiles linked to either side. */
46
+ t('relationship_added', { objectType: pick(z.string().max(64), 'object_type').optional(), kind: z.string().max(64).optional() }),
47
+ /** A score model's value crossed `threshold` upwards. */
48
+ /** `enrollExisting`: when first published, also enroll everyone already at or above the threshold (batched, honours re-entry rules). */
49
+ t('score_reached', { modelId: refId('score'), threshold: z.number(), enrollExisting: z.boolean().optional() }),
50
+ /** Catalog events `back_in_stock` / `price_drop` (properties: sku, dropPercent) emitted by the catalog feed diff. */
51
+ t('back_in_stock', { sku: pick(z.string().max(128), 'product').optional() }),
52
+ t('price_drop', { sku: pick(z.string().max(128), 'product').optional(), minPercent: z.number().min(0).max(100).optional() }),
53
+ /** `offsetDays`: negative = before the date, positive = after. `yearly`: match the date's month and day every year (birthdays, renewals). */
54
+ t('date_property', { attribute: FieldRef, offsetDays: z.number().int(), time: z.string().regex(/^\d{2}:\d{2}$/), tz: pick(z.string(), 'timezone'), yearly: z.boolean().optional() }),
55
+ /** Catalog event `catalog.low_inventory` (stock fell through 10, 5, 3 or 1); `below` narrows to a lower stock level. */
56
+ t('low_inventory', { sku: pick(z.string().max(128), 'product').optional(), below: z.number().int().min(1).max(10).optional() }),
57
+ /** `completed`: on a step-by-step form, start when the last step is saved (every answer on the contact) instead of at step 1. */
58
+ t('form_submitted', { formId: refId('form'), completed: z.boolean().optional() }),
59
+ /** `endsAt` (ISO date-time) and `maxRuns` stop the recurrence; leave both empty to repeat until unpublished. `maxEntriesPerRun` caps how many enter at each occurrence.
60
+ * `localTime`: the cron runs on each person's own wall clock (their profile zone, else `tz`), so "9:00" is 9:00 where they are. */
61
+ t('schedule', {
62
+ cron: z.string().min(1).max(100), tz: pick(z.string(), 'timezone'), audience: z.object({ segmentId: refId('segment').optional(), listId: refId('list').optional() }), endsAt: z.iso.datetime({ offset: true }).optional(), maxRuns: z.number().int().min(1).max(100_000).optional(),
63
+ maxEntriesPerRun: z.number().int().min(1).max(100_000).optional(), localTime: z.boolean().optional(),
64
+ }),
65
+ /** A new item (published within the last poll window) appeared in the feed; starts the audience, with the item as the trigger event. */
66
+ t('rss_item', { url: z.url(), audience: z.object({ segmentId: refId('segment').optional(), listId: refId('list').optional() }) }),
67
+ t('webhook', { inboundKey: z.string().min(1).max(64) }),
68
+ t('api', {}),
69
+ t('prospect_enrolled', {}),
70
+ /** `url`: for clicks, only this link (substring match). */
71
+ t('message_event', { kind: pick(z.string().min(1).max(32), 'message_event'), url: z.string().max(500).optional() }),
72
+ /** `keyword`: for SMS replies, the first word of the reply (case-insensitive), e.g. STOP-style opt-ins like JOIN. */
73
+ t('reply_received', { classification: pick(z.string(), 'reply_class').optional(), keyword: z.string().max(64).optional() }),
74
+ t('meeting_booked', {}),
75
+ /** A lead signal (`lead.signal`) for the contact on it or a contact linked to its company. Empty `signalType` = any signal. */
76
+ t('lead_signal', { signalType: z.enum(['job_change', 'new_hire', 'hiring', 'funding', 'website_visit']).optional() }),
77
+ /** The person's device entered an in-app geofence (the SDK hit is recorded as a `geofence_entered` event, so the app sends nothing custom). Empty `geofenceId` = any geofence. */
78
+ t('geofence_entered', { geofenceId: pick(z.string().max(128), 'geofence').optional() }),
79
+ /** A workspace-registered trigger type (Settings > Custom actions and triggers): fires on its event when every `values` entry equals the event property. */
80
+ t('custom', { typeKey: pick(z.string().regex(/^[a-z][a-z0-9_]{0,47}$/), 'custom_trigger'), values: z.record(z.string(), z.unknown()).default({}) }),
81
+ t('mailbox_disconnected', {}),
82
+ t('campaign_paused', {}),
83
+ /** Loyalty ledger (packages/loyalty). `direction`: earned = points added, spent = points removed. */
84
+ t('loyalty_points_changed', { programId: refId('loyalty_program').optional(), direction: z.enum(['earned', 'spent', 'any']).optional() }),
85
+ t('loyalty_tier_changed', { programId: refId('loyalty_program').optional(), toTierId: refId('loyalty_tier').optional() }),
86
+ t('loyalty_reward_available', { programId: refId('loyalty_program').optional(), rewardId: refId('loyalty_reward').optional() }),
87
+ ]);
88
+ export const Goal = z.object({
89
+ kind: z.enum(['event', 'segment']),
90
+ eventName: pick(z.string().max(128), 'event').optional(),
91
+ filter: z.record(z.string(), z.unknown()).optional(),
92
+ definition: SegmentDefinition.optional(),
93
+ windowDays: z.number().int().min(1).max(365).default(30),
94
+ /** `exit` ends the enrollment with goal_reached; `continue` only records the conversion. */
95
+ /** `jump` moves the contact to the first goal node (skip-ahead) and keeps going. */
96
+ onReach: z.enum(['exit', 'continue', 'jump']).default('exit'),
97
+ });
98
+ const Minutes = z.number().int().min(0).max(1440);
99
+ export const WorkflowSettings = z.object({
100
+ purpose: Purpose.default('marketing'),
101
+ mode: WorkflowMode.default('journey'),
102
+ filterCheck: z.enum(['entry', 'every_step', 'before_send']).default('before_send'),
103
+ /** When the profile filter fails after entry: `exit` ends the journey, `skip` passes over just that step (or message) and carries on, so someone who qualifies later is still reached. */
104
+ filterFailAction: z.enum(['exit', 'skip']).default('exit'),
105
+ profileFilter: SegmentDefinition.optional(),
106
+ goal: Goal.optional(),
107
+ /** Quiet hours / frequency caps are enforced by delivery; this only chooses whether the workflow overrides workspace defaults. */
108
+ quietHours: z.union([z.literal('inherit'), z.object({ startMin: Minutes, endMin: Minutes })]).default('inherit'),
109
+ /** What a send does when per-flow quiet hours are closed: hold until they end (default), skip that step, or end the journey. Consented sends are never silently dropped without this explicit choice. */
110
+ quietHoursAction: z.enum(['wait', 'skip', 'exit']).optional(),
111
+ sendWindow: z.object({ startMin: Minutes, endMin: Minutes, weekdays: z.array(z.number().int().min(1).max(7)).optional() }).optional(),
112
+ /** Per-flow smart sending, applied through delivery's workflow-scoped frequency settings on publish. */
113
+ smartSending: z.object({
114
+ skipIfMessagedWithinHours: z.number().int().min(1).max(24 * 14).optional(),
115
+ frequencyCap: z.object({ maxSends: z.number().int().min(1).max(1000), windowHours: z.number().int().min(1).max(24 * 30) }).optional(),
116
+ }).optional(),
117
+ /** Journey caps: total enrollments ever, and enrollments in flight at once. Entrants over a cap are skipped (`cap_reached`). */
118
+ enrollmentCap: z.object({ maxTotal: z.number().int().min(1).optional(), maxConcurrent: z.number().int().min(1).optional() }).optional(),
119
+ /** Entry rate: at most `perHour` people start per clock hour. Over it, `delay` starts them in the next hour with room (up to 30 days ahead), `skip` turns them away (`rate_limited`). Empty = no limit. */
120
+ entryRate: z.object({ perHour: z.number().int().min(1).max(1_000_000), onExceed: z.enum(['delay', 'skip']).default('delay') }).optional(),
121
+ /** Longest any one step may hold a person: a delay or wait whose timer is later is cut to this and its timeout path is taken. Empty = no limit. */
122
+ maxWait: Duration.optional(),
123
+ /** Publish up / down dates: outside this window nobody enters and steps are held (like a pause); inside it the journey runs as published. */
124
+ activeWindow: z.object({ from: z.iso.datetime({ offset: true }).optional(), until: z.iso.datetime({ offset: true }).optional() }).optional(),
125
+ /** Who is told (in-app always, plus email) when an enrollment fails. */
126
+ failureAlert: z.object({ userIds: z.array(refId('user')).max(20).default([]), emails: z.array(z.email()).max(20).default([]) }).optional(),
127
+ timezoneSource: z.enum(['profile', 'workspace']).default('profile'),
128
+ timezone: pick(z.string(), 'timezone').default('UTC'),
129
+ exitOn: SegmentDefinition.optional(),
130
+ /** Present on mode=sequence workflows (stop rules, mailbox, schedule, dedupe, the step list the graph was compiled from). */
131
+ sequence: SequenceSettings.optional(),
132
+ });
133
+ export const WorkflowGraph = z.object({ start: NodeId.nullable().default(null), nodes: z.array(WorkflowNode).max(MAX_NODES + 1), edges: z.array(Edge).max(MAX_NODES * 30) });
134
+ /** Everything a version freezes. */
135
+ export const WorkflowDefinition = z.object({ graph: WorkflowGraph, triggers: z.array(Trigger).max(20), settings: WorkflowSettings });
136
+ export const ValidationIssue = z.object({ severity: z.enum(['error', 'warning']), code: z.string(), message: z.string(), nodeId: z.string().optional(), /** The exact change that clears this issue, in plain words. */ fix: z.string().optional() });
137
+ export const ValidationResult = z.object({ ok: z.boolean(), errors: z.array(ValidationIssue), warnings: z.array(ValidationIssue) });
138
+ /** Validate an unsaved draft; omit `definition` to validate the stored draft. */
139
+ export const ValidateBody = z.object({ definition: WorkflowDefinition.optional() });
140
+ export const CreateWorkflowBody = z.object({
141
+ name: z.string().trim().min(1).max(200),
142
+ purpose: Purpose.default('marketing'),
143
+ mode: WorkflowMode.default('journey'),
144
+ folder: z.string().max(100).nullish(),
145
+ tags: z.array(z.string().max(64)).max(50).default([]),
146
+ definition: WorkflowDefinition.partial().optional(),
147
+ /** Product (app slug) that owns the journey; an app-bound API key stamps its own. */
148
+ app: AppSlug.nullish(),
149
+ });
150
+ export const WorkflowColor = z.string().regex(/^#[0-9a-fA-F]{6}$/, 'Use a #rrggbb colour');
151
+ export const UpdateWorkflowBody = z.object({
152
+ name: z.string().trim().min(1).max(200).optional(),
153
+ color: WorkflowColor.nullable().optional(),
154
+ folder: z.string().max(100).nullish(),
155
+ tags: z.array(z.string().max(64)).max(50).optional(),
156
+ definition: WorkflowDefinition.optional(),
157
+ /** Move to another product, or null to share. App-bound keys cannot. */
158
+ app: AppSlug.nullable().optional(),
159
+ });
160
+ /** `started*` is when the first version went live. Sorts other than the default (newest id first) still page by cursor. */
161
+ export const WorkflowListQuery = PageQuery.extend({
162
+ status: WorkflowStatus.optional(), folder: z.string().optional(), mode: WorkflowMode.optional(),
163
+ q: z.string().trim().max(200).optional(), archived: z.enum(['true', 'false']).optional(), triggerType: z.string().max(32).optional(),
164
+ createdFrom: DateTimeIn().optional(), createdTo: DateTimeIn().optional(), updatedFrom: DateTimeIn().optional(), updatedTo: DateTimeIn().optional(),
165
+ startedFrom: DateTimeIn().optional(), startedTo: DateTimeIn().optional(), app: AppSlug.optional(),
166
+ sort: z.enum(['created', '-created', 'updated', '-updated', 'name', '-name']).optional(),
167
+ });
168
+ const Row = z.looseObject({ id: Id });
169
+ export const AbState = z.object({ variants: z.array(z.object({ versionId: Id, weight: z.number().int() })), startedAt: Timestamp }).nullable();
170
+ /** Draft graph / triggers / settings are jsonb validated on write (WorkflowDefinition); they are passed through unparsed to keep list responses cheap. */
171
+ export const WorkflowDto = z.object({
172
+ id: Id,
173
+ name: z.string(),
174
+ purpose: Purpose,
175
+ mode: WorkflowMode,
176
+ status: WorkflowStatus,
177
+ publishedVersionId: Id.nullable(),
178
+ folder: z.string().nullable(),
179
+ tags: z.array(z.string()),
180
+ color: z.string().nullable().optional(),
181
+ app: z.string().nullable().optional(),
182
+ draftGraph: z.unknown(),
183
+ draftTriggers: z.unknown(),
184
+ draftSettings: z.unknown(),
185
+ /** Flow-level A/B: entrants are split across these published versions. */
186
+ ab: AbState.optional(),
187
+ createdAt: Timestamp,
188
+ updatedAt: Timestamp,
189
+ });
190
+ export const WorkflowPage = pageResult(WorkflowDto);
191
+ export const VersionDto = z.object({
192
+ id: Id, workflowId: Id, n: z.number().int(), graph: z.unknown(), trigger: z.unknown(), settings: z.unknown(), checksum: z.string(), publishedAt: Timestamp, publishedBy: z.string(),
193
+ });
194
+ export const StuckReason = z.enum(['schedule_lost', 'overdue', 'failed', 'paused', 'awaiting_signal']);
195
+ export const EnrollmentDto = Row.extend({ stuckReason: StuckReason.nullable().optional(), profileEmail: z.string().nullable().optional(), lastError: z.string().nullable().optional() });
196
+ export const EnrollmentPage = pageResult(EnrollmentDto);
197
+ export const EnrollmentListQuery = PageQuery.extend({ state: EnrollmentState.optional(), profileId: Id.optional(),
198
+ nodeId: NodeId.optional(), /** Exact email address of the profile. */ email: z.string().max(320).optional(), stuck: z.literal('true').optional(), /** Only subscribers an admin removed from the journey. */ removed: z.literal('true').optional() });
199
+ export const ResumeBody = z.object({ policy: z.enum(['run_now', 'skip_missed_sends']).default('run_now') });
200
+ /** `data` is exposed to the journey as the trigger event (`trigger` conditions, `{{ trigger.x }}` / `{{ event.x }}` liquid). */
201
+ export const EnrollBody = z.object({ profileIds: z.array(Id).min(1).max(1000), triggerType: z.string().max(32).default('api'), data: z.record(z.string(), z.unknown()).optional() });
202
+ export const EnrollResult = z.object({ enrolled: z.number().int(), skipped: z.array(z.object({ profileId: Id, reason: z.string() })), /** The rest of an object segment is enrolled by the worker. */ queued: z.boolean().optional() });
203
+ /** Inbound-webhook trigger: who to enroll (an existing profile id, or identifiers that find or create one) and the data the journey sees as its trigger event. */
204
+ export const WebhookEnrollBody = z.object({
205
+ profileId: Id.optional(), email: z.string().max(320).optional(), phone: z.string().max(40).optional(), externalId: z.string().min(1).max(256).optional(),
206
+ data: z.record(z.string(), z.unknown()).default({}),
207
+ }).refine((b) => b.profileId || b.email || b.phone || b.externalId, { message: 'Give profileId, email, phone or externalId', path: ['email'] });
208
+ export const WebhookEnrollResult = z.object({ status: z.enum(['enrolled', 'skipped']), reason: z.string().optional(), enrollmentId: Id.optional() });
209
+ /** Inbound-webhook keys shorter than this are refused by the receiver (the key is the URL's secret). */
210
+ export const MIN_INBOUND_KEY = 16;
211
+ export const JumpBody = z.object({ nodeId: NodeId });
212
+ /** New wake-up time for a waiting person; must be in the future. */
213
+ export const RescheduleBody = z.object({ runAt: DateTimeIn() });
214
+ export const MigrateBody = z.object({ fromVersionId: Id, toVersionId: Id, nodeMap: z.record(z.string(), z.string()).default({}) });
215
+ export const MigrateResult = z.object({ moved: z.number().int(), exitedUnmapped: z.number().int() });
216
+ export const SampleProfile = z.object({
217
+ id: z.string().min(1).max(64),
218
+ fields: z.record(z.string(), z.unknown()).default({}),
219
+ tags: z.array(z.string()).default([]),
220
+ listIds: z.array(z.string()).default([]),
221
+ segmentIds: z.array(z.string()).default([]),
222
+ timezone: z.string().default('UTC'),
223
+ /** "channel:purpose" -> true when granted, e.g. "email:marketing". */
224
+ consents: z.array(z.string()).default([]),
225
+ });
226
+ export const TimedEvent = z.object({ profileId: z.string(), name: z.string(), at: DateTimeIn(), properties: z.record(z.string(), z.unknown()).default({}) });
227
+ export const SimulateBody = z.object({
228
+ profiles: z.array(SampleProfile).min(1).max(100),
229
+ events: z.array(TimedEvent).max(1000).default([]),
230
+ start: DateTimeIn(),
231
+ until: DateTimeIn().optional(),
232
+ /** Inline definition to simulate an unsaved draft; defaults to the stored draft. */
233
+ definition: WorkflowDefinition.optional(),
234
+ /** Segment ids / definitions can't be evaluated in memory; profiles list matching segments in `segmentIds`. */
235
+ matchDefinitions: z.boolean().default(false),
236
+ /** The event that starts the journey as `{ name, properties }`: what `trigger` conditions, `for_each_item` and `{{ trigger.properties.x }}` read. */
237
+ triggerEvent: z.record(z.string(), z.unknown()).optional(),
238
+ /** Per "wait until they open / click / reply..." step: does it happen (`happens`) or not (`never`, the wait times out). Steps not listed use the person's real history when known, else do not happen. */
239
+ waitOutcomes: z.record(NodeId, z.enum(['happens', 'never'])).default({}),
240
+ });
241
+ export const TraceEntry = z.object({ at: Timestamp, nodeId: z.string(), kind: z.string(), handle: z.string().optional(), note: z.string().optional() });
242
+ export const SimulateResult = z.object({
243
+ traces: z.record(z.string(), z.array(TraceEntry)),
244
+ nodeCounts: z.record(z.string(), z.number().int()),
245
+ pathCounts: z.record(z.string(), z.number().int()),
246
+ warnings: z.array(ValidationIssue),
247
+ });
248
+ export const NodeReportRow = z.object({ nodeId: z.string(), entered: z.number().int(), completed: z.number().int(), exited: z.number().int(), errors: z.number().int(), waiting: z.number().int(), /** Enrollments that passed through this node and reached the goal. */ converted: z.number().int().default(0) });
249
+ export const WorkflowReport = z.object({
250
+ workflowId: Id,
251
+ nodes: z.array(NodeReportRow),
252
+ paths: z.record(z.string(), z.number().int()),
253
+ states: z.record(z.string(), z.number().int()),
254
+ goal: z.object({ conversions: z.number().int(), timeToConvertP50Sec: z.number().nullable(), timeToConvertP90Sec: z.number().nullable() }),
255
+ messages: z.record(z.string(), z.number().int()),
256
+ });
257
+ export const ReportQuery = z.object({ from: DateTimeIn().optional(), to: DateTimeIn().optional() });
258
+ /** A starter scenario for the simulator: what starts the journey, what happens after (hours from start) and how each engagement wait resolves. */
259
+ export const SimPreset = z.object({
260
+ triggerEvent: z.record(z.string(), z.unknown()).optional(),
261
+ events: z.array(z.object({ name: z.string(), afterHours: z.number() })),
262
+ waitOutcomes: z.record(z.string(), z.enum(['happens', 'never'])),
263
+ tags: z.array(z.string()),
264
+ smsConsent: z.boolean(),
265
+ /** Profile date fields the flow waits on, as days from the simulation start. */
266
+ dateFields: z.record(z.string(), z.number()),
267
+ });
268
+ export const WorkflowTemplateDto = z.object({
269
+ key: z.string(), name: z.string(), description: z.string(), definition: WorkflowDefinition,
270
+ /** Gallery email templates designed for this flow, and the simulator scenario that walks it. */
271
+ templates: z.array(z.string()).default([]), preset: SimPreset.optional(),
272
+ /** The converting variant of `preset`: awaited events happen and engagement waits are met. */
273
+ happyPreset: SimPreset.optional(),
274
+ category: z.string().default('lifecycle'),
275
+ /** Events the flow relies on; `missing` lists those this workspace has never received (filled by the API). */
276
+ requires: z.array(z.string()).default([]),
277
+ missing: z.array(z.string()).default([]),
278
+ });
279
+ export const InstallReport = z.object({
280
+ templatesCreated: z.number().int(), missingEvents: z.array(z.string()),
281
+ /** Things the user must still do before publishing. */
282
+ todo: z.array(z.string()),
283
+ });
284
+ export const ExportDto = z.object({ name: z.string(), purpose: Purpose, mode: WorkflowMode, definition: WorkflowDefinition });
285
+ export const ImportBody = ExportDto.extend({ name: z.string().trim().min(1).max(200), app: AppSlug.nullish() });
286
+ /** What happens to enrollments already inside when a new version goes live. */
287
+ export const PublishBody = z.object({
288
+ inFlight: z.enum(['stay', 'migrate', 'exit']).default('stay'),
289
+ /** old node id -> new node id, for removed (or deliberately re-targeted) nodes that still hold enrollments. */
290
+ nodeMap: z.record(z.string(), z.string()).default({}),
291
+ });
292
+ export const PublishImpact = z.object({
293
+ inFlight: z.number().int(),
294
+ /** Nodes present in the live version, absent (or changed type) in the draft, with the enrollments they hold. */
295
+ removed: z.array(z.object({ nodeId: z.string(), holding: z.number().int() })),
296
+ });
297
+ export const AbBody = z.object({ variants: z.array(z.object({ versionId: Id, weight: z.number().int().min(1).max(100) })).min(2).max(5) });
298
+ export const AbReport = z.object({
299
+ variants: z.array(z.object({ versionId: Id, n: z.number().int(), weight: z.number().int(), entered: z.number().int(), completed: z.number().int(), converted: z.number().int(), conversionRate: z.number() })),
300
+ });
301
+ export const PromoteBody = z.object({ versionId: Id });
302
+ // ---- per-step controls (Mailchimp automation emails / Klaviyo flow actions) -------------------------------------
303
+ export const WorkflowNodeDto = z.object({
304
+ nodeId: z.string(), type: z.string(), config: z.unknown(), status: z.enum(['live', 'paused']), pauseMode: z.enum(['wait', 'skip', 'review']).nullable(),
305
+ entered: z.number().int(), completed: z.number().int(), errors: z.number().int(), queued: z.number().int(),
306
+ });
307
+ export const WorkflowNodeList = z.object({ items: z.array(WorkflowNodeDto) });
308
+ export const NodeParams = z.object({ id: Id, nodeId: NodeId });
309
+ export const NodeProfileParams = NodeParams.extend({ profileId: Id });
310
+ export const WorkflowProfileParams = z.object({ id: Id, profileId: Id });
311
+ /** `wait` holds everyone, `skip` is Draft, `review` is Manual: each person's message waits for approval. */
312
+ export const PauseNodeBody = z.object({ mode: z.enum(['wait', 'skip', 'review']).default('wait') });
313
+ /** Klaviyo-style status write: `live` resumes, `paused` pauses (mode as above). */
314
+ export const PatchNodeBody = z.object({ status: z.enum(['live', 'paused']), mode: z.enum(['wait', 'skip', 'review']).default('wait') });
315
+ export const QueueAddBody = z.object({ profileIds: z.array(Id).min(1).max(1000) });
316
+ export const RemoveSubscriberBody = z.object({ profileId: Id });
317
+ // ---- live edit of a running journey (Mailchimp: edit or delete a step of a live automation) ---------------------------
318
+ /** `new_entrants`: only people who enter later get the change. `waiting`: people already inside move to the new version too. */
319
+ export const LiveEditApply = z.enum(['new_entrants', 'waiting']);
320
+ export const LiveEditBody = z.object({ config: z.record(z.string(), z.unknown()), apply: LiveEditApply.default('new_entrants') });
321
+ /** Deleting a step: those waiting at it either continue to the step after it or leave. */
322
+ export const LiveDeleteQuery = z.object({ apply: LiveEditApply.default('new_entrants'), waiting: z.enum(['move_on', 'exit']).default('move_on') });
323
+ /** Add one action to the draft (optionally spliced after a step's exit). */
324
+ export const AddDraftNodeBody = z.object({
325
+ id: NodeId.optional(), type: z.string().min(1).max(64), config: z.record(z.string(), z.unknown()).default({}),
326
+ position: z.object({ x: z.number(), y: z.number() }).optional(), after: z.object({ nodeId: NodeId, handle: z.string().min(1).max(64).default('next') }).optional(),
327
+ });
328
+ export const DraftNodeResult = z.object({ nodeId: NodeId, validation: ValidationResult });
329
+ export const LiveEditResult = z.object({ version: VersionDto, moved: z.number().int(), exited: z.number().int() });
330
+ // ---- per-profile and per-enrollment reads --------------------------------------------------------------------------
331
+ export const ProfileJourneyDto = z.object({
332
+ enrollmentId: Id, workflowId: Id, workflowName: z.string(), workflowStatus: WorkflowStatus, state: EnrollmentState, currentNodeId: z.string().nullable(),
333
+ enteredAt: Timestamp, exitedAt: Timestamp.nullable(), exitedReason: z.string().nullable(), goalReachedAt: Timestamp.nullable(), triggerType: z.string(),
334
+ });
335
+ export const ProfileJourneyPage = pageResult(ProfileJourneyDto);
336
+ export const ProfileJourneysQuery = PageQuery.extend({ state: EnrollmentState.optional(), live: z.literal('true').optional() });
337
+ export const EnrollmentStepDto = z.object({ id: Id, nodeId: z.string(), stepSeq: z.number().int(), kind: z.string(), handle: z.string().nullable(), note: z.string().nullable(), at: Timestamp });
338
+ export const EnrollmentStepPage = pageResult(EnrollmentStepDto);
339
+ export const BatchReadBody = z.object({ ids: z.array(Id).min(1).max(100) });
340
+ // ---- goals (flow goal in settings + goal steps) and per-enrollment hold ----------------------------------------------------
341
+ export const GoalNodeDto = z.object({ nodeId: NodeId, name: z.string(), skipAhead: z.boolean(), match: GoalMatch.nullable() });
342
+ export const WorkflowGoalsDto = z.object({
343
+ flowGoal: Goal.nullable(),
344
+ nodes: z.array(GoalNodeDto),
345
+ /** `converted` = enrollments that reached the flow goal or any goal step. */
346
+ conversions: z.object({ enrolled: z.number().int(), converted: z.number().int(), rate: z.number() }),
347
+ });
348
+ export const GoalNodeParams = z.object({ id: Id, nodeId: NodeId });
349
+ export const GoalNodeBody = z.object({ name: z.string().max(64).optional(), skipAhead: z.boolean().optional(), match: GoalMatch.nullable().optional() });
350
+ export const PauseEnrollmentBody = z.object({ reason: z.string().trim().min(1).max(100).default('manual') });