@hogsend/engine 0.66.0 → 0.68.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 (760) hide show
  1. package/README.md +3 -2
  2. package/dist/account-links/__fixtures__/fake-fetch.d.ts +38 -0
  3. package/dist/account-links/__fixtures__/fake-fetch.d.ts.map +1 -0
  4. package/dist/account-links/battlenet.d.ts +36 -0
  5. package/dist/account-links/battlenet.d.ts.map +1 -0
  6. package/dist/account-links/epic.d.ts +36 -0
  7. package/dist/account-links/epic.d.ts.map +1 -0
  8. package/dist/account-links/index.d.ts +7 -0
  9. package/dist/account-links/index.d.ts.map +1 -0
  10. package/dist/account-links/riot.d.ts +35 -0
  11. package/dist/account-links/riot.d.ts.map +1 -0
  12. package/dist/account-links/steam.d.ts +35 -0
  13. package/dist/account-links/steam.d.ts.map +1 -0
  14. package/dist/account-links/twitch.d.ts +38 -0
  15. package/dist/account-links/twitch.d.ts.map +1 -0
  16. package/dist/account-links/xbox.d.ts +39 -0
  17. package/dist/account-links/xbox.d.ts.map +1 -0
  18. package/dist/app.d.ts +50 -0
  19. package/dist/app.d.ts.map +1 -0
  20. package/dist/buckets/bucket-access.d.ts +60 -0
  21. package/dist/buckets/bucket-access.d.ts.map +1 -0
  22. package/dist/buckets/bucket-reactions.d.ts +100 -0
  23. package/dist/buckets/bucket-reactions.d.ts.map +1 -0
  24. package/dist/buckets/check-membership.d.ts +105 -0
  25. package/dist/buckets/check-membership.d.ts.map +1 -0
  26. package/dist/buckets/define-bucket.d.ts +53 -0
  27. package/dist/buckets/define-bucket.d.ts.map +1 -0
  28. package/dist/buckets/membership-epoch.d.ts +74 -0
  29. package/dist/buckets/membership-epoch.d.ts.map +1 -0
  30. package/dist/buckets/registry-singleton.d.ts +6 -0
  31. package/dist/buckets/registry-singleton.d.ts.map +1 -0
  32. package/dist/buckets/registry.d.ts +59 -0
  33. package/dist/buckets/registry.d.ts.map +1 -0
  34. package/dist/campaigns/cohort-sql.d.ts +54 -0
  35. package/dist/campaigns/cohort-sql.d.ts.map +1 -0
  36. package/dist/campaigns/define-campaign.d.ts +105 -0
  37. package/dist/campaigns/define-campaign.d.ts.map +1 -0
  38. package/dist/campaigns/reconcile.d.ts +13 -0
  39. package/dist/campaigns/reconcile.d.ts.map +1 -0
  40. package/dist/campaigns/steps.d.ts +29 -0
  41. package/dist/campaigns/steps.d.ts.map +1 -0
  42. package/dist/cold-connect/index.d.ts +98 -0
  43. package/dist/cold-connect/index.d.ts.map +1 -0
  44. package/dist/cold-connect/page.d.ts +69 -0
  45. package/dist/cold-connect/page.d.ts.map +1 -0
  46. package/dist/cold-connect/throttle.d.ts +39 -0
  47. package/dist/cold-connect/throttle.d.ts.map +1 -0
  48. package/dist/cold-connect/token.d.ts +57 -0
  49. package/dist/cold-connect/token.d.ts.map +1 -0
  50. package/dist/connectors/action-registry-singleton.d.ts +21 -0
  51. package/dist/connectors/action-registry-singleton.d.ts.map +1 -0
  52. package/dist/connectors/define-action.d.ts +117 -0
  53. package/dist/connectors/define-action.d.ts.map +1 -0
  54. package/dist/connectors/define-connector.d.ts +172 -0
  55. package/dist/connectors/define-connector.d.ts.map +1 -0
  56. package/dist/connectors/presets/index.d.ts +17 -0
  57. package/dist/connectors/presets/index.d.ts.map +1 -0
  58. package/dist/connectors/registry-singleton.d.ts +34 -0
  59. package/dist/connectors/registry-singleton.d.ts.map +1 -0
  60. package/dist/connectors/runtime.d.ts +68 -0
  61. package/dist/connectors/runtime.d.ts.map +1 -0
  62. package/dist/container.d.ts +678 -0
  63. package/dist/container.d.ts.map +1 -0
  64. package/dist/destinations/define-destination.d.ts +96 -0
  65. package/dist/destinations/define-destination.d.ts.map +1 -0
  66. package/dist/destinations/presets/index.d.ts +42 -0
  67. package/dist/destinations/presets/index.d.ts.map +1 -0
  68. package/dist/destinations/presets/posthog.d.ts +12 -0
  69. package/dist/destinations/presets/posthog.d.ts.map +1 -0
  70. package/dist/destinations/presets/segment.d.ts +15 -0
  71. package/dist/destinations/presets/segment.d.ts.map +1 -0
  72. package/dist/destinations/presets/slack.d.ts +10 -0
  73. package/dist/destinations/presets/slack.d.ts.map +1 -0
  74. package/dist/destinations/presets/webhook.d.ts +14 -0
  75. package/dist/destinations/presets/webhook.d.ts.map +1 -0
  76. package/dist/destinations/registry-singleton.d.ts +44 -0
  77. package/dist/destinations/registry-singleton.d.ts.map +1 -0
  78. package/dist/env.d.ts +119 -0
  79. package/dist/env.d.ts.map +1 -0
  80. package/dist/flags/reconcile.d.ts +36 -0
  81. package/dist/flags/reconcile.d.ts.map +1 -0
  82. package/dist/index.d.ts +210 -0
  83. package/dist/index.d.ts.map +1 -0
  84. package/dist/journeys/authoring.d.ts +15 -0
  85. package/dist/journeys/authoring.d.ts.map +1 -0
  86. package/dist/journeys/client-defaults-singleton.d.ts +16 -0
  87. package/dist/journeys/client-defaults-singleton.d.ts.map +1 -0
  88. package/dist/journeys/constants.d.ts +32 -0
  89. package/dist/journeys/constants.d.ts.map +1 -0
  90. package/dist/journeys/define-journey.d.ts +33 -0
  91. package/dist/journeys/define-journey.d.ts.map +1 -0
  92. package/dist/journeys/durable-law-harness.d.ts +74 -0
  93. package/dist/journeys/durable-law-harness.d.ts.map +1 -0
  94. package/dist/journeys/errors.d.ts +13 -0
  95. package/dist/journeys/errors.d.ts.map +1 -0
  96. package/dist/journeys/execute-journey-run.d.ts +160 -0
  97. package/dist/journeys/execute-journey-run.d.ts.map +1 -0
  98. package/dist/journeys/graph/build-graph.d.ts +24 -0
  99. package/dist/journeys/graph/build-graph.d.ts.map +1 -0
  100. package/dist/journeys/group-scope.d.ts +56 -0
  101. package/dist/journeys/group-scope.d.ts.map +1 -0
  102. package/dist/journeys/journey-boundary.d.ts +264 -0
  103. package/dist/journeys/journey-boundary.d.ts.map +1 -0
  104. package/dist/journeys/journey-context.d.ts +60 -0
  105. package/dist/journeys/journey-context.d.ts.map +1 -0
  106. package/dist/journeys/journey-log.d.ts +42 -0
  107. package/dist/journeys/journey-log.d.ts.map +1 -0
  108. package/dist/journeys/journey-source-locations-singleton.d.ts +6 -0
  109. package/dist/journeys/journey-source-locations-singleton.d.ts.map +1 -0
  110. package/dist/journeys/journey-sources-singleton.d.ts +5 -0
  111. package/dist/journeys/journey-sources-singleton.d.ts.map +1 -0
  112. package/dist/journeys/journey-task-factory.d.ts +11 -0
  113. package/dist/journeys/journey-task-factory.d.ts.map +1 -0
  114. package/dist/journeys/journey-task-runtime.d.ts +2 -0
  115. package/dist/journeys/journey-task-runtime.d.ts.map +1 -0
  116. package/dist/journeys/journey-version.d.ts +71 -0
  117. package/dist/journeys/journey-version.d.ts.map +1 -0
  118. package/dist/journeys/record-once.d.ts +56 -0
  119. package/dist/journeys/record-once.d.ts.map +1 -0
  120. package/dist/journeys/registry-singleton.d.ts +6 -0
  121. package/dist/journeys/registry-singleton.d.ts.map +1 -0
  122. package/dist/journeys/registry.d.ts +59 -0
  123. package/dist/journeys/registry.d.ts.map +1 -0
  124. package/dist/journeys/with-durable-gate.d.ts +97 -0
  125. package/dist/journeys/with-durable-gate.d.ts.map +1 -0
  126. package/dist/lib/account-link-emit.d.ts +69 -0
  127. package/dist/lib/account-link-emit.d.ts.map +1 -0
  128. package/dist/lib/account-link-events.d.ts +128 -0
  129. package/dist/lib/account-link-events.d.ts.map +1 -0
  130. package/dist/lib/account-link-hooks.d.ts +32 -0
  131. package/dist/lib/account-link-hooks.d.ts.map +1 -0
  132. package/dist/lib/account-link-ingest.d.ts +78 -0
  133. package/dist/lib/account-link-ingest.d.ts.map +1 -0
  134. package/dist/lib/account-link-nonce.d.ts +29 -0
  135. package/dist/lib/account-link-nonce.d.ts.map +1 -0
  136. package/dist/lib/account-link-origins.d.ts +37 -0
  137. package/dist/lib/account-link-origins.d.ts.map +1 -0
  138. package/dist/lib/account-link-pkce.d.ts +48 -0
  139. package/dist/lib/account-link-pkce.d.ts.map +1 -0
  140. package/dist/lib/account-link-provider-registry.d.ts +35 -0
  141. package/dist/lib/account-link-provider-registry.d.ts.map +1 -0
  142. package/dist/lib/account-link-throttle.d.ts +76 -0
  143. package/dist/lib/account-link-throttle.d.ts.map +1 -0
  144. package/dist/lib/account-link-url.d.ts +41 -0
  145. package/dist/lib/account-link-url.d.ts.map +1 -0
  146. package/dist/lib/account-links-from-env.d.ts +62 -0
  147. package/dist/lib/account-links-from-env.d.ts.map +1 -0
  148. package/dist/lib/account-links.d.ts +353 -0
  149. package/dist/lib/account-links.d.ts.map +1 -0
  150. package/dist/lib/agent/config.d.ts +14 -0
  151. package/dist/lib/agent/config.d.ts.map +1 -0
  152. package/dist/lib/agent/proposals.d.ts +52 -0
  153. package/dist/lib/agent/proposals.d.ts.map +1 -0
  154. package/dist/lib/agent/provider.d.ts +9 -0
  155. package/dist/lib/agent/provider.d.ts.map +1 -0
  156. package/dist/lib/agent/risk.d.ts +24 -0
  157. package/dist/lib/agent/risk.d.ts.map +1 -0
  158. package/dist/lib/agent/system-prompt.d.ts +8 -0
  159. package/dist/lib/agent/system-prompt.d.ts.map +1 -0
  160. package/dist/lib/agent/tools.d.ts +258 -0
  161. package/dist/lib/agent/tools.d.ts.map +1 -0
  162. package/dist/lib/alerting.d.ts +7 -0
  163. package/dist/lib/alerting.d.ts.map +1 -0
  164. package/dist/lib/analytics-adapter.d.ts +24 -0
  165. package/dist/lib/analytics-adapter.d.ts.map +1 -0
  166. package/dist/lib/analytics-identity.d.ts +60 -0
  167. package/dist/lib/analytics-identity.d.ts.map +1 -0
  168. package/dist/lib/analytics-provider-registry.d.ts +20 -0
  169. package/dist/lib/analytics-provider-registry.d.ts.map +1 -0
  170. package/dist/lib/analytics-providers-from-env.d.ts +41 -0
  171. package/dist/lib/analytics-providers-from-env.d.ts.map +1 -0
  172. package/dist/lib/analytics-singleton.d.ts +10 -0
  173. package/dist/lib/analytics-singleton.d.ts.map +1 -0
  174. package/dist/lib/api-key-hash.d.ts +9 -0
  175. package/dist/lib/api-key-hash.d.ts.map +1 -0
  176. package/dist/lib/app-secret.d.ts +29 -0
  177. package/dist/lib/app-secret.d.ts.map +1 -0
  178. package/dist/lib/attachments.d.ts +53 -0
  179. package/dist/lib/attachments.d.ts.map +1 -0
  180. package/dist/lib/attribution-backfill.d.ts +48 -0
  181. package/dist/lib/attribution-backfill.d.ts.map +1 -0
  182. package/dist/lib/attribution.d.ts +44 -0
  183. package/dist/lib/attribution.d.ts.map +1 -0
  184. package/dist/lib/auth.d.ts +136 -0
  185. package/dist/lib/auth.d.ts.map +1 -0
  186. package/dist/lib/backfill.d.ts +41 -0
  187. package/dist/lib/backfill.d.ts.map +1 -0
  188. package/dist/lib/banner.d.ts +52 -0
  189. package/dist/lib/banner.d.ts.map +1 -0
  190. package/dist/lib/blueprint-lock.d.ts +19 -0
  191. package/dist/lib/blueprint-lock.d.ts.map +1 -0
  192. package/dist/lib/blueprints.d.ts +573 -0
  193. package/dist/lib/blueprints.d.ts.map +1 -0
  194. package/dist/lib/boot-api-key.d.ts +38 -0
  195. package/dist/lib/boot-api-key.d.ts.map +1 -0
  196. package/dist/lib/boot.d.ts +23 -0
  197. package/dist/lib/boot.d.ts.map +1 -0
  198. package/dist/lib/bootstrap-admin.d.ts +33 -0
  199. package/dist/lib/bootstrap-admin.d.ts.map +1 -0
  200. package/dist/lib/bot-prefetch.d.ts +21 -0
  201. package/dist/lib/bot-prefetch.d.ts.map +1 -0
  202. package/dist/lib/bucket-emit.d.ts +75 -0
  203. package/dist/lib/bucket-emit.d.ts.map +1 -0
  204. package/dist/lib/bucket-posthog-sync.d.ts +29 -0
  205. package/dist/lib/bucket-posthog-sync.d.ts.map +1 -0
  206. package/dist/lib/campaign-send-key.d.ts +31 -0
  207. package/dist/lib/campaign-send-key.d.ts.map +1 -0
  208. package/dist/lib/connector-actions.d.ts +83 -0
  209. package/dist/lib/connector-actions.d.ts.map +1 -0
  210. package/dist/lib/connector-heartbeat.d.ts +35 -0
  211. package/dist/lib/connector-heartbeat.d.ts.map +1 -0
  212. package/dist/lib/connector-link-codes.d.ts +105 -0
  213. package/dist/lib/connector-link-codes.d.ts.map +1 -0
  214. package/dist/lib/connector-state.d.ts +97 -0
  215. package/dist/lib/connector-state.d.ts.map +1 -0
  216. package/dist/lib/contacts.d.ts +622 -0
  217. package/dist/lib/contacts.d.ts.map +1 -0
  218. package/dist/lib/conversion-dispatch.d.ts +98 -0
  219. package/dist/lib/conversion-dispatch.d.ts.map +1 -0
  220. package/dist/lib/conversions.d.ts +75 -0
  221. package/dist/lib/conversions.d.ts.map +1 -0
  222. package/dist/lib/create-admin.d.ts +54 -0
  223. package/dist/lib/create-admin.d.ts.map +1 -0
  224. package/dist/lib/crm-deals.d.ts +66 -0
  225. package/dist/lib/crm-deals.d.ts.map +1 -0
  226. package/dist/lib/crm-ingest.d.ts +38 -0
  227. package/dist/lib/crm-ingest.d.ts.map +1 -0
  228. package/dist/lib/crm-provider-registry.d.ts +20 -0
  229. package/dist/lib/crm-provider-registry.d.ts.map +1 -0
  230. package/dist/lib/crm-registry-singleton.d.ts +18 -0
  231. package/dist/lib/crm-registry-singleton.d.ts.map +1 -0
  232. package/dist/lib/db.d.ts +3 -0
  233. package/dist/lib/db.d.ts.map +1 -0
  234. package/dist/lib/deal-money-events.d.ts +35 -0
  235. package/dist/lib/deal-money-events.d.ts.map +1 -0
  236. package/dist/lib/discord-gateway-heartbeat.d.ts +47 -0
  237. package/dist/lib/discord-gateway-heartbeat.d.ts.map +1 -0
  238. package/dist/lib/domain-status.d.ts +87 -0
  239. package/dist/lib/domain-status.d.ts.map +1 -0
  240. package/dist/lib/email-provider-registry.d.ts +30 -0
  241. package/dist/lib/email-provider-registry.d.ts.map +1 -0
  242. package/dist/lib/email-providers-from-env.d.ts +12 -0
  243. package/dist/lib/email-providers-from-env.d.ts.map +1 -0
  244. package/dist/lib/email-service-types.d.ts +189 -0
  245. package/dist/lib/email-service-types.d.ts.map +1 -0
  246. package/dist/lib/email-stats.d.ts +12 -0
  247. package/dist/lib/email-stats.d.ts.map +1 -0
  248. package/dist/lib/email.d.ts +73 -0
  249. package/dist/lib/email.d.ts.map +1 -0
  250. package/dist/lib/enrichment-ledger.d.ts +101 -0
  251. package/dist/lib/enrichment-ledger.d.ts.map +1 -0
  252. package/dist/lib/enrichment-provider-registry.d.ts +20 -0
  253. package/dist/lib/enrichment-provider-registry.d.ts.map +1 -0
  254. package/dist/lib/enrichment-providers-from-env.d.ts +13 -0
  255. package/dist/lib/enrichment-providers-from-env.d.ts.map +1 -0
  256. package/dist/lib/enrichment-registry-singleton.d.ts +9 -0
  257. package/dist/lib/enrichment-registry-singleton.d.ts.map +1 -0
  258. package/dist/lib/enrollment-guards.d.ts +28 -0
  259. package/dist/lib/enrollment-guards.d.ts.map +1 -0
  260. package/dist/lib/enrollment-policy.d.ts +25 -0
  261. package/dist/lib/enrollment-policy.d.ts.map +1 -0
  262. package/dist/lib/event-names.d.ts +27 -0
  263. package/dist/lib/event-names.d.ts.map +1 -0
  264. package/dist/lib/feed.d.ts +64 -0
  265. package/dist/lib/feed.d.ts.map +1 -0
  266. package/dist/lib/flags-registry.d.ts +23 -0
  267. package/dist/lib/flags-registry.d.ts.map +1 -0
  268. package/dist/lib/flags.d.ts +143 -0
  269. package/dist/lib/flags.d.ts.map +1 -0
  270. package/dist/lib/frequency-cap.d.ts +38 -0
  271. package/dist/lib/frequency-cap.d.ts.map +1 -0
  272. package/dist/lib/from-address.d.ts +15 -0
  273. package/dist/lib/from-address.d.ts.map +1 -0
  274. package/dist/lib/funnel-progress.d.ts +37 -0
  275. package/dist/lib/funnel-progress.d.ts.map +1 -0
  276. package/dist/lib/funnel-registry.d.ts +44 -0
  277. package/dist/lib/funnel-registry.d.ts.map +1 -0
  278. package/dist/lib/funnel-transitions.d.ts +63 -0
  279. package/dist/lib/funnel-transitions.d.ts.map +1 -0
  280. package/dist/lib/fx.d.ts +118 -0
  281. package/dist/lib/fx.d.ts.map +1 -0
  282. package/dist/lib/global-control-readout.d.ts +72 -0
  283. package/dist/lib/global-control-readout.d.ts.map +1 -0
  284. package/dist/lib/groups.d.ts +138 -0
  285. package/dist/lib/groups.d.ts.map +1 -0
  286. package/dist/lib/hatchet-duration.d.ts +14 -0
  287. package/dist/lib/hatchet-duration.d.ts.map +1 -0
  288. package/dist/lib/hatchet.d.ts +3 -0
  289. package/dist/lib/hatchet.d.ts.map +1 -0
  290. package/dist/lib/headers.d.ts +8 -0
  291. package/dist/lib/headers.d.ts.map +1 -0
  292. package/dist/lib/holdout.d.ts +36 -0
  293. package/dist/lib/holdout.d.ts.map +1 -0
  294. package/dist/lib/html.d.ts +5 -0
  295. package/dist/lib/html.d.ts.map +1 -0
  296. package/dist/lib/identity-service.d.ts +60 -0
  297. package/dist/lib/identity-service.d.ts.map +1 -0
  298. package/dist/lib/identity-token.d.ts +81 -0
  299. package/dist/lib/identity-token.d.ts.map +1 -0
  300. package/dist/lib/ingestion.d.ts +218 -0
  301. package/dist/lib/ingestion.d.ts.map +1 -0
  302. package/dist/lib/journey-lift.d.ts +56 -0
  303. package/dist/lib/journey-lift.d.ts.map +1 -0
  304. package/dist/lib/journey-suppress.d.ts +59 -0
  305. package/dist/lib/journey-suppress.d.ts.map +1 -0
  306. package/dist/lib/leader-lease.d.ts +36 -0
  307. package/dist/lib/leader-lease.d.ts.map +1 -0
  308. package/dist/lib/lift-stats.d.ts +46 -0
  309. package/dist/lib/lift-stats.d.ts.map +1 -0
  310. package/dist/lib/links.d.ts +186 -0
  311. package/dist/lib/links.d.ts.map +1 -0
  312. package/dist/lib/load-optional-plugin.d.ts +47 -0
  313. package/dist/lib/load-optional-plugin.d.ts.map +1 -0
  314. package/dist/lib/logger.d.ts +4 -0
  315. package/dist/lib/logger.d.ts.map +1 -0
  316. package/dist/lib/mailer.d.ts +43 -0
  317. package/dist/lib/mailer.d.ts.map +1 -0
  318. package/dist/lib/metrics-sql.d.ts +11 -0
  319. package/dist/lib/metrics-sql.d.ts.map +1 -0
  320. package/dist/lib/notifications.d.ts +17 -0
  321. package/dist/lib/notifications.d.ts.map +1 -0
  322. package/dist/lib/oauth-token-manager.d.ts +74 -0
  323. package/dist/lib/oauth-token-manager.d.ts.map +1 -0
  324. package/dist/lib/operator-settings.d.ts +33 -0
  325. package/dist/lib/operator-settings.d.ts.map +1 -0
  326. package/dist/lib/operator.d.ts +20 -0
  327. package/dist/lib/operator.d.ts.map +1 -0
  328. package/dist/lib/outbound-endpoint-cache.d.ts +25 -0
  329. package/dist/lib/outbound-endpoint-cache.d.ts.map +1 -0
  330. package/dist/lib/outbound.d.ts +687 -0
  331. package/dist/lib/outbound.d.ts.map +1 -0
  332. package/dist/lib/phone.d.ts +11 -0
  333. package/dist/lib/phone.d.ts.map +1 -0
  334. package/dist/lib/posthog-scopes.d.ts +30 -0
  335. package/dist/lib/posthog-scopes.d.ts.map +1 -0
  336. package/dist/lib/posthog.d.ts +16 -0
  337. package/dist/lib/posthog.d.ts.map +1 -0
  338. package/dist/lib/preferences.d.ts +72 -0
  339. package/dist/lib/preferences.d.ts.map +1 -0
  340. package/dist/lib/provider-credentials.d.ts +149 -0
  341. package/dist/lib/provider-credentials.d.ts.map +1 -0
  342. package/dist/lib/provision-posthog-loop.d.ts +100 -0
  343. package/dist/lib/provision-posthog-loop.d.ts.map +1 -0
  344. package/dist/lib/recipient-preferences.d.ts +29 -0
  345. package/dist/lib/recipient-preferences.d.ts.map +1 -0
  346. package/dist/lib/redis.d.ts +33 -0
  347. package/dist/lib/redis.d.ts.map +1 -0
  348. package/dist/lib/referral-intent.d.ts +99 -0
  349. package/dist/lib/referral-intent.d.ts.map +1 -0
  350. package/dist/lib/referral-link.d.ts +59 -0
  351. package/dist/lib/referral-link.d.ts.map +1 -0
  352. package/dist/lib/referral-registry.d.ts +37 -0
  353. package/dist/lib/referral-registry.d.ts.map +1 -0
  354. package/dist/lib/referral-report.d.ts +178 -0
  355. package/dist/lib/referral-report.d.ts.map +1 -0
  356. package/dist/lib/referral-runtime.d.ts +43 -0
  357. package/dist/lib/referral-runtime.d.ts.map +1 -0
  358. package/dist/lib/referrals.d.ts +184 -0
  359. package/dist/lib/referrals.d.ts.map +1 -0
  360. package/dist/lib/refine-chain.d.ts +236 -0
  361. package/dist/lib/refine-chain.d.ts.map +1 -0
  362. package/dist/lib/refine-traits.d.ts +78 -0
  363. package/dist/lib/refine-traits.d.ts.map +1 -0
  364. package/dist/lib/refine.d.ts +35 -0
  365. package/dist/lib/refine.d.ts.map +1 -0
  366. package/dist/lib/reset-email.d.ts +38 -0
  367. package/dist/lib/reset-email.d.ts.map +1 -0
  368. package/dist/lib/revenue.d.ts +61 -0
  369. package/dist/lib/revenue.d.ts.map +1 -0
  370. package/dist/lib/schemas.d.ts +9 -0
  371. package/dist/lib/schemas.d.ts.map +1 -0
  372. package/dist/lib/seed-posthog-destination.d.ts +22 -0
  373. package/dist/lib/seed-posthog-destination.d.ts.map +1 -0
  374. package/dist/lib/semantic-click.d.ts +58 -0
  375. package/dist/lib/semantic-click.d.ts.map +1 -0
  376. package/dist/lib/sending-domain-guidance.d.ts +40 -0
  377. package/dist/lib/sending-domain-guidance.d.ts.map +1 -0
  378. package/dist/lib/singleton.d.ts +24 -0
  379. package/dist/lib/singleton.d.ts.map +1 -0
  380. package/dist/lib/sms-frequency-cap.d.ts +16 -0
  381. package/dist/lib/sms-frequency-cap.d.ts.map +1 -0
  382. package/dist/lib/sms-inbound.d.ts +37 -0
  383. package/dist/lib/sms-inbound.d.ts.map +1 -0
  384. package/dist/lib/sms-link-tracking.d.ts +53 -0
  385. package/dist/lib/sms-link-tracking.d.ts.map +1 -0
  386. package/dist/lib/sms-mailer.d.ts +12 -0
  387. package/dist/lib/sms-mailer.d.ts.map +1 -0
  388. package/dist/lib/sms-provider-registry.d.ts +20 -0
  389. package/dist/lib/sms-provider-registry.d.ts.map +1 -0
  390. package/dist/lib/sms-providers-from-env.d.ts +4 -0
  391. package/dist/lib/sms-providers-from-env.d.ts.map +1 -0
  392. package/dist/lib/sms-service-types.d.ts +131 -0
  393. package/dist/lib/sms-service-types.d.ts.map +1 -0
  394. package/dist/lib/sms-tracked.d.ts +36 -0
  395. package/dist/lib/sms-tracked.d.ts.map +1 -0
  396. package/dist/lib/sms.d.ts +58 -0
  397. package/dist/lib/sms.d.ts.map +1 -0
  398. package/dist/lib/snippet.d.ts +32 -0
  399. package/dist/lib/snippet.d.ts.map +1 -0
  400. package/dist/lib/stable-stringify.d.ts +12 -0
  401. package/dist/lib/stable-stringify.d.ts.map +1 -0
  402. package/dist/lib/studio.d.ts +21 -0
  403. package/dist/lib/studio.d.ts.map +1 -0
  404. package/dist/lib/survey.d.ts +35 -0
  405. package/dist/lib/survey.d.ts.map +1 -0
  406. package/dist/lib/test-mode.d.ts +77 -0
  407. package/dist/lib/test-mode.d.ts.map +1 -0
  408. package/dist/lib/timezone.d.ts +55 -0
  409. package/dist/lib/timezone.d.ts.map +1 -0
  410. package/dist/lib/tracked.d.ts +95 -0
  411. package/dist/lib/tracked.d.ts.map +1 -0
  412. package/dist/lib/tracking-event-names.d.ts +7 -0
  413. package/dist/lib/tracking-event-names.d.ts.map +1 -0
  414. package/dist/lib/tracking-events.d.ts +232 -0
  415. package/dist/lib/tracking-events.d.ts.map +1 -0
  416. package/dist/lib/tracking.d.ts +47 -0
  417. package/dist/lib/tracking.d.ts.map +1 -0
  418. package/dist/lib/unconfigured-email-provider.d.ts +20 -0
  419. package/dist/lib/unconfigured-email-provider.d.ts.map +1 -0
  420. package/dist/lib/unique-violation.d.ts +22 -0
  421. package/dist/lib/unique-violation.d.ts.map +1 -0
  422. package/dist/lib/user-token.d.ts +44 -0
  423. package/dist/lib/user-token.d.ts.map +1 -0
  424. package/dist/lib/variant.d.ts +44 -0
  425. package/dist/lib/variant.d.ts.map +1 -0
  426. package/dist/lib/webhook-signing.d.ts +120 -0
  427. package/dist/lib/webhook-signing.d.ts.map +1 -0
  428. package/dist/lib/worker-heartbeat.d.ts +18 -0
  429. package/dist/lib/worker-heartbeat.d.ts.map +1 -0
  430. package/dist/lists/channels.d.ts +43 -0
  431. package/dist/lists/channels.d.ts.map +1 -0
  432. package/dist/lists/define-list.d.ts +76 -0
  433. package/dist/lists/define-list.d.ts.map +1 -0
  434. package/dist/lists/registry-singleton.d.ts +8 -0
  435. package/dist/lists/registry-singleton.d.ts.map +1 -0
  436. package/dist/lists/registry.d.ts +66 -0
  437. package/dist/lists/registry.d.ts.map +1 -0
  438. package/dist/lists/subscription.d.ts +10 -0
  439. package/dist/lists/subscription.d.ts.map +1 -0
  440. package/dist/mcp/authoring-guide.d.ts +33 -0
  441. package/dist/mcp/authoring-guide.d.ts.map +1 -0
  442. package/dist/mcp/blueprint-tools.d.ts +266 -0
  443. package/dist/mcp/blueprint-tools.d.ts.map +1 -0
  444. package/dist/middleware/api-key.d.ts +45 -0
  445. package/dist/middleware/api-key.d.ts.map +1 -0
  446. package/dist/middleware/audit.d.ts +3 -0
  447. package/dist/middleware/audit.d.ts.map +1 -0
  448. package/dist/middleware/error-handler.d.ts +4 -0
  449. package/dist/middleware/error-handler.d.ts.map +1 -0
  450. package/dist/middleware/publishable-key.d.ts +27 -0
  451. package/dist/middleware/publishable-key.d.ts.map +1 -0
  452. package/dist/middleware/rate-limit.d.ts +105 -0
  453. package/dist/middleware/rate-limit.d.ts.map +1 -0
  454. package/dist/middleware/request-logger.d.ts +4 -0
  455. package/dist/middleware/request-logger.d.ts.map +1 -0
  456. package/dist/middleware/require-admin.d.ts +3 -0
  457. package/dist/middleware/require-admin.d.ts.map +1 -0
  458. package/dist/routes/_shared.d.ts +52 -0
  459. package/dist/routes/_shared.d.ts.map +1 -0
  460. package/dist/routes/accounts/callback.d.ts +18 -0
  461. package/dist/routes/accounts/callback.d.ts.map +1 -0
  462. package/dist/routes/accounts/emit.d.ts +96 -0
  463. package/dist/routes/accounts/emit.d.ts.map +1 -0
  464. package/dist/routes/accounts/import-links.d.ts +4 -0
  465. package/dist/routes/accounts/import-links.d.ts.map +1 -0
  466. package/dist/routes/accounts/index.d.ts +39 -0
  467. package/dist/routes/accounts/index.d.ts.map +1 -0
  468. package/dist/routes/accounts/lookup.d.ts +6 -0
  469. package/dist/routes/accounts/lookup.d.ts.map +1 -0
  470. package/dist/routes/accounts/me.d.ts +5 -0
  471. package/dist/routes/accounts/me.d.ts.map +1 -0
  472. package/dist/routes/accounts/mint.d.ts +5 -0
  473. package/dist/routes/accounts/mint.d.ts.map +1 -0
  474. package/dist/routes/accounts/pages.d.ts +23 -0
  475. package/dist/routes/accounts/pages.d.ts.map +1 -0
  476. package/dist/routes/accounts/resolve.d.ts +33 -0
  477. package/dist/routes/accounts/resolve.d.ts.map +1 -0
  478. package/dist/routes/accounts/serialize.d.ts +57 -0
  479. package/dist/routes/accounts/serialize.d.ts.map +1 -0
  480. package/dist/routes/accounts/shared.d.ts +68 -0
  481. package/dist/routes/accounts/shared.d.ts.map +1 -0
  482. package/dist/routes/accounts/start.d.ts +16 -0
  483. package/dist/routes/accounts/start.d.ts.map +1 -0
  484. package/dist/routes/accounts/unlink.d.ts +36 -0
  485. package/dist/routes/accounts/unlink.d.ts.map +1 -0
  486. package/dist/routes/admin/agent.d.ts +4 -0
  487. package/dist/routes/admin/agent.d.ts.map +1 -0
  488. package/dist/routes/admin/alerts.d.ts +190 -0
  489. package/dist/routes/admin/alerts.d.ts.map +1 -0
  490. package/dist/routes/admin/analytics.d.ts +137 -0
  491. package/dist/routes/admin/analytics.d.ts.map +1 -0
  492. package/dist/routes/admin/api-keys.d.ts +158 -0
  493. package/dist/routes/admin/api-keys.d.ts.map +1 -0
  494. package/dist/routes/admin/attribution.d.ts +93 -0
  495. package/dist/routes/admin/attribution.d.ts.map +1 -0
  496. package/dist/routes/admin/audit-logs.d.ts +40 -0
  497. package/dist/routes/admin/audit-logs.d.ts.map +1 -0
  498. package/dist/routes/admin/blueprints.d.ts +4 -0
  499. package/dist/routes/admin/blueprints.d.ts.map +1 -0
  500. package/dist/routes/admin/buckets.d.ts +215 -0
  501. package/dist/routes/admin/buckets.d.ts.map +1 -0
  502. package/dist/routes/admin/bulk.d.ts +203 -0
  503. package/dist/routes/admin/bulk.d.ts.map +1 -0
  504. package/dist/routes/admin/campaigns.d.ts +198 -0
  505. package/dist/routes/admin/campaigns.d.ts.map +1 -0
  506. package/dist/routes/admin/connectors.d.ts +116 -0
  507. package/dist/routes/admin/connectors.d.ts.map +1 -0
  508. package/dist/routes/admin/contacts.d.ts +246 -0
  509. package/dist/routes/admin/contacts.d.ts.map +1 -0
  510. package/dist/routes/admin/conversions.d.ts +103 -0
  511. package/dist/routes/admin/conversions.d.ts.map +1 -0
  512. package/dist/routes/admin/deals.d.ts +136 -0
  513. package/dist/routes/admin/deals.d.ts.map +1 -0
  514. package/dist/routes/admin/dlq.d.ts +100 -0
  515. package/dist/routes/admin/dlq.d.ts.map +1 -0
  516. package/dist/routes/admin/domain.d.ts +314 -0
  517. package/dist/routes/admin/domain.d.ts.map +1 -0
  518. package/dist/routes/admin/emails.d.ts +127 -0
  519. package/dist/routes/admin/emails.d.ts.map +1 -0
  520. package/dist/routes/admin/events.d.ts +140 -0
  521. package/dist/routes/admin/events.d.ts.map +1 -0
  522. package/dist/routes/admin/flags.d.ts +719 -0
  523. package/dist/routes/admin/flags.d.ts.map +1 -0
  524. package/dist/routes/admin/funnels.d.ts +71 -0
  525. package/dist/routes/admin/funnels.d.ts.map +1 -0
  526. package/dist/routes/admin/groups.d.ts +169 -0
  527. package/dist/routes/admin/groups.d.ts.map +1 -0
  528. package/dist/routes/admin/identity.d.ts +72 -0
  529. package/dist/routes/admin/identity.d.ts.map +1 -0
  530. package/dist/routes/admin/impact-schemas.d.ts +48 -0
  531. package/dist/routes/admin/impact-schemas.d.ts.map +1 -0
  532. package/dist/routes/admin/impact.d.ts +316 -0
  533. package/dist/routes/admin/impact.d.ts.map +1 -0
  534. package/dist/routes/admin/index.d.ts +4 -0
  535. package/dist/routes/admin/index.d.ts.map +1 -0
  536. package/dist/routes/admin/journey-impact.d.ts +320 -0
  537. package/dist/routes/admin/journey-impact.d.ts.map +1 -0
  538. package/dist/routes/admin/journey-logs.d.ts +57 -0
  539. package/dist/routes/admin/journey-logs.d.ts.map +1 -0
  540. package/dist/routes/admin/journeys.d.ts +736 -0
  541. package/dist/routes/admin/journeys.d.ts.map +1 -0
  542. package/dist/routes/admin/links.d.ts +382 -0
  543. package/dist/routes/admin/links.d.ts.map +1 -0
  544. package/dist/routes/admin/lists.d.ts +22 -0
  545. package/dist/routes/admin/lists.d.ts.map +1 -0
  546. package/dist/routes/admin/maintenance.d.ts +72 -0
  547. package/dist/routes/admin/maintenance.d.ts.map +1 -0
  548. package/dist/routes/admin/metrics.d.ts +212 -0
  549. package/dist/routes/admin/metrics.d.ts.map +1 -0
  550. package/dist/routes/admin/open-editor.d.ts +36 -0
  551. package/dist/routes/admin/open-editor.d.ts.map +1 -0
  552. package/dist/routes/admin/preferences.d.ts +109 -0
  553. package/dist/routes/admin/preferences.d.ts.map +1 -0
  554. package/dist/routes/admin/provider-credentials.d.ts +108 -0
  555. package/dist/routes/admin/provider-credentials.d.ts.map +1 -0
  556. package/dist/routes/admin/readiness.d.ts +24 -0
  557. package/dist/routes/admin/readiness.d.ts.map +1 -0
  558. package/dist/routes/admin/referrals.d.ts +230 -0
  559. package/dist/routes/admin/referrals.d.ts.map +1 -0
  560. package/dist/routes/admin/reporting.d.ts +149 -0
  561. package/dist/routes/admin/reporting.d.ts.map +1 -0
  562. package/dist/routes/admin/settings.d.ts +80 -0
  563. package/dist/routes/admin/settings.d.ts.map +1 -0
  564. package/dist/routes/admin/suppressions.d.ts +90 -0
  565. package/dist/routes/admin/suppressions.d.ts.map +1 -0
  566. package/dist/routes/admin/targeting.d.ts +58 -0
  567. package/dist/routes/admin/targeting.d.ts.map +1 -0
  568. package/dist/routes/admin/templates.d.ts +197 -0
  569. package/dist/routes/admin/templates.d.ts.map +1 -0
  570. package/dist/routes/admin/timeline.d.ts +51 -0
  571. package/dist/routes/admin/timeline.d.ts.map +1 -0
  572. package/dist/routes/admin/webhooks.d.ts +250 -0
  573. package/dist/routes/admin/webhooks.d.ts.map +1 -0
  574. package/dist/routes/campaigns/index.d.ts +239 -0
  575. package/dist/routes/campaigns/index.d.ts.map +1 -0
  576. package/dist/routes/connectors/index.d.ts +16 -0
  577. package/dist/routes/connectors/index.d.ts.map +1 -0
  578. package/dist/routes/contacts/index.d.ts +187 -0
  579. package/dist/routes/contacts/index.d.ts.map +1 -0
  580. package/dist/routes/email/index.d.ts +4 -0
  581. package/dist/routes/email/index.d.ts.map +1 -0
  582. package/dist/routes/email/preferences.d.ts +17 -0
  583. package/dist/routes/email/preferences.d.ts.map +1 -0
  584. package/dist/routes/email/unsubscribe.d.ts +17 -0
  585. package/dist/routes/email/unsubscribe.d.ts.map +1 -0
  586. package/dist/routes/emails/index.d.ts +90 -0
  587. package/dist/routes/emails/index.d.ts.map +1 -0
  588. package/dist/routes/events/index.d.ts +116 -0
  589. package/dist/routes/events/index.d.ts.map +1 -0
  590. package/dist/routes/feed/index.d.ts +248 -0
  591. package/dist/routes/feed/index.d.ts.map +1 -0
  592. package/dist/routes/feed/recipient.d.ts +65 -0
  593. package/dist/routes/feed/recipient.d.ts.map +1 -0
  594. package/dist/routes/flags/index.d.ts +94 -0
  595. package/dist/routes/flags/index.d.ts.map +1 -0
  596. package/dist/routes/groups/index.d.ts +192 -0
  597. package/dist/routes/groups/index.d.ts.map +1 -0
  598. package/dist/routes/health.d.ts +57 -0
  599. package/dist/routes/health.d.ts.map +1 -0
  600. package/dist/routes/index.d.ts +8 -0
  601. package/dist/routes/index.d.ts.map +1 -0
  602. package/dist/routes/lists/index.d.ts +266 -0
  603. package/dist/routes/lists/index.d.ts.map +1 -0
  604. package/dist/routes/referrals/index.d.ts +22 -0
  605. package/dist/routes/referrals/index.d.ts.map +1 -0
  606. package/dist/routes/referrals/me.d.ts +4 -0
  607. package/dist/routes/referrals/me.d.ts.map +1 -0
  608. package/dist/routes/referrals/report.d.ts +5 -0
  609. package/dist/routes/referrals/report.d.ts.map +1 -0
  610. package/dist/routes/referrals/shared.d.ts +16 -0
  611. package/dist/routes/referrals/shared.d.ts.map +1 -0
  612. package/dist/routes/referrals/touch.d.ts +5 -0
  613. package/dist/routes/referrals/touch.d.ts.map +1 -0
  614. package/dist/routes/snippet.d.ts +12 -0
  615. package/dist/routes/snippet.d.ts.map +1 -0
  616. package/dist/routes/tracking/answer.d.ts +56 -0
  617. package/dist/routes/tracking/answer.d.ts.map +1 -0
  618. package/dist/routes/tracking/arrive.d.ts +32 -0
  619. package/dist/routes/tracking/arrive.d.ts.map +1 -0
  620. package/dist/routes/tracking/click-pipeline.d.ts +213 -0
  621. package/dist/routes/tracking/click-pipeline.d.ts.map +1 -0
  622. package/dist/routes/tracking/click.d.ts +26 -0
  623. package/dist/routes/tracking/click.d.ts.map +1 -0
  624. package/dist/routes/tracking/identify.d.ts +32 -0
  625. package/dist/routes/tracking/identify.d.ts.map +1 -0
  626. package/dist/routes/tracking/index.d.ts +4 -0
  627. package/dist/routes/tracking/index.d.ts.map +1 -0
  628. package/dist/routes/tracking/open.d.ts +17 -0
  629. package/dist/routes/tracking/open.d.ts.map +1 -0
  630. package/dist/routes/tracking/short.d.ts +17 -0
  631. package/dist/routes/tracking/short.d.ts.map +1 -0
  632. package/dist/routes/tracking/vanity.d.ts +17 -0
  633. package/dist/routes/tracking/vanity.d.ts.map +1 -0
  634. package/dist/routes/webhooks/crm-provider.d.ts +24 -0
  635. package/dist/routes/webhooks/crm-provider.d.ts.map +1 -0
  636. package/dist/routes/webhooks/email-provider.d.ts +21 -0
  637. package/dist/routes/webhooks/email-provider.d.ts.map +1 -0
  638. package/dist/routes/webhooks/index.d.ts +8 -0
  639. package/dist/routes/webhooks/index.d.ts.map +1 -0
  640. package/dist/routes/webhooks/resend.d.ts +35 -0
  641. package/dist/routes/webhooks/resend.d.ts.map +1 -0
  642. package/dist/routes/webhooks/sms-provider.d.ts +23 -0
  643. package/dist/routes/webhooks/sms-provider.d.ts.map +1 -0
  644. package/dist/routes/webhooks/sources.d.ts +12 -0
  645. package/dist/routes/webhooks/sources.d.ts.map +1 -0
  646. package/dist/sources/define-contact-source.d.ts +114 -0
  647. package/dist/sources/define-contact-source.d.ts.map +1 -0
  648. package/dist/sources/registry.d.ts +31 -0
  649. package/dist/sources/registry.d.ts.map +1 -0
  650. package/dist/sources/webhook-source.d.ts +53 -0
  651. package/dist/sources/webhook-source.d.ts.map +1 -0
  652. package/dist/testing.d.ts +10 -0
  653. package/dist/testing.d.ts.map +1 -0
  654. package/dist/webhook-sources/define-webhook-source.d.ts +60 -0
  655. package/dist/webhook-sources/define-webhook-source.d.ts.map +1 -0
  656. package/dist/webhook-sources/presets/clerk.d.ts +9 -0
  657. package/dist/webhook-sources/presets/clerk.d.ts.map +1 -0
  658. package/dist/webhook-sources/presets/index.d.ts +140 -0
  659. package/dist/webhook-sources/presets/index.d.ts.map +1 -0
  660. package/dist/webhook-sources/presets/intercom.d.ts +44 -0
  661. package/dist/webhook-sources/presets/intercom.d.ts.map +1 -0
  662. package/dist/webhook-sources/presets/segment.d.ts +16 -0
  663. package/dist/webhook-sources/presets/segment.d.ts.map +1 -0
  664. package/dist/webhook-sources/presets/stripe.d.ts +20 -0
  665. package/dist/webhook-sources/presets/stripe.d.ts.map +1 -0
  666. package/dist/webhook-sources/presets/supabase.d.ts +23 -0
  667. package/dist/webhook-sources/presets/supabase.d.ts.map +1 -0
  668. package/dist/webhook-sources/verify.d.ts +48 -0
  669. package/dist/webhook-sources/verify.d.ts.map +1 -0
  670. package/dist/worker.d.ts +37 -0
  671. package/dist/worker.d.ts.map +1 -0
  672. package/dist/workflows/backfill-contact-id.d.ts +202 -0
  673. package/dist/workflows/backfill-contact-id.d.ts.map +1 -0
  674. package/dist/workflows/bucket-backfill.d.ts +64 -0
  675. package/dist/workflows/bucket-backfill.d.ts.map +1 -0
  676. package/dist/workflows/bucket-reconcile.d.ts +73 -0
  677. package/dist/workflows/bucket-reconcile.d.ts.map +1 -0
  678. package/dist/workflows/check-alerts.d.ts +10 -0
  679. package/dist/workflows/check-alerts.d.ts.map +1 -0
  680. package/dist/workflows/confirm-semantic-click.d.ts +15 -0
  681. package/dist/workflows/confirm-semantic-click.d.ts.map +1 -0
  682. package/dist/workflows/crm-reconcile.d.ts +27 -0
  683. package/dist/workflows/crm-reconcile.d.ts.map +1 -0
  684. package/dist/workflows/deliver-webhook.d.ts +88 -0
  685. package/dist/workflows/deliver-webhook.d.ts.map +1 -0
  686. package/dist/workflows/dispatch-conversion.d.ts +14 -0
  687. package/dist/workflows/dispatch-conversion.d.ts.map +1 -0
  688. package/dist/workflows/identity-alias-backfill.d.ts +96 -0
  689. package/dist/workflows/identity-alias-backfill.d.ts.map +1 -0
  690. package/dist/workflows/impact-digest.d.ts +142 -0
  691. package/dist/workflows/impact-digest.d.ts.map +1 -0
  692. package/dist/workflows/import-contacts.d.ts +14 -0
  693. package/dist/workflows/import-contacts.d.ts.map +1 -0
  694. package/dist/workflows/import-suppressions.d.ts +55 -0
  695. package/dist/workflows/import-suppressions.d.ts.map +1 -0
  696. package/dist/workflows/journey-blueprint-interpreter.d.ts +73 -0
  697. package/dist/workflows/journey-blueprint-interpreter.d.ts.map +1 -0
  698. package/dist/workflows/send-campaign.d.ts +128 -0
  699. package/dist/workflows/send-campaign.d.ts.map +1 -0
  700. package/dist/workflows/send-email.d.ts +15 -0
  701. package/dist/workflows/send-email.d.ts.map +1 -0
  702. package/dist/workflows/send-feed.d.ts +37 -0
  703. package/dist/workflows/send-feed.d.ts.map +1 -0
  704. package/package.json +60 -22
  705. package/src/app.ts +9 -1
  706. package/src/buckets/check-membership.ts +54 -20
  707. package/src/container.ts +77 -0
  708. package/src/env.ts +30 -0
  709. package/src/index.ts +78 -0
  710. package/src/journeys/journey-log.ts +25 -8
  711. package/src/lib/contacts.ts +117 -1
  712. package/src/lib/email-service-types.ts +10 -0
  713. package/src/lib/ingestion.ts +91 -19
  714. package/src/lib/links.ts +94 -11
  715. package/src/lib/mailer-bounce-idempotency.test.ts +7 -2
  716. package/src/lib/mailer-replied.test.ts +7 -2
  717. package/src/lib/mailer.ts +1 -0
  718. package/src/lib/outbound-endpoint-cache.ts +83 -0
  719. package/src/lib/outbound.ts +150 -37
  720. package/src/lib/referral-intent.ts +723 -0
  721. package/src/lib/referral-link.ts +200 -0
  722. package/src/lib/referral-registry.ts +83 -0
  723. package/src/lib/referral-report.ts +739 -0
  724. package/src/lib/referral-runtime.ts +49 -0
  725. package/src/lib/referrals-no-emit.test.ts +109 -0
  726. package/src/lib/referrals.ts +712 -0
  727. package/src/lib/seed-posthog-destination.ts +5 -1
  728. package/src/lib/tracked.ts +11 -3
  729. package/src/lib/tracking-events.ts +20 -3
  730. package/src/lib/webhook-signing.ts +10 -0
  731. package/src/middleware/api-key.ts +69 -60
  732. package/src/middleware/publishable-key.ts +11 -23
  733. package/src/middleware/rate-limit.ts +165 -3
  734. package/src/routes/admin/api-keys.ts +153 -0
  735. package/src/routes/admin/index.ts +2 -0
  736. package/src/routes/admin/links.ts +14 -5
  737. package/src/routes/admin/referrals.ts +565 -0
  738. package/src/routes/admin/targeting.ts +6 -1
  739. package/src/routes/admin/webhooks.ts +4 -0
  740. package/src/routes/contacts/index.ts +78 -0
  741. package/src/routes/index.ts +104 -22
  742. package/src/routes/referrals/index.ts +41 -0
  743. package/src/routes/referrals/me.ts +123 -0
  744. package/src/routes/referrals/report.ts +285 -0
  745. package/src/routes/referrals/shared.ts +34 -0
  746. package/src/routes/referrals/touch.ts +313 -0
  747. package/src/routes/tracking/arrive.ts +90 -0
  748. package/src/routes/tracking/click-pipeline.ts +8 -0
  749. package/src/workflows/backfill-contact-id.ts +3 -7
  750. package/src/workflows/bucket-backfill.ts +2 -2
  751. package/src/workflows/bucket-reconcile.ts +28 -12
  752. package/src/workflows/check-alerts.ts +3 -9
  753. package/src/workflows/crm-reconcile.ts +3 -2
  754. package/src/workflows/deliver-webhook.ts +21 -8
  755. package/src/workflows/dispatch-conversion.ts +2 -2
  756. package/src/workflows/identity-alias-backfill.ts +3 -2
  757. package/src/workflows/impact-digest.ts +2 -2
  758. package/src/workflows/import-contacts.ts +3 -4
  759. package/src/workflows/import-suppressions.ts +4 -5
  760. package/src/workflows/send-campaign.ts +10 -1
@@ -0,0 +1,723 @@
1
+ import type { HatchetClient } from "@hatchet-dev/typescript-sdk/v1/index.js";
2
+ import type { AnalyticsProvider, DefinedReferral } from "@hogsend/core";
3
+ import { evaluatePropertyConditions } from "@hogsend/core";
4
+ import type { JourneyRegistry } from "@hogsend/core/registry";
5
+ import {
6
+ attributionCredits,
7
+ contacts,
8
+ type Database,
9
+ referralTouches,
10
+ userEvents,
11
+ } from "@hogsend/db";
12
+ import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm";
13
+ import { getJourneyRegistrySingleton } from "../journeys/registry-singleton.js";
14
+ import { getAnalytics } from "./analytics-singleton.js";
15
+ import { createLogger, type Logger } from "./logger.js";
16
+ import {
17
+ emitOutbound,
18
+ type OutboundPayloads,
19
+ type ReferralTouchPayload,
20
+ } from "./outbound.js";
21
+ import type { ReferralRegistry } from "./referral-registry.js";
22
+ import { getReferralRuntime } from "./referral-runtime.js";
23
+ import {
24
+ bindTouches,
25
+ qualifyTouch,
26
+ type ReferralTouchRecord,
27
+ type ReferralTouchSource,
28
+ recordTouch,
29
+ } from "./referrals.js";
30
+
31
+ /**
32
+ * THE REFERRAL INTENT LAYER (PRD 05 §6, stage 3) - the ONLY module that calls
33
+ * the store's mutators AND emits. The split is the same one
34
+ * `lib/account-links.ts` / `lib/account-link-ingest.ts` draw, for the same
35
+ * reason:
36
+ *
37
+ * - `lib/referrals.ts` (the STORE) writes `referral_touches` and NEVER emits.
38
+ * Two tests pin that (`referrals-no-emit.test.ts`).
39
+ * - THIS module calls the store, reads the returned FACTS, and fans each fact
40
+ * out onto BOTH planes, side by side:
41
+ * • the OUTBOUND spine (`emitOutbound`) → `webhook_deliveries` → the
42
+ * customer's subscriber. Full state, dedupe-keyed.
43
+ * • the JOURNEY plane (`ingestEvent`) → `user_events` + a Hatchet push, so
44
+ * `defineJourney({ trigger: { event: "referral.qualified" } })` fires.
45
+ *
46
+ * NEITHER PLANE MAY BE COLLAPSED INTO THE OTHER. Delete either and the other
47
+ * keeps working silently: an outbound-only build leaves every reward journey
48
+ * dead; an ingest-only build leaves every customer mirror stale.
49
+ *
50
+ * ## Identity law
51
+ *
52
+ * Every re-ingest carries the engine-internal `contactId` PIN. The bare
53
+ * canonical key of a referrer is `contactKey()` - possibly an ANONYMOUS id -
54
+ * and passing that alone would have the resolver read it as `external` and
55
+ * mint `external_id = <anonId>` (the ghost-contact law). The referee side of a
56
+ * COLD touch has no contact at all, which is exactly why `referral.touched` is
57
+ * emitted to the REFERRER only: the referee is a browser id, not a person, and
58
+ * minting a CRM row for them is the very thing PRD 02 forbade.
59
+ *
60
+ * ## Replay / exactly-once
61
+ *
62
+ * Every emit is dedupe-keyed off a durable row id, never a clock:
63
+ * `referral:touch:<touchId>`, `referral:bound:<touchId>`,
64
+ * `referral:qualified:<touchId>`, `referral:conv:<conversionId>:<beneficiary>`.
65
+ * The bus keys append the RECIPIENT contact id, because `user_events`
66
+ * `idempotency_key` is globally unique and a two-sided fact (bound / qualified
67
+ * reaches referrer AND referee) would otherwise deliver to one of them only.
68
+ */
69
+
70
+ const fallbackLogger = createLogger(process.env.LOG_LEVEL);
71
+
72
+ /** The container handles, when the caller has them. */
73
+ export interface ReferralIntentHandles {
74
+ db: Database;
75
+ hatchet?: HatchetClient;
76
+ registry?: JourneyRegistry;
77
+ logger?: Logger;
78
+ analytics?: AnalyticsProvider;
79
+ /** The referral registry; falls back to the process runtime. */
80
+ referrals?: ReferralRegistry;
81
+ }
82
+
83
+ type ReferralEvent =
84
+ | "referral.touched"
85
+ | "referral.bound"
86
+ | "referral.qualified"
87
+ | "referral.converted"
88
+ | "referral.tree_converted"
89
+ | "referral.rejected";
90
+
91
+ /** The identity pin + recipient fields a re-ingest needs. */
92
+ interface ContactPin {
93
+ contactId: string;
94
+ userId: string;
95
+ email: string | null;
96
+ }
97
+
98
+ async function loadPins(
99
+ db: Database,
100
+ ids: string[],
101
+ ): Promise<Map<string, ContactPin>> {
102
+ const unique = [...new Set(ids.filter(Boolean))];
103
+ if (unique.length === 0) return new Map();
104
+ const rows = await db
105
+ .select({
106
+ id: contacts.id,
107
+ externalId: contacts.externalId,
108
+ anonymousId: contacts.anonymousId,
109
+ email: contacts.email,
110
+ })
111
+ .from(contacts)
112
+ .where(inArray(contacts.id, unique));
113
+ return new Map(
114
+ rows.map((row) => [
115
+ row.id,
116
+ {
117
+ contactId: row.id,
118
+ userId: row.externalId ?? row.anonymousId ?? row.id,
119
+ email: row.email,
120
+ },
121
+ ]),
122
+ );
123
+ }
124
+
125
+ /**
126
+ * Fan ONE fact onto BOTH planes for ONE recipient. Fire-and-forget with an
127
+ * attributed catch: a referral is a side effect of something the visitor
128
+ * already did (a click, an identify, a purchase), so a Hatchet hiccup must
129
+ * never fail that.
130
+ */
131
+ function emitBoth<E extends ReferralEvent>(opts: {
132
+ handles: ReferralIntentHandles;
133
+ event: E;
134
+ /** The contact this copy of the fact is FOR (the bus subject). */
135
+ recipient: ContactPin | undefined;
136
+ /**
137
+ * The catalogued payload, which doubles VERBATIM as the journey-bus
138
+ * `eventProperties` - hence the scalar intersection. `ingestEvent` filters
139
+ * the Hatchet push down to scalars, so a nested field here would vanish
140
+ * between `user_events` and the journey it was meant to steer.
141
+ */
142
+ payload: OutboundPayloads[E] &
143
+ Record<string, string | number | boolean | null>;
144
+ dedupeKey: string;
145
+ }): void {
146
+ const { handles, event, recipient, payload, dedupeKey } = opts;
147
+ const runtime = getReferralRuntime();
148
+ const logger = handles.logger ?? runtime?.logger ?? fallbackLogger;
149
+ const db = handles.db;
150
+
151
+ void (async () => {
152
+ // Prefer the CONTAINER's handles (passed, or held on the runtime) over the
153
+ // module singletons: importing `./hatchet.js` runs `HatchetClient.init`,
154
+ // which throws where no real token exists.
155
+ const hatchet =
156
+ handles.hatchet ??
157
+ runtime?.hatchet ??
158
+ (await import("./hatchet.js")).hatchet;
159
+ await emitOutbound({
160
+ db,
161
+ hatchet,
162
+ logger,
163
+ event,
164
+ payload,
165
+ dedupeKey,
166
+ });
167
+ if (!recipient) return;
168
+ // Dynamic import for the same two reasons `account-link-ingest.ts` gives:
169
+ // `lib/contacts.ts` reaches this module (the bind), and `lib/ingestion.ts`
170
+ // reaches `lib/contacts.ts`, so a static import is a module cycle; and
171
+ // importing `./hatchet.js` eagerly runs `HatchetClient.init`.
172
+ const { ingestEvent } = await import("./ingestion.js");
173
+ const analytics = handles.analytics ?? runtime?.analytics ?? getAnalytics();
174
+ await ingestEvent({
175
+ db,
176
+ registry:
177
+ handles.registry ?? runtime?.registry ?? getJourneyRegistrySingleton(),
178
+ hatchet,
179
+ logger,
180
+ ...(analytics ? { analytics } : {}),
181
+ event: {
182
+ event,
183
+ // The value key only has to EXIST (the resolver requires one); the pin
184
+ // beside it decides the row and can never mint.
185
+ userId: recipient.userId,
186
+ contactId: recipient.contactId,
187
+ ...(recipient.email ? { userEmail: recipient.email } : {}),
188
+ eventProperties: payload,
189
+ source: "referral",
190
+ idempotencyKey: `${dedupeKey}:${recipient.contactId}`,
191
+ },
192
+ });
193
+ })().catch((error: unknown) => {
194
+ logger.error("referral fact emit failed", {
195
+ event,
196
+ dedupeKey,
197
+ error: error instanceof Error ? error.message : String(error),
198
+ });
199
+ });
200
+ }
201
+
202
+ /** Scalar-only payload for a touch-shaped fact. */
203
+ function touchPayload(touch: ReferralTouchRecord): ReferralTouchPayload {
204
+ return {
205
+ referralId: touch.referralId,
206
+ touchId: touch.id,
207
+ referrerContactId: touch.referrerContactId,
208
+ refereeContactId: touch.refereeContactId,
209
+ refereeKey: touch.refereeKey,
210
+ source: touch.source,
211
+ linkId: touch.linkId,
212
+ clickId: touch.clickId,
213
+ status: touch.status,
214
+ touchedAt: touch.touchedAt.toISOString(),
215
+ };
216
+ }
217
+
218
+ // ---------------------------------------------------------------------------
219
+ // touch
220
+ // ---------------------------------------------------------------------------
221
+
222
+ export interface TouchReferralInput extends ReferralIntentHandles {
223
+ referral: DefinedReferral;
224
+ referrerContactId: string;
225
+ /** The toucher's canonical key - an ANONYMOUS id on a cold touch. */
226
+ refereeKey: string;
227
+ /** Set only when the toucher is already a known person. */
228
+ refereeContactId?: string | null;
229
+ linkId?: string | null;
230
+ clickId?: string | null;
231
+ source: ReferralTouchSource;
232
+ properties?: Record<string, unknown>;
233
+ idempotencyKey?: string;
234
+ }
235
+
236
+ export interface TouchReferralResult {
237
+ touch: ReferralTouchRecord | null;
238
+ created: boolean;
239
+ rejected: boolean;
240
+ }
241
+
242
+ /**
243
+ * Record a referral touch and announce it. `referral.touched` goes to the
244
+ * REFERRER only (see the identity note in the module header).
245
+ */
246
+ export async function touchReferral(
247
+ input: TouchReferralInput,
248
+ ): Promise<TouchReferralResult> {
249
+ const { referral, db } = input;
250
+ const result = await recordTouch({
251
+ db,
252
+ referral,
253
+ referralId: referral.id,
254
+ referrerContactId: input.referrerContactId,
255
+ refereeKey: input.refereeKey,
256
+ refereeContactId: input.refereeContactId ?? null,
257
+ linkId: input.linkId ?? null,
258
+ clickId: input.clickId ?? null,
259
+ source: input.source,
260
+ ...(input.properties ? { properties: input.properties } : {}),
261
+ ...(input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {}),
262
+ });
263
+
264
+ // Only a FRESH write is news. A replayed click / same-pair re-touch recovered
265
+ // an existing row and announcing it again would re-fire the reward journey.
266
+ if (!result.created) {
267
+ return { touch: result.touch, created: false, rejected: result.rejected };
268
+ }
269
+
270
+ const pins = await loadPins(db, [
271
+ result.touch.referrerContactId,
272
+ ...(result.touch.refereeContactId ? [result.touch.refereeContactId] : []),
273
+ ]);
274
+ const referrer = pins.get(result.touch.referrerContactId);
275
+
276
+ if (result.rejected) {
277
+ emitBoth({
278
+ handles: input,
279
+ event: "referral.rejected",
280
+ recipient: referrer,
281
+ payload: {
282
+ ...touchPayload(result.touch),
283
+ reason: result.touch.rejectedReason,
284
+ },
285
+ dedupeKey: `referral:rejected:${result.touch.id}`,
286
+ });
287
+ return { touch: result.touch, created: true, rejected: true };
288
+ }
289
+
290
+ emitBoth({
291
+ handles: input,
292
+ event: "referral.touched",
293
+ recipient: referrer,
294
+ payload: touchPayload(result.touch),
295
+ dedupeKey: `referral:touch:${result.touch.id}`,
296
+ });
297
+
298
+ // An already-identified toucher binds at the same instant, so the bind fact
299
+ // is due now: a reward journey listens on `referral.bound`, and only the
300
+ // COLD path reaches `bindReferral` later.
301
+ if (result.touch.status === "bound" && result.touch.refereeContactId) {
302
+ announceBound(input, result.touch, pins);
303
+ // Same law as the cold path in `bindReferral`: a referral with NO qualify
304
+ // config is EARNED at bind. Without this an identified toucher (token
305
+ // arrival, invite, manual) would sit at `bound` forever and no reward
306
+ // journey would ever see `referral.qualified`.
307
+ if (!referral.meta.qualify) {
308
+ await qualifyReferral({ ...input, touch: result.touch, referral });
309
+ }
310
+ }
311
+
312
+ return { touch: result.touch, created: true, rejected: false };
313
+ }
314
+
315
+ // ---------------------------------------------------------------------------
316
+ // bind
317
+ // ---------------------------------------------------------------------------
318
+
319
+ export interface BindReferralInput extends ReferralIntentHandles {
320
+ /** The anonymous/canonical key the visitor touched under. */
321
+ refereeKey: string;
322
+ /** The contact that key just resolved to. */
323
+ contactId: string;
324
+ }
325
+
326
+ /**
327
+ * Bind every unbound touch for a key at identity-adoption time, and announce
328
+ * each outcome. Called POST-COMMIT from `resolveContactShared` - never inside
329
+ * the resolver's transaction, because this emits and a rolled-back merge must
330
+ * never have announced a bind that never happened.
331
+ */
332
+ export async function bindReferral(input: BindReferralInput): Promise<void> {
333
+ const referrals = resolveRegistry(input);
334
+ if (!referrals || referrals.count() === 0) return;
335
+
336
+ const result = await bindTouches({
337
+ db: input.db,
338
+ refereeKey: input.refereeKey,
339
+ contactId: input.contactId,
340
+ resolveReferral: (id) => referrals.get(id),
341
+ });
342
+ if (result.bound.length === 0 && result.rejected.length === 0) return;
343
+
344
+ const pins = await loadPins(input.db, [
345
+ input.contactId,
346
+ ...result.bound.map((t) => t.referrerContactId),
347
+ ...result.rejected.map((r) => r.touch.referrerContactId),
348
+ ]);
349
+
350
+ for (const touch of result.bound) {
351
+ announceBound(input, touch, pins);
352
+ // A referral with NO qualify config is EARNED at bind: the referee is a
353
+ // known person, which is all the program asked for. Without this the touch
354
+ // would sit at `bound` forever and no reward journey would ever fire.
355
+ const referral = referrals.get(touch.referralId);
356
+ if (referral && !referral.meta.qualify) {
357
+ await qualifyReferral({ ...input, touch, referral });
358
+ }
359
+ }
360
+
361
+ for (const { touch, reason, detail } of result.rejected) {
362
+ emitBoth({
363
+ handles: input,
364
+ event: "referral.rejected",
365
+ recipient: pins.get(touch.referrerContactId),
366
+ payload: {
367
+ ...touchPayload(touch),
368
+ reason,
369
+ detail: detail ?? null,
370
+ },
371
+ dedupeKey: `referral:rejected:${touch.id}`,
372
+ });
373
+ }
374
+ }
375
+
376
+ /** `referral.bound` reaches BOTH ends - the referrer and the referee. */
377
+ function announceBound(
378
+ handles: ReferralIntentHandles,
379
+ touch: ReferralTouchRecord,
380
+ pins: Map<string, ContactPin>,
381
+ ): void {
382
+ const payload = {
383
+ ...touchPayload(touch),
384
+ boundAt: touch.boundAt?.toISOString() ?? new Date().toISOString(),
385
+ };
386
+ emitBoth({
387
+ handles,
388
+ event: "referral.bound",
389
+ recipient: pins.get(touch.referrerContactId),
390
+ payload: { ...payload, side: "referrer" },
391
+ dedupeKey: `referral:bound:${touch.id}`,
392
+ });
393
+ if (touch.refereeContactId) {
394
+ emitBoth({
395
+ handles,
396
+ event: "referral.bound",
397
+ recipient: pins.get(touch.refereeContactId),
398
+ payload: { ...payload, side: "referee" },
399
+ // SAME outbound dedupe key: the customer's subscriber gets ONE delivery
400
+ // of the fact (the payload is the same edge). The bus keys differ only
401
+ // because `emitBoth` appends the recipient id.
402
+ dedupeKey: `referral:bound:${touch.id}`,
403
+ });
404
+ }
405
+ }
406
+
407
+ // ---------------------------------------------------------------------------
408
+ // qualify
409
+ // ---------------------------------------------------------------------------
410
+
411
+ export interface QualifyReferralInput extends ReferralIntentHandles {
412
+ touch: ReferralTouchRecord;
413
+ referral?: DefinedReferral;
414
+ event?: string;
415
+ eventProperties?: Record<string, unknown>;
416
+ conversionId?: string | null;
417
+ }
418
+
419
+ /**
420
+ * Promote a BOUND touch to qualified and announce it to BOTH ends. The store's
421
+ * `qualified_at IS NULL` predicate is the exactly-once guard, so a redelivered
422
+ * qualify event returns `existing` and emits nothing.
423
+ */
424
+ export async function qualifyReferral(
425
+ input: QualifyReferralInput,
426
+ ): Promise<void> {
427
+ const result = await qualifyTouch({
428
+ db: input.db,
429
+ touchId: input.touch.id,
430
+ ...(input.referral ? { referral: input.referral } : {}),
431
+ ...(input.event ? { event: input.event } : {}),
432
+ ...(input.eventProperties
433
+ ? { eventProperties: input.eventProperties }
434
+ : {}),
435
+ ...(input.conversionId ? { conversionId: input.conversionId } : {}),
436
+ });
437
+ const touch = result.touch;
438
+ if (!touch) return;
439
+
440
+ const pins = await loadPins(input.db, [
441
+ touch.referrerContactId,
442
+ ...(touch.refereeContactId ? [touch.refereeContactId] : []),
443
+ ]);
444
+
445
+ if (result.rejected) {
446
+ emitBoth({
447
+ handles: input,
448
+ event: "referral.rejected",
449
+ recipient: pins.get(touch.referrerContactId),
450
+ payload: {
451
+ ...touchPayload(touch),
452
+ reason: touch.rejectedReason,
453
+ detail: result.reason ?? null,
454
+ },
455
+ dedupeKey: `referral:rejected:${touch.id}`,
456
+ });
457
+ return;
458
+ }
459
+ if (!result.qualified) return;
460
+
461
+ const payload = {
462
+ ...touchPayload(touch),
463
+ event: input.event ?? null,
464
+ conversionId: touch.qualifiedConversionId,
465
+ qualifiedAt: touch.qualifiedAt?.toISOString() ?? new Date().toISOString(),
466
+ };
467
+ emitBoth({
468
+ handles: input,
469
+ event: "referral.qualified",
470
+ recipient: pins.get(touch.referrerContactId),
471
+ payload: { ...payload, side: "referrer" },
472
+ dedupeKey: `referral:qualified:${touch.id}`,
473
+ });
474
+ if (touch.refereeContactId) {
475
+ emitBoth({
476
+ handles: input,
477
+ event: "referral.qualified",
478
+ recipient: pins.get(touch.refereeContactId),
479
+ payload: { ...payload, side: "referee" },
480
+ dedupeKey: `referral:qualified:${touch.id}`,
481
+ });
482
+ }
483
+ }
484
+
485
+ /**
486
+ * The `ingestEvent` hook: does THIS event qualify any of this contact's bound
487
+ * touches? Cheap on a miss - one map lookup on the registry - so it is safe to
488
+ * call on every ingested event.
489
+ */
490
+ export async function qualifyReferralsForEvent(opts: {
491
+ handles: ReferralIntentHandles;
492
+ event: string;
493
+ eventProperties: Record<string, unknown>;
494
+ contactId: string;
495
+ }): Promise<void> {
496
+ const referrals = resolveRegistry(opts.handles);
497
+ const watching = referrals?.byQualifyEvent(opts.event) ?? [];
498
+ if (watching.length === 0) return;
499
+
500
+ const rows = await opts.handles.db
501
+ .select()
502
+ .from(referralTouches)
503
+ .where(
504
+ and(
505
+ eq(referralTouches.refereeContactId, opts.contactId),
506
+ eq(referralTouches.status, "bound"),
507
+ isNull(referralTouches.qualifiedAt),
508
+ inArray(
509
+ referralTouches.referralId,
510
+ watching.map((r) => r.id),
511
+ ),
512
+ ),
513
+ )
514
+ .orderBy(asc(referralTouches.touchedAt));
515
+
516
+ for (const row of rows) {
517
+ const referral = watching.find((r) => r.id === row.referralId);
518
+ if (!referral) continue;
519
+ // The `where` on `qualify` is the SAME builder journeys use for
520
+ // `trigger.where`, normalized once at `defineReferral` time - so "first
521
+ // paid invoice over 10" needs no custom veto hook.
522
+ if (
523
+ referral.qualifyWhere &&
524
+ !evaluatePropertyConditions({
525
+ conditions: referral.qualifyWhere,
526
+ properties: opts.eventProperties,
527
+ })
528
+ ) {
529
+ continue;
530
+ }
531
+ await qualifyReferral({
532
+ ...opts.handles,
533
+ touch: toTouchRecord(row),
534
+ referral,
535
+ event: opts.event,
536
+ eventProperties: opts.eventProperties,
537
+ });
538
+ }
539
+ }
540
+
541
+ // ---------------------------------------------------------------------------
542
+ // convert
543
+ // ---------------------------------------------------------------------------
544
+
545
+ /** How far up the tree a conversion is announced. Hard cap (PRD 05 §5.3). */
546
+ export const REFERRAL_TREE_MAX_DEPTH = 5;
547
+
548
+ export interface ConvertReferralInput extends ReferralIntentHandles {
549
+ /** The contact who converted - the REFEREE at level 1. */
550
+ contactId: string;
551
+ conversionId: string;
552
+ value: number | null;
553
+ currency: string | null;
554
+ occurredAt: Date;
555
+ }
556
+
557
+ /**
558
+ * Announce a conversion up the referral tree: `referral.converted` to the
559
+ * DIRECT referrer, `referral.tree_converted` to each ancestor above them, to
560
+ * {@link REFERRAL_TREE_MAX_DEPTH}.
561
+ *
562
+ * `level` is a FACT on the event, never program config - a reward journey
563
+ * filters with `trigger.where: (b) => b.prop("level").eq(1)`. That is the only
564
+ * place levels appear in code, which is what keeps depth and weights
565
+ * report-time parameters.
566
+ */
567
+ export async function convertReferral(
568
+ input: ConvertReferralInput,
569
+ ): Promise<void> {
570
+ const referrals = resolveRegistry(input);
571
+ if (!referrals || referrals.count() === 0) return;
572
+
573
+ const first = await firstBoundTouch(input.db, input.contactId);
574
+ if (!first) return;
575
+
576
+ // Best-effort ledger stamp: tie the credits earned by this touch's own
577
+ // click/arrive touchpoint to the edge, so `attribution_credits` and the
578
+ // referral tree reconcile. Nothing downstream depends on it, so a miss is
579
+ // silent (the touchpoint may predate the ledger window, or the conversion
580
+ // may have no touchpoint rows at all).
581
+ await stampAttributionCredits(input, first).catch((err: unknown) => {
582
+ (input.logger ?? fallbackLogger).warn("referral attribution stamp failed", {
583
+ error: err instanceof Error ? err.message : String(err),
584
+ });
585
+ });
586
+
587
+ // Walk UP: level 1 is the referee's direct referrer, level 2 that person's
588
+ // referrer, and so on. `visited` is the cycle guard - A referred B referred A
589
+ // is legal data (two edges, both valid) and would otherwise loop forever.
590
+ const visited = new Set<string>([input.contactId]);
591
+ let via = input.contactId;
592
+ let touch: ReferralTouchRecord | null = first;
593
+ const pinIds: string[] = [input.contactId];
594
+
595
+ const hops: Array<{
596
+ level: number;
597
+ beneficiary: string;
598
+ via: string;
599
+ touch: ReferralTouchRecord;
600
+ }> = [];
601
+ for (let level = 1; level <= REFERRAL_TREE_MAX_DEPTH && touch; level++) {
602
+ const beneficiary = touch.referrerContactId;
603
+ if (visited.has(beneficiary)) break;
604
+ visited.add(beneficiary);
605
+ hops.push({ level, beneficiary, via, touch });
606
+ pinIds.push(beneficiary);
607
+ via = beneficiary;
608
+ touch = await firstBoundTouch(input.db, beneficiary);
609
+ }
610
+ if (hops.length === 0) return;
611
+
612
+ const pins = await loadPins(input.db, pinIds);
613
+ for (const hop of hops) {
614
+ emitBoth({
615
+ handles: input,
616
+ event: hop.level === 1 ? "referral.converted" : "referral.tree_converted",
617
+ recipient: pins.get(hop.beneficiary),
618
+ payload: {
619
+ referralId: hop.touch.referralId,
620
+ touchId: hop.touch.id,
621
+ level: hop.level,
622
+ beneficiaryContactId: hop.beneficiary,
623
+ refereeContactId: input.contactId,
624
+ // The NEXT hop toward the referee, so a journey can name "your
625
+ // friend's friend" without walking the tree itself.
626
+ viaContactId: hop.via,
627
+ conversionId: input.conversionId,
628
+ // NOT `value` - see `ReferralConversionPayload.conversionValue`.
629
+ conversionValue: input.value,
630
+ currency: input.currency,
631
+ at: input.occurredAt.toISOString(),
632
+ },
633
+ dedupeKey: `referral:conv:${input.conversionId}:${hop.beneficiary}`,
634
+ });
635
+ }
636
+ }
637
+
638
+ /**
639
+ * The FIRST bound touch for a referee, by `touched_at`. First-touch is the pin
640
+ * for the tree walk on purpose: the walk must be STABLE (a later touch would
641
+ * silently re-parent an ancestor chain already announced), while the report
642
+ * picks its own model over the full edge log at query time.
643
+ */
644
+ async function firstBoundTouch(
645
+ db: Database,
646
+ contactId: string,
647
+ ): Promise<ReferralTouchRecord | null> {
648
+ const [row] = await db
649
+ .select()
650
+ .from(referralTouches)
651
+ .where(
652
+ and(
653
+ eq(referralTouches.refereeContactId, contactId),
654
+ inArray(referralTouches.status, ["bound", "qualified"]),
655
+ ),
656
+ )
657
+ .orderBy(asc(referralTouches.touchedAt))
658
+ .limit(1);
659
+ return row ? toTouchRecord(row) : null;
660
+ }
661
+
662
+ /**
663
+ * Stamp `attribution_credits.referral_touch_id` on the rows this conversion
664
+ * produced whose touchpoint IS this touch's click/arrive event, so
665
+ * `WHERE channel = 'referral'` reconciles with the tree.
666
+ */
667
+ async function stampAttributionCredits(
668
+ input: ConvertReferralInput,
669
+ touch: ReferralTouchRecord,
670
+ ): Promise<void> {
671
+ if (!touch.clickId) return;
672
+ await input.db
673
+ .update(attributionCredits)
674
+ .set({ referralTouchId: touch.id })
675
+ .where(
676
+ and(
677
+ eq(attributionCredits.conversionId, input.conversionId),
678
+ isNull(attributionCredits.referralTouchId),
679
+ inArray(
680
+ attributionCredits.touchpointEventId,
681
+ input.db
682
+ .select({ id: userEvents.id })
683
+ .from(userEvents)
684
+ .where(
685
+ sql`${userEvents.properties}->>'ref' = ${touch.clickId} or ${userEvents.properties}->>'clickId' = ${touch.clickId}`,
686
+ ),
687
+ ),
688
+ ),
689
+ );
690
+ }
691
+
692
+ // ---------------------------------------------------------------------------
693
+ // shared
694
+ // ---------------------------------------------------------------------------
695
+
696
+ function resolveRegistry(
697
+ handles: ReferralIntentHandles,
698
+ ): ReferralRegistry | undefined {
699
+ return handles.referrals ?? getReferralRuntime()?.referrals;
700
+ }
701
+
702
+ /** `referral_touches` row → the store's record shape. */
703
+ function toTouchRecord(
704
+ row: typeof referralTouches.$inferSelect,
705
+ ): ReferralTouchRecord {
706
+ return {
707
+ id: row.id,
708
+ referralId: row.referralId,
709
+ referrerContactId: row.referrerContactId,
710
+ refereeKey: row.refereeKey,
711
+ refereeContactId: row.refereeContactId,
712
+ linkId: row.linkId,
713
+ clickId: row.clickId,
714
+ source: row.source,
715
+ touchedAt: row.touchedAt,
716
+ boundAt: row.boundAt,
717
+ status: row.status as ReferralTouchRecord["status"],
718
+ rejectedReason: row.rejectedReason as ReferralTouchRecord["rejectedReason"],
719
+ qualifiedAt: row.qualifiedAt,
720
+ qualifiedConversionId: row.qualifiedConversionId,
721
+ properties: (row.properties ?? {}) as Record<string, unknown>,
722
+ };
723
+ }