@shware/workflow-ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (363) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +180 -2
  3. package/dist/assets/iphone-17-pro-DzaacWSl.png +0 -0
  4. package/dist/assets/pixel-10-pro-back-7MDj1_lz.webp +0 -0
  5. package/dist/assets/pixel-10-pro-mask-Bi1deQ9Y.webp +0 -0
  6. package/dist/cli.d.mts +1 -0
  7. package/dist/cli.mjs +673 -0
  8. package/dist/cli.mjs.map +1 -0
  9. package/dist/config.d.mts +247 -0
  10. package/dist/config.d.mts.map +1 -0
  11. package/dist/config.mjs +27 -0
  12. package/dist/config.mjs.map +1 -0
  13. package/dist/index.d.mts +451 -0
  14. package/dist/index.d.mts.map +1 -0
  15. package/dist/index.mjs +2722 -0
  16. package/dist/index.mjs.map +1 -0
  17. package/dist/postgres.d.mts +34 -0
  18. package/dist/postgres.d.mts.map +1 -0
  19. package/dist/postgres.mjs +313 -0
  20. package/dist/postgres.mjs.map +1 -0
  21. package/package.json +93 -3
  22. package/src/app/assets/devices/iphone-17-pro.png +0 -0
  23. package/src/app/assets/devices/pixel-10-pro-back.webp +0 -0
  24. package/src/app/assets/devices/pixel-10-pro-mask.webp +0 -0
  25. package/src/app/assets/flags/AC.svg +1 -0
  26. package/src/app/assets/flags/AD.svg +1 -0
  27. package/src/app/assets/flags/AE.svg +1 -0
  28. package/src/app/assets/flags/AF.svg +1 -0
  29. package/src/app/assets/flags/AG.svg +1 -0
  30. package/src/app/assets/flags/AI.svg +1 -0
  31. package/src/app/assets/flags/AL.svg +1 -0
  32. package/src/app/assets/flags/AM.svg +1 -0
  33. package/src/app/assets/flags/AO.svg +1 -0
  34. package/src/app/assets/flags/AQ.svg +1 -0
  35. package/src/app/assets/flags/AR.svg +1 -0
  36. package/src/app/assets/flags/AS.svg +1 -0
  37. package/src/app/assets/flags/AT.svg +1 -0
  38. package/src/app/assets/flags/AU.svg +1 -0
  39. package/src/app/assets/flags/AW.svg +1 -0
  40. package/src/app/assets/flags/AX.svg +1 -0
  41. package/src/app/assets/flags/AZ.svg +1 -0
  42. package/src/app/assets/flags/BA.svg +1 -0
  43. package/src/app/assets/flags/BB.svg +1 -0
  44. package/src/app/assets/flags/BD.svg +1 -0
  45. package/src/app/assets/flags/BE.svg +1 -0
  46. package/src/app/assets/flags/BF.svg +1 -0
  47. package/src/app/assets/flags/BG.svg +1 -0
  48. package/src/app/assets/flags/BH.svg +1 -0
  49. package/src/app/assets/flags/BI.svg +1 -0
  50. package/src/app/assets/flags/BJ.svg +1 -0
  51. package/src/app/assets/flags/BL.svg +1 -0
  52. package/src/app/assets/flags/BM.svg +1 -0
  53. package/src/app/assets/flags/BN.svg +1 -0
  54. package/src/app/assets/flags/BO.svg +1 -0
  55. package/src/app/assets/flags/BQ-BO.svg +1 -0
  56. package/src/app/assets/flags/BQ-SA.svg +1 -0
  57. package/src/app/assets/flags/BQ-SE.svg +1 -0
  58. package/src/app/assets/flags/BQ.svg +1 -0
  59. package/src/app/assets/flags/BR.svg +1 -0
  60. package/src/app/assets/flags/BS.svg +1 -0
  61. package/src/app/assets/flags/BT.svg +1 -0
  62. package/src/app/assets/flags/BV.svg +1 -0
  63. package/src/app/assets/flags/BW.svg +1 -0
  64. package/src/app/assets/flags/BY.svg +1 -0
  65. package/src/app/assets/flags/BZ.svg +1 -0
  66. package/src/app/assets/flags/CA.svg +1 -0
  67. package/src/app/assets/flags/CC.svg +1 -0
  68. package/src/app/assets/flags/CD.svg +1 -0
  69. package/src/app/assets/flags/CF.svg +1 -0
  70. package/src/app/assets/flags/CG.svg +1 -0
  71. package/src/app/assets/flags/CH.svg +1 -0
  72. package/src/app/assets/flags/CI.svg +1 -0
  73. package/src/app/assets/flags/CK.svg +1 -0
  74. package/src/app/assets/flags/CL.svg +1 -0
  75. package/src/app/assets/flags/CM.svg +1 -0
  76. package/src/app/assets/flags/CN.svg +1 -0
  77. package/src/app/assets/flags/CO.svg +1 -0
  78. package/src/app/assets/flags/CR.svg +1 -0
  79. package/src/app/assets/flags/CU.svg +1 -0
  80. package/src/app/assets/flags/CV.svg +1 -0
  81. package/src/app/assets/flags/CW.svg +1 -0
  82. package/src/app/assets/flags/CX.svg +1 -0
  83. package/src/app/assets/flags/CY.svg +1 -0
  84. package/src/app/assets/flags/CZ.svg +1 -0
  85. package/src/app/assets/flags/DE.svg +1 -0
  86. package/src/app/assets/flags/DJ.svg +1 -0
  87. package/src/app/assets/flags/DK.svg +1 -0
  88. package/src/app/assets/flags/DM.svg +1 -0
  89. package/src/app/assets/flags/DO.svg +1 -0
  90. package/src/app/assets/flags/DZ.svg +1 -0
  91. package/src/app/assets/flags/EC.svg +1 -0
  92. package/src/app/assets/flags/EE.svg +1 -0
  93. package/src/app/assets/flags/EG.svg +1 -0
  94. package/src/app/assets/flags/EH.svg +1 -0
  95. package/src/app/assets/flags/ER.svg +1 -0
  96. package/src/app/assets/flags/ES-CT.svg +1 -0
  97. package/src/app/assets/flags/ES.svg +1 -0
  98. package/src/app/assets/flags/ET.svg +1 -0
  99. package/src/app/assets/flags/EU.svg +1 -0
  100. package/src/app/assets/flags/FI.svg +1 -0
  101. package/src/app/assets/flags/FJ.svg +1 -0
  102. package/src/app/assets/flags/FK.svg +1 -0
  103. package/src/app/assets/flags/FM.svg +1 -0
  104. package/src/app/assets/flags/FO.svg +1 -0
  105. package/src/app/assets/flags/FR.svg +1 -0
  106. package/src/app/assets/flags/GA.svg +1 -0
  107. package/src/app/assets/flags/GB-ENG.svg +1 -0
  108. package/src/app/assets/flags/GB-NIR.svg +1 -0
  109. package/src/app/assets/flags/GB-SCT.svg +1 -0
  110. package/src/app/assets/flags/GB-WLS.svg +1 -0
  111. package/src/app/assets/flags/GB.svg +1 -0
  112. package/src/app/assets/flags/GD.svg +1 -0
  113. package/src/app/assets/flags/GE.svg +1 -0
  114. package/src/app/assets/flags/GF.svg +1 -0
  115. package/src/app/assets/flags/GG.svg +1 -0
  116. package/src/app/assets/flags/GH.svg +1 -0
  117. package/src/app/assets/flags/GI.svg +1 -0
  118. package/src/app/assets/flags/GL.svg +1 -0
  119. package/src/app/assets/flags/GM.svg +1 -0
  120. package/src/app/assets/flags/GN.svg +1 -0
  121. package/src/app/assets/flags/GP.svg +1 -0
  122. package/src/app/assets/flags/GQ.svg +1 -0
  123. package/src/app/assets/flags/GR.svg +1 -0
  124. package/src/app/assets/flags/GS.svg +1 -0
  125. package/src/app/assets/flags/GT.svg +1 -0
  126. package/src/app/assets/flags/GU.svg +1 -0
  127. package/src/app/assets/flags/GW.svg +1 -0
  128. package/src/app/assets/flags/GY.svg +1 -0
  129. package/src/app/assets/flags/HK.svg +1 -0
  130. package/src/app/assets/flags/HM.svg +1 -0
  131. package/src/app/assets/flags/HN.svg +1 -0
  132. package/src/app/assets/flags/HR.svg +1 -0
  133. package/src/app/assets/flags/HT.svg +1 -0
  134. package/src/app/assets/flags/HU.svg +1 -0
  135. package/src/app/assets/flags/IC.svg +1 -0
  136. package/src/app/assets/flags/ID.svg +1 -0
  137. package/src/app/assets/flags/IE.svg +1 -0
  138. package/src/app/assets/flags/IL.svg +1 -0
  139. package/src/app/assets/flags/IM.svg +1 -0
  140. package/src/app/assets/flags/IN.svg +1 -0
  141. package/src/app/assets/flags/IO.svg +1 -0
  142. package/src/app/assets/flags/IQ.svg +1 -0
  143. package/src/app/assets/flags/IR.svg +1 -0
  144. package/src/app/assets/flags/IS.svg +1 -0
  145. package/src/app/assets/flags/IT.svg +1 -0
  146. package/src/app/assets/flags/JE.svg +1 -0
  147. package/src/app/assets/flags/JM.svg +1 -0
  148. package/src/app/assets/flags/JO.svg +1 -0
  149. package/src/app/assets/flags/JP.svg +1 -0
  150. package/src/app/assets/flags/KE.svg +1 -0
  151. package/src/app/assets/flags/KG.svg +1 -0
  152. package/src/app/assets/flags/KH.svg +1 -0
  153. package/src/app/assets/flags/KI.svg +1 -0
  154. package/src/app/assets/flags/KM.svg +1 -0
  155. package/src/app/assets/flags/KN.svg +1 -0
  156. package/src/app/assets/flags/KP.svg +1 -0
  157. package/src/app/assets/flags/KR.svg +1 -0
  158. package/src/app/assets/flags/KW.svg +1 -0
  159. package/src/app/assets/flags/KY.svg +1 -0
  160. package/src/app/assets/flags/KZ.svg +1 -0
  161. package/src/app/assets/flags/LA.svg +1 -0
  162. package/src/app/assets/flags/LB.svg +1 -0
  163. package/src/app/assets/flags/LC.svg +1 -0
  164. package/src/app/assets/flags/LI.svg +1 -0
  165. package/src/app/assets/flags/LK.svg +1 -0
  166. package/src/app/assets/flags/LR.svg +1 -0
  167. package/src/app/assets/flags/LS.svg +1 -0
  168. package/src/app/assets/flags/LT.svg +1 -0
  169. package/src/app/assets/flags/LU.svg +1 -0
  170. package/src/app/assets/flags/LV.svg +1 -0
  171. package/src/app/assets/flags/LY.svg +1 -0
  172. package/src/app/assets/flags/MA.svg +1 -0
  173. package/src/app/assets/flags/MC.svg +1 -0
  174. package/src/app/assets/flags/MD.svg +1 -0
  175. package/src/app/assets/flags/ME.svg +1 -0
  176. package/src/app/assets/flags/MF.svg +1 -0
  177. package/src/app/assets/flags/MG.svg +1 -0
  178. package/src/app/assets/flags/MH.svg +1 -0
  179. package/src/app/assets/flags/MK.svg +1 -0
  180. package/src/app/assets/flags/ML.svg +1 -0
  181. package/src/app/assets/flags/MM.svg +1 -0
  182. package/src/app/assets/flags/MN.svg +1 -0
  183. package/src/app/assets/flags/MO.svg +1 -0
  184. package/src/app/assets/flags/MP.svg +1 -0
  185. package/src/app/assets/flags/MQ.svg +1 -0
  186. package/src/app/assets/flags/MR.svg +1 -0
  187. package/src/app/assets/flags/MS.svg +1 -0
  188. package/src/app/assets/flags/MT.svg +1 -0
  189. package/src/app/assets/flags/MU.svg +1 -0
  190. package/src/app/assets/flags/MV.svg +1 -0
  191. package/src/app/assets/flags/MW.svg +1 -0
  192. package/src/app/assets/flags/MX.svg +1 -0
  193. package/src/app/assets/flags/MY.svg +1 -0
  194. package/src/app/assets/flags/MZ.svg +1 -0
  195. package/src/app/assets/flags/NA.svg +1 -0
  196. package/src/app/assets/flags/NC.svg +1 -0
  197. package/src/app/assets/flags/NE.svg +1 -0
  198. package/src/app/assets/flags/NF.svg +1 -0
  199. package/src/app/assets/flags/NG.svg +1 -0
  200. package/src/app/assets/flags/NI.svg +1 -0
  201. package/src/app/assets/flags/NL.svg +1 -0
  202. package/src/app/assets/flags/NO.svg +1 -0
  203. package/src/app/assets/flags/NP.svg +1 -0
  204. package/src/app/assets/flags/NR.svg +1 -0
  205. package/src/app/assets/flags/NU.svg +1 -0
  206. package/src/app/assets/flags/NZ.svg +1 -0
  207. package/src/app/assets/flags/OM.svg +1 -0
  208. package/src/app/assets/flags/PA.svg +1 -0
  209. package/src/app/assets/flags/PE.svg +1 -0
  210. package/src/app/assets/flags/PF.svg +1 -0
  211. package/src/app/assets/flags/PG.svg +1 -0
  212. package/src/app/assets/flags/PH.svg +1 -0
  213. package/src/app/assets/flags/PK.svg +1 -0
  214. package/src/app/assets/flags/PL.svg +1 -0
  215. package/src/app/assets/flags/PM.svg +1 -0
  216. package/src/app/assets/flags/PN.svg +1 -0
  217. package/src/app/assets/flags/PR.svg +1 -0
  218. package/src/app/assets/flags/PS.svg +1 -0
  219. package/src/app/assets/flags/PT.svg +1 -0
  220. package/src/app/assets/flags/PW.svg +1 -0
  221. package/src/app/assets/flags/PY.svg +1 -0
  222. package/src/app/assets/flags/QA.svg +1 -0
  223. package/src/app/assets/flags/RE.svg +1 -0
  224. package/src/app/assets/flags/README.md +6 -0
  225. package/src/app/assets/flags/RO.svg +1 -0
  226. package/src/app/assets/flags/RS.svg +1 -0
  227. package/src/app/assets/flags/RU.svg +1 -0
  228. package/src/app/assets/flags/RW.svg +1 -0
  229. package/src/app/assets/flags/SA.svg +1 -0
  230. package/src/app/assets/flags/SB.svg +1 -0
  231. package/src/app/assets/flags/SC.svg +1 -0
  232. package/src/app/assets/flags/SD.svg +1 -0
  233. package/src/app/assets/flags/SE.svg +1 -0
  234. package/src/app/assets/flags/SG.svg +1 -0
  235. package/src/app/assets/flags/SH.svg +1 -0
  236. package/src/app/assets/flags/SI.svg +1 -0
  237. package/src/app/assets/flags/SJ.svg +1 -0
  238. package/src/app/assets/flags/SK.svg +1 -0
  239. package/src/app/assets/flags/SL.svg +1 -0
  240. package/src/app/assets/flags/SM.svg +1 -0
  241. package/src/app/assets/flags/SN.svg +1 -0
  242. package/src/app/assets/flags/SO.svg +1 -0
  243. package/src/app/assets/flags/SR.svg +1 -0
  244. package/src/app/assets/flags/SS.svg +1 -0
  245. package/src/app/assets/flags/ST.svg +1 -0
  246. package/src/app/assets/flags/SV.svg +1 -0
  247. package/src/app/assets/flags/SX.svg +1 -0
  248. package/src/app/assets/flags/SY.svg +1 -0
  249. package/src/app/assets/flags/SZ.svg +1 -0
  250. package/src/app/assets/flags/TA.svg +1 -0
  251. package/src/app/assets/flags/TC.svg +1 -0
  252. package/src/app/assets/flags/TD.svg +1 -0
  253. package/src/app/assets/flags/TF.svg +1 -0
  254. package/src/app/assets/flags/TG.svg +1 -0
  255. package/src/app/assets/flags/TH.svg +1 -0
  256. package/src/app/assets/flags/TJ.svg +1 -0
  257. package/src/app/assets/flags/TK.svg +1 -0
  258. package/src/app/assets/flags/TL.svg +1 -0
  259. package/src/app/assets/flags/TM.svg +1 -0
  260. package/src/app/assets/flags/TN.svg +1 -0
  261. package/src/app/assets/flags/TO.svg +1 -0
  262. package/src/app/assets/flags/TR.svg +1 -0
  263. package/src/app/assets/flags/TT.svg +1 -0
  264. package/src/app/assets/flags/TV.svg +1 -0
  265. package/src/app/assets/flags/TW.svg +1 -0
  266. package/src/app/assets/flags/TZ.svg +1 -0
  267. package/src/app/assets/flags/UA.svg +1 -0
  268. package/src/app/assets/flags/UG.svg +1 -0
  269. package/src/app/assets/flags/UM.svg +1 -0
  270. package/src/app/assets/flags/US.svg +1 -0
  271. package/src/app/assets/flags/UY.svg +1 -0
  272. package/src/app/assets/flags/UZ.svg +1 -0
  273. package/src/app/assets/flags/VA.svg +1 -0
  274. package/src/app/assets/flags/VC.svg +1 -0
  275. package/src/app/assets/flags/VE.svg +1 -0
  276. package/src/app/assets/flags/VG.svg +1 -0
  277. package/src/app/assets/flags/VI.svg +1 -0
  278. package/src/app/assets/flags/VN.svg +1 -0
  279. package/src/app/assets/flags/VU.svg +1 -0
  280. package/src/app/assets/flags/WF.svg +1 -0
  281. package/src/app/assets/flags/WS.svg +1 -0
  282. package/src/app/assets/flags/XA.svg +1 -0
  283. package/src/app/assets/flags/XC.svg +1 -0
  284. package/src/app/assets/flags/XK.svg +1 -0
  285. package/src/app/assets/flags/XO.svg +1 -0
  286. package/src/app/assets/flags/YE.svg +1 -0
  287. package/src/app/assets/flags/YT.svg +1 -0
  288. package/src/app/assets/flags/ZA.svg +1 -0
  289. package/src/app/assets/flags/ZM.svg +1 -0
  290. package/src/app/assets/flags/ZW.svg +1 -0
  291. package/src/app/email-preview.ts +46 -0
  292. package/src/app/index.css +203 -0
  293. package/src/app/index.html +12 -0
  294. package/src/app/integrations/i18n/react-i18next.d.ts +11 -0
  295. package/src/app/integrations/i18n/root-provider.tsx +62 -0
  296. package/src/app/integrations/tanstack-query/devtools.tsx +6 -0
  297. package/src/app/integrations/tanstack-query/root-provider.tsx +37 -0
  298. package/src/app/integrations/theme/root-provider.tsx +75 -0
  299. package/src/app/integrations/toast/toast-provider.tsx +46 -0
  300. package/src/app/locales/en-US/common.ts +268 -0
  301. package/src/app/locales/zh-CN/common.ts +263 -0
  302. package/src/app/main.tsx +40 -0
  303. package/src/app/page-chrome.tsx +79 -0
  304. package/src/app/router.tsx +40 -0
  305. package/src/app/routes/__root.tsx +293 -0
  306. package/src/app/routes/emails.tsx +199 -0
  307. package/src/app/routes/home.tsx +87 -0
  308. package/src/app/routes/index.ts +19 -0
  309. package/src/app/routes/metrics.tsx +541 -0
  310. package/src/app/routes/segment-overview.tsx +211 -0
  311. package/src/app/routes/segments.tsx +236 -0
  312. package/src/app/routes/settings.tsx +90 -0
  313. package/src/app/routes/workflows.tsx +348 -0
  314. package/src/app/studio.ts +16 -0
  315. package/src/app/svg.d.ts +17 -0
  316. package/src/app/virtual-config.d.ts +6 -0
  317. package/src/cli.ts +110 -0
  318. package/src/components/avatar.tsx +57 -0
  319. package/src/components/breadcrumb.tsx +49 -0
  320. package/src/components/button/index.tsx +86 -0
  321. package/src/components/channel-icon.ts +39 -0
  322. package/src/components/chat-markup.tsx +109 -0
  323. package/src/components/corner-shape.ts +13 -0
  324. package/src/components/date-range.tsx +181 -0
  325. package/src/components/discord-preview.tsx +165 -0
  326. package/src/components/dropdown/index.tsx +172 -0
  327. package/src/components/email-defaults.tsx +40 -0
  328. package/src/components/email-list.tsx +149 -0
  329. package/src/components/email-thumbnail.tsx +123 -0
  330. package/src/components/flag.tsx +40 -0
  331. package/src/components/input/index.tsx +40 -0
  332. package/src/components/input/search-input.tsx +24 -0
  333. package/src/components/layout.ts +403 -0
  334. package/src/components/menu/index.tsx +118 -0
  335. package/src/components/metric-card.tsx +321 -0
  336. package/src/components/modal/index.tsx +70 -0
  337. package/src/components/nav-drawer.tsx +84 -0
  338. package/src/components/node-inspector.tsx +242 -0
  339. package/src/components/profile-drawer.tsx +331 -0
  340. package/src/components/push-preview.tsx +470 -0
  341. package/src/components/push-thumbnail.tsx +78 -0
  342. package/src/components/segment-list.tsx +184 -0
  343. package/src/components/select/index.tsx +70 -0
  344. package/src/components/series-chart.tsx +120 -0
  345. package/src/components/slack-preview.tsx +223 -0
  346. package/src/components/sparkline.tsx +58 -0
  347. package/src/components/tabs/index.tsx +45 -0
  348. package/src/components/template-refs.ts +110 -0
  349. package/src/components/templates-page.tsx +601 -0
  350. package/src/components/textarea/index.tsx +37 -0
  351. package/src/components/thumbnail-window.tsx +65 -0
  352. package/src/components/workflow-canvas.tsx +503 -0
  353. package/src/components/workflow-list.tsx +231 -0
  354. package/src/config.ts +288 -0
  355. package/src/generate.ts +56 -0
  356. package/src/index.ts +35 -0
  357. package/src/postgres.ts +415 -0
  358. package/src/server/project.ts +290 -0
  359. package/src/server.ts +500 -0
  360. package/src/utils/cn.ts +6 -0
  361. package/src/utils/label.ts +12 -0
  362. package/src/utils/lookup.ts +11 -0
  363. package/src/utils/template-content.ts +213 -0
@@ -0,0 +1,415 @@
1
+ import { type JourneyConfig, resolveRuntime } from '@shware/workflow';
2
+ import { DEFAULT_SCHEMA } from '@shware/workflow/store';
3
+ import postgres from 'postgres';
4
+ import {
5
+ type Granularity,
6
+ type MetricChannel,
7
+ type StatsRange,
8
+ type StatsSource,
9
+ defineStats,
10
+ } from './config';
11
+
12
+ /**
13
+ * `@shware/workflow-ui/postgres` — the Studio's numbers read straight from the reporting a
14
+ * journeyWorker on Postgres keeps (the engine's schema, `database.schema` in the config). The
15
+ * Studio runs a stats source on its dev server, never in the browser, so it connects with a real
16
+ * connection string:
17
+ *
18
+ * // workflow.stats.ts
19
+ * export default postgresStats({ config, connectionString: process.env.STATS_DATABASE_URL });
20
+ *
21
+ * Time: a fast-forwarded environment (`runtime.<environment>.timeScale`) plays a journey day out
22
+ * in minutes, so every timestamp is read on the journey's clock — `now - (anchor - t) ×
23
+ * timeScale`, the anchor being the latest activity — and the Studio's date ranges are mapped back
24
+ * the same way. A local run of an hour then reads as weeks of history; production (scale 1) is
25
+ * unchanged.
26
+ *
27
+ * Days: the Studio's dates are the viewer's calendar days, so buckets are cut in the same time
28
+ * zone (this machine's by default). Cut in UTC instead, "today" east of Greenwich is an empty
29
+ * bucket on every chart.
30
+ */
31
+
32
+ export interface PostgresStatsOptions {
33
+ /** The project's `workflow.config.ts`: its database schema, and the runtime's time scale. */
34
+ config: JourneyConfig;
35
+ connectionString: string;
36
+ /** Which `runtime` entry the data was written under; `development` by default. */
37
+ environment?: string;
38
+ /** The zone the Studio's days are cut in; this machine's by default. */
39
+ timeZone?: string;
40
+ }
41
+
42
+ /** A calendar day `count` days from a `YYYY-MM-DD` one: plain date math, no zone in it. */
43
+ const addDays = (day: string, count: number) =>
44
+ new Date(Date.parse(`${day}T00:00:00Z`) + count * 86_400_000).toISOString().slice(0, 10);
45
+
46
+ /**
47
+ * One pool per database across reloads: the dev server re-evaluates the stats module on every
48
+ * config change, and a pool per evaluation kept its connections open until Postgres ran out.
49
+ */
50
+ const pools = ((
51
+ globalThis as { __workflowStatsPools?: Map<string, postgres.Sql> }
52
+ ).__workflowStatsPools ??= new Map());
53
+
54
+ function pool(connectionString: string): postgres.Sql {
55
+ let sql = pools.get(connectionString);
56
+ if (sql === undefined) {
57
+ sql = postgres(connectionString, { max: 4, idle_timeout: 20, fetch_types: false });
58
+ pools.set(connectionString, sql);
59
+ }
60
+ return sql;
61
+ }
62
+
63
+ export function postgresStats(options: PostgresStatsOptions): StatsSource {
64
+ const sql = pool(options.connectionString);
65
+ const schema = options.config.database?.schema ?? DEFAULT_SCHEMA;
66
+ /** A table of the engine's schema. */
67
+ const t = (name: string) => sql(`${schema}.${name}`);
68
+ const scale = resolveRuntime(
69
+ options.config.runtime,
70
+ options.environment ?? 'development'
71
+ ).timeScale;
72
+ const timeZone = options.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
73
+
74
+ /**
75
+ * The moment the journey clock reads "now": the latest activity in the data, so a
76
+ * fast-forwarded run keeps reading as the history up to today however long ago it ran —
77
+ * anchored on the real now instead, a run from last night had drifted hundreds of journey days
78
+ * out of every range by morning. Refreshed at the start of every call; with scale 1 it is now.
79
+ */
80
+ let anchor = Date.now();
81
+
82
+ async function refreshAnchor(): Promise<void> {
83
+ if (scale === 1) {
84
+ anchor = Date.now();
85
+ return;
86
+ }
87
+ const [row] = await sql<{ latest: Date | null }[]>`
88
+ select greatest(
89
+ (select max(sent_at) from ${t('message')}),
90
+ (select max(node_at) from ${t('instance')}),
91
+ (select max(finished_at) from ${t('instance')}),
92
+ (select max(taken_at) from ${t('segment_snapshot')})
93
+ ) as latest`;
94
+ const latest =
95
+ row?.latest === null || row?.latest === undefined
96
+ ? Date.now()
97
+ : new Date(row.latest).getTime();
98
+ anchor = Math.min(latest, Date.now());
99
+ }
100
+
101
+ /** An instant on the journey's clock: `now - (anchor - t) × timeScale`. */
102
+ const onJourneyClock = (instant: postgres.PendingQuery<postgres.Row[]>) =>
103
+ sql`(${new Date().toISOString()}::timestamptz - (${new Date(anchor).toISOString()}::timestamptz - ${instant}) * ${scale}::float)`;
104
+ const virtual = (column: string) => onJourneyClock(sql`${sql(column)}`);
105
+
106
+ /** A column on the journey's clock, as a wall-clock time in the viewer's zone. */
107
+ const local = (column: string) => sql`(${virtual(column)} at time zone ${timeZone})`;
108
+
109
+ /** `YYYY-MM-DD` of an instant in the viewer's zone. */
110
+ const localDate = (ms: number) =>
111
+ new Intl.DateTimeFormat('en-CA', {
112
+ timeZone,
113
+ year: 'numeric',
114
+ month: '2-digit',
115
+ day: '2-digit',
116
+ }).format(ms);
117
+
118
+ /** The instant a local calendar day starts. */
119
+ function startOfLocalDay(day: string): number {
120
+ const utcMidnight = Date.parse(`${day}T00:00:00Z`);
121
+ // The zone's offset at that moment: how far its wall clock reads from UTC
122
+ const parts = Object.fromEntries(
123
+ new Intl.DateTimeFormat('en-US', {
124
+ timeZone,
125
+ hourCycle: 'h23',
126
+ year: 'numeric',
127
+ month: '2-digit',
128
+ day: '2-digit',
129
+ hour: '2-digit',
130
+ minute: '2-digit',
131
+ second: '2-digit',
132
+ })
133
+ .formatToParts(utcMidnight)
134
+ .map((part) => [part.type, part.value])
135
+ );
136
+ const n = (type: string) => Number(parts[type] ?? 0);
137
+ const wall = Date.UTC(n('year'), n('month') - 1, n('day'), n('hour'), n('minute'), n('second'));
138
+ return utcMidnight - (wall - utcMidnight);
139
+ }
140
+
141
+ /** The real instants a virtual `YYYY-MM-DD` range (both ends inclusive, local days) covers. */
142
+ function realRange({ from, to }: StatsRange): { from: string; to: string } {
143
+ const now = Date.now();
144
+ const back = (ms: number) => new Date(anchor - (now - ms) / scale).toISOString();
145
+ // The end is the start of the next local day, not 24 hours on: a DST day is 23 or 25
146
+ return { from: back(startOfLocalDay(from)), to: back(startOfLocalDay(addDays(to, 1))) };
147
+ }
148
+
149
+ /**
150
+ * When a copy reached its recipient: the transport's acceptance for email and Android, the
151
+ * device's own report for iOS and the web — a push APNs or a push service accepted can still
152
+ * never arrive (the app was deleted, the device stayed off). An app version without the
153
+ * reporting extension shows its iOS pushes undelivered.
154
+ */
155
+ const reached = sql`(case when m.channel in ('push_ios', 'push_web') then m.device_delivered_at else m.delivered_at end)`;
156
+
157
+ /**
158
+ * A converted instance: `converted_at` is set whatever the status (with `exitOnMatch: false` a
159
+ * conversion ends `completed`); rows written before the column existed only had status `goal`.
160
+ */
161
+ const converted = sql`(converted_at is not null or status = 'goal')`;
162
+
163
+ const channelFilter = (channel: MetricChannel | undefined) =>
164
+ channel === undefined ? sql`true` : sql`m.channel = ${channel}`;
165
+
166
+ /** The last 14 journey days, oldest first, as local `YYYY-MM-DD`. */
167
+ function lastDays(count = 14): string[] {
168
+ const today = localDate(Date.now());
169
+ return Array.from({ length: count }, (_, i) => addDays(today, i - (count - 1)));
170
+ }
171
+
172
+ return defineStats({
173
+ async reports() {
174
+ await refreshAnchor();
175
+ const totals = await sql<
176
+ { id: string; entered: number; active: number; completed: number; converted: number }[]
177
+ >`
178
+ select workflow as id,
179
+ count(*)::int as entered,
180
+ count(*) filter (where status = 'running')::int as active,
181
+ count(*) filter (where status in ('completed', 'exited', 'exit_when', 'goal'))::int as completed,
182
+ count(*) filter (where ${converted})::int as converted
183
+ from ${t('instance')} group by workflow`;
184
+ const engagement = await sql<
185
+ { id: string; delivered: number; opened: number; clicked: number }[]
186
+ >`
187
+ select workflow as id,
188
+ count(${reached})::int as delivered,
189
+ count(opened_at) filter (where ${reached} is not null)::int as opened,
190
+ count(clicked_at) filter (where ${reached} is not null)::int as clicked
191
+ from ${t('message')} m group by workflow`;
192
+ const days = lastDays();
193
+ const series = await sql<
194
+ { id: string; day: string; delivered: number; opened: number; clicked: number }[]
195
+ >`
196
+ select workflow as id, to_char(${local('delivered_at')}, 'YYYY-MM-DD') as day,
197
+ count(${reached})::int as delivered,
198
+ count(opened_at) filter (where ${reached} is not null)::int as opened,
199
+ count(clicked_at) filter (where ${reached} is not null)::int as clicked
200
+ from ${t('message')} m where delivered_at is not null
201
+ group by 1, 2`;
202
+ const conversions = await sql<{ id: string; day: string; converted: number }[]>`
203
+ select workflow as id,
204
+ to_char(${onJourneyClock(sql`coalesce(converted_at, finished_at)`)} at time zone ${timeZone}, 'YYYY-MM-DD') as day,
205
+ count(*)::int as converted
206
+ from ${t('instance')} where ${converted} group by 1, 2`;
207
+ const daily = (id: string, rows: { id: string; day: string }[], key: string) =>
208
+ days.map(
209
+ (day) =>
210
+ (
211
+ rows.find((r) => r.id === id && r.day === day) as Record<string, number> | undefined
212
+ )?.[key] ?? 0
213
+ );
214
+ return totals.map((total) => {
215
+ const e = engagement.find((row) => row.id === total.id);
216
+ return {
217
+ id: total.id,
218
+ entered: total.entered,
219
+ active: total.active,
220
+ completed: total.completed,
221
+ converted: total.converted,
222
+ delivered: e?.delivered ?? 0,
223
+ opened: e?.opened ?? 0,
224
+ clicked: e?.clicked ?? 0,
225
+ series: {
226
+ delivered: daily(total.id, series, 'delivered'),
227
+ opened: daily(total.id, series, 'opened'),
228
+ clicked: daily(total.id, series, 'clicked'),
229
+ converted: daily(total.id, conversions, 'converted'),
230
+ },
231
+ };
232
+ });
233
+ },
234
+
235
+ async nodeStats(workflow) {
236
+ await refreshAnchor();
237
+ const rows = await sql<{ node_id: string; users: number }[]>`
238
+ select node_id, count(*)::int as users from ${t('instance')}
239
+ where workflow = ${workflow} and status = 'running' and node_id is not null
240
+ group by node_id`;
241
+ return Object.fromEntries(rows.map((row) => [row.node_id, row.users]));
242
+ },
243
+
244
+ async metrics(workflow, query) {
245
+ await refreshAnchor();
246
+ const { from, to } = realRange(query);
247
+ const unit: Granularity = query.granularity;
248
+ const bucket = (column: string) =>
249
+ sql`to_char(date_trunc(${unit}, ${local(column)}), 'YYYY-MM-DD')`;
250
+ const messages = await sql<
251
+ {
252
+ day: string;
253
+ sent: number;
254
+ delivered: number;
255
+ opened: number;
256
+ opened_human: number;
257
+ clicked: number;
258
+ clicked_human: number;
259
+ }[]
260
+ >`
261
+ with m as (
262
+ select * from ${t('message')} m
263
+ where m.workflow = ${workflow} and ${channelFilter(query.channel)}
264
+ ),
265
+ events as (
266
+ select ${bucket('sent_at')} as day, 'sent' as kind, false as human from m
267
+ where sent_at between ${from} and ${to}
268
+ union all select ${bucket('delivered_at')}, 'delivered', false from m
269
+ where ${reached} is not null and delivered_at between ${from} and ${to}
270
+ -- Opens and clicks count against the bucket the message was delivered in (its cohort),
271
+ -- not the day they happened: the rates drawn are opened / delivered, and an open
272
+ -- counted on another day than its delivery reads as 160% on a quiet day
273
+ union all select ${bucket('delivered_at')}, 'opened', human_opened_at is not null from m
274
+ where opened_at is not null and ${reached} is not null and delivered_at between ${from} and ${to}
275
+ union all select ${bucket('delivered_at')}, 'clicked', human_clicked_at is not null from m
276
+ where clicked_at is not null and ${reached} is not null and delivered_at between ${from} and ${to}
277
+ )
278
+ select day,
279
+ count(*) filter (where kind = 'sent')::int as sent,
280
+ count(*) filter (where kind = 'delivered')::int as delivered,
281
+ count(*) filter (where kind = 'opened')::int as opened,
282
+ count(*) filter (where kind = 'opened' and human)::int as opened_human,
283
+ count(*) filter (where kind = 'clicked')::int as clicked,
284
+ count(*) filter (where kind = 'clicked' and human)::int as clicked_human
285
+ from events group by day`;
286
+ // Users by the bucket they entered in, and how many of each cohort reached the goal: the
287
+ // conversion rate is a share of one group of people, so it stays within 100%
288
+ const cohorts = await sql<{ day: string; entered: number; converted: number }[]>`
289
+ select ${bucket('entered_at')} as day, count(*)::int as entered,
290
+ count(*) filter (where ${converted})::int as converted
291
+ from ${t('instance')}
292
+ where workflow = ${workflow} and entered_at between ${from} and ${to}
293
+ group by 1`;
294
+ const buckets = await sql<{ day: string }[]>`
295
+ select to_char(d, 'YYYY-MM-DD') as day
296
+ from generate_series(date_trunc(${unit}, ${query.from}::date), ${query.to}::date, ${`1 ${unit}`}::interval) d`;
297
+ return buckets.map(({ day }) => {
298
+ const m = messages.find((row) => row.day === day);
299
+ const opened = m?.opened ?? 0;
300
+ const clicked = m?.clicked ?? 0;
301
+ const cohort = cohorts.find((row) => row.day === day);
302
+ return {
303
+ date: day,
304
+ sent: m?.sent ?? 0,
305
+ delivered: m?.delivered ?? 0,
306
+ opened,
307
+ openedHuman: m?.opened_human ?? 0,
308
+ openedMachine: opened - (m?.opened_human ?? 0),
309
+ clicked,
310
+ clickedHuman: m?.clicked_human ?? 0,
311
+ clickedMachine: clicked - (m?.clicked_human ?? 0),
312
+ entered: cohort?.entered ?? 0,
313
+ converted: cohort?.converted ?? 0,
314
+ };
315
+ });
316
+ },
317
+
318
+ async links(workflow, query) {
319
+ await refreshAnchor();
320
+ const { from, to } = realRange(query);
321
+ return sql<{ url: string; clicks: number }[]>`
322
+ select c.url, count(*)::int as clicks
323
+ from ${t('message_click')} c
324
+ join ${t('message')} m on m.id = c.message_id
325
+ where m.workflow = ${workflow} and ${channelFilter(query.channel)}
326
+ and c.clicked_at between ${from} and ${to}
327
+ -- People's clicks only: a scanner follows every link, the footer's included
328
+ and not c.machine
329
+ group by c.url order by clicks desc limit 50`;
330
+ },
331
+
332
+ async messages(workflow, query) {
333
+ await refreshAnchor();
334
+ const { from, to } = realRange(query);
335
+ return sql<
336
+ {
337
+ nodeId: string;
338
+ template: string;
339
+ channel: MetricChannel;
340
+ sent: number;
341
+ delivered: number;
342
+ opened: number;
343
+ clicked: number;
344
+ unsubscribed: number;
345
+ }[]
346
+ >`
347
+ select node_id as "nodeId", template, channel,
348
+ count(*)::int as sent,
349
+ count(${reached})::int as delivered,
350
+ count(opened_at) filter (where ${reached} is not null)::int as opened,
351
+ count(clicked_at) filter (where ${reached} is not null)::int as clicked,
352
+ count(unsubscribed_at)::int as unsubscribed
353
+ from ${t('message')} m
354
+ where m.workflow = ${workflow} and ${channelFilter(query.channel)}
355
+ and m.sent_at between ${from} and ${to}
356
+ group by node_id, template, channel order by node_id, channel`;
357
+ },
358
+
359
+ async segments() {
360
+ await refreshAnchor();
361
+ const sizes = await sql<{ id: string; size: number }[]>`
362
+ select s.id, count(m.user_id)::int as size
363
+ from ${t('segment')} s
364
+ left join ${t('segment_member')} m on m.segment = s.id
365
+ group by s.id`;
366
+ const days = lastDays();
367
+ // The last snapshot of each journey day
368
+ const snapshots = await sql<{ id: string; day: string; size: number }[]>`
369
+ select distinct on (segment, day) segment as id, day, size from (
370
+ select segment, size, taken_at, to_char(${local('taken_at')}, 'YYYY-MM-DD') as day
371
+ from ${t('segment_snapshot')}
372
+ ) s order by segment, day, taken_at desc`;
373
+ return sizes.map(({ id, size }) => {
374
+ let last = 0;
375
+ const series = days.map((day) => {
376
+ last = snapshots.find((s) => s.id === id && s.day === day)?.size ?? last;
377
+ return last;
378
+ });
379
+ return { id, size, series };
380
+ });
381
+ },
382
+
383
+ async profiles(segment, { limit, offset }) {
384
+ await refreshAnchor();
385
+ const [count] = await sql<{ total: number }[]>`
386
+ select count(*)::int as total from ${t('segment_member')} where segment = ${segment}`;
387
+ // "Created" is the user's first event: the engine knows nothing older about them
388
+ const rows = await sql<
389
+ { id: string; props: Record<string, unknown> | null; created_at: Date | null }[]
390
+ >`
391
+ select m.user_id as id, p.props,
392
+ ${onJourneyClock(sql`first_event.ts`)} as created_at
393
+ from ${t('segment_member')} m
394
+ left join ${t('profile')} p on p.user_id = m.user_id
395
+ left join lateral (
396
+ select min(ts) as ts from ${t('event')} e where e.user_id = m.user_id
397
+ ) first_event on true
398
+ where m.segment = ${segment}
399
+ order by m.ts desc, m.user_id
400
+ limit ${limit} offset ${offset}`;
401
+ return {
402
+ total: count?.total ?? 0,
403
+ profiles: rows.map(({ id, props, created_at }) => {
404
+ const { email, ...properties } = props ?? {};
405
+ const profile: { id: string; email?: string; createdAt?: string } & {
406
+ properties: Record<string, unknown>;
407
+ } = { id, properties };
408
+ if (typeof email === 'string') profile.email = email;
409
+ if (created_at !== null) profile.createdAt = new Date(created_at).toISOString();
410
+ return profile;
411
+ }),
412
+ };
413
+ },
414
+ });
415
+ }