sendwend 0.0.1 → 12.7.3

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 (684) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +2065 -22
  3. package/dist/_virtual/_rolldown/runtime.cjs +22 -0
  4. package/dist/apns-relay.cjs +91 -0
  5. package/dist/apns-relay.cjs.map +1 -0
  6. package/dist/apns-relay.d.cts +26 -0
  7. package/dist/apns-relay.d.cts.map +1 -0
  8. package/dist/apns-relay.d.mts +26 -0
  9. package/dist/apns-relay.d.mts.map +1 -0
  10. package/dist/apns-relay.mjs +90 -0
  11. package/dist/apns-relay.mjs.map +1 -0
  12. package/dist/apns.cjs +215 -0
  13. package/dist/apns.cjs.map +1 -0
  14. package/dist/apns.d.cts +110 -0
  15. package/dist/apns.d.cts.map +1 -0
  16. package/dist/apns.d.mts +110 -0
  17. package/dist/apns.d.mts.map +1 -0
  18. package/dist/apns.mjs +207 -0
  19. package/dist/apns.mjs.map +1 -0
  20. package/dist/aws/engine-step.cjs +105 -0
  21. package/dist/aws/engine-step.cjs.map +1 -0
  22. package/dist/aws/engine-step.d.cts +42 -0
  23. package/dist/aws/engine-step.d.cts.map +1 -0
  24. package/dist/aws/engine-step.d.mts +42 -0
  25. package/dist/aws/engine-step.d.mts.map +1 -0
  26. package/dist/aws/engine-step.mjs +103 -0
  27. package/dist/aws/engine-step.mjs.map +1 -0
  28. package/dist/aws/function-url.cjs +53 -0
  29. package/dist/aws/function-url.cjs.map +1 -0
  30. package/dist/aws/function-url.d.cts +36 -0
  31. package/dist/aws/function-url.d.cts.map +1 -0
  32. package/dist/aws/function-url.d.mts +36 -0
  33. package/dist/aws/function-url.d.mts.map +1 -0
  34. package/dist/aws/function-url.mjs +50 -0
  35. package/dist/aws/function-url.mjs.map +1 -0
  36. package/dist/aws/index.cjs +232 -0
  37. package/dist/aws/index.cjs.map +1 -0
  38. package/dist/aws/index.d.cts +73 -0
  39. package/dist/aws/index.d.cts.map +1 -0
  40. package/dist/aws/index.d.mts +73 -0
  41. package/dist/aws/index.d.mts.map +1 -0
  42. package/dist/aws/index.mjs +218 -0
  43. package/dist/aws/index.mjs.map +1 -0
  44. package/dist/aws/instances.cjs +218 -0
  45. package/dist/aws/instances.cjs.map +1 -0
  46. package/dist/aws/instances.d.cts +102 -0
  47. package/dist/aws/instances.d.cts.map +1 -0
  48. package/dist/aws/instances.d.mts +102 -0
  49. package/dist/aws/instances.d.mts.map +1 -0
  50. package/dist/aws/instances.mjs +214 -0
  51. package/dist/aws/instances.mjs.map +1 -0
  52. package/dist/aws/lambda-api.cjs +86 -0
  53. package/dist/aws/lambda-api.cjs.map +1 -0
  54. package/dist/aws/lambda-api.d.cts +41 -0
  55. package/dist/aws/lambda-api.d.cts.map +1 -0
  56. package/dist/aws/lambda-api.d.mts +41 -0
  57. package/dist/aws/lambda-api.d.mts.map +1 -0
  58. package/dist/aws/lambda-api.mjs +85 -0
  59. package/dist/aws/lambda-api.mjs.map +1 -0
  60. package/dist/client.cjs +216 -0
  61. package/dist/client.cjs.map +1 -0
  62. package/dist/client.d.cts +193 -0
  63. package/dist/client.d.cts.map +1 -0
  64. package/dist/client.d.mts +193 -0
  65. package/dist/client.d.mts.map +1 -0
  66. package/dist/client.mjs +212 -0
  67. package/dist/client.mjs.map +1 -0
  68. package/dist/cloudflare/bindings.cjs +49 -0
  69. package/dist/cloudflare/bindings.cjs.map +1 -0
  70. package/dist/cloudflare/bindings.d.cts +31 -0
  71. package/dist/cloudflare/bindings.d.cts.map +1 -0
  72. package/dist/cloudflare/bindings.d.mts +31 -0
  73. package/dist/cloudflare/bindings.d.mts.map +1 -0
  74. package/dist/cloudflare/bindings.mjs +46 -0
  75. package/dist/cloudflare/bindings.mjs.map +1 -0
  76. package/dist/cloudflare/index.cjs +73 -0
  77. package/dist/cloudflare/index.d.cts +25 -0
  78. package/dist/cloudflare/index.d.mts +25 -0
  79. package/dist/cloudflare/index.mjs +20 -0
  80. package/dist/cloudflare/runner.cjs +200 -0
  81. package/dist/cloudflare/runner.cjs.map +1 -0
  82. package/dist/cloudflare/runner.d.cts +83 -0
  83. package/dist/cloudflare/runner.d.cts.map +1 -0
  84. package/dist/cloudflare/runner.d.mts +83 -0
  85. package/dist/cloudflare/runner.d.mts.map +1 -0
  86. package/dist/cloudflare/runner.mjs +199 -0
  87. package/dist/cloudflare/runner.mjs.map +1 -0
  88. package/dist/cloudflare/worker.cjs +106 -0
  89. package/dist/cloudflare/worker.cjs.map +1 -0
  90. package/dist/cloudflare/worker.d.cts +52 -0
  91. package/dist/cloudflare/worker.d.cts.map +1 -0
  92. package/dist/cloudflare/worker.d.mts +52 -0
  93. package/dist/cloudflare/worker.d.mts.map +1 -0
  94. package/dist/cloudflare/worker.mjs +104 -0
  95. package/dist/cloudflare/worker.mjs.map +1 -0
  96. package/dist/cloudflare/workers.d.cjs +0 -0
  97. package/dist/cloudflare/workers.d.cts +42 -0
  98. package/dist/cloudflare/workers.d.cts.map +1 -0
  99. package/dist/cloudflare/workers.d.mts +42 -0
  100. package/dist/cloudflare/workers.d.mts.map +1 -0
  101. package/dist/config.cjs +257 -0
  102. package/dist/config.cjs.map +1 -0
  103. package/dist/config.d.cts +184 -0
  104. package/dist/config.d.cts.map +1 -0
  105. package/dist/config.d.mts +184 -0
  106. package/dist/config.d.mts.map +1 -0
  107. package/dist/config.mjs +246 -0
  108. package/dist/config.mjs.map +1 -0
  109. package/dist/contract.cjs +222 -0
  110. package/dist/contract.cjs.map +1 -0
  111. package/dist/contract.d.cts +110 -0
  112. package/dist/contract.d.cts.map +1 -0
  113. package/dist/contract.d.mts +110 -0
  114. package/dist/contract.d.mts.map +1 -0
  115. package/dist/contract.mjs +216 -0
  116. package/dist/contract.mjs.map +1 -0
  117. package/dist/date-time.cjs +22 -0
  118. package/dist/date-time.cjs.map +1 -0
  119. package/dist/date-time.d.cts +10 -0
  120. package/dist/date-time.d.cts.map +1 -0
  121. package/dist/date-time.d.mts +10 -0
  122. package/dist/date-time.d.mts.map +1 -0
  123. package/dist/date-time.mjs +21 -0
  124. package/dist/date-time.mjs.map +1 -0
  125. package/dist/dsl/action.cjs +25 -0
  126. package/dist/dsl/action.cjs.map +1 -0
  127. package/dist/dsl/action.d.cts +63 -0
  128. package/dist/dsl/action.d.cts.map +1 -0
  129. package/dist/dsl/action.d.mts +63 -0
  130. package/dist/dsl/action.d.mts.map +1 -0
  131. package/dist/dsl/action.mjs +24 -0
  132. package/dist/dsl/action.mjs.map +1 -0
  133. package/dist/dsl/base.cjs +33 -0
  134. package/dist/dsl/base.cjs.map +1 -0
  135. package/dist/dsl/base.d.cts +43 -0
  136. package/dist/dsl/base.d.cts.map +1 -0
  137. package/dist/dsl/base.d.mts +43 -0
  138. package/dist/dsl/base.d.mts.map +1 -0
  139. package/dist/dsl/base.mjs +29 -0
  140. package/dist/dsl/base.mjs.map +1 -0
  141. package/dist/dsl/bundle.cjs +287 -0
  142. package/dist/dsl/bundle.cjs.map +1 -0
  143. package/dist/dsl/bundle.d.cts +33 -0
  144. package/dist/dsl/bundle.d.cts.map +1 -0
  145. package/dist/dsl/bundle.d.mts +33 -0
  146. package/dist/dsl/bundle.d.mts.map +1 -0
  147. package/dist/dsl/bundle.mjs +284 -0
  148. package/dist/dsl/bundle.mjs.map +1 -0
  149. package/dist/dsl/condition.cjs +200 -0
  150. package/dist/dsl/condition.cjs.map +1 -0
  151. package/dist/dsl/condition.d.cts +151 -0
  152. package/dist/dsl/condition.d.cts.map +1 -0
  153. package/dist/dsl/condition.d.mts +151 -0
  154. package/dist/dsl/condition.d.mts.map +1 -0
  155. package/dist/dsl/condition.mjs +178 -0
  156. package/dist/dsl/condition.mjs.map +1 -0
  157. package/dist/dsl/flow.cjs +335 -0
  158. package/dist/dsl/flow.cjs.map +1 -0
  159. package/dist/dsl/flow.d.cts +278 -0
  160. package/dist/dsl/flow.d.cts.map +1 -0
  161. package/dist/dsl/flow.d.mts +278 -0
  162. package/dist/dsl/flow.d.mts.map +1 -0
  163. package/dist/dsl/flow.mjs +331 -0
  164. package/dist/dsl/flow.mjs.map +1 -0
  165. package/dist/dsl/index.cjs +37 -0
  166. package/dist/dsl/index.d.cts +34 -0
  167. package/dist/dsl/index.d.mts +34 -0
  168. package/dist/dsl/index.mjs +9 -0
  169. package/dist/dsl/refs.cjs +101 -0
  170. package/dist/dsl/refs.cjs.map +1 -0
  171. package/dist/dsl/refs.d.cts +127 -0
  172. package/dist/dsl/refs.d.cts.map +1 -0
  173. package/dist/dsl/refs.d.mts +127 -0
  174. package/dist/dsl/refs.d.mts.map +1 -0
  175. package/dist/dsl/refs.mjs +93 -0
  176. package/dist/dsl/refs.mjs.map +1 -0
  177. package/dist/dsl/template.cjs +19 -0
  178. package/dist/dsl/template.cjs.map +1 -0
  179. package/dist/dsl/template.d.cts +30 -0
  180. package/dist/dsl/template.d.cts.map +1 -0
  181. package/dist/dsl/template.d.mts +30 -0
  182. package/dist/dsl/template.d.mts.map +1 -0
  183. package/dist/dsl/template.mjs +18 -0
  184. package/dist/dsl/template.mjs.map +1 -0
  185. package/dist/dsl/trigger.cjs +53 -0
  186. package/dist/dsl/trigger.cjs.map +1 -0
  187. package/dist/dsl/trigger.d.cts +112 -0
  188. package/dist/dsl/trigger.d.cts.map +1 -0
  189. package/dist/dsl/trigger.d.mts +112 -0
  190. package/dist/dsl/trigger.d.mts.map +1 -0
  191. package/dist/dsl/trigger.mjs +52 -0
  192. package/dist/dsl/trigger.mjs.map +1 -0
  193. package/dist/dsl/workflow.cjs +143 -0
  194. package/dist/dsl/workflow.cjs.map +1 -0
  195. package/dist/dsl/workflow.d.cts +88 -0
  196. package/dist/dsl/workflow.d.cts.map +1 -0
  197. package/dist/dsl/workflow.d.mts +88 -0
  198. package/dist/dsl/workflow.d.mts.map +1 -0
  199. package/dist/dsl/workflow.mjs +142 -0
  200. package/dist/dsl/workflow.mjs.map +1 -0
  201. package/dist/email-context.cjs +28 -0
  202. package/dist/email-context.cjs.map +1 -0
  203. package/dist/email-context.d.cts +9 -0
  204. package/dist/email-context.d.cts.map +1 -0
  205. package/dist/email-context.d.mts +9 -0
  206. package/dist/email-context.d.mts.map +1 -0
  207. package/dist/email-context.mjs +26 -0
  208. package/dist/email-context.mjs.map +1 -0
  209. package/dist/email-sender.cjs +93 -0
  210. package/dist/email-sender.cjs.map +1 -0
  211. package/dist/email-sender.d.cts +88 -0
  212. package/dist/email-sender.d.cts.map +1 -0
  213. package/dist/email-sender.d.mts +88 -0
  214. package/dist/email-sender.d.mts.map +1 -0
  215. package/dist/email-sender.mjs +90 -0
  216. package/dist/email-sender.mjs.map +1 -0
  217. package/dist/email.cjs +73 -0
  218. package/dist/email.cjs.map +1 -0
  219. package/dist/email.d.cts +59 -0
  220. package/dist/email.d.cts.map +1 -0
  221. package/dist/email.d.mts +59 -0
  222. package/dist/email.d.mts.map +1 -0
  223. package/dist/email.mjs +68 -0
  224. package/dist/email.mjs.map +1 -0
  225. package/dist/engine/actions.cjs +19 -0
  226. package/dist/engine/actions.cjs.map +1 -0
  227. package/dist/engine/actions.d.cts +27 -0
  228. package/dist/engine/actions.d.cts.map +1 -0
  229. package/dist/engine/actions.d.mts +27 -0
  230. package/dist/engine/actions.d.mts.map +1 -0
  231. package/dist/engine/actions.mjs +18 -0
  232. package/dist/engine/actions.mjs.map +1 -0
  233. package/dist/engine/bucket.cjs +71 -0
  234. package/dist/engine/bucket.cjs.map +1 -0
  235. package/dist/engine/bucket.d.cts +30 -0
  236. package/dist/engine/bucket.d.cts.map +1 -0
  237. package/dist/engine/bucket.d.mts +30 -0
  238. package/dist/engine/bucket.d.mts.map +1 -0
  239. package/dist/engine/bucket.mjs +68 -0
  240. package/dist/engine/bucket.mjs.map +1 -0
  241. package/dist/engine/condition.cjs +199 -0
  242. package/dist/engine/condition.cjs.map +1 -0
  243. package/dist/engine/condition.d.cts +76 -0
  244. package/dist/engine/condition.d.cts.map +1 -0
  245. package/dist/engine/condition.d.mts +76 -0
  246. package/dist/engine/condition.d.mts.map +1 -0
  247. package/dist/engine/condition.mjs +192 -0
  248. package/dist/engine/condition.mjs.map +1 -0
  249. package/dist/engine/duration.cjs +33 -0
  250. package/dist/engine/duration.cjs.map +1 -0
  251. package/dist/engine/duration.d.cts +3 -0
  252. package/dist/engine/duration.d.cts.map +1 -0
  253. package/dist/engine/duration.d.mts +3 -0
  254. package/dist/engine/duration.d.mts.map +1 -0
  255. package/dist/engine/duration.mjs +32 -0
  256. package/dist/engine/duration.mjs.map +1 -0
  257. package/dist/engine/index.cjs +33 -0
  258. package/dist/engine/index.d.cts +10 -0
  259. package/dist/engine/index.d.mts +10 -0
  260. package/dist/engine/index.mjs +9 -0
  261. package/dist/engine/interpreter.cjs +613 -0
  262. package/dist/engine/interpreter.cjs.map +1 -0
  263. package/dist/engine/interpreter.d.cts +4 -0
  264. package/dist/engine/interpreter.d.cts.map +1 -0
  265. package/dist/engine/interpreter.d.mts +4 -0
  266. package/dist/engine/interpreter.d.mts.map +1 -0
  267. package/dist/engine/interpreter.mjs +612 -0
  268. package/dist/engine/interpreter.mjs.map +1 -0
  269. package/dist/engine/ports.cjs +0 -0
  270. package/dist/engine/ports.d.cts +373 -0
  271. package/dist/engine/ports.d.cts.map +1 -0
  272. package/dist/engine/ports.d.mts +373 -0
  273. package/dist/engine/ports.d.mts.map +1 -0
  274. package/dist/engine/ports.mjs +1 -0
  275. package/dist/engine/recipient.cjs +22 -0
  276. package/dist/engine/recipient.cjs.map +1 -0
  277. package/dist/engine/recipient.d.cts +11 -0
  278. package/dist/engine/recipient.d.cts.map +1 -0
  279. package/dist/engine/recipient.d.mts +11 -0
  280. package/dist/engine/recipient.d.mts.map +1 -0
  281. package/dist/engine/recipient.mjs +21 -0
  282. package/dist/engine/recipient.mjs.map +1 -0
  283. package/dist/engine/retry.cjs +106 -0
  284. package/dist/engine/retry.cjs.map +1 -0
  285. package/dist/engine/retry.d.cts +73 -0
  286. package/dist/engine/retry.d.cts.map +1 -0
  287. package/dist/engine/retry.d.mts +73 -0
  288. package/dist/engine/retry.d.mts.map +1 -0
  289. package/dist/engine/retry.mjs +98 -0
  290. package/dist/engine/retry.mjs.map +1 -0
  291. package/dist/engine/time-scale.cjs +153 -0
  292. package/dist/engine/time-scale.cjs.map +1 -0
  293. package/dist/engine/time-scale.d.cts +41 -0
  294. package/dist/engine/time-scale.d.cts.map +1 -0
  295. package/dist/engine/time-scale.d.mts +41 -0
  296. package/dist/engine/time-scale.d.mts.map +1 -0
  297. package/dist/engine/time-scale.mjs +150 -0
  298. package/dist/engine/time-scale.mjs.map +1 -0
  299. package/dist/engine/time-window.cjs +148 -0
  300. package/dist/engine/time-window.cjs.map +1 -0
  301. package/dist/engine/time-window.d.cts +20 -0
  302. package/dist/engine/time-window.d.cts.map +1 -0
  303. package/dist/engine/time-window.d.mts +20 -0
  304. package/dist/engine/time-window.d.mts.map +1 -0
  305. package/dist/engine/time-window.mjs +146 -0
  306. package/dist/engine/time-window.mjs.map +1 -0
  307. package/dist/fcm.cjs +208 -0
  308. package/dist/fcm.cjs.map +1 -0
  309. package/dist/fcm.d.cts +89 -0
  310. package/dist/fcm.d.cts.map +1 -0
  311. package/dist/fcm.d.mts +89 -0
  312. package/dist/fcm.d.mts.map +1 -0
  313. package/dist/fcm.mjs +202 -0
  314. package/dist/fcm.mjs.map +1 -0
  315. package/dist/hash.cjs +244 -0
  316. package/dist/hash.cjs.map +1 -0
  317. package/dist/hash.d.cts +28 -0
  318. package/dist/hash.d.cts.map +1 -0
  319. package/dist/hash.d.mts +28 -0
  320. package/dist/hash.d.mts.map +1 -0
  321. package/dist/hash.mjs +238 -0
  322. package/dist/hash.mjs.map +1 -0
  323. package/dist/host/auth.cjs +48 -0
  324. package/dist/host/auth.cjs.map +1 -0
  325. package/dist/host/auth.d.cts +33 -0
  326. package/dist/host/auth.d.cts.map +1 -0
  327. package/dist/host/auth.d.mts +33 -0
  328. package/dist/host/auth.d.mts.map +1 -0
  329. package/dist/host/auth.mjs +45 -0
  330. package/dist/host/auth.mjs.map +1 -0
  331. package/dist/host/batch.cjs +178 -0
  332. package/dist/host/batch.cjs.map +1 -0
  333. package/dist/host/batch.d.cts +92 -0
  334. package/dist/host/batch.d.cts.map +1 -0
  335. package/dist/host/batch.d.mts +92 -0
  336. package/dist/host/batch.d.mts.map +1 -0
  337. package/dist/host/batch.mjs +169 -0
  338. package/dist/host/batch.mjs.map +1 -0
  339. package/dist/host/channels.cjs +256 -0
  340. package/dist/host/channels.cjs.map +1 -0
  341. package/dist/host/channels.d.cts +66 -0
  342. package/dist/host/channels.d.cts.map +1 -0
  343. package/dist/host/channels.d.mts +66 -0
  344. package/dist/host/channels.d.mts.map +1 -0
  345. package/dist/host/channels.mjs +252 -0
  346. package/dist/host/channels.mjs.map +1 -0
  347. package/dist/host/execute.cjs +102 -0
  348. package/dist/host/execute.cjs.map +1 -0
  349. package/dist/host/execute.d.cts +38 -0
  350. package/dist/host/execute.d.cts.map +1 -0
  351. package/dist/host/execute.d.mts +38 -0
  352. package/dist/host/execute.d.mts.map +1 -0
  353. package/dist/host/execute.mjs +101 -0
  354. package/dist/host/execute.mjs.map +1 -0
  355. package/dist/host/fresh-read.cjs +29 -0
  356. package/dist/host/fresh-read.cjs.map +1 -0
  357. package/dist/host/fresh-read.d.cts +16 -0
  358. package/dist/host/fresh-read.d.cts.map +1 -0
  359. package/dist/host/fresh-read.d.mts +16 -0
  360. package/dist/host/fresh-read.d.mts.map +1 -0
  361. package/dist/host/fresh-read.mjs +28 -0
  362. package/dist/host/fresh-read.mjs.map +1 -0
  363. package/dist/host/http.cjs +393 -0
  364. package/dist/host/http.cjs.map +1 -0
  365. package/dist/host/http.d.cts +61 -0
  366. package/dist/host/http.d.cts.map +1 -0
  367. package/dist/host/http.d.mts +61 -0
  368. package/dist/host/http.d.mts.map +1 -0
  369. package/dist/host/http.mjs +389 -0
  370. package/dist/host/http.mjs.map +1 -0
  371. package/dist/host/ingest.cjs +1210 -0
  372. package/dist/host/ingest.cjs.map +1 -0
  373. package/dist/host/ingest.d.cts +497 -0
  374. package/dist/host/ingest.d.cts.map +1 -0
  375. package/dist/host/ingest.d.mts +497 -0
  376. package/dist/host/ingest.d.mts.map +1 -0
  377. package/dist/host/ingest.mjs +1172 -0
  378. package/dist/host/ingest.mjs.map +1 -0
  379. package/dist/host/journey-host.cjs +223 -0
  380. package/dist/host/journey-host.cjs.map +1 -0
  381. package/dist/host/journey-host.d.cts +118 -0
  382. package/dist/host/journey-host.d.cts.map +1 -0
  383. package/dist/host/journey-host.d.mts +118 -0
  384. package/dist/host/journey-host.d.mts.map +1 -0
  385. package/dist/host/journey-host.mjs +219 -0
  386. package/dist/host/journey-host.mjs.map +1 -0
  387. package/dist/host/platform.cjs +20 -0
  388. package/dist/host/platform.cjs.map +1 -0
  389. package/dist/host/platform.d.cts +120 -0
  390. package/dist/host/platform.d.cts.map +1 -0
  391. package/dist/host/platform.d.mts +120 -0
  392. package/dist/host/platform.d.mts.map +1 -0
  393. package/dist/host/platform.mjs +18 -0
  394. package/dist/host/platform.mjs.map +1 -0
  395. package/dist/host/senders.cjs +71 -0
  396. package/dist/host/senders.cjs.map +1 -0
  397. package/dist/host/senders.d.cts +34 -0
  398. package/dist/host/senders.d.cts.map +1 -0
  399. package/dist/host/senders.d.mts +34 -0
  400. package/dist/host/senders.d.mts.map +1 -0
  401. package/dist/host/senders.mjs +67 -0
  402. package/dist/host/senders.mjs.map +1 -0
  403. package/dist/host/workflow-cache.cjs +47 -0
  404. package/dist/host/workflow-cache.cjs.map +1 -0
  405. package/dist/host/workflow-cache.d.cts +21 -0
  406. package/dist/host/workflow-cache.d.cts.map +1 -0
  407. package/dist/host/workflow-cache.d.mts +21 -0
  408. package/dist/host/workflow-cache.d.mts.map +1 -0
  409. package/dist/host/workflow-cache.mjs +46 -0
  410. package/dist/host/workflow-cache.mjs.map +1 -0
  411. package/dist/http2-client.cjs +89 -0
  412. package/dist/http2-client.cjs.map +1 -0
  413. package/dist/http2-client.d.cts +45 -0
  414. package/dist/http2-client.d.cts.map +1 -0
  415. package/dist/http2-client.d.mts +45 -0
  416. package/dist/http2-client.d.mts.map +1 -0
  417. package/dist/http2-client.mjs +87 -0
  418. package/dist/http2-client.mjs.map +1 -0
  419. package/dist/index.cjs +130 -0
  420. package/dist/index.d.cts +21 -0
  421. package/dist/index.d.mts +21 -0
  422. package/dist/index.mjs +20 -0
  423. package/dist/inflight.cjs +116 -0
  424. package/dist/inflight.cjs.map +1 -0
  425. package/dist/inflight.d.cts +49 -0
  426. package/dist/inflight.d.cts.map +1 -0
  427. package/dist/inflight.d.mts +49 -0
  428. package/dist/inflight.d.mts.map +1 -0
  429. package/dist/inflight.mjs +113 -0
  430. package/dist/inflight.mjs.map +1 -0
  431. package/dist/ir.cjs +429 -0
  432. package/dist/ir.cjs.map +1 -0
  433. package/dist/ir.d.cts +593 -0
  434. package/dist/ir.d.cts.map +1 -0
  435. package/dist/ir.d.mts +593 -0
  436. package/dist/ir.d.mts.map +1 -0
  437. package/dist/ir.mjs +404 -0
  438. package/dist/ir.mjs.map +1 -0
  439. package/dist/jwt.cjs +17 -0
  440. package/dist/jwt.cjs.map +1 -0
  441. package/dist/jwt.d.cts +7 -0
  442. package/dist/jwt.d.cts.map +1 -0
  443. package/dist/jwt.d.mts +7 -0
  444. package/dist/jwt.d.mts.map +1 -0
  445. package/dist/jwt.mjs +15 -0
  446. package/dist/jwt.mjs.map +1 -0
  447. package/dist/node/index.cjs +231 -0
  448. package/dist/node/index.cjs.map +1 -0
  449. package/dist/node/index.d.cts +59 -0
  450. package/dist/node/index.d.cts.map +1 -0
  451. package/dist/node/index.d.mts +59 -0
  452. package/dist/node/index.d.mts.map +1 -0
  453. package/dist/node/index.mjs +225 -0
  454. package/dist/node/index.mjs.map +1 -0
  455. package/dist/node/runs.cjs +222 -0
  456. package/dist/node/runs.cjs.map +1 -0
  457. package/dist/node/runs.d.cts +93 -0
  458. package/dist/node/runs.d.cts.map +1 -0
  459. package/dist/node/runs.d.mts +93 -0
  460. package/dist/node/runs.d.mts.map +1 -0
  461. package/dist/node/runs.mjs +221 -0
  462. package/dist/node/runs.mjs.map +1 -0
  463. package/dist/node/runtime.cjs +351 -0
  464. package/dist/node/runtime.cjs.map +1 -0
  465. package/dist/node/runtime.d.cts +96 -0
  466. package/dist/node/runtime.d.cts.map +1 -0
  467. package/dist/node/runtime.d.mts +96 -0
  468. package/dist/node/runtime.d.mts.map +1 -0
  469. package/dist/node/runtime.mjs +348 -0
  470. package/dist/node/runtime.mjs.map +1 -0
  471. package/dist/plan.cjs +221 -0
  472. package/dist/plan.cjs.map +1 -0
  473. package/dist/plan.d.cts +68 -0
  474. package/dist/plan.d.cts.map +1 -0
  475. package/dist/plan.d.mts +68 -0
  476. package/dist/plan.d.mts.map +1 -0
  477. package/dist/plan.mjs +218 -0
  478. package/dist/plan.mjs.map +1 -0
  479. package/dist/postgres-js.cjs +51 -0
  480. package/dist/postgres-js.cjs.map +1 -0
  481. package/dist/postgres-js.d.cts +32 -0
  482. package/dist/postgres-js.d.cts.map +1 -0
  483. package/dist/postgres-js.d.mts +32 -0
  484. package/dist/postgres-js.d.mts.map +1 -0
  485. package/dist/postgres-js.mjs +46 -0
  486. package/dist/postgres-js.mjs.map +1 -0
  487. package/dist/provenance.cjs +66 -0
  488. package/dist/provenance.cjs.map +1 -0
  489. package/dist/provenance.d.cts +40 -0
  490. package/dist/provenance.d.cts.map +1 -0
  491. package/dist/provenance.d.mts +40 -0
  492. package/dist/provenance.d.mts.map +1 -0
  493. package/dist/provenance.mjs +64 -0
  494. package/dist/provenance.mjs.map +1 -0
  495. package/dist/push.cjs +11 -0
  496. package/dist/push.cjs.map +1 -0
  497. package/dist/push.d.cts +14 -0
  498. package/dist/push.d.cts.map +1 -0
  499. package/dist/push.d.mts +14 -0
  500. package/dist/push.d.mts.map +1 -0
  501. package/dist/push.mjs +10 -0
  502. package/dist/push.mjs.map +1 -0
  503. package/dist/react-email.cjs +56 -0
  504. package/dist/react-email.cjs.map +1 -0
  505. package/dist/react-email.d.cts +5 -0
  506. package/dist/react-email.d.cts.map +1 -0
  507. package/dist/react-email.d.mts +5 -0
  508. package/dist/react-email.d.mts.map +1 -0
  509. package/dist/react-email.mjs +55 -0
  510. package/dist/react-email.mjs.map +1 -0
  511. package/dist/reporting/classify.cjs +46 -0
  512. package/dist/reporting/classify.cjs.map +1 -0
  513. package/dist/reporting/classify.d.cts +65 -0
  514. package/dist/reporting/classify.d.cts.map +1 -0
  515. package/dist/reporting/classify.d.mts +65 -0
  516. package/dist/reporting/classify.d.mts.map +1 -0
  517. package/dist/reporting/classify.mjs +42 -0
  518. package/dist/reporting/classify.mjs.map +1 -0
  519. package/dist/reporting/observer.cjs +137 -0
  520. package/dist/reporting/observer.cjs.map +1 -0
  521. package/dist/reporting/observer.d.cts +31 -0
  522. package/dist/reporting/observer.d.cts.map +1 -0
  523. package/dist/reporting/observer.d.mts +31 -0
  524. package/dist/reporting/observer.d.mts.map +1 -0
  525. package/dist/reporting/observer.mjs +134 -0
  526. package/dist/reporting/observer.mjs.map +1 -0
  527. package/dist/reporting/tracking.cjs +185 -0
  528. package/dist/reporting/tracking.cjs.map +1 -0
  529. package/dist/reporting/tracking.d.cts +63 -0
  530. package/dist/reporting/tracking.d.cts.map +1 -0
  531. package/dist/reporting/tracking.d.mts +63 -0
  532. package/dist/reporting/tracking.d.mts.map +1 -0
  533. package/dist/reporting/tracking.mjs +182 -0
  534. package/dist/reporting/tracking.mjs.map +1 -0
  535. package/dist/runtime.cjs +18 -0
  536. package/dist/runtime.cjs.map +1 -0
  537. package/dist/runtime.d.cts +44 -0
  538. package/dist/runtime.d.cts.map +1 -0
  539. package/dist/runtime.d.mts +44 -0
  540. package/dist/runtime.d.mts.map +1 -0
  541. package/dist/runtime.mjs +17 -0
  542. package/dist/runtime.mjs.map +1 -0
  543. package/dist/store/condition-sql.cjs +145 -0
  544. package/dist/store/condition-sql.cjs.map +1 -0
  545. package/dist/store/condition-sql.d.cts +38 -0
  546. package/dist/store/condition-sql.d.cts.map +1 -0
  547. package/dist/store/condition-sql.d.mts +38 -0
  548. package/dist/store/condition-sql.d.mts.map +1 -0
  549. package/dist/store/condition-sql.mjs +144 -0
  550. package/dist/store/condition-sql.mjs.map +1 -0
  551. package/dist/store/erasure.cjs +21 -0
  552. package/dist/store/erasure.cjs.map +1 -0
  553. package/dist/store/erasure.d.cts +16 -0
  554. package/dist/store/erasure.d.cts.map +1 -0
  555. package/dist/store/erasure.d.mts +16 -0
  556. package/dist/store/erasure.d.mts.map +1 -0
  557. package/dist/store/erasure.mjs +20 -0
  558. package/dist/store/erasure.mjs.map +1 -0
  559. package/dist/store/facts.cjs +79 -0
  560. package/dist/store/facts.cjs.map +1 -0
  561. package/dist/store/facts.d.cts +41 -0
  562. package/dist/store/facts.d.cts.map +1 -0
  563. package/dist/store/facts.d.mts +41 -0
  564. package/dist/store/facts.d.mts.map +1 -0
  565. package/dist/store/facts.mjs +77 -0
  566. package/dist/store/facts.mjs.map +1 -0
  567. package/dist/store/identity.cjs +34 -0
  568. package/dist/store/identity.cjs.map +1 -0
  569. package/dist/store/identity.d.cts +13 -0
  570. package/dist/store/identity.d.cts.map +1 -0
  571. package/dist/store/identity.d.mts +13 -0
  572. package/dist/store/identity.d.mts.map +1 -0
  573. package/dist/store/identity.mjs +30 -0
  574. package/dist/store/identity.mjs.map +1 -0
  575. package/dist/store/index.cjs +35 -0
  576. package/dist/store/index.cjs.map +1 -0
  577. package/dist/store/index.d.cts +766 -0
  578. package/dist/store/index.d.cts.map +1 -0
  579. package/dist/store/index.d.mts +766 -0
  580. package/dist/store/index.d.mts.map +1 -0
  581. package/dist/store/index.mjs +22 -0
  582. package/dist/store/index.mjs.map +1 -0
  583. package/dist/store/postgres-reporting.cjs +327 -0
  584. package/dist/store/postgres-reporting.cjs.map +1 -0
  585. package/dist/store/postgres-reporting.d.cts +95 -0
  586. package/dist/store/postgres-reporting.d.cts.map +1 -0
  587. package/dist/store/postgres-reporting.d.mts +95 -0
  588. package/dist/store/postgres-reporting.d.mts.map +1 -0
  589. package/dist/store/postgres-reporting.mjs +326 -0
  590. package/dist/store/postgres-reporting.mjs.map +1 -0
  591. package/dist/store/postgres.cjs +1173 -0
  592. package/dist/store/postgres.cjs.map +1 -0
  593. package/dist/store/postgres.d.cts +199 -0
  594. package/dist/store/postgres.d.cts.map +1 -0
  595. package/dist/store/postgres.d.mts +199 -0
  596. package/dist/store/postgres.d.mts.map +1 -0
  597. package/dist/store/postgres.mjs +1170 -0
  598. package/dist/store/postgres.mjs.map +1 -0
  599. package/dist/store/sql.cjs +24 -0
  600. package/dist/store/sql.cjs.map +1 -0
  601. package/dist/store/sql.d.cts +26 -0
  602. package/dist/store/sql.d.cts.map +1 -0
  603. package/dist/store/sql.d.mts +26 -0
  604. package/dist/store/sql.d.mts.map +1 -0
  605. package/dist/store/sql.mjs +23 -0
  606. package/dist/store/sql.mjs.map +1 -0
  607. package/dist/store/tables.cjs +660 -0
  608. package/dist/store/tables.cjs.map +1 -0
  609. package/dist/store/tables.d.cts +103 -0
  610. package/dist/store/tables.d.cts.map +1 -0
  611. package/dist/store/tables.d.mts +103 -0
  612. package/dist/store/tables.d.mts.map +1 -0
  613. package/dist/store/tables.mjs +653 -0
  614. package/dist/store/tables.mjs.map +1 -0
  615. package/dist/store/user-lock.cjs +42 -0
  616. package/dist/store/user-lock.cjs.map +1 -0
  617. package/dist/store/user-lock.d.cts +30 -0
  618. package/dist/store/user-lock.d.cts.map +1 -0
  619. package/dist/store/user-lock.d.mts +30 -0
  620. package/dist/store/user-lock.d.mts.map +1 -0
  621. package/dist/store/user-lock.mjs +39 -0
  622. package/dist/store/user-lock.mjs.map +1 -0
  623. package/dist/template-rules.cjs +94 -0
  624. package/dist/template-rules.cjs.map +1 -0
  625. package/dist/template-rules.d.cts +80 -0
  626. package/dist/template-rules.d.cts.map +1 -0
  627. package/dist/template-rules.d.mts +80 -0
  628. package/dist/template-rules.d.mts.map +1 -0
  629. package/dist/template-rules.mjs +86 -0
  630. package/dist/template-rules.mjs.map +1 -0
  631. package/dist/templates.cjs +375 -0
  632. package/dist/templates.cjs.map +1 -0
  633. package/dist/templates.d.cts +358 -0
  634. package/dist/templates.d.cts.map +1 -0
  635. package/dist/templates.d.mts +358 -0
  636. package/dist/templates.d.mts.map +1 -0
  637. package/dist/templates.mjs +353 -0
  638. package/dist/templates.mjs.map +1 -0
  639. package/dist/transports/cloudflare-email.cjs +69 -0
  640. package/dist/transports/cloudflare-email.cjs.map +1 -0
  641. package/dist/transports/cloudflare-email.d.cts +63 -0
  642. package/dist/transports/cloudflare-email.d.cts.map +1 -0
  643. package/dist/transports/cloudflare-email.d.mts +63 -0
  644. package/dist/transports/cloudflare-email.d.mts.map +1 -0
  645. package/dist/transports/cloudflare-email.mjs +67 -0
  646. package/dist/transports/cloudflare-email.mjs.map +1 -0
  647. package/dist/transports/ses.cjs +142 -0
  648. package/dist/transports/ses.cjs.map +1 -0
  649. package/dist/transports/ses.d.cts +49 -0
  650. package/dist/transports/ses.d.cts.map +1 -0
  651. package/dist/transports/ses.d.mts +49 -0
  652. package/dist/transports/ses.d.mts.map +1 -0
  653. package/dist/transports/ses.mjs +139 -0
  654. package/dist/transports/ses.mjs.map +1 -0
  655. package/dist/transports/sigv4.cjs +86 -0
  656. package/dist/transports/sigv4.cjs.map +1 -0
  657. package/dist/transports/sigv4.d.cts +25 -0
  658. package/dist/transports/sigv4.d.cts.map +1 -0
  659. package/dist/transports/sigv4.d.mts +25 -0
  660. package/dist/transports/sigv4.d.mts.map +1 -0
  661. package/dist/transports/sigv4.mjs +85 -0
  662. package/dist/transports/sigv4.mjs.map +1 -0
  663. package/dist/webhooks.cjs +97 -0
  664. package/dist/webhooks.cjs.map +1 -0
  665. package/dist/webhooks.d.cts +23 -0
  666. package/dist/webhooks.d.cts.map +1 -0
  667. package/dist/webhooks.d.mts +23 -0
  668. package/dist/webhooks.d.mts.map +1 -0
  669. package/dist/webhooks.mjs +95 -0
  670. package/dist/webhooks.mjs.map +1 -0
  671. package/dist/webpush.cjs +361 -0
  672. package/dist/webpush.cjs.map +1 -0
  673. package/dist/webpush.d.cts +135 -0
  674. package/dist/webpush.d.cts.map +1 -0
  675. package/dist/webpush.d.mts +135 -0
  676. package/dist/webpush.d.mts.map +1 -0
  677. package/dist/webpush.mjs +350 -0
  678. package/dist/webpush.mjs.map +1 -0
  679. package/package.json +270 -31
  680. package/src/cloudflare/workers.d.ts +44 -0
  681. package/index.cjs +0 -18
  682. package/index.d.cts +0 -4
  683. package/index.d.mts +0 -4
  684. package/index.mjs +0 -1
package/README.md CHANGED
@@ -1,40 +1,2083 @@
1
- # SendWend
1
+ # sendwend
2
2
 
3
- Get the last value of a finite iterable or async iterable with constant extra memory. Zero dependencies. Supports ESM, CommonJS, and TypeScript.
3
+ Code-first customer journeys. Workflows are written as TypeScript, compiled to a
4
+ versioned IR, and executed by a single generic runner: the IR is data, so one
5
+ deployed Worker runs every journey. Events and profile fields are typed by a
6
+ shared Zod contract, messages are typed templates (React email, push, Slack,
7
+ Discord), and the host is a Cloudflare Worker on Cloudflare Workflows, with its
8
+ data in your own Postgres.
4
9
 
5
- ```sh
6
- npm install sendwend
10
+ ```ts
11
+ const welcome = workflow({
12
+ id: 'welcome',
13
+ reentry: { mode: 'never' },
14
+ trigger: trigger.event(e.sign_up),
15
+ })
16
+ .email(email.getting_started, { name: u.name })
17
+ .delay('3 days')
18
+ .waitUntil(performed(e.activated), {
19
+ timeout: '7 days',
20
+ onTimeout: (w) => w.email(email.nudge, { name: u.name }),
21
+ });
7
22
  ```
8
23
 
24
+ ## Install
25
+
26
+ ```bash
27
+ pnpm add sendwend zod
28
+ ```
29
+
30
+ The peer dependencies are optional; install the ones the subpaths you use need:
31
+
32
+ | Peer | Needed by |
33
+ | -------------------- | ---------------------------------------------------------------- |
34
+ | `react`, `react-dom` | `sendwend/react-email`, and `sendwend/cloudflare`, which uses it |
35
+ | `postgres` | `sendwend/postgres-js` |
36
+
37
+ Email components are usually written with `@react-email/components`, and the
38
+ Worker is deployed with `wrangler`.
39
+
40
+ ## Quick start
41
+
42
+ A project has one contract, a set of templates, the workflows, and one
43
+ `workflow.config.ts` that registers all of it. The compiler, the Worker and the
44
+ Workflow Studio (`@sendwend/studio`) all read that one object.
45
+
46
+ ### 1. The contract
47
+
48
+ The events journeys react to and the profile fields they read, as Zod schemas.
49
+ Put it in a module both the producer (your api) and the Worker can import.
50
+
51
+ ```ts
52
+ import { defineContract } from 'sendwend';
53
+ import { email, looseObject, number, optional, strictObject, string } from 'zod/mini';
54
+
55
+ export const contract = defineContract({
56
+ events: {
57
+ login: looseObject({ method: string() }),
58
+ purchase: looseObject({ transaction_id: string(), currency: string(), value: number() }),
59
+ },
60
+ profile: strictObject({ email: optional(email()), name: string() }),
61
+ subscriptions: { topics: ['promotions', 'newsletter', 'tips'] },
62
+ });
63
+
64
+ /** The DSL's reference tables: `e.login`, `u.name`. */
65
+ export const e = contract.events;
66
+ export const u = contract.user;
67
+ ```
68
+
69
+ Event payloads are object schemas (`looseObject` keeps extra analytics fields).
70
+ The profile is a flat object of string, number, boolean, enum and literal
71
+ fields. Defaults, transforms, coercion and custom refinements are refused when
72
+ the contract is defined, because input and output must mean the same JSON.
73
+
74
+ **A profile field's schema checks what is written, not that it was written.**
75
+ The profile is merged a patch at a time (`identify`), so `name: string()` means
76
+ "a name, when there is one, is a string": a user nobody has sent a name for has
77
+ none, and `null` removes one. The DSL takes the declaration at its word and
78
+ types `u.name` as a `string`, which holds only if your app writes the field for
79
+ every user a journey can reach (at sign-up, say). Where it does not — a sign-in
80
+ that gives no name, an event that arrives before the first `identify`, a
81
+ visitor — declare the field `optional(string())`: `u.name` is then
82
+ `string | undefined`, a template whose prop is required no longer compiles with
83
+ it, and the template says what to show instead. The engine fills no defaults.
84
+
85
+ `subscriptions.topics` lists the subscription topics: content categories
86
+ ("offers", "tips"), not channels — ids only (a plain token; the app's i18n gives
87
+ them names). A plain array literal is enough: `defineContract` keeps the
88
+ literals, and the union they form types every email and push template's
89
+ `topic`, the config and `JourneyClient.setSubscriptions`. A user opts out of a
90
+ topic per channel (the preference page is topic × channel), or of a whole
91
+ channel; the engine keeps that record and is the one source of truth for it
92
+ (see [Email](#email), [Push](#push) and [`JourneyClient`](#journeyclient)).
93
+ Leave the field out when every email and push is transactional.
94
+
95
+ ### 2. Templates
96
+
97
+ One object per template, identified by its own `id` (unique per channel): the
98
+ IR, the manifest, every send and the studio name it by that id, so keep it
99
+ stable and rename `title` instead. Its strict Zod `props` schema is the only
100
+ source of the props type: the DSL's arguments, the `preview` and the component
101
+ are all derived from it, and every send parses the props against it first.
102
+
103
+ ```ts
104
+ // src/contract.ts (continued): the template factories bound to the contract
105
+ export const { emailTemplate, pushTemplate } = templatesFor(contract);
106
+ ```
107
+
108
+ ```tsx
109
+ // src/email/welcome.tsx
110
+ import { Html, Text } from '@react-email/components';
111
+ import { strictObject, string } from 'zod/mini';
112
+ import { emailTemplate } from '../contract';
113
+
114
+ export default emailTemplate({
115
+ id: 'welcome',
116
+ transactional: true,
117
+ from: { email: 'noreply@acme.test', name: 'Acme' },
118
+ title: 'Welcome',
119
+ props: strictObject({ name: string() }),
120
+ subject: 'Welcome aboard',
121
+ preview: { name: 'John Doe' },
122
+ component: ({ name }) => (
123
+ <Html>
124
+ <Text>Welcome, {name}! Create your first project; it takes a minute.</Text>
125
+ </Html>
126
+ ),
127
+ });
128
+ ```
129
+
130
+ Every email and push template says what it is: `topic: 'tips'` (a topic the
131
+ contract declares, which the user can opt out of on that channel) or
132
+ `transactional: true` (a receipt, a code, an invite: sent whatever they opted
133
+ out of; for an email, with no unsubscribe link). Leaving both out, or giving
134
+ both, is a type error and a compile error, and the error says so in words.
135
+ `templatesFor(contract)` gives the factories with the topic typed by the
136
+ contract, so a topic it does not declare is an error at the template's own
137
+ `topic` line, in the editor and when the module loads; the bare `emailTemplate`
138
+ / `pushTemplate` from `sendwend` are for a project without a contract
139
+ (transactional templates only), and the compile checks every template again.
140
+
141
+ Gather them per channel; the workflows send the definitions and the config
142
+ registers the whole:
143
+
144
+ ```ts
145
+ // src/email/index.ts
146
+ import tip from './tip';
147
+ import welcome from './welcome';
148
+
149
+ export const email = { welcome, tip };
150
+ ```
151
+
152
+ ```ts
153
+ // src/templates.ts
154
+ import { email } from './email';
155
+
156
+ export const templates = { email };
157
+ ```
158
+
159
+ `tip.tsx` is written the same way, with `topic: 'tips'`, and so is a
160
+ `pushTemplate`. The property names are JavaScript names only. `.email(email.welcome, props)` checks `props`
161
+ against that template's schema, and a push template is not accepted where an
162
+ email is. The compile refuses an id registered twice in a channel, a workflow
163
+ sending a definition other than the one registered under its id, and a topic
164
+ the contract does not declare (with a `contract` in the config, the editor
165
+ refuses it first).
166
+
167
+ ### 3. A workflow
168
+
169
+ ```ts
170
+ // src/workflows/welcome.ts
171
+ import { not, performed, trigger, workflow } from 'sendwend';
172
+ import { e, u } from '../contract';
173
+ import { email } from '../email';
174
+
175
+ export const welcomeSeries = workflow({
176
+ id: 'welcome_series',
177
+ reentry: { mode: 'never' },
178
+ name: 'Welcome series',
179
+ trigger: trigger.event(e.login),
180
+ goal: { condition: performed(e.purchase), within: '7 days' },
181
+ })
182
+ .email(email.welcome, { name: u.name })
183
+ .delay('2 days')
184
+ .branch([not(performed(e.purchase)), (w) => w.email(email.tip, { name: u.name })]);
185
+ ```
186
+
187
+ `id` is wire identity (instances, the entry ledger and stats are keyed on it),
188
+ so rename `name` instead.
189
+
190
+ ### 4. The config
191
+
192
+ ```ts
193
+ // workflow.config.ts
194
+ import { defineConfig } from 'sendwend';
195
+ import { contract } from './src/contract';
196
+ import { templates } from './src/templates';
197
+ import { welcomeSeries } from './src/workflows/welcome';
198
+
199
+ export default defineConfig({
200
+ title: 'Workflow Studio · Acme',
201
+ contract,
202
+ workflows: [welcomeSeries],
203
+ templates,
204
+ email: { unsubscribeUrl: 'https://acme.test/unsubscribe' },
205
+ runtime: {
206
+ development: { timeScale: 600, logMessages: true },
207
+ production: { timeScale: 1, logMessages: false },
208
+ },
209
+ });
210
+ ```
211
+
212
+ ### 5. The Worker
213
+
214
+ ```ts
215
+ // src/index.ts
216
+ import { type JourneyEnv, journeyWorker } from 'sendwend/cloudflare';
217
+ import { postgresJsStore } from 'sendwend/postgres-js';
218
+ import { cloudflareEmailTransport } from 'sendwend/transports/cloudflare-email';
219
+ import config from '../workflow.config';
220
+
221
+ interface Env extends JourneyEnv {
222
+ HYPERDRIVE: { connectionString: string };
223
+ EMAIL: NonNullable<JourneyEnv['EMAIL']>;
224
+ }
225
+
226
+ const journeys = journeyWorker<Env>({
227
+ config,
228
+ store: (env, database) => postgresJsStore(env.HYPERDRIVE.connectionString, database),
229
+ email: (env) => cloudflareEmailTransport({ binding: env.EMAIL }),
230
+ });
231
+
232
+ /** The wrangler `workflows` binding's class_name. */
233
+ export const AcmeJourneyRunner = journeys.Runner;
234
+
235
+ export default { fetch: journeys.fetch, scheduled: journeys.scheduled };
236
+ ```
237
+
238
+ `store` names the engine's Postgres (here through Hyperdrive); create its tables
239
+ first (see [Postgres](#postgres)).
240
+
241
+ ```jsonc
242
+ // wrangler.jsonc
243
+ {
244
+ "name": "acme-workflow",
245
+ "main": "src/index.ts",
246
+ "compatibility_date": "2026-09-12",
247
+ "compatibility_flags": ["nodejs_compat"],
248
+ "workflows": [
249
+ { "name": "acme-journey", "binding": "JOURNEY", "class_name": "AcmeJourneyRunner" },
250
+ ],
251
+ "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "<hyperdrive id>" }],
252
+ "send_email": [{ "name": "EMAIL" }],
253
+ "vars": { "ENVIRONMENT": "production", "WORKFLOW_ORIGIN": "https://workflow.acme.test" },
254
+ "triggers": { "crons": ["*/15 * * * *"] },
255
+ }
256
+ ```
257
+
258
+ ### 6. Deploy
259
+
260
+ ```bash
261
+ wrangler secret put API_TOKEN
262
+ wrangler deploy
263
+ curl -X POST https://workflow.acme.test/bundle/deploy -H "authorization: Bearer $API_TOKEN"
264
+ ```
265
+
266
+ `POST /bundle/deploy` compiles the config the Worker was built with and swaps
267
+ the routing table. Run it after every deploy that changes a journey. Before
268
+ `wrangler deploy`, `sendwend-studio plan --database-url $DATABASE_URL` checks the
269
+ bundle against the journeys still running (see [Versioning](#versioning)).
270
+
271
+ ### 7. Send events
272
+
273
+ From the service that knows what users do:
274
+
275
+ ```ts
276
+ import { contract } from '@acme/workflow-contract';
277
+ import { JourneyClient } from 'sendwend/client';
278
+
279
+ export const journeys = new JourneyClient({
280
+ contract,
281
+ origin: 'https://workflow.acme.test',
282
+ token: process.env.WORKFLOW_API_TOKEN,
283
+ });
284
+
285
+ await journeys.ingest({
286
+ userId: user.id,
287
+ profile: { email: user.email, name: user.name },
288
+ events: [{ event: 'login', payload: { method: 'google' }, id: `login-${session.id}` }],
289
+ });
290
+ ```
291
+
292
+ Identify the properties a journey reads before the event that starts it.
293
+
294
+ ## The three planes
295
+
296
+ | Plane | What it is | Where it lives |
297
+ | --------- | ------------------------------------------ | --------------------- |
298
+ | Authoring | The DSL, compiled to IR by `compileBundle` | `sendwend` |
299
+ | Execution | The interpreter, over abstract ports | `sendwend/engine` |
300
+ | Adapter | Cloudflare bindings, ingest, runner | `sendwend/cloudflare` |
301
+
302
+ The interpreter never touches a database or a network. Everything it needs
303
+ arrives through the ports in `engine/ports.ts`, which is what makes a journey
304
+ testable without deploying one.
305
+
306
+ ## Authoring
307
+
308
+ Chained calls and condition expressions build a serializable graph, never
309
+ runtime code. Sub-flow callbacks run exactly once, while the workflow is
310
+ defined, and runtime values are always references (`u.xxx`), not closures.
311
+
312
+ ### Reference tables
313
+
314
+ `contract.events` and `contract.user` are the typed reference tables: `e.purchase`
315
+ is an event reference, `u.name` a profile reference (`u.userId` is always
316
+ there). Without a contract, build them from TypeScript types:
317
+
318
+ ```ts
319
+ import { event, user } from 'sendwend';
320
+
321
+ const e = event<{ demo_signup: Record<never, never>; demo_purchase: { value: number } }>();
322
+ const u = user<{ userId: string; email: string; plan: string }>();
323
+ ```
324
+
325
+ ### `workflow(definition)`
326
+
327
+ | Option | Meaning |
328
+ | ------------- | --------------------------------------------------------------------------------- |
329
+ | `id` | Wire identity; never rename it for readability |
330
+ | `trigger` | A `trigger.xxx()` asset |
331
+ | `reentry` | Required: whether a user may enter again — see [Re-entry](#re-entry) |
332
+ | `goal` | A condition, or `{ condition, within?, exitOnMatch? }`; exits on match by default |
333
+ | `exitWhen` | Leave without counting as a conversion (unsubscribed, no longer eligible) |
334
+ | `name` | Studio label; metadata, outside the hash |
335
+ | `description` | One line on what the flow does; metadata, outside the hash |
336
+
337
+ The goal is checked before each node runs. A `performed()` inside a goal counts
338
+ from workflow entry, so earlier history cannot satisfy it.
339
+
340
+ ### Triggers
341
+
342
+ ```ts
343
+ trigger.event(e.login);
344
+ trigger.event(e.purchase_failed, (p) => notInArray(p.code, ['CHECKOUT_CANCELED']));
345
+ trigger.event(e.sign_up, { filter: exists(u.email) });
346
+ trigger.enters(dormant7d);
347
+ trigger.date('2026-12-25 09:00:00', { filter: purchaser });
348
+ trigger.webhook();
349
+ ```
350
+
351
+ - `event` takes an optional payload `where` (typed by the event) and a profile
352
+ `filter`; the user enters only when the event fired and both hold.
353
+ - `enters` starts the journey when a user goes from not matching a named
354
+ segment to matching it. Membership is re-evaluated on the user's events and
355
+ identifies, and by the segment sweep (the cron trigger), which catches
356
+ segments entered by the clock alone. (`trigger.segment` is its earlier name,
357
+ still accepted.)
358
+ - `date` starts a journey, once, for every known user its `filter` holds for
359
+ when the time comes (below).
360
+ - `webhook` compiles and deploys, but is not routed by the runtime yet: deploy
361
+ lists it in `unrouted`.
362
+
363
+ #### A send at a time
364
+
365
+ ```ts
366
+ workflow({
367
+ id: 'black_friday',
368
+ reentry: { mode: 'never' },
369
+ trigger: trigger.date('2026-11-27 09:00:00', { filter: purchaser }),
370
+ }).email(email.black_friday, { name: u.name });
371
+ ```
372
+
373
+ At that time (UTC) every known user the `filter` holds for enters — asked when
374
+ the sweep reaches them, not from a membership kept beforehand, so someone who has been a purchaser for three years enters like
375
+ one who became one yesterday. Without a `filter`, every known user does.
376
+ Visitors do not.
377
+
378
+ - **The sweep does the starting.** The send begins at the first sweep (the cron
379
+ trigger) at or after the time, so a 15-minute cron starts it within 15
380
+ minutes. It goes through the audience a page of 500 at a time and keeps its
381
+ place in the store: a sweep spends about 30 seconds on it and the next one
382
+ carries on, and one that is cut off loses nobody and repeats nobody. A large
383
+ audience therefore takes several sweeps; run the cron more often around a
384
+ big send if that matters.
385
+ - **A time runs once.** The run is identified by the workflow and the time.
386
+ Redeploying does not repeat it, and a deploy that lands just after the time
387
+ does not cancel it. Changing the time is another run, and who enters again
388
+ is the workflow's `reentry` policy.
389
+ - **A time already past when the trigger is first deployed is not run**, and
390
+ neither is one that no sweep picked up within a day (a cron that was off):
391
+ a send that is that late is not the one that was scheduled.
392
+ - **A start that fails is retried.** The page it was on is done again by the
393
+ next sweep (whoever already entered is skipped), other date triggers that
394
+ are due go on meanwhile, and a user who still cannot be started a day after
395
+ the time is passed over.
396
+ - **The filter is checked before an instance exists.** A user it turns away
397
+ has not entered: no Workflow instance, nothing held against `reentry`,
398
+ nothing in the entry counts. That is the difference from a `filter` step.
399
+ - The journey's entry time is the trigger's, and its trigger carries no
400
+ payload.
401
+
402
+ #### Entering a segment is not being in it
403
+
404
+ `trigger.enters(s)` looks forward. Whoever already matches `s` when it is first
405
+ deployed — or when its condition changes, or that of a segment it is built on —
406
+ is recorded as a member and starts nothing: they did not enter, they were
407
+ there. The sweep after the deploy does the recording, in a pass over every
408
+ user (one sweep for most audiences, several for a large one: below); from the
409
+ moment that pass completes, a user who newly matches enters. Until then a user
410
+ who matches on their own activity is recorded the same way.
411
+
412
+ So a deploy never starts journeys in bulk, and the outcome does not depend on
413
+ whether the segment happened to exist before its trigger did.
414
+
415
+ A segment named in a condition is a different question and has no such rule: a
416
+ trigger's `filter`, a `branch` or a `waitUntil` on `s` asks each user whether
417
+ they match **now**, long-standing members included.
418
+
419
+ ```ts
420
+ trigger.enters(dormant7d); // whoever goes quiet from here on
421
+ trigger.event(e.session_start, { filter: purchaser }); // every purchaser, at their next session
422
+ ```
423
+
424
+ #### Reading the triggering event
425
+
426
+ `trigger.event()` returns a handle on the event that started the journey. Its
427
+ `payload` is a table of that event's fields, typed by the event, and a field
428
+ can go wherever a profile property can: a predicate, a message prop, an
429
+ emitted payload, an action argument.
430
+
431
+ ```ts
432
+ const checkout = trigger.event(e.begin_checkout);
433
+
434
+ workflow({ id: 'checkout_recovery', reentry: { mode: 'never' }, trigger: checkout })
435
+ .delay('1 hour')
436
+ .branch([gte(checkout.payload.value, 100), (w) => w.email(email.vip_offer)], (w) =>
437
+ w.email(email.reminder)
438
+ )
439
+ .email(email.cart_summary, {
440
+ total: checkout.payload.value,
441
+ currency: checkout.payload.currency,
442
+ });
443
+ ```
444
+
445
+ - **It is a snapshot.** The journey reads the payload it entered with, for as
446
+ long as it runs. A second `begin_checkout` a day later changes nothing a
447
+ running journey reads (whether it starts another journey is the `reentry`
448
+ policy's business).
449
+ - **Scalars only.** A nested field is reached by its path
450
+ (`checkout.payload.cart.items`); an object or an array is not a value, and
451
+ reads as missing. A field the event left out reads as missing too, as an
452
+ unset profile property does.
453
+ - **Only in the workflow the trigger starts.** `compileBundle` refuses a
454
+ reference taken from another trigger, one in a workflow with a segment, date
455
+ or webhook trigger (they carry no payload), and one in a segment or a trigger
456
+ `filter` (neither runs inside a journey: test the event with the trigger's
457
+ `where`). With a contract, `compileConfig` also checks that every field read
458
+ is one the event declares.
459
+ - To act on an event that arrives _during_ the journey, use
460
+ `performed(e.purchase, (p) => gte(p.value, 100))` in a `waitUntil` or a
461
+ `branch`: that tests the event log, not the trigger.
462
+
463
+ ### Steps
464
+
465
+ | Step | What it does |
466
+ | --------------------------------------------- | ------------------------------------------------------------------------- |
467
+ | `.email(email.k, props)` | Send an email |
468
+ | `.push(push.k, props, { devices? })` | Push to every device of the user, or only the `'latest'`; skipped if none |
469
+ | `.slack(slack.k, props)` | Post to a Slack incoming webhook |
470
+ | `.discord(discord.k, props)` | Post to a Discord webhook |
471
+ | `.sms()`, `.inApp()`, `.survey()` | Message nodes with no built-in sender (see [Channels](#channels)) |
472
+ | `.prefer([first, second], props, { label? })` | One push and one email: the first the user is reachable on |
473
+ | `.delay('1 day')` | Sleep; `{ min, max }` sleeps a random time in between |
474
+ | `.timeWindow({ days?, between, tz? })` | Hold until inside a weekly window |
475
+ | `.waitUntil(condition, opts)` | Wait for a condition, or time out |
476
+ | `.branch(label?, ...arms)` | First-match branch; rejoins the main line afterwards |
477
+ | `.filter(condition, { reason? })` | Exit unless the condition holds |
478
+ | `.cohort(arms, { key? })` | Random A/B split; weights sum to 100 |
479
+ | `.exit(reason?)` | End the journey; inside an arm, do not rejoin |
480
+ | `.sendEvent(e.x, payload?)` | Emit an event, which may trigger another workflow |
481
+ | `.run(action, args)` | Run a custom action inside a durable step |
482
+ | `.use(fragment)` | Splice a `flow(...)` fragment in place |
483
+
484
+ Props may reference the profile (`{ name: u.name }`); references resolve at send
485
+ time and are parsed by the template then. A reference the user has no value
486
+ for is passed as absent: a template that requires the prop refuses it, the
487
+ message is not sent and the journey fails there without a retry, with an error
488
+ that names the field (`props.name reads profile field 'name', which this user
489
+ has no value for`). Either the data is missing or the field should have been
490
+ declared optional (see the contract above). Durations are typed literals such as
491
+ `'30 minutes'`, `'1 day'` or `'2 weeks'`, so a typo does not compile.
492
+
493
+ **prefer** is sugar for the branch it compiles to: the choice is made once when
494
+ the step is reached, and a first choice that fails to send retries as itself.
495
+ Both templates must declare the same props type.
496
+
497
+ ```ts
498
+ workflow({ id: 'welcome_series', reentry: { mode: 'never' }, trigger: trigger.event(e.login) })
499
+ .email(email.welcome, { name: u.name })
500
+ .delay('1 day')
501
+ .prefer([push.tip_push, email.tip], { name: u.name }, { label: 'tip by channel' });
502
+ ```
503
+
504
+ **timeWindow** takes `between: ['09:00', '17:00']` (24-hour, leading zeros, not
505
+ overnight), `days` (all week by default) and `tz`: `'user'` (the default) reads
506
+ the profile's `time_zone` property, an IANA id, falling back to UTC when it is
507
+ invalid; any other string is a fixed IANA zone.
508
+
509
+ **waitUntil** continues on the main line once the condition holds. On timeout it
510
+ does `onTimeout`: `'continue'` (the default), `'exit'`, or a sub-flow. A
511
+ `performed()` inside it counts from the moment the wait began.
512
+
513
+ ```ts
514
+ workflow({
515
+ id: 'notification_optin',
516
+ reentry: { mode: 'never' },
517
+ trigger: trigger.event(e.login),
518
+ }).waitUntil(
519
+ or(
520
+ reachable('push'),
521
+ performed(e.notification_permission, (p) => eq(p.status, 'granted'))
522
+ ),
523
+ {
524
+ timeout: '1 day',
525
+ onTimeout: (w) => w.email(email.enable_notifications, { name: u.name }),
526
+ }
527
+ );
528
+ ```
529
+
530
+ **branch** arms are `[condition, sub-flow]` tuples; a bare sub-flow in last
531
+ position is the default arm. With no match and no default, execution
532
+ continues.
533
+
534
+ ```ts
535
+ workflow({
536
+ id: 'nps_followup',
537
+ reentry: { mode: 'after_exit' },
538
+ trigger: trigger.event(e.nps_sent),
539
+ }).branch(
540
+ 'by score',
541
+ [
542
+ performed(e.nps_sent, (p) => gte(p.score, 9)),
543
+ (w) => w.delay('1 day').email(email.review_ask, { name: u.name }),
544
+ ],
545
+ [
546
+ performed(e.nps_sent, (p) => lte(p.score, 6)),
547
+ (w) => w.slack(slack.nps_detractor, { name: u.name }).exit('handed to support'),
548
+ ]
549
+ );
550
+ ```
551
+
552
+ **cohort** arm names are letters, digits, `_` and `-`, not starting with a
553
+ digit, and weights have at most two decimals. Set `key` for any experiment you
554
+ intend to read: bucketing then hashes `userId:key`, so assignments survive
555
+ edits to the workflow.
556
+
557
+ ```ts
558
+ workflow({
559
+ id: 'checkout_recovery',
560
+ reentry: { mode: 'after_exit', cooldown: '7 days' },
561
+ trigger: trigger.event(e.begin_checkout),
562
+ })
563
+ .delay('1 day')
564
+ .cohort(
565
+ {
566
+ discount: { weight: 50, flow: (w) => w.email(email.offer_discount, { name: u.name }) },
567
+ social_proof: { weight: 50, flow: (w) => w.email(email.offer_reviews, { name: u.name }) },
568
+ },
569
+ { key: 'checkout_offer_v1' }
570
+ );
571
+ ```
572
+
573
+ **sendEvent** carries scalar fields only (literals or `u.xxx`), and the event is
574
+ checked against the contract like any ingested one. A self-triggering `sendEvent`
575
+ re-enters only as the workflow's `reentry` allows: not under `never`, and not under
576
+ `after_exit` either (the event arrives while the instance still runs); `concurrent`
577
+ with a `cooldown` makes it a periodic flow.
578
+
579
+ **run** executes a custom action. The IR records only its name, args and a hash
580
+ of its code; the implementation ships in the Worker and is registered through
581
+ the config's `actions`. It is retried on throw, so pass `ctx.idempotencyKey` to
582
+ any external side effect.
583
+
584
+ ```ts
585
+ import { action } from 'sendwend';
586
+
587
+ export const issueCoupon = action<{ code: string }>('issue_coupon', async ({ code }, ctx) => {
588
+ await billing.issueCoupon({ code, userId: ctx.userId, idempotencyKey: ctx.idempotencyKey });
589
+ });
590
+
591
+ workflow({ id: 'winback', reentry: { mode: 'never' }, trigger: trigger.enters(dormant7d) }).run(
592
+ issueCoupon,
593
+ {
594
+ code: '15OFF',
595
+ }
596
+ );
597
+ ```
598
+
599
+ **flow** names a reusable fragment, for `.use()` or as a branch arm. Each use
600
+ gets its own copy:
601
+
602
+ ```ts
603
+ const officeHours = flow((w) =>
604
+ w.timeWindow({ days: ['mon', 'tue', 'wed', 'thu', 'fri'], between: ['09:00', '17:00'] })
605
+ );
606
+ ```
607
+
608
+ ### Conditions
609
+
610
+ | Function | Meaning |
611
+ | ------------------------------------------------- | ----------------------------------------------------------------- |
612
+ | `eq`, `ne` | Equal / not equal |
613
+ | `gt`, `gte`, `lt`, `lte` | Ordered comparison (string or number) |
614
+ | `between`, `notBetween` | Inclusive range |
615
+ | `inArray`, `notInArray` | Membership in a list |
616
+ | `exists`, `notExists` | Property present / absent |
617
+ | `contains`, `notContains` | Substring (string) |
618
+ | `performed(e.x, where?, { within?, count? })` | Did the event, optionally matching, in a window, at least N times |
619
+ | `reachable(channel)` | Push: has a registered device; other channels: has the address |
620
+ | `and`, `or`, `not` | Combinators; nest freely |
621
+ | `segment({ id, condition, name?, description? })` | A named condition: reusable, swept, usable as a trigger |
622
+
623
+ Predicates take a profile reference (`eq(u.platform, 'ios')`), or, inside a
624
+ `where`, a payload reference (`(p) => gt(p.value, 100)`). Values are typed by
625
+ the reference, so `eq(u.platform, 'ios ')` against an enum does not compile.
626
+ "Did not do" is `not(performed(...))`.
627
+
628
+ ```ts
629
+ export const dormant7d = segment({
630
+ id: 'dormant_7d',
631
+ name: 'Dormant (7d)',
632
+ condition: and(performed(e.login), not(performed(e.login, { within: '7 days' }))),
633
+ });
634
+ ```
635
+
636
+ Segments a workflow references must be passed in the config's `segments`, or
637
+ the compile fails.
638
+
639
+ ## Channels
640
+
641
+ ### Email
642
+
643
+ `emailTemplate({ id, topic | transactional, from, replyTo?, unsubscribeUrl?, title, description?, props, subject, preview, component })`
644
+ declares one. The Worker renders it with `sendwend/react-email` (React's
645
+ streaming renderer, which waits for react-email's `<Tailwind>`) and sends it
646
+ through the host's email transport, from the template's own `from`:
647
+
648
+ ```ts
649
+ // src/email/tip.tsx
650
+ export default emailTemplate({
651
+ id: 'tip',
652
+ topic: 'tips',
653
+ from: { email: 'noreply@acme.test', name: 'Acme' },
654
+ replyTo: { email: 'support@acme.test', name: 'Acme Support' }, // left out: no Reply-To
655
+ title: 'Weekly tip',
656
+ props: strictObject({ name: string() }),
657
+ subject: 'One thing to try this week',
658
+ preview: { name: 'John Doe' },
659
+ component: ({ name }) => <Layout name={name}>…</Layout>,
660
+ });
661
+ ```
662
+
663
+ Every template is one of two kinds, by type: a **topic** email names one of the
664
+ contract's `subscriptions.topics`, and a **transactional** email says
665
+ `transactional: true` (and takes no `unsubscribeUrl`). The kind decides what
666
+ the engine does before and after the send:
667
+
668
+ | Email | Before sending | Unsubscribe link, `List-Unsubscribe` |
669
+ | ------------- | -------------------------------------------------------------- | ------------------------------------- |
670
+ | topic | skipped when the user opted out of that topic, or of all email | yes |
671
+ | transactional | always sent (a receipt, a code, an invite) | none, whatever `email.unsubscribeUrl` |
672
+
673
+ There is no global sender: share addresses through a module of your own. A
674
+ topic email's unsubscribe link is the template's `unsubscribeUrl`, else the
675
+ config's `email.unsubscribeUrl`, else none; its preferences link is the config's
676
+ `email.preferencesUrl` with the copy's message id, when the copy has one; a
677
+ transactional email never has either (`resolveEmail` is the rule). A layout
678
+ reads them from the render, never from a constant, so a template's own URL
679
+ reaches its HTML and each copy's link names that copy; the resolved `topic` is
680
+ there too, for a line like "you get these because you subscribed to tips":
681
+
682
+ ```tsx
683
+ import { useEmailContext } from 'sendwend/email-context';
684
+
685
+ const { unsubscribeUrl, preferencesUrl } = useEmailContext();
686
+ {
687
+ preferencesUrl !== undefined && <Link href={preferencesUrl}>Email preferences</Link>;
688
+ }
689
+ {
690
+ unsubscribeUrl !== undefined && <Link href={unsubscribeUrl}>Unsubscribe</Link>;
691
+ }
692
+ ```
693
+
694
+ ```ts
695
+ // workflow.config.ts
696
+ email: {
697
+ unsubscribeUrl: 'https://acme.test/unsubscribe', // templates without their own
698
+ preferencesUrl: 'https://acme.test/settings/email', // the app's preference page
699
+ tracking: { quickClickMs: 1_000 }, // the default
700
+ },
701
+ ```
702
+
703
+ The transport is the host's `email` option, chosen independently of where the
704
+ workflow runs. Rendering, tracking and the tracked-link commit happen before it,
705
+ the same for every provider (`EmailSender`):
706
+
707
+ | Transport | Import |
708
+ | -------------------------------------------------------------------------- | -------------------------------------- |
709
+ | `cloudflareEmailTransport({ binding })` — a Worker's `send_email` | `sendwend/transports/cloudflare-email` |
710
+ | `cloudflareEmailTransport({ accountId, apiToken })` — REST, anywhere | `sendwend/transports/cloudflare-email` |
711
+ | `sesEmailTransport({ region, credentials? })` — SES v2, SigV4 over `fetch` | `sendwend/transports/ses` |
712
+
713
+ `sesEmailTransport` runs in a Worker and in Node alike. Without `credentials` it
714
+ reads `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` / `AWS_SESSION_TOKEN` at send
715
+ time (a Lambda's execution role); a Worker passes them, or a provider, from its
716
+ env. Neither SES nor Cloudflare Email Service accepts an idempotency key, so the
717
+ engine itself keeps a copy from going out twice — see [Delivery guarantee](#delivery-guarantee).
718
+ A host whose workflows send email but that has no `email` option (nor a
719
+ `messages` override) fails when it is created, naming those workflows.
720
+
721
+ An email with an unsubscribe link also carries `List-Unsubscribe` (RFC 2369), so
722
+ a mail client's own unsubscribe button works. With reporting on (a Postgres store and
723
+ `WORKFLOW_ORIGIN`), it names the copy's one-click endpoint `/t/u/<message>`, together with
724
+ `List-Unsubscribe-Post: List-Unsubscribe=One-Click` (RFC 8058). Gmail and Yahoo require
725
+ one-click unsubscribe for bulk senders. The provider's POST there unsubscribes at once from
726
+ the email's topic; the same URL opened in a browser (and the email's own link) asks first, with
727
+ two buttons: the email's topic, and all email. Without reporting, the header names the
728
+ template's own unsubscribe link, with no one-click claim. Only https URLs are named, so a local
729
+ `http://` origin sends no header.
730
+
731
+ So a topic email carries two ways out, for two readers. The **header** is for the mail client:
732
+ `List-Unsubscribe` points at the Worker's own `/t/u/<message>`, which a one-click POST or the
733
+ Worker's plain confirmation page settles without the app. The **footer** is for the person:
734
+ `preferencesUrl` is the app's own page, branded, signed in or not, reached as
735
+ `https://acme.test/settings/email?m=<message id>` (the page's own query is kept, `m` set beside
736
+ it). The message id in `m` is how the page knows the recipient without a login: it is the
737
+ capability, an unguessable UUID that only ever reached that mailbox, the same trust `/t/u` runs
738
+ on. The page's API calls `GET /subscriptions/by-message/<m>` with the bearer
739
+ (`JourneyClient.getSubscriptionsByMessage`), gets the recipient's record plus
740
+ `message: { channel, topic }` to highlight the topic that email belonged to, and writes with
741
+ `PUT /subscriptions/by-message/<m>` (`setSubscriptionsByMessage`), the same patch as the user
742
+ endpoint. An id that names no copy (never sent, or erased with its user by `/users/forget`) or a
743
+ transactional one answers 404, the rule `/t/u` applies: show the link as expired. The Worker
744
+ does not rate-limit these routes; the app's proxy does, as it sees fit. The link is tracked as
745
+ an ordinary click (`/t/l/...`), never as an unsubscribe: `preferencesUrl` must not share its
746
+ origin and path with `unsubscribeUrl` (or a template's own), and the config refuses one that
747
+ does. Without reporting (no Postgres reporting or no `WORKFLOW_ORIGIN`) there is no message id,
748
+ so `preferencesUrl` is `undefined` in the render and the footer shows nothing; a preview
749
+ (`GET /preview` and the studio) renders it with a placeholder id, `PREVIEW_MESSAGE_ID`.
750
+
751
+ What a user opted out of is the engine's record, per topic and channel: a topic email is
752
+ skipped while its topic (on email) or all email is opted out, a transactional email never is,
753
+ and `reachable('email')` reads the all-email opt-out only — a user unsubscribed from one topic
754
+ is still reachable, so an `exitWhen: not(reachable('email'))` fires on "all email", not on a
755
+ topic. An email opt-out says nothing about push: the same topic is opted out per channel. The
756
+ app reads and sets the record through `GET` / `PUT /subscriptions/:userId`
757
+ (`JourneyClient.getSubscriptions` / `setSubscriptions`), which is how a signed-in preference
758
+ page is built: the engine holds the truth, the page shows it. The all-email opt-out and the
759
+ topic opt-outs are separate records: `all: false` masks every topic, whatever its own flag says,
760
+ and `all: true` clears only the all-email opt-out — a topic opted out on its own stays off until
761
+ a patch names it.
762
+
763
+ An email step refuses to send when the profile has no `email`.
764
+ `GET /preview/<id>?props=<JSON>` renders a template, with the subject in the
765
+ `x-subject` header.
766
+
767
+ ### Push
768
+
769
+ `pushTemplate({ id, topic | transactional, title, description?, props, preview, content })`,
770
+ where `content(props)` returns `{ title, body, image?, url? }`: final text, never
771
+ placeholder-expanded. `url` is the page a browser push opens.
772
+
773
+ ```ts
774
+ export default pushTemplate({
775
+ id: 'onboarding_tip_push',
776
+ topic: 'tips',
777
+ title: 'Onboarding tip (push)',
778
+ props: strictObject({ name: string() }),
779
+ preview: { name: 'John Doe' },
780
+ content: ({ name }) => ({ title: 'A tip for today', body: `Face a window, ${name}.` }),
781
+ });
782
+ ```
783
+
784
+ A push is a **topic** push (one of the contract's `subscriptions.topics`) or a
785
+ **transactional** one (`transactional: true`: a code, a receipt, a reply), like
786
+ an email. A topic push is skipped while the user opted out of that topic on
787
+ push, or of all push; a transactional push always goes. The app records the
788
+ opt-outs through `PUT /subscriptions/:userId` (`JourneyClient.setSubscriptions`
789
+ with `{ push: { all?, topics? } }`), which is the in-app switch App Store Review
790
+ Guideline 4.5.4 requires for marketing pushes: `push.all: false` is "no
791
+ promotional notifications", a topic `false` is one category off. The opt-outs are
792
+ per channel: a topic switched off for push is still sent by email.
793
+ `reachable('push')` is a device plus no all-push opt-out; a topic opt-out leaves
794
+ it true. Changing `push.all` wakes the waits on it, as a device change does.
795
+
796
+ Pushes go to the devices the engine keeps. The app registers each token with
797
+ `JourneyClient.registerDevice(userId, { token, platform })`, and a token moves
798
+ to the latest user that registers it. Each platform is turned on by the config,
799
+ with its secret in the environment:
800
+
801
+ | Platform | Config | Secret | Transport |
802
+ | --------- | --------------------------------------------------- | --------------------------------------- | ------------------ |
803
+ | `ios` | `apns: { topic, keyId, teamId, environment? }` | `APNS_PRIVATE_KEY_BASE64` (the `.p8`) | `sendwend/apns` |
804
+ | `android` | `fcm: { androidChannelId? }` | `GOOGLE_APPLICATION_CREDENTIALS_BASE64` | `sendwend/fcm` |
805
+ | `web` | `webPush: { subject, openedEvent?, pushServices? }` | `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` | `sendwend/webpush` |
806
+
807
+ A secret is only read when something is sent on that platform. Only a token
808
+ the provider reports as gone is removed (and waits on `reachable('push')` wake
809
+ on every device change); a refusal for good keeps the device and settles the
810
+ copy undelivered under its reason, without a retry and without failing the
811
+ journey (see [Delivery guarantee](#delivery-guarantee)), and a transient answer
812
+ is retried:
813
+
814
+ | Provider | Token removed, copy settled | Settled, device kept | Refused for good: settled, no retry | Retried |
815
+ | -------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
816
+ | APNs | 410; `Unregistered`, `ExpiredToken` | `BadDeviceToken` (a token or the environment), `DeviceTokenNotForTopic` (a token of another app) | `TopicDisallowed`, `BadTopic`, `MissingTopic`, bad certificate or provider token, other 4xx | 403 `ExpiredProviderToken` (re-signed), 429, 5xx |
817
+ | FCM | `UNREGISTERED`; 404 `NOT_FOUND` | `INVALID_ARGUMENT`, `SENDER_ID_MISMATCH` (a token of another Firebase project) | `THIRD_PARTY_AUTH_ERROR`, other 4xx | 401 (access token re-minted), `QUOTA_EXCEEDED`, `UNAVAILABLE`, 429, 5xx |
818
+ | Web Push | 404, 410; an endpoint that is no push service's | 400, 401, 403, 413, other 4xx (`Refused<status>`) | payload over 3993 bytes (refused before sending) | 429, 5xx |
819
+
820
+ **One device's refusal does not end the journey.** A step that fails without a
821
+ retry fails the instance: the user's other devices are not sent to, and neither
822
+ is anything later in the workflow. So an answer that is about one device — a
823
+ development build's token registered against the production backend is the
824
+ usual one — settles that copy as undelivered, with the reason in the report,
825
+ and the journey goes on. The device is kept: the same answers are what every
826
+ device gives when the deployment's own environment, project or VAPID key is
827
+ wrong, and nothing is deleted on a guess. If a reason in this column shows up
828
+ for every device, it is the configuration. What no device could get past — the
829
+ topic, the certificate, the provider key — is refused for good: that copy is
830
+ settled under its reason too, and the journey goes on (see
831
+ [Delivery guarantee](#delivery-guarantee)).
832
+
833
+ Every APNs request carries `apns-id` and `apns-collapse-id`, and every web
834
+ push a `Topic`, derived from the copy's idempotency key, so the rare copy sent
835
+ again (a template with `redelivery: 'resend'`) collapses on the device; FCM has no
836
+ such header and does not de-duplicate — see [Delivery guarantee](#delivery-guarantee).
837
+ Provider credentials are kept
838
+ per host (`ApnsProviderToken`, `FcmAccessToken`, `VapidSigner`): the APNs
839
+ provider token, the FCM access token and the VAPID key are reused across runs,
840
+ while the senders themselves are built per run.
841
+
842
+ `apns.environment` maps a mode to `sandbox` or `production`; unlisted modes use
843
+ `production` in production and `sandbox` otherwise. Generate a VAPID pair once
844
+ per environment with `generateVapidKeys()` from `sendwend/webpush`.
845
+ `webPush.openedEvent` names the contract event a browser's notification tap is
846
+ also recorded as (`{ message_id }`), so conditions see web opens too.
847
+
848
+ A browser subscription's endpoint is the URL the host POSTs each push to, and
849
+ it is whatever the registering client says. Only an https endpoint on a
850
+ browser's push service is used — `fcm.googleapis.com` (Chrome and the Chromium
851
+ browsers), `*.push.services.mozilla.com` (Firefox), `*.notify.windows.com`
852
+ (Edge) and `*.push.apple.com` (Safari): `POST /devices` answers 400 for any
853
+ other, and one already stored is settled undelivered and forgotten at its next
854
+ send, without a request being made. `webPush.pushServices` names further hosts
855
+ (`'push.example.com'`, or `'*.example.com'` for its subdomains).
856
+
857
+ APNs speaks HTTP/2 only, which `wrangler dev` cannot. Locally, run the relay
858
+ next to it and point the Worker at it with `APNS_RELAY_ORIGIN`:
859
+
9
860
  ```js
10
- import { last, lastAsync } from 'sendwend';
861
+ import { startApnsRelay } from 'sendwend/apns-relay';
862
+
863
+ const relay = await startApnsRelay({ port: 8280 });
864
+ // wrangler dev --var APNS_RELAY_ORIGIN:http://localhost:8280
865
+ ```
866
+
867
+ The relay sees the provider JWT, so production (`ENVIRONMENT` unset or
868
+ `production`) ignores `APNS_RELAY_ORIGIN`: it calls APNs directly and logs one
869
+ `console.error` saying the variable was ignored.
870
+
871
+ ### Slack and Discord
872
+
873
+ Team-channel messages go through incoming webhooks. The URL is a secret, so the
874
+ template reads it from the Worker's environment when it sends. Pass the
875
+ environment's Zod schema to `journeyWorker({ env })`: it is checked on the
876
+ first request, every problem listed, and the parsed values are what templates
877
+ see.
878
+
879
+ ```ts
880
+ import { slackTemplate } from 'sendwend';
881
+ import { optional, strictObject, string } from 'zod/mini';
882
+ import type { Env } from '../env';
883
+
884
+ export default slackTemplate({
885
+ id: 'nps_detractor',
886
+ title: 'NPS detractor (support)',
887
+ props: strictObject({ name: string(), email: optional(string()) }),
888
+ preview: { name: 'John Doe', email: 'john@example.com' },
889
+ webhook: (env: Env) => env.WEBHOOK_SLACK_SUPPORT,
890
+ content: ({ name }) => ({ text: `${name} gave us a low NPS score` }),
891
+ });
892
+ ```
893
+
894
+ `discordTemplate` takes the same fields; its `content` returns a Discord webhook
895
+ body (`content`, `embeds`, `allowed_mentions`, …). Register both under
896
+ `templates: { email, push, slack, discord }`. A request the channel refuses for
897
+ good settles the copy as undelivered rather than retrying, so a team-channel
898
+ post never holds up the messages after it.
899
+
900
+ ### Delivery guarantee
901
+
902
+ A message is delivered **at most once**. Each copy goes through one durable step:
903
+ the copy's row is recorded, the copy is _claimed_ (`message.claimed_at`, committed
904
+ before the send), the transport takes it, and the result is settled
905
+ (`delivered_at` or `undelivered_reason`). On a replay of the step:
11
906
 
12
- last([1, 2, 3]); // 3
13
- last([], 'empty'); // 'empty'
14
- last(new Set(['a', 'b'])); // 'b'
907
+ - a settled copy is skipped;
908
+ - a copy that failed in a way another attempt can fix had its claim released, so
909
+ the retry sends it. That is a provider answering 429 or 5xx, or a sender that
910
+ never got as far as asking: a token that expired, an exchange that timed out;
911
+ - a copy **refused for good** is settled undelivered under the refusal's reason,
912
+ and the journey goes on (see below);
913
+ - a copy that is **claimed but not settled** is treated as possibly delivered and
914
+ is **not sent again**. The run that claimed it died between the transport taking
915
+ the copy and the report (or the step's checkpoint) committing, so no one knows
916
+ whether it went out. The engine logs a warning with the idempotency key,
917
+ settles the copy undelivered as `unconfirmed` and moves on.
15
918
 
16
- async function* values() {
17
- yield 1;
18
- yield 2;
919
+ **A request the provider never answered is not a refusal.** The connection
920
+ dropped or the fetch timed out after the request left: the provider may have
921
+ taken the message, and a second attempt would be a second message. The senders
922
+ that cannot de-duplicate — SES, the Cloudflare Email REST API, FCM, the Slack and
923
+ Discord webhooks — throw an `UnansweredSendError` for it. The engine keeps the
924
+ claim, settles the copy undelivered as `no_answer`, and goes on to the next
925
+ step; nothing is retried. A `fetch` that fails does not say whether it failed
926
+ before or after the request left, so a connection that could not be opened is
927
+ treated the same way, and that copy is lost. APNs and Web Push are retried as
928
+ before, because a repeat collapses on the device, and so is a
929
+ `WebhookMessageSender`, whose receiver de-duplicates on the idempotency key. A
930
+ 2xx whose body cannot be read is a delivery: the status is the answer.
931
+
932
+ **A refusal ends the copy, not the journey.** When no attempt would go
933
+ differently — a `PermanentError`, or a transport error with `retryable: false`:
934
+ the provider refused this token, this address or this payload, or the channel is
935
+ not configured — the copy is settled undelivered under the refusal's reason, an
936
+ error is logged with the provider's answer, and the journey goes on to the user's
937
+ other devices and to the next step. The reason is the provider's own code where
938
+ it gave one (`BadTopic`, `THIRD_PARTY_AUTH_ERROR`, `PayloadTooLarge`, SES's
939
+ `MessageRejected`), `Refused<status>` for a bare status, `bad_credentials`
940
+ or `not_configured` for a secret that is malformed or missing, and `refused`
941
+ for an error that names none. One rejected address or one template whose push
942
+ is too large therefore costs that copy only. So does a deployment-wide
943
+ mistake (a wrong APNs key, a revoked service account): the journeys keep
944
+ running, the later steps still send once it is fixed, and what it cost is the
945
+ count of that reason in the delivery report — watch it, because no instance
946
+ fails for it. A transport of your own names the reason with a `reason` string
947
+ on the error it throws. A template refusing its props or its content still
948
+ fails the step, before the send or inside the sender: that is the workflow, not
949
+ the recipient.
950
+
951
+ `no_answer` and `unconfirmed` are `undelivered_reason`s like any other, so the
952
+ copies at-most-once cost are in the delivery report and can be counted. A
953
+ transport of your own marks the same case by throwing an error with
954
+ `unanswered: true` (or `UnansweredSendError`, `awaitAnswer` from
955
+ `sendwend/engine`). The Cloudflare `send_email` binding is not covered:
956
+ what it throws is taken as a refusal and retried, as before.
957
+
958
+ Exactly-once is not available: Cloudflare Email Service accepts no idempotency
959
+ key or client message id — the `send_email` binding's `send()` takes only the
960
+ addresses, subject, body, headers and attachments and returns a server-generated
961
+ `messageId` ([Workers API](https://developers.cloudflare.com/email-service/api/send-emails/workers-api/)),
962
+ and the REST endpoint is the same — and SES has none either. APNs (`apns-collapse-id`)
963
+ and Web Push (`Topic`) collapse a repeat on the device; FCM does not.
964
+
965
+ Between the two options left, at most once is the one for journeys: a duplicate
966
+ marketing email costs spam complaints, unsubscribes and sender reputation, while a
967
+ lost nudge is invisible to the user and the journey has later steps. Customer.io
968
+ and Braze behave the same way — the delivery record is the source of truth, nothing
969
+ is resent on uncertainty, and frequency caps sit on top. A transactional template
970
+ that must arrive opts into at-least-once per template:
971
+
972
+ ```ts
973
+ emailTemplate({
974
+ id: 'dispute_opened',
975
+ transactional: true,
976
+ redelivery: 'resend', // a duplicate is a nuisance here; a missing copy is a failure
977
+ // ...
978
+ });
979
+ ```
980
+
981
+ `redelivery` (`'skip'` by default, `'resend'` to opt in) exists on every template
982
+ kind — email, push, Slack, Discord. This is a deliberate product decision made on
983
+ 2026-11-10 after reviewing the alternatives (provider-side de-duplication, a
984
+ shorter claim window, resending with a dedupe header): do not change the default
985
+ back to at-least-once; set `redelivery: 'resend'` on the templates that need it.
986
+
987
+ The decision is kept by the host's reporting store: `claimed_at` is a column of
988
+ `message` (hosts upgrading regenerate the drizzle file and migrate, see
989
+ [Postgres](#postgres)). Without a reporting store there is no record between two
990
+ runs of a step, and a replay sends again — the behaviour of every version before.
991
+
992
+ ### Other channels
993
+
994
+ `.sms()`, `.inApp()` and `.survey()` compile, and take a hand-typed reference
995
+ by key: `template.sms<P>(key)` (also `inApp`, `survey`). The config's channels deliver only email, push, Slack and
996
+ Discord; supply anything else with `journeyWorker({ messages })`.
997
+
998
+ ## Configuration
999
+
1000
+ `defineConfig` takes:
1001
+
1002
+ | Field | Holds |
1003
+ | ----------- | ----------------------------------------------------------------------------------------- |
1004
+ | `title` | The Studio title |
1005
+ | `contract` | The `defineContract(...)` every `/ingest` is validated against |
1006
+ | `workflows` | The workflows to deploy |
1007
+ | `segments` | Named segments |
1008
+ | `actions` | Custom actions `.run()` uses |
1009
+ | `templates` | The registries: `{ email?, push?, discord?, slack? }`; topics typed by the contract |
1010
+ | `email` | `{ unsubscribeUrl?, preferencesUrl?, tracking? }`: what every topic email template shares |
1011
+ | `runtime` | Per mode (`development`, `production`, …): `{ timeScale?, logMessages? }` |
1012
+ | `apns` | `{ topic, keyId, teamId, environment? }` |
1013
+ | `fcm` | `{ androidChannelId? }` |
1014
+ | `webPush` | `{ subject, openedEvent?, pushServices? }` |
1015
+ | `database` | `{ schema? }`: the Postgres schema, `workflow` by default |
1016
+
1017
+ The `ENVIRONMENT` var picks the `runtime` entry (production when unset).
1018
+ `timeScale` fast-forwards every duration: 600 turns "1 day" into 2.4 minutes. Time windows are
1019
+ times of day and cannot be compressed, so a scaled journey skips them instead of sleeping until
1020
+ the morning. The `production`
1021
+ entry's type holds it at `1` (`ProductionRuntimeOptions`): a development factor pasted under the
1022
+ production key is a compile error, not every user's journey compressed. A deploy meant to run fast
1023
+ is not production: give it a mode of its own (`ENVIRONMENT=rehearsal`), as free as `development`.
1024
+ Secrets never go in the config; the Worker reads them from its environment:
1025
+
1026
+ | Variable | Purpose |
1027
+ | --------------------------------------- | ---------------------------------------------------------- |
1028
+ | `API_TOKEN` | Bearer for every endpoint but `/health` and `/t/...` |
1029
+ | `WORKFLOW_ORIGIN` | Public origin for email tracking and push delivery reports |
1030
+ | `ENVIRONMENT` | Which `runtime` entry and APNs environment apply |
1031
+ | `APNS_PRIVATE_KEY_BASE64` | The APNs `.p8` key, base64 |
1032
+ | `GOOGLE_APPLICATION_CREDENTIALS_BASE64` | The Firebase service account JSON, base64 |
1033
+ | `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` | The Web Push key pair |
1034
+ | `APNS_RELAY_ORIGIN` | Development only: the local APNs relay |
1035
+
1036
+ `journeyWorker` (and `journeyLambda`) also take `messages` and `runtime` overrides, an
1037
+ `observer`, `contractMode: 'report'` to log contract refusals instead of answering 400, and
1038
+ `authorize` to replace the `API_TOKEN` bearer with a check of your own (see
1039
+ [AWS deployment notes](#aws-deployment-notes)).
1040
+
1041
+ An `observer` is added to the store's own, not put in its place: the store keeps recording
1042
+ (its claim is what delivers a copy [at most once](#delivery-guarantee)), and your hooks run after
1043
+ its own. Only an observer that decides delivery itself — one that implements `messageSettled`,
1044
+ `messageClaimed` and `messageReleased`, such as `reportingObserver(...)` spread into an object
1045
+ of your own — is used alone.
1046
+
1047
+ ## `JourneyClient`
1048
+
1049
+ `sendwend/client` is the producer side: plain fetch, no dependencies.
1050
+ With a `contract`, event names and payloads are typed and checked before
1051
+ anything is sent (a refusal throws `JourneyValidationError`); a failed request
1052
+ throws `JourneyClientError` with its status and body.
1053
+
1054
+ ```ts
1055
+ const journeys = new JourneyClient({ contract, origin, token });
1056
+ ```
1057
+
1058
+ | Method | Endpoint | Does |
1059
+ | --------------------------------------------------------------------- | --------------------------------- | ---------------------------------------------------------------------------------- |
1060
+ | `ingest({ userId?, visitorId?, profile?, events? })` | `POST /ingest` | The one way in: merge a visitor, then the profile, then record the events in order |
1061
+ | `registerDevice({ deviceId?, userId?, visitorId?, token, platform })` | `POST /devices` | Register a push token for whoever holds the device now |
1062
+ | `unbindDevice(token)` | `POST /devices/unbind` | Signed out: the token stays, bound to nobody |
1063
+ | `removeDevice(token)` | `POST /devices/remove` | Forget a token for good |
1064
+ | `messageOpened(userId, messageId)` | `POST /messages/opened` | A journey push tapped open (the `message_id` it carried) |
1065
+ | `getSubscriptions(userId)` | `GET /subscriptions/…` | `{ email, push }`, each `{ all, topics }`, `true` = on |
1066
+ | `setSubscriptions(userId, patch)` | `PUT /subscriptions/…` | Change what the patch names; answers the new state |
1067
+ | `getSubscriptionsByMessage(messageId)` | `GET /subscriptions/by-message/…` | The recipient's record by a copy's id, plus `message: { channel, topic }` |
1068
+ | `setSubscriptionsByMessage(messageId, patch)` | `PUT /subscriptions/by-message/…` | The same patch, for the copy's recipient; answers as the GET does |
1069
+ | `forgetUser(userId)` | `POST /users/forget` | Stop the user's journeys and erase their data |
1070
+ | `forgetVisitor(visitorId)` | `POST /users/forget` | The same for a visitor who never signed in |
1071
+ | `deploy(bundle)` | `POST /deploy` | Deploy a compiled bundle (development; a production host with its own answers 409) |
1072
+
1073
+ Pass each event's `id` whenever a caller may retry; see
1074
+ [Give each event an `id`](#give-each-event-an-id).
1075
+
1076
+ `ingest` is the only way to report: the profile and the events it belongs to travel
1077
+ as one batch, so a journey an event starts always finds its recipient. With separate
1078
+ calls an email step could run before the address arrives and settle as `no_recipient`.
1079
+
1080
+ ### Visitors and devices
1081
+
1082
+ Three ids, with different jobs:
1083
+
1084
+ | Id | What it says | At sign-out |
1085
+ | ----------- | ------------------------------- | ---------------- |
1086
+ | `userId` | Which account | No longer sent |
1087
+ | `visitorId` | Who this is before signing in | Must be replaced |
1088
+ | `deviceId` | Which device holds a push token | Stays |
1089
+
1090
+ `visitorId` is any stable id for one client, as long as it changes when a user signs
1091
+ out; `visitorId()` from `@shware/analytics` already does. Journeys and events belong
1092
+ to a user or a visitor, never to a device: one device can pass between people.
1093
+
1094
+ ```ts
1095
+ await journeys.ingest({ visitorId, events }); // not signed in
1096
+ await journeys.ingest({ userId, visitorId, profile, events }); // signed in
1097
+ await journeys.registerDevice({ deviceId, visitorId, token, platform });
1098
+ ```
1099
+
1100
+ Naming both ids says this visitor is this user. Their events, profile, devices and
1101
+ opt-outs move to the user, once, and a later report of that visitor reaches the user.
1102
+ A visitor already linked stays with its first user. Their running journeys carry on
1103
+ as the user's, except one the user is already in, which stops.
1104
+
1105
+ A visitor enters a workflow only if its trigger asks for them. They have no address,
1106
+ so such a journey reaches them by push, and an entry made as a visitor counts as the
1107
+ user's once they sign in, against the workflow's `reentry` policy like any other:
1108
+
1109
+ ```ts
1110
+ workflow({
1111
+ id: 'offer',
1112
+ reentry: { mode: 'never' },
1113
+ trigger: trigger.event(e.browse, { visitors: true }),
1114
+ });
1115
+ ```
1116
+
1117
+ Segments are about users: visitors are not swept and do not enter segment triggers.
1118
+
1119
+ A visitor who never signs in is deleted 90 days after they were last heard from, unless
1120
+ a journey of theirs is still running. A link to a user is kept, so late reports still
1121
+ reach the user and, once the user is erased, are refused.
1122
+
1123
+ A device table row holds only the current owner, so after a sign-out the previous user
1124
+ can no longer be reached there. `unbindDevice` clears it at sign-out; the client then
1125
+ registers again with its new `visitorId`.
1126
+
1127
+ ### `JourneyQueue`
1128
+
1129
+ `JourneyQueue` sends the same batch through a queue, for a producer that must
1130
+ neither lose a report nor wait for the engine:
1131
+
1132
+ ```ts
1133
+ const queue = new JourneyQueue({ contract, queue: env.JOURNEY_QUEUE });
1134
+ await queue.ingest({
1135
+ userId,
1136
+ visitorId,
1137
+ profile: { email, name },
1138
+ events: [{ event: 'login', payload: { method }, id: rowId, ts }],
1139
+ });
1140
+ ```
1141
+
1142
+ Once `ingest` resolves the batch is durable. A rejection means it was not queued,
1143
+ and the caller decides what follows. Export `journeys.queue` from the Worker and
1144
+ declare the queue with a dead letter queue:
1145
+
1146
+ ```jsonc
1147
+ "queues": {
1148
+ "consumers": [
1149
+ { "queue": "journey", "max_retries": 8, "dead_letter_queue": "journey-dead" }
1150
+ ]
19
1151
  }
1152
+ ```
1153
+
1154
+ The consumer retries a failed batch with a backoff from 30 seconds up to 15
1155
+ minutes. A batch the contract refuses is retried the same way, logging its field
1156
+ paths: the contract is the host's version of it, so a producer deployed ahead of
1157
+ the host passes once the host catches up, and what never does ends in the dead
1158
+ letter queue rather than dropped. Only a batch for an erased user is acknowledged
1159
+ unapplied. Delivery is at least once
1160
+ and in no guaranteed order. Batches can arrive out of order, but event ids absorb
1161
+ repeats and each profile property keeps its latest `at`, so send what must stay
1162
+ in order as one batch.
1163
+
1164
+ `getSubscriptions` and `setSubscriptions` are typed by the contract's
1165
+ `subscriptions.topics`, and a topic it does not declare is refused before the
1166
+ request. The record is topic × channel: `email` and `push` each list every
1167
+ topic. A preference page is a thin proxy over them:
1168
+
1169
+ ```ts
1170
+ const { email, push } = await journeys.getSubscriptions(userId);
1171
+ // email: { all: false, topics: { promotions: false, newsletter: true, tips: true } }
1172
+ // push: { all: true, topics: { promotions: true, newsletter: true, tips: true } }
1173
+ // `all: false` masks every topic: newsletter reads true, but no email is sent until `all` is
1174
+ // true again. Each flag is its own record, so a preference page shows `all` as the master
1175
+ // switch and the topics as they are. Push is untouched by the email record.
1176
+ await journeys.setSubscriptions(userId, { email: { all: true } });
1177
+ // email: { all: true, topics: { promotions: false, newsletter: true, tips: true } }
1178
+ // `all: true` cleared only the all-email opt-out; promotions stays off until named:
1179
+ await journeys.setSubscriptions(userId, { email: { topics: { promotions: true } } });
1180
+ await journeys.setSubscriptions(userId, { email: { all: false } }); // unsubscribe from everything
1181
+ await journeys.setSubscriptions(userId, { push: { all: false } }); // the in-app "no promotional pushes"
1182
+ await journeys.setSubscriptions(userId, { push: { topics: { promotions: false } } }); // one category off, on push only
1183
+ ```
1184
+
1185
+ A "subscribe to all" button sends `all: true` plus every topic `true`; an
1186
+ "unsubscribe from all" sends `all: false` and leaves the topics as they are, so
1187
+ turning `all` back on restores the user's own choices.
1188
+
1189
+ The same page opened from an email's footer, with no session, reads the `m` query parameter the
1190
+ `preferencesUrl` link carries and goes by the copy instead of the user (see
1191
+ [Email](#email)); a 404 (`JourneyClientError` with `status` 404) is an expired link:
1192
+
1193
+ ```ts
1194
+ // GET /api/email-preferences?m=<message id>, proxied by the app's API, rate-limited there
1195
+ const { email, push, message } = await journeys.getSubscriptionsByMessage(m);
1196
+ // message: { channel: 'email', topic: 'promotions' } — the email this page was opened from
1197
+ await journeys.setSubscriptionsByMessage(m, { email: { topics: { [message.topic]: false } } });
1198
+ ```
1199
+
1200
+ ## Compiling and planning
1201
+
1202
+ `compileConfig(config)` returns the `BundleIR` the Worker deploys. It is
1203
+ `compileBundle` plus a template manifest generated from the registries, and it
1204
+ checks every message node: an unregistered or cross-channel template, a missing
1205
+ or undeclared prop, a literal the schema refuses, or a `u.xxx` the contract's
1206
+ profile does not declare fails with the workflow and node named
1207
+ (`ConfigCompileError`).
1208
+
1209
+ `compileBundle({ workflows, segments?, templates?, actions? })` is the lower
1210
+ level: it compiles each workflow, rejects duplicate ids, segment references
1211
+ missing from the bundle, payload predicates outside a `where`, and actions that
1212
+ are not passed in.
1213
+
1214
+ ```ts
1215
+ import { compileConfig, plan } from 'sendwend';
1216
+ import config from './workflow.config';
1217
+
1218
+ const bundle = compileConfig(config);
1219
+ const changes = plan(bundle, deployedBundle); // deployed: `GET /bundle` of the running Worker
1220
+ if (changes.hasChanges) console.log(changes.workflows.filter((w) => w.status !== 'unchanged'));
1221
+ ```
1222
+
1223
+ `plan(local, deployed?)` diffs workflows, segments, templates and actions.
1224
+ Each change is `added`, `removed`, `changed`, `metadata_only` or `unchanged`,
1225
+ and a workflow change lists the fields (`trigger`, `goal`, `exitWhen`) and
1226
+ nodes that moved. Omitting `deployed` plans a first deploy.
1227
+
1228
+ ## Versioning
1229
+
1230
+ Every workflow carries a `contentHash` over its own IR, with metadata excluded,
1231
+ so a reworded description is not a new version but a changed delay is. The hash
1232
+ is the address the IR is stored under, and a journey is pinned to the hash it
1233
+ entered on. An in-flight journey therefore finishes on the version it started,
1234
+ however many times you deploy underneath it.
1235
+
1236
+ The pin covers the workflow's structure and nothing else, on purpose. The IR
1237
+ names a template by channel and key, a segment or an action by id, and each is
1238
+ resolved when the journey reaches it, against the deployed bundle and the code
1239
+ serving it:
1240
+
1241
+ - **Templates: the latest content goes out.** A typo fixed in an email reaches
1242
+ everyone, including the journeys that entered before the fix. So does what
1243
+ the template says about itself: a send checks the opt-out of the `topic` the
1244
+ template declares now, and follows its `redelivery` as it is now, so the
1245
+ topic a copy is checked against is the one its unsubscribe link names.
1246
+ - **Segments: a segment is a live audience.** A `branch` or `waitUntil` on a
1247
+ segment asks whether the user is in it _now_, under the deployed condition.
1248
+ A changed condition starts no journey by itself: the people it newly covers
1249
+ are recorded as members of a segment a `trigger.enters` waits on, not entered
1250
+ into it (Triggers, "Entering a segment is not being in it").
1251
+ - **Actions: the current handler runs.** Their code ships in the Worker, never
1252
+ in IR.
1253
+
1254
+ That is how marketing automation behaves, and the engine does not try to
1255
+ improve on it. Customer.io lets people already in a campaign continue their
1256
+ journey when its trigger changes, re-evaluates them when a segment filter
1257
+ changes, and sends the saved version of a message to those who have not
1258
+ reached it yet. Braze's Canvas creates a new version on every update and moves
1259
+ the people already in it onto the new version. Iterable switches people in a
1260
+ published journey to the new version as they finish their current step, and
1261
+ exits those sitting in a deleted tile. Durable-execution engines sit at the
1262
+ other end, for another reason: Temporal's _pinned_ mode and AWS Lambda durable
1263
+ functions keep an execution on the code version it started on so that replay
1264
+ stays deterministic — a property of code, not of content. (Sources at the end
1265
+ of this section.)
1266
+
1267
+ What a deploy must never do is take away something a pinned IR still names: a
1268
+ template removed or moved to another channel, a new required prop the pinned
1269
+ props do not supply, a segment or an action no longer in the bundle, a field of
1270
+ the triggering event's payload a journey reads gone from the contract, an event a
1271
+ journey emits or still waits for (a `waitUntil`, `exitWhen`, the goal) no longer
1272
+ in the contract. A running journey would reach that node and fail, or wait for
1273
+ something that can no longer arrive. So before any write, a deploy holds the
1274
+ bundle — and the templates of the code deploying it — against the IRs journeys
1275
+ are still running on (`checkInFlight`) and refuses with `InFlightError`: a 409
1276
+ on `POST /deploy` and `POST /bundle/deploy`, listing each pinned version, how
1277
+ many journeys it carries and what breaks. A compatible change passes: a
1278
+ reworded template, a new optional prop, a segment whose condition changed.
1279
+ `?force=1` deploys anyway and reports what it broke in `inFlight`. This is the
1280
+ engine's counterpart to Temporal's replay test in CI and to the publish-time
1281
+ rules of the UI products (Braze refuses some edits on a live Canvas, Iterable
1282
+ settles what happens to people in a deleted tile); it is cheap here because IR
1283
+ is declarative — the message node is checked against the schema, no history
1284
+ has to be replayed.
1285
+
1286
+ On Cloudflare a published version's code serves at once, whether or not its
1287
+ bundle is applied, and Workflows does not document whether a running instance
1288
+ resumes on the version it started on — so run the same check _before_
1289
+ publishing: `sendwend-studio plan --database-url …` compiles the project, reads the
1290
+ pinned IRs from the database and exits non-zero on a problem — put it in CI
1291
+ ahead of `wrangler deploy`. `journeyWorker` runs the check again when a version
1292
+ applies its own bundle and leaves the routes alone when it fails (an error is
1293
+ logged; `POST /bundle/deploy?force=1` applies it regardless). On AWS the
1294
+ platform pins each execution to the published function version, so a template
1295
+ change cannot reach a running journey there; the segment and action checks
1296
+ still matter, since those come from the database.
1297
+
1298
+ `plan()` diffs a compiled bundle against what is deployed and reports which
1299
+ workflows actually changed. Deploy recomputes every declared hash and refuses a
1300
+ bundle whose hashes do not describe its contents.
1301
+
1302
+ Node ids are structural paths, so inserting a node shifts the ids of the nodes
1303
+ after it.
1304
+
1305
+ Sources: Customer.io, [Edit triggers, filters, or frequencies in live
1306
+ automations](https://docs.customer.io/journeys/campaign-changes/) and [Workflow
1307
+ changes](https://docs.customer.io/journeys/workflow-changes/); Braze, [Canvas
1308
+ version
1309
+ history](https://www.braze.com/docs/user_guide/messaging/canvas/managing_canvases/canvas_version_history)
1310
+ and [Edit Canvases after
1311
+ launch](https://www.braze.com/docs/user_guide/engagement_tools/canvas/managing_canvases/change_your_canvas_after_launch/);
1312
+ Iterable, [Editing
1313
+ journeys](https://support.iterable.com/hc/en-us/articles/18346367178644-Editing-Journeys);
1314
+ Temporal, [Worker
1315
+ versioning](https://docs.temporal.io/production-deployment/worker-deployments/worker-versioning);
1316
+ AWS, [Invoking Lambda durable
1317
+ functions](https://docs.aws.amazon.com/lambda/latest/dg/durable-invoking.html).
1318
+
1319
+ ## Re-entry
1320
+
1321
+ Every workflow says whether a user who already entered it may enter again. The
1322
+ option is required:
1323
+
1324
+ ```ts
1325
+ workflow({ id: 'onboarding', trigger: trigger.event(e.sign_up), reentry: { mode: 'never' } });
1326
+ workflow({
1327
+ id: 'checkout_recovery',
1328
+ trigger: trigger.event(e.begin_checkout),
1329
+ reentry: { mode: 'after_exit', cooldown: '7 days' },
1330
+ });
1331
+ workflow({
1332
+ id: 'nps_followup',
1333
+ trigger: trigger.event(e.nps_sent),
1334
+ reentry: { mode: 'after_exit' },
1335
+ });
1336
+ workflow({
1337
+ id: 'purchase_thanks',
1338
+ trigger: trigger.event(e.purchase),
1339
+ reentry: { mode: 'concurrent' },
1340
+ });
1341
+ ```
1342
+
1343
+ | Mode | A user enters again… |
1344
+ | ------------ | ----------------------------------------------------------------------------------- |
1345
+ | `never` | never: once per user (onboarding, a welcome series) |
1346
+ | `after_exit` | once their previous instance of this workflow has ended; at most one runs at a time |
1347
+ | `concurrent` | even while a previous instance still runs |
1348
+
1349
+ An instance has ended when it completed, reached its goal, exited (an `exit`
1350
+ step or `exitWhen`) or failed. `cooldown` (optional, positive, `after_exit` and
1351
+ `concurrent` only) is the least time from the user's **previous entry** to the
1352
+ next one — measured from when they entered, not from when they left. With
1353
+ `after_exit` the two are independent conditions and both must hold: the previous
1354
+ instance has ended, and the cooldown since its entry has passed. A trigger that
1355
+ arrives while the policy refuses it is dropped, not queued.
1356
+
1357
+ - **Event triggers**: each occurrence is one entry attempt. A redelivered event
1358
+ (the same `id`, see [Give each event an `id`](#give-each-event-an-id)) is the
1359
+ same occurrence and enters at most once, in every mode.
1360
+ - **Segment triggers**: an entry attempt is a fresh qualification — the user
1361
+ left the segment and matched again. Staying a member never enters again, however
1362
+ often the segment is evaluated (Customer.io's rule for segment-triggered
1363
+ campaigns).
1364
+ - An instance that failed (its start was lost, the platform ended it) records an
1365
+ outage, not a journey: it neither blocks re-entry nor starts a cooldown, in
1366
+ every mode. A retry of the same occurrence takes its row over; any other
1367
+ occurrence is a new entry if the policy allows it.
1368
+
1369
+ Cross-workflow frequency capping (no more than N messages a week across every
1370
+ journey) is a separate concern, not part of re-entry.
1371
+
1372
+ ### Why it looks like this
1373
+
1374
+ **Required, with no default.** Once and every-time are both reasonable defaults,
1375
+ and whichever one is picked is wrong for the other half of workflows — silently.
1376
+ A recurring workflow that enters each user once looks healthy and simply stops
1377
+ reaching anyone who already went through it. A required field makes the policy
1378
+ visible where the workflow is defined, and an omitted one is a compile error, not
1379
+ a production surprise.
1380
+
1381
+ **A discriminated union with a single written form.** The policy is always an
1382
+ object naming its `mode`; there is no `'never'` string shorthand and no `{}`
1383
+ meaning "allowed". Impossible combinations cannot be written: `never` takes no
1384
+ `cooldown`, an unknown mode does not compile, and plain JavaScript callers get
1385
+ the same refusal at compile time (`toIR()`). One form keeps the DSL and the IR
1386
+ identical (`WorkflowIR.reentry` is exactly what you wrote, with the cooldown
1387
+ normalised like every duration), and `grep "mode: 'concurrent'"` finds every
1388
+ workflow that allows parallel journeys.
1389
+
1390
+ **`reentry`, one word.** It is one English word, spelled like the existing
1391
+ `redelivery` option on templates — not `reEntry`.
1392
+
1393
+ ### How other products do it
1394
+
1395
+ These products document behaviour, not storage; the per-entry ledger keyed by
1396
+ the trigger occurrence (below) is this package's own choice, driven by the
1397
+ engine's idempotent ingest and at-most-once entry.
1398
+
1399
+ - **Salesforce Marketing Cloud Journey Builder** offers three contact-entry
1400
+ modes: no re-entry, re-entry only after exiting, and re-entry anytime
1401
+ ([Trailhead](https://trailhead.salesforce.com/content/learn/modules/journey-builder-campaigns/build-a-journey-campaign)).
1402
+ Our modes map 1:1. The third is called `concurrent` here because "anytime"
1403
+ reads as contradicting a cooldown.
1404
+ - **Adobe Journey Optimizer** has "Allow re-entrance" plus a "Re-entrance wait
1405
+ period", and a profile cannot re-enter until it fully exited the previous
1406
+ instance
1407
+ ([journey properties](https://experienceleague.adobe.com/en/docs/journey-optimizer/using/orchestrate-journeys/create-journey/journey-properties),
1408
+ [entry management](https://experienceleague.adobe.com/en/docs/journey-optimizer/using/orchestrate-journeys/manage-journey/entry-management)).
1409
+ Adobe's B2B product measures the wait from either the start or the end of the
1410
+ journey
1411
+ ([B2B re-entry](https://experienceleague.adobe.com/en/docs/journey-optimizer-b2b/user/journeys/journey-re-entry));
1412
+ we measure only from entry, which is simpler. A `cooldownFrom` could be added
1413
+ later without breaking anything.
1414
+ - **Braze Canvas** has "Allow users to re-enter this Canvas" with a
1415
+ re-eligibility window counted from entry; being re-eligible and being blocked
1416
+ because the user is still inside are separate, and a zero window allows
1417
+ re-entry without exiting
1418
+ ([re-eligibility](https://www.braze.com/docs/user_guide/messaging/messaging_fundamentals/re_eligibility),
1419
+ [troubleshooting](https://braze.com/docs/user_guide/messaging/canvas/troubleshooting/)).
1420
+ That separation is our `after_exit` versus `concurrent`, with `cooldown` as
1421
+ the window.
1422
+ - **Iterable** has a simultaneous-entries setting (unlimited is capped at 1,000
1423
+ per user) and a maximum number of entries, documented for scheduled entry
1424
+ sources
1425
+ ([journey entry](https://support.iterable.com/hc/articles/5367225442324),
1426
+ [entry limits](https://community.iterable.com/product-updates/new-options-for-journey-entry-limits-1204)).
1427
+ We did not add a maximum-entries field: only one of these products has it and
1428
+ no current workflow needs it. It can be added later as an optional field on the
1429
+ non-`never` branches without breaking callers.
1430
+ - **Customer.io** enters a person once by default, or on every event;
1431
+ segment- and attribute-triggered campaigns re-enter only after the person
1432
+ stops matching and matches again; and it offers re-entry at fixed intervals
1433
+ ([campaign triggers](https://docs.customer.io/journeys/campaign-triggers/),
1434
+ [troubleshooting entrance](https://docs.customer.io/journeys/troubleshoot-campaign-entrance/)).
1435
+ Our segment-trigger rule follows the same re-match edge; fixed intervals were
1436
+ not added.
1437
+
1438
+ ### How it is stored
1439
+
1440
+ The entry ledger (`entry`) holds one row per entry: the instance it started, its
1441
+ status (`running` until the run finalizes it), its anchor `ts` and the
1442
+ triggering `occurrence` — the event id, or `$segment:<segment>:<since>` for a
1443
+ segment qualification. The re-entry decision reads the user's rows of the
1444
+ workflow under the user's lock, so concurrent ingests are admitted exactly as
1445
+ they would be one after another, and the unique key `(workflow, user_id,
1446
+ occurrence)` keeps a redelivered trigger from entering twice. The deploy guard
1447
+ counts `running` rows (one per running instance), and an erasure deletes every
1448
+ row of the user. Each route (`trigger`, `segment_trigger`) carries the workflow's
1449
+ policy as deployed, so deciding an entry reads no IR.
1450
+
1451
+ ## Cloudflare setup
1452
+
1453
+ The Worker needs two bindings, named as in `JourneyEnv` and the quick start's `wrangler.jsonc`:
20
1454
 
21
- await lastAsync(values()); // 2
22
- await lastAsync([Promise.resolve(1), Promise.resolve(2)]); // 2
1455
+ | Binding | Type | Holds |
1456
+ | ------------ | ---------- | ----------------------------------------------------------- |
1457
+ | `JOURNEY` | Workflow | The `JourneyRunner` entrypoint |
1458
+ | `HYPERDRIVE` | Hyperdrive | The connection to the engine's Postgres (`postgresJsStore`) |
1459
+
1460
+ The Worker needs the `nodejs_compat` compatibility flag (the bearer check uses
1461
+ `node:crypto`'s `timingSafeEqual`). Add the `EMAIL` send_email binding
1462
+ when it sends through Cloudflare Email (`cloudflareEmailTransport({ binding: env.EMAIL })`), and a `triggers.crons` entry with `scheduled`
1463
+ exported to run the segment sweep.
1464
+
1465
+ Set `API_TOKEN` in production: a host whose `ENVIRONMENT` resolves to `production` refuses every
1466
+ request but `GET /health` and `/t/...` with a 503 until it is set. Running open has to be asked
1467
+ for by name, for local work only — `/deploy` rewrites the whole routing table: `development`,
1468
+ `test`, or a mode with a `runtime` entry of its own in the config (`rehearsal`). Any other value
1469
+ is held to production's rule, so a typo (`prod`, `Production`) is refused, not served open. In production a
1470
+ host that carries its bundle (`journeyWorker`, the AWS host) refuses `POST /deploy` with a 409:
1471
+ it deploys by publishing a version (the new version applies its own bundle on its first request;
1472
+ `POST /bundle/deploy` re-applies it after a rollback), so a bundle posted by hand there could only
1473
+ be a leaked bearer at work. The bare `handleRequest` API carries none and still takes one.
1474
+
1475
+ Erasing a user (`POST /users/forget`) commits an erasure tombstone first,
1476
+ which every write about the user is conditional on from then on. A runner
1477
+ admits itself against that tombstone before its first effect — before the
1478
+ observer hears of it, before any action or send — on every invocation and on
1479
+ every replay after an eviction, never from a checkpoint: an instance whose
1480
+ `create` lands after the tombstone, or that wakes after it, exits without
1481
+ running. The erasure stops the admitted instances (`terminate`), and only once
1482
+ each is known stopped deletes the data; `erased: true` means every admitted
1483
+ runner was confirmed stopped, the entries never admitted can never run, and
1484
+ the data is gone. An admitted instance that will not stop answers
1485
+ `erased: false` and the scheduled sweep retries it. Every write about the user
1486
+ runs in the user's locked transaction, the lock the tombstone itself takes: a
1487
+ write either committed before the tombstone and is deleted by the erase, or
1488
+ waited for the lock and is refused by the tombstone it then sees. There is no
1489
+ window to come back for and no second pass; the tombstone stays, so a late
1490
+ write cannot bring the user back.
1491
+
1492
+ One database per host. The routing tables are global (`triggers`, `segments`, the live
1493
+ `deployment` row), so two Workers on one Postgres schema would swap each other's routes on
1494
+ every deploy: give staging and production their own schema (`database: { schema }`) or
1495
+ database.
1496
+
1497
+ ### Cloudflare deployment notes
1498
+
1499
+ - **Email transport.** Pass `email` explicitly: `cloudflareEmailTransport({ binding: env.EMAIL })`
1500
+ for Cloudflare Email, or `sesEmailTransport({ region, credentials })` with credentials from the
1501
+ Worker's env, since a Worker has no execution role. A Worker whose workflows email without one
1502
+ fails at startup.
1503
+ - **List-Unsubscribe.** Cloudflare Email rejects a `List-Unsubscribe` header with a non-TLS URI, so
1504
+ the one-click header is only sent with an https `WORKFLOW_ORIGIN`. `wrangler dev` on
1505
+ `http://localhost` sends none.
1506
+ - **Workflows limits** (paid plan):
1507
+ - An instance's wall time is unlimited.
1508
+ - A single `step.sleep` lasts at most 365 days.
1509
+ - 10,000 steps per instance by default, configurable up to 25,000. Sleeps do not count, but every
1510
+ wait attempt costs a few steps.
1511
+ - A step's result is at most 1 MiB.
1512
+ - A completed instance's state is kept 7 days by default, and up to 30 on a paid plan.
1513
+ - **Authorization.** Set `API_TOKEN` with `wrangler secret put`, or pass `authorize` (below).
1514
+ The tracking routes (`/t/...`) stay public by design.
1515
+ - **Deploying.** With the `CF_VERSION_METADATA` binding, each `wrangler deploy` makes its own
1516
+ bundle live (see [Postgres](#postgres)); `POST /bundle/deploy` forces it.
1517
+ - **APNs in development.** `wrangler dev` (workerd) cannot make HTTP/2 subrequests: run
1518
+ `sendwend/apns-relay` and point `APNS_RELAY_ORIGIN` at it. A deployed Worker needs no
1519
+ relay, and production ignores the variable.
1520
+
1521
+ ## AWS Lambda
1522
+
1523
+ The same config runs as one Lambda durable function behind a Function URL, on
1524
+ Postgres. `@aws/durable-execution-sdk-js` and `@aws-sdk/client-lambda` are optional
1525
+ peer dependencies, needed only by `sendwend/aws`. The durable SDK's own type
1526
+ declarations reference `aws-lambda`, so a TypeScript project that type-checks
1527
+ dependencies (no `skipLibCheck`) also needs `@types/aws-lambda`.
1528
+
1529
+ ```ts
1530
+ // src/aws.ts
1531
+ import { journeyLambda } from 'sendwend/aws';
1532
+ import { postgresJsStore } from 'sendwend/postgres-js';
1533
+ import { sesEmailTransport } from 'sendwend/transports/ses';
1534
+ import config from '../workflow.config';
1535
+ import { env } from './env.aws'; // process.env, parsed with zod
1536
+
1537
+ const journeys = journeyLambda({
1538
+ config,
1539
+ env,
1540
+ store: (env, database) => postgresJsStore(env.DATABASE_URL, database),
1541
+ email: (env) => sesEmailTransport({ region: env.AWS_REGION }),
1542
+ });
1543
+
1544
+ export const handler = journeys.handler;
1545
+ ```
1546
+
1547
+ One handler serves three inputs, told apart by the event's top-level shape, so
1548
+ no HTTP body can pass for the others:
1549
+
1550
+ - **A Function URL request**: the HTTP API, as on Cloudflare. A journey it
1551
+ starts is its own durable execution, submitted with an asynchronous `Invoke`
1552
+ of this function's numbered version under a stable execution name, and the
1553
+ request returns.
1554
+ - **A run** (`$workflow.run`): one instance. Steps, delays and waits map onto
1555
+ the durable SDK's `step`, `wait` and callbacks; a wait parks on a fresh
1556
+ callback, recorded in Postgres, which the next relevant event completes.
1557
+ - **A sweep** (`{ "type": "$workflow.sweep" }`, from EventBridge Scheduler, or
1558
+ `POST /segments/sweep` from an existing cron): the segment sweep, plus
1559
+ retrying starts whose submit was never confirmed and reconciling executions
1560
+ the platform ended (timeout, stop) into the ledger. Without one, clock-only
1561
+ segments and this upkeep do not happen.
1562
+
1563
+ A start is recorded with its entry in one transaction (the `execution` table),
1564
+ so a lost `Invoke` response is retried with the same name and payload and never
1565
+ re-entered as a second execution. Retries stop after 12 hours (`startRetryMs`,
1566
+ keep it under the execution retention) and the start is left unresolved. A
1567
+ failed entry that is entered again gets a new execution, never the closed one.
1568
+
1569
+ Erasing a user (`POST /users/forget`) commits the tombstone, stops their
1570
+ admitted executions, then waits `stopDrainMs` (15 minutes by default; at least
1571
+ the function's timeout) before erasing: a stop does not interrupt an invocation
1572
+ already running, which goes on to its next checkpoint. Until then the erasure
1573
+ answers `erased: false` and the sweep finishes it; the drain is one judgment
1574
+ for every path — the sweep's reconcile keeps a stopped execution's entry
1575
+ `running` until the drain has passed, and an execution the platform reports
1576
+ stopped before the stop was recorded is dated at its first sighting, never
1577
+ later. An execution whose runner never admitted itself needs no stop: its run
1578
+ entry meets the tombstone and exits, and so does a wake of a stopped one. The
1579
+ tombstone takes the user's lock, which every write about the user also takes,
1580
+ so nothing of theirs lands after it and no second pass is needed.
1581
+
1582
+ Deploy one artifact per version: publish a numbered version and point the
1583
+ `live` alias, which the Function URL is bound to, at it. Each version carries its
1584
+ compiled bundle and makes it live by itself, only over an older one. Each route
1585
+ records the version that applied it, and an instance it starts runs on that
1586
+ version, so its IR and its code always match, even while an older version is
1587
+ still serving; executions stay on the version that started them. `POST /deploy` of an arbitrary bundle is
1588
+ refused.
1589
+
1590
+ ```yaml
1591
+ Workflow:
1592
+ Type: AWS::Serverless::Function
1593
+ Properties:
1594
+ Runtime: nodejs24.x
1595
+ Handler: aws.handler
1596
+ Timeout: 60
1597
+ AutoPublishAlias: live
1598
+ # ExecutionTimeout: the longest journey (waits, delays and the goal window), up to 366 days;
1599
+ # pass the same value to journeyLambda({ executionTimeoutMs }) to check it at startup
1600
+ DurableConfig: { ExecutionTimeout: 2592000, RetentionPeriodInDays: 30 }
1601
+ FunctionUrlConfig: { AuthType: NONE, InvokeMode: BUFFERED }
1602
+ ```
1603
+
1604
+ ### AWS deployment notes
1605
+
1606
+ Checked against a real durable Lambda (Node 24, us-east-1).
1607
+
1608
+ **Function URL: `AuthType: NONE`, with the API protected in the app.** Not every caller can
1609
+ sign a request:
1610
+
1611
+ | Caller | Routes |
1612
+ | ------------------------------------------ | ------------------------------------------- |
1613
+ | Your backend | `/ingest`, `/devices`, `/users/forget`, ... |
1614
+ | Recipients' mail clients and browsers | `/t/o`, `/t/l`, `/t/u` |
1615
+ | Gmail / Yahoo one-click unsubscribe | `POST /t/u/<message>` (RFC 8058) |
1616
+ | iOS notification extension, service worker | `POST /t/d`, `POST /t/p` |
1617
+
1618
+ An alias has one URL and one auth type, and the tracking and one-click routes must stay public:
1619
+
1620
+ - `AWS_IAM` would break those routes. SigV4 also takes the `Authorization` header, so the bearer
1621
+ could not travel with it.
1622
+ - CloudFront's origin access control (OAC) does not help either: with OAC, every POST must carry
1623
+ the body's SHA-256 in `x-amz-content-sha256`, and a mail provider's one-click POST does not.
1624
+
1625
+ Keep the routes public and protect the API in the app: the `API_TOKEN` bearer by default, or
1626
+ your own `authorize`. Production refuses to serve without one of the two.
1627
+
1628
+ **Your own authorization.** `authorize(request, env)` replaces the bearer check on every API
1629
+ route, in any format you choose: an HMAC over the body, a JWT, a header your proxy adds. It
1630
+ receives a copy of the request, so it can read the body, and the env the host validated. True
1631
+ lets the request through, false answers 401, and a throw answers 500 rather than letting the
1632
+ request in. The tracking routes and `/health` never ask it. `bearerMatches` and
1633
+ `timingSafeEqual` are exported for building one:
1634
+
1635
+ ```ts
1636
+ import { journeyLambda, timingSafeEqual } from 'sendwend/aws';
1637
+
1638
+ journeyLambda({
1639
+ // ...
1640
+ authorize: async (request, env) =>
1641
+ timingSafeEqual(
1642
+ request.headers.get('x-signature') ?? '',
1643
+ await hmac(env.SECRET, await request.text())
1644
+ ),
1645
+ });
1646
+ ```
1647
+
1648
+ **Resource policy.** Grant `lambda:InvokeFunctionUrl` to everyone (`FunctionUrlAuthType: NONE`)
1649
+ and `lambda:InvokeFunction` only with `lambda:InvokedViaFunctionUrl = true`, so the URL cannot
1650
+ be used to invoke the function directly.
1651
+
1652
+ **Put CloudFront and WAF in front, without OAC.** A custom domain needs CloudFront (or another
1653
+ HTTPS proxy) anyway; Route 53 alone cannot terminate TLS for a Function URL. Add a rate-based WAF
1654
+ rule there: every request that reaches the function starts a durable execution and is billed,
1655
+ even one the app answers 401. Reserved concurrency caps what a flood can cost.
1656
+
1657
+ **What a request costs.** Every Function URL request is a durable execution of its own:
1658
+
1659
+ | Execution | Durable ops | Per million |
1660
+ | ------------------------------------------- | ----------- | ----------- |
1661
+ | `GET` (pixel, redirect, `/health`), no step | 1 | about $9 |
1662
+ | `POST` (an event, an identify), one step | 2 | about $17 |
1663
+ | A plain, non-durable Lambda for comparison | - | about $1 |
1664
+ | A journey: email, delay, one wake-up, email | 24 | about $190 |
1665
+
1666
+ Durable operations cost $8 per million, on top of Lambda's request and duration charges. That is
1667
+ negligible at thousands of requests a month and worth a second, non-durable function for HTTP at
1668
+ tens of millions. Server-side latency stays small: `/health` takes about 6 ms, a write 40–300 ms.
1669
+
1670
+ **Quotas.**
1671
+
1672
+ - Starting durable executions: 3,000 per second (6,000 in us-east-1, us-west-2 and eu-west-1).
1673
+ HTTP requests and journey starts share it.
1674
+ - 30,000 operations per execution, which cannot be raised. A wait attempt costs about five: the
1675
+ callback plus four steps.
1676
+ - 1 MB per operation's payload. Reads (`GET`, `HEAD`) are answered outside a step so their bodies
1677
+ are not checkpointed.
1678
+
1679
+ **Timeouts and retention.**
1680
+
1681
+ - Set `DurableConfig.ExecutionTimeout` to the longest journey (waits, delays and the goal
1682
+ window), up to 366 days, and pass the same value as `journeyLambda({ executionTimeoutMs })`: a
1683
+ workflow that could outlive it fails at startup instead of being stopped midway.
1684
+ - `RetentionPeriodInDays` (1–90) only keeps history after an execution ends. Keep `startRetryMs`
1685
+ (12 hours) well under it.
1686
+ - Keep `stopDrainMs` (15 minutes) at least the function's `Timeout`: a stop does not interrupt a
1687
+ running invocation.
1688
+
1689
+ **Execution role.**
1690
+
1691
+ - `AWSLambdaBasicDurableExecutionRolePolicy` (checkpoints, state, logs).
1692
+ - On `arn:...:function:<name>` and `arn:...:function:<name>:*`: `lambda:InvokeFunction`,
1693
+ `lambda:SendDurableExecutionCallbackSuccess`, `lambda:GetDurableExecution`,
1694
+ `lambda:StopDurableExecution` and `lambda:ListDurableExecutionsByFunction`. Durable execution
1695
+ ARNs carry the version, so an unqualified ARN alone matches nothing.
1696
+ - `ses:SendEmail` when sending through SES.
1697
+
1698
+ **Versions.**
1699
+
1700
+ - Publish numbered versions behind the `live` alias. `$LATEST` lets a paused execution resume on
1701
+ changed code.
1702
+ - Do not delete a version while executions are pinned to it.
1703
+ - Rolling the alias back does not roll the routes back: the newer bundle stays live until
1704
+ `POST /bundle/deploy` from the restored version.
1705
+
1706
+ **Emails.** The one-click unsubscribe header needs an https `WORKFLOW_ORIGIN`; over http no
1707
+ `List-Unsubscribe` is sent. Mailbox providers honour the header only when DKIM signs it, so check
1708
+ one real message for `dkim=pass` with `list-unsubscribe` in `h=`.
1709
+
1710
+ **Memory.** Size it for the app; the store is remote. APNs goes over the package's Node HTTP/2
1711
+ client, because Node 24's `fetch` speaks HTTP/1.1 only (see `src/http2-client.ts`).
1712
+
1713
+ ## Node (self-hosted)
1714
+
1715
+ The same host as a Node process, with Postgres and nothing else: no Workflow binding, no
1716
+ durable-function service. The process is the runtime — instances are rows, and workers in every
1717
+ process started this way take them a turn at a time.
1718
+
1719
+ ```ts
1720
+ import postgres from 'postgres';
1721
+ import { journeyNode } from 'sendwend/node';
1722
+ import { postgresJsClient } from 'sendwend/postgres-js';
1723
+ import config from './workflow.config';
1724
+
1725
+ const journeys = journeyNode({
1726
+ config,
1727
+ sql: postgresJsClient(postgres(process.env.DATABASE_URL)),
1728
+ vars: { ENVIRONMENT: 'production', API_TOKEN: process.env.API_TOKEN },
1729
+ version: { id: process.env.GIT_SHA, createdAt: Date.parse(process.env.BUILD_TIME) },
1730
+ });
1731
+ await journeys.start({ port: 8787 });
1732
+ process.on('SIGTERM', () => void journeys.stop());
1733
+ ```
1734
+
1735
+ - `sql` is a client several things may use at once (a pool). `vars` is what the other hosts read
1736
+ from their platform's env.
1737
+ - With `version`, the bundle compiled into the process goes live by itself, only over an older
1738
+ one. Without it, deploy with `POST /bundle/deploy`.
1739
+ - Run as many processes as you like: a run is claimed with `FOR UPDATE SKIP LOCKED`, and every
1740
+ write of a turn is fenced by the claim, so a worker that stalled cannot write over the one that
1741
+ took its run. One of the processes runs each sweep.
1742
+ - A step is retried 5 times (10 seconds, doubling) and an attempt may take 10 minutes; a process
1743
+ takes 10 runs at once; a run that ended is kept 7 days. `retry`, `concurrency`, `retentionMs`,
1744
+ `pollMs`, `sweepMs` and `leaseMs` change them.
1745
+ - Steps are **at least once**, as on the other runtimes: a process that dies between a step's
1746
+ effect and its checkpoint leaves the step to be run again.
1747
+ - For tests, `journeys.fetch(request)` and `journeys.drain()` run everything in-process with
1748
+ nothing started, over PGlite if you like.
1749
+
1750
+ - **Set `concurrency` from your slowest action.** A run holds one of the process's places while
1751
+ its action runs, so a process does `concurrency ÷ action time` actions a second: at the
1752
+ default of 10 and a send that takes a second, that is 10 sends a second, with the process
1753
+ and the database idle. Waiting on a provider costs almost nothing — 200 is reasonable on one
1754
+ vCPU — and the pool need not grow with it: a connection is held for a query, not an action.
1755
+
1756
+ This host is new. Its claim, its wakes and a process killed mid-step are tested on a real
1757
+ Postgres with several connections and processes (`tests/integration/node-host.test.ts`). On a
1758
+ 2 vCPU Postgres it ran about 450 runs (1,350 actions) a second whatever the size of the user
1759
+ base up to a million, the database being the limit; `bench/node-host.mjs` measures it.
1760
+
1761
+ ## Postgres
1762
+
1763
+ A host on Postgres (through Hyperdrive, say) keeps Cloudflare Workflows for
1764
+ execution and the data in its own database. Turn Hyperdrive's query caching off for this
1765
+ database (`caching: { disabled: true }` on the Hyperdrive config): the engine reads wake
1766
+ subscriptions, profiles and segment membership right after writing them, and a cached answer
1767
+ up to 60 seconds old misses wakes and decides on stale data.
1768
+
1769
+ ```ts
1770
+ const journeys = journeyWorker<Env>({
1771
+ config,
1772
+ store: (env, database) => postgresJsStore(env.HYPERDRIVE.connectionString, database),
1773
+ });
1774
+ export default { fetch: journeys.fetch, scheduled: journeys.scheduled };
1775
+ ```
1776
+
1777
+ The engine's tables live in one Postgres schema, `workflow` unless the config
1778
+ says `database: { schema }`, so their short names never meet the app's. The
1779
+ host owns the migrations. `npx sendwend-studio generate --out <file>` (from
1780
+ `@sendwend/studio`) writes the tables as one drizzle file on that schema;
1781
+ re-export it from your drizzle schema and let drizzle-kit write the migration.
1782
+ Run `--check` in CI to catch an SDK upgrade that changed them. The file is laid
1783
+ out the way a prettier-compatible formatter at 100 columns lays it out, so
1784
+ formatting it changes nothing and a regeneration shows only real changes. The unique index
1785
+ on `event` is on `(user_id, event_id)`: regenerate and migrate before deploying —
1786
+ the deploy check verifies the unique indexes and constraints as well as the columns, and refuses
1787
+ to run until they match. Without drizzle,
1788
+ `renderPostgresDdl()` returns the same tables as plain DDL. Nothing creates or
1789
+ alters them at runtime: `POST /bundle/deploy` checks the live database first
1790
+ and answers 503 with every missing table or column.
1791
+
1792
+ **Upgrading to 12.0 (re-entry).** A breaking change with no migration path for
1793
+ old data. Every `workflow()` needs a `reentry` policy (`{ mode: 'never' }` is
1794
+ the old behaviour). The IR is version 3 (`reentry` is required), so IRs stored
1795
+ by an earlier version no longer parse, and every content hash changes. The
1796
+ tables change:
1797
+
1798
+ - `entry`: one row per entry instead of one per `(workflow, user_id)` — the
1799
+ primary key moves to `instance_id`, a NOT NULL `occurrence` column is added
1800
+ with a unique index on `(workflow, user_id, occurrence)`, and the separate
1801
+ `instance_id` index goes (the primary key covers it).
1802
+ - `trigger` and `segment_trigger`: a NOT NULL `reentry` jsonb column.
1803
+
1804
+ Old ledger rows, stored IRs and journeys in flight are not migrated: the engine
1805
+ has no meaning for an entry without an occurrence or an IR without a policy.
1806
+ Drain or reset the engine's data (or migrate it as you see fit), regenerate the
1807
+ drizzle file (`sendwend-studio generate`), let drizzle-kit write the migration, and
1808
+ redeploy, which rewrites the routes. `POST /bundle/deploy` refuses to run until
1809
+ the new columns and indexes exist.
1810
+
1811
+ **Upgrading to 12.7 (self-hosted runtime).** Two tables are added, `run` and
1812
+ `run_step`, the state of `sendwend/node`. Regenerate the drizzle file and
1813
+ let drizzle-kit write the migration; `POST /bundle/deploy` refuses to run until
1814
+ they exist, on every runtime (the schema check knows one set of tables). On
1815
+ Cloudflare and AWS they stay empty.
1816
+
1817
+ **Upgrading to 12.5 (a sweep that carries on).** One table is added,
1818
+ `sweep_pass`: where the segment sweep's pass over the users stands (one row
1819
+ while a pass is under way). Regenerate the drizzle file and let drizzle-kit
1820
+ write the migration, before the new version serves; `POST /bundle/deploy`
1821
+ refuses to run until it exists. A sweep now stops after about 30 seconds on
1822
+ the segments and the next one carries on, so its response may say
1823
+ `finished: false` with empty `sizes`.
1824
+
1825
+ **Upgrading to 12.3 (date triggers).** Two tables are added, `date_trigger`
1826
+ (the routes) and `date_run` (how far each send got). Regenerate the drizzle
1827
+ file and let drizzle-kit write the migration, before the new version serves;
1828
+ `POST /bundle/deploy` refuses to run until they exist. **A workflow on
1829
+ `trigger.date` now runs.** Until this version it compiled, deployed and never
1830
+ started (`unrouted`); one whose time is still ahead when the new version
1831
+ deploys will fire at that time, to every known user unless it has a `filter`.
1832
+ One whose time has passed is recorded as over and does nothing. Check the date
1833
+ triggers you have before upgrading.
1834
+
1835
+ **Upgrading to 12.2 (segment entry).** `segment` gains a nullable
1836
+ `seeding_since` (set while a new or changed segment's membership is being
1837
+ established). Regenerate the drizzle file and let drizzle-kit write the
1838
+ migration, before the new version serves; it needs no data step, and the
1839
+ segments already deployed keep working as they did (a null is a seeded
1840
+ segment). What changes is what a deploy does from then on: a segment shipped
1841
+ together with its `trigger.enters`, or one whose condition was edited, used to
1842
+ start a journey for everyone it covered at the next sweep, and now starts none
1843
+ for them. To reach everyone in a segment, name it in a trigger's `filter`.
1844
+ `POST /bundle/deploy` refuses to run until the column exists.
1845
+
1846
+ **Upgrading to 12.1 (unsubscribe clicks).** `message_link` gains a nullable
1847
+ `purpose` (null for a link of the email's content, `'unsubscribe'` for its
1848
+ unsubscribe link). Regenerate the drizzle file and let drizzle-kit write the
1849
+ migration; it needs no data step. Links recorded before the upgrade keep a null
1850
+ purpose, so clicks on the unsubscribe links of emails already sent go on
1851
+ counting as clicks; emails sent after it are measured without them.
1852
+ **Run the migration before the new version serves.** The column is nullable and
1853
+ the previous version ignores it, so migrating first is safe; the other order is
1854
+ not — the new code writes and reads the column on every tracked email, so
1855
+ without it those sends fail and are retried, and tracked links (the unsubscribe
1856
+ link included) answer 500. `POST /bundle/deploy` refuses to run until the column
1857
+ exists, but a version already serving does not wait for it.
1858
+
1859
+ **Upgrading to 9.1 (at-most-once delivery).** `message` gains a nullable
1860
+ `claimed_at` (set just before the transport takes a copy, cleared when the send
1861
+ throws). Regenerate the drizzle file and let drizzle-kit write the migration; it
1862
+ needs no data step, and rows from before keep their meaning — a copy from before
1863
+ the upgrade has no claim, and its `delivered_at` still says it was sent.
1864
+ `POST /bundle/deploy` refuses to run until the column exists.
1865
+
1866
+ **Upgrading to 6.0 (topics).** `suppression` gains a nullable `topic`
1867
+ column, loses its `(user_id, channel)` primary key and gets a
1868
+ `UNIQUE NULLS NOT DISTINCT (user_id, channel, topic)` constraint (Postgres 15+),
1869
+ and `message` gains a nullable `topic` (written for email and push copies).
1870
+ Regenerate the drizzle file and let drizzle-kit write the migration; it needs no
1871
+ data step. Rows from before keep their meaning: a `suppression` row whose
1872
+ `topic` is null is an opt-out from the whole channel, which is what every
1873
+ unsubscribe recorded before topics was.
1874
+
1875
+ ### Deploying is `wrangler deploy`
1876
+
1877
+ The journeys are compiled into the Worker, so a new version carries its own
1878
+ bundle. Add Cloudflare's version metadata binding and each new version makes
1879
+ that bundle live by itself, with nothing to call after `wrangler deploy`:
1880
+
1881
+ ```jsonc
1882
+ // wrangler.jsonc
1883
+ "version_metadata": { "binding": "CF_VERSION_METADATA" }
1884
+ ```
1885
+
1886
+ The first request or cron run an isolate serves reads which version's bundle
1887
+ is live (one row, `workflow.deployment`) and applies its own only over an older
1888
+ version, in the same transaction that records it. Isolates of the old version
1889
+ keep serving for a few seconds after a deploy; they can never put their routes
1890
+ back. Until the new version first runs, events still follow the old routes.
1891
+ The check runs once per isolate, in the background; a failure (migrations not
1892
+ applied, say) is logged and retried a minute later.
1893
+
1894
+ With a gradual deployment the newest version's bundle goes live as soon as
1895
+ that version serves its first request, whatever share of traffic it has.
1896
+
1897
+ `wrangler rollback` restores an older version, which does not apply itself over
1898
+ the newer one. Call `POST /bundle/deploy` after a rollback: it applies the
1899
+ running version's bundle whatever is live, and records that version as the live
1900
+ one — so a newer version that serves again later puts its own bundle back, as a
1901
+ deploy always does.
1902
+
1903
+ On Postgres the engine also keeps:
1904
+
1905
+ - **Reporting.** Instances, every message copy, opens and clicks, recorded
1906
+ by the default observer. With `WORKFLOW_ORIGIN` set, email links and an open
1907
+ pixel are tracked through the Worker's `/t/...` routes. Each open and click
1908
+ is classified as a person's or a machine's (Apple Mail Privacy Protection,
1909
+ link scanners, prefetches). A click from a cloud's or a mail security
1910
+ vendor's network is a machine's; one from a corporate web proxy's (Zscaler,
1911
+ Cisco…) is a machine's only if it also came within a second of delivery or
1912
+ with another link, since staff browse through those. The network is known on
1913
+ Cloudflare only, so on AWS and Node these two rules do not apply and the
1914
+ human click rate reads higher. An email's unsubscribe
1915
+ link gets a confirmation page; which link that is was fixed when the email was sent. Following it is
1916
+ recorded, and counts as an open, but is not a click of the copy: `clicked_at`
1917
+ and the click rates are about the links of the content.
1918
+ A push carries `message_id`; report the tap with `messageOpened`.
1919
+ - **Segments.** The cron trigger runs `sweepSegments`, which keeps every
1920
+ segment's membership and size, starts the journeys of segments entered by
1921
+ the clock alone, and ends the seeding of the segments a deploy brought in new
1922
+ or changed. Before that it starts the journeys of the date triggers that are
1923
+ due. `POST /segments/sweep` runs it on demand. One SQL statement per
1924
+ page finds who may have to change, compiled from the segments' conditions, and
1925
+ the evaluator journeys use decides each of them, so a sweep costs what changed,
1926
+ not how many users there are. Its response counts them as `evaluated`.
1927
+ **A sweep spends a bounded time** (about 30 seconds on the segments, as much
1928
+ on the date triggers) and keeps its place in the store (`sweep_pass`): when
1929
+ there is more to change than one call gets through, the next sweep carries on
1930
+ from where this one stopped instead of starting over, on every host. The
1931
+ response's `finished` says whether the pass has been through every user;
1932
+ seeding ends and the sizes are recorded when it has, so `sizes` is empty for
1933
+ a sweep that left the pass unfinished.
1934
+
1935
+ `@sendwend/studio/postgres` reads all of it for the studio.
1936
+
1937
+ ## HTTP surface
1938
+
1939
+ `handleRequest` serves the ingest API. It applies the same production gate as
1940
+ the full host: with no `API_TOKEN` and an `ENVIRONMENT` that is not a mode that runs open
1941
+ (`development`, `test`; a host's config can name more), everything but `GET /health` and
1942
+ `/t/...` answers 503.
1943
+
1944
+ - `GET /health` is the only unauthenticated one. Every other route asks the
1945
+ host's `authorize`, or without one the `API_TOKEN` bearer: its scheme is
1946
+ matched case-insensitively and the token compared in constant time.
1947
+ - `POST /ingest` takes `{ userId?, visitorId?, profile?, at?, events? }` with at
1948
+ least one id, each event being `{ event, payload?, ts?, id? }`, and answers
1949
+ `{ profile?, events }`, each event's result naming the id it was recorded under.
1950
+ The whole batch is checked first, one bad part refuses all of it; then a visitor
1951
+ merges, the profile is merged and the events recorded in order. Event names
1952
+ beginning with `$` are reserved, and a `userId` cannot begin with `visitor:`.
1953
+ `ts` is epoch milliseconds: a non-negative integer no later than five minutes
1954
+ ahead of the host's clock (400 otherwise). Profile values are scalars (string,
1955
+ number, boolean); a property set to `null` is removed, which is the only way to
1956
+ unset one. Nested objects are refused with a 400. A property written with a later
1957
+ `at` keeps its value. An event's `payload` may be at most 128 KiB as JSON
1958
+ (`MAX_EVENT_PAYLOAD_BYTES`): a larger one refuses the batch with a 400 naming the
1959
+ event and its size. A triggering event's payload travels in the instance's
1960
+ parameters for the whole journey, and the runtimes cap those.
1961
+ - A user with an erasure tombstone (`POST /users/forget`, finished or not) is
1962
+ refused on `/ingest` and `/devices` with a 410: nothing is
1963
+ written about them between the stop of their journeys and the erase, and the
1964
+ id is never reactivated after it.
1965
+ - A body that is not JSON answers 400, never 500.
1966
+ - `POST /devices` takes `{ userId, token, platform, ts? }`;
1967
+ `POST /devices/unbind` and `POST /devices/remove` take `{ token }`.
1968
+ - `POST /messages/opened` takes `{ userId, messageId }`.
1969
+ - `GET /subscriptions/:userId` answers `{ email: { all, topics }, push: { all, topics } }`
1970
+ (`true` is subscribed; each channel's `topics` has one key per topic the
1971
+ deployed bundle declares). `PUT /subscriptions/:userId` takes a partial body
1972
+ `{ email?: { all?, topics? }, push?: { all?, topics? } }` and changes only
1973
+ what it names, per channel: `all: false` opts out of the whole channel,
1974
+ `topics: { newsletter: false }` of one topic on it, and `all: true` clears
1975
+ the channel-wide opt-out only (a topic opted out on its own stays off until
1976
+ named). An answer's `all: false` masks every topic of that channel, whatever
1977
+ the topic's own flag says. An undeclared topic, an unknown channel or a
1978
+ non-boolean answers 400 with the field paths; an erased user 410. Changing
1979
+ `email.all` wakes the waits on `reachable('email')`, `push.all` those on
1980
+ `reachable('push')`.
1981
+ - `GET /subscriptions/by-message/:messageId` answers the same record for the
1982
+ recipient of that copy, plus `message: { channel, topic }` (`channel` is
1983
+ `email` or `push`, the channel the copy went out on); `PUT` takes the same
1984
+ patch as `/subscriptions/:userId` and answers as the GET does. The message id
1985
+ is the capability (the `m` of an email's `preferencesUrl` link), so the app
1986
+ proxies and rate-limits these routes behind its own API; the bearer still
1987
+ guards them. An id that names no copy — never sent, not a UUID, or erased
1988
+ with its user — or a transactional copy (`topic` null) answers 404, the rule
1989
+ `/t/u` applies; a user whose erasure is pending answers 410, as above.
1990
+ - `POST /users/forget` takes `{ userId }`; the erasure takes the user's opt-outs
1991
+ with the rest, since nothing is ever sent to that id again.
1992
+ - `POST /deploy` takes a compiled bundle and swaps the routing table atomically.
1993
+ It answers 409 when the bundle would break journeys still running, listing
1994
+ them (see [Versioning](#versioning)); `?force=1` deploys anyway and reports
1995
+ what it broke in `inFlight`. `POST /bundle/deploy` takes the same `?force=1`.
1996
+
1997
+ `journeyWorker` adds `GET /bundle` (the compiled config), `POST /bundle/deploy`
1998
+ (deploy it), `GET /preview/<key>`, `POST /segments/sweep`, and the `/t/...`
1999
+ tracking routes recipients open, which need no bearer. `POST /t/u/<message>`
2000
+ (the one-click unsubscribe, and the confirmation page's first button) opts the
2001
+ recipient out of that email's topic; with `?scope=all` (the second button) out
2002
+ of every email. A transactional email never carried the link, so every `/t/u`
2003
+ variant answers 404 for it. With a contract, an event or identify it refuses is
2004
+ answered with a 400 and the field paths, before anything is stored, woken or
2005
+ started.
2006
+
2007
+ ### Give each event an `id`
2008
+
2009
+ `id` is the occurrence's identity **for that user**, and sending the same one
2010
+ twice records it once. This matters because every count- and window-based condition reads the
2011
+ event log, so a second copy of one event silently changes what a journey
2012
+ decides.
2013
+
2014
+ Only the sender knows whether two deliveries describe one occurrence or two, so
2015
+ the engine never guesses. An event that arrives without an id is given a fresh
2016
+ one, which records it as its own occurrence. If you retry a request, send an id
2017
+ you can reproduce and the retry costs nothing.
2018
+
2019
+ ```json
2020
+ { "id": "order-8841-confirmed", "userId": "u_123", "event": "purchase" }
23
2021
  ```
24
2022
 
25
- CommonJS: `const { last, lastAsync } = require('sendwend');`
2023
+ Use something that identifies the occurrence, not the event name: a row id from
2024
+ your own system, an upstream webhook's delivery id, or a message id from your
2025
+ queue. The id is scoped to the user (the unique key is `(user_id, event_id)`),
2026
+ so two users may reuse one id without one of them losing their event. Workflows emitting events through `.sendEvent()` already do this, passing
2027
+ the node's identity within the running instance.
2028
+
2029
+ ## Entry policy
2030
+
2031
+ Whether a user enters again is the workflow's [`reentry`](#re-entry) policy,
2032
+ decided on the entry ledger atomically under concurrent ingests. Whatever the
2033
+ mode, one occurrence enters at most once. An entry whose instance died records a
2034
+ failure, not a journey the user received: it blocks nothing, and a retry of the
2035
+ same occurrence reclaims its row.
26
2036
 
27
- This early release provides the iterable helpers below. The workflow orchestration API is not included in this release.
2037
+ The entry commits before the platform creates the instance, so a host cut off
2038
+ between the two leaves an entry with nothing behind it. Two things repair it: a
2039
+ retry of the same event (same `id`) creates the missing instance — the
2040
+ instance id is the platform's identity too, so a second create is harmless — and
2041
+ the sweep's maintenance marks an entry left unadmitted for 15 minutes, whose
2042
+ instance the runtime does not know or reports ended, as failed, so the user's
2043
+ next trigger re-enters. Neither can start a second journey for the occurrence.
28
2044
 
29
- Project website: https://sendwend.com
2045
+ An instance can also end after it was admitted without finalizing its entry:
2046
+ terminated from the dashboard or the API, errored for good because a step kept
2047
+ failing, or evicted. The same maintenance samples the entries admitted more than
2048
+ 15 minutes ago (a bounded random sample each sweep, so every entry is reached
2049
+ eventually however many journeys are running), and one whose instance the
2050
+ runtime reports `complete`, `errored` or `terminated`, or no longer knows, is
2051
+ marked failed, its wake subscriptions dropped and its ending reported — what the
2052
+ finalize step would have done. An instance still running, or one whose lookup
2053
+ fails for any other reason, is left alone. It no longer counts as running, so
2054
+ the next trigger the policy allows enters again.
30
2055
 
31
- ## API
2056
+ ## Exports
32
2057
 
33
- - `last(iterable, fallback?)`: returns the final value, or the fallback if the input is empty. The default fallback is `undefined`.
34
- - `lastAsync(iterable, fallback?)`: returns a Promise for the final value or fallback. Accepts sync and async iterables and awaits values from sync iterables.
2058
+ | Subpath | Contents |
2059
+ | ---------------------- | -------------------------------------------------------------------------------------------------- |
2060
+ | `sendwend` | The DSL, `defineContract`, `defineConfig`, `compileConfig`, `compileBundle`, `plan`, templates, IR |
2061
+ | `sendwend/engine` | The interpreter (`runJourney`) and its ports, condition evaluation, bucketing |
2062
+ | `sendwend/cloudflare` | `journeyWorker`, `JourneyRunner`, `handleRequest`, the ingest functions, senders, the store |
2063
+ | `sendwend/store` | The `JourneyStore` port, the Postgres store, `renderPostgresDdl`, `renderDrizzleSchema` |
2064
+ | `sendwend/client` | `JourneyClient`, the producer side of the HTTP API |
2065
+ | `sendwend/postgres-js` | `postgresJsStore`, the Postgres store over postgres.js (peer `postgres`) |
2066
+ | `sendwend/react-email` | `registryRenderer`, the email renderer over the registry (peers `react`, `react-dom`) |
2067
+ | `sendwend/push` | `registryPushRenderer`, push content from the registry |
2068
+ | `sendwend/apns` | `ApnsPushSender` over an `ApnsProviderToken`, token-based APNs over HTTP/2 |
2069
+ | `sendwend/apns-relay` | `startApnsRelay`, the Node HTTP/1.1 to HTTP/2 relay for `wrangler dev` |
2070
+ | `sendwend/fcm` | `FcmPushSender` over an `FcmAccessToken`, FCM HTTP v1 for Android |
2071
+ | `sendwend/webpush` | `WebPushSender` over a `VapidSigner`, `generateVapidKeys`; standard Web Push with VAPID |
2072
+ | `sendwend/webhooks` | `SlackWebhookSender` and `DiscordWebhookSender` |
35
2073
 
36
- Both functions consume the entire input once, run in O(n) time, and use O(1) extra memory. Use finite inputs only. Iterator errors propagate to the caller. An actual last value of `undefined` is returned as-is, even when a fallback is provided. The async function follows JavaScript's `for await...of` semantics.
2074
+ ## Testing
37
2075
 
38
- ## License
2076
+ See [TESTING.md](./TESTING.md). The interpreter runs against in-memory ports and
2077
+ the Cloudflare adapter against fakes that dispatch on the exact SQL strings the
2078
+ real code sends, so changing a query means updating the fake, deliberately.
39
2079
 
40
- MIT
2080
+ In an app, `compileConfig(config)` makes the compiled IR snapshot-testable, and
2081
+ `runJourney` from `sendwend/engine` runs a journey against an in-memory
2082
+ host, with `registryRenderer` and `registryPushRenderer` rendering what it
2083
+ sends.