sendwend 0.0.0-stage → 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 (680) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2082 -2
  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 +279 -3
  680. package/src/cloudflare/workers.d.ts +44 -0
@@ -0,0 +1,221 @@
1
+ import { DEFAULT_SCHEMA, TABLES } from "../store/tables.mjs";
2
+ import { beginReadCommitted } from "../store/user-lock.mjs";
3
+ // src/node/runs.ts
4
+ /**
5
+ * The self-hosted runtime's own tables, `run` and `run_step`: every statement the runtime issues
6
+ * is here, so the rules that make it safe are in one place.
7
+ *
8
+ * Two of them carry everything:
9
+ *
10
+ * - **The claim** picks one due run with `FOR UPDATE SKIP LOCKED` and increments its
11
+ * `lease_gen`. Any number of workers, in any number of processes, can run it at once and no
12
+ * run is handed to two of them.
13
+ * - **The fence**: every write a turn makes names the `lease_gen` it claimed with and requires
14
+ * the run to be `running` still. A worker whose lease expired and was taken over, or whose run
15
+ * was terminated under it, finds its write refused (`false`) and drops the turn — it was only
16
+ * slow, and its successor's state is the one that counts.
17
+ *
18
+ * Time is always the caller's clock, passed in: the runtime is driven by an injected clock in
19
+ * tests, and one clock for the claim, the wake instants and the leases keeps them comparable.
20
+ */
21
+ const TS = (param) => `to_timestamp(${param}::double precision / 1000)`;
22
+ const MS = (column) => `(extract(epoch FROM ${column}) * 1000)::double precision`;
23
+ /** The states a run is in while it can still be picked up. */
24
+ const LIVE = `('queued', 'running', 'sleeping', 'waiting')`;
25
+ var RunStore = class RunStore {
26
+ sql;
27
+ run;
28
+ step;
29
+ constructor(sql, schema = DEFAULT_SCHEMA) {
30
+ this.sql = sql;
31
+ this.run = `"${schema}"."${TABLES.run.name}"`;
32
+ this.step = `"${schema}"."${TABLES.runStep.name}"`;
33
+ }
34
+ /**
35
+ * One statement that may meet another worker's write to the same row. Each is a transaction
36
+ * of its own, so under READ COMMITTED (the server's default) it simply sees the row as the
37
+ * other left it. A pool that defaults to REPEATABLE READ or SERIALIZABLE gets a serialization
38
+ * failure there instead (40001), with nothing written: the statement is then run again in a
39
+ * transaction pinned to READ COMMITTED, where it cannot fail that way. The default pays
40
+ * nothing for it.
41
+ */
42
+ async write(text, params) {
43
+ try {
44
+ return await this.sql.query(text, params);
45
+ } catch (error) {
46
+ if (error?.code !== "40001") throw error;
47
+ return this.sql.transaction(async (tx) => {
48
+ await beginReadCommitted(tx);
49
+ return tx.query(text, params);
50
+ });
51
+ }
52
+ }
53
+ /** A new run, due at once. False when the id is taken: an instance id names one run for good. */
54
+ async create(id, params, enteredAt, now) {
55
+ return (await this.sql.query(`INSERT INTO ${this.run}
56
+ (instance_id, params, entered_at, status, wake_at, signals, lease_gen, created_at)
57
+ VALUES ($1, $2::text::jsonb, ${TS("$3")}, 'queued', ${TS("$4")}, 0, 0, ${TS("$4")})
58
+ ON CONFLICT DO NOTHING RETURNING instance_id`, [
59
+ id,
60
+ JSON.stringify(params),
61
+ enteredAt,
62
+ now
63
+ ])).length > 0;
64
+ }
65
+ async status(id) {
66
+ return (await this.sql.transaction((tx) => tx.query(`SELECT status FROM ${this.run} WHERE instance_id = $1`, [id]))).at(0)?.status;
67
+ }
68
+ /**
69
+ * A wake: the counter moves, and a run that is parked or asleep becomes due now. A run in the
70
+ * middle of a turn only gets the counter — its park is conditional on it (`Suspension`).
71
+ * False when the run is unknown or over.
72
+ */
73
+ async signal(id, now) {
74
+ return (await this.write(`UPDATE ${this.run} SET signals = signals + 1,
75
+ wake_at = CASE WHEN status = 'running' THEN wake_at ELSE LEAST(wake_at, ${TS("$2")}) END
76
+ WHERE instance_id = $1 AND status IN ${LIVE} RETURNING instance_id`, [id, now])).length > 0;
77
+ }
78
+ /** Stop a run for good. False when it is unknown or had already ended. */
79
+ async terminate(id, now) {
80
+ return (await this.write(`UPDATE ${this.run} SET status = 'terminated', wake_at = NULL, finished_at = ${TS("$2")},
81
+ lease_owner = NULL, lease_until = NULL
82
+ WHERE instance_id = $1 AND status IN ${LIVE} RETURNING instance_id`, [id, now])).length > 0;
83
+ }
84
+ /**
85
+ * The earliest due run nobody holds — one whose lease ran out included, which is how a run
86
+ * outlives the worker that died with it.
87
+ */
88
+ async claim(owner, now, leaseMs) {
89
+ const row = (await this.write(`UPDATE ${this.run} AS r SET status = 'running', lease_owner = $1,
90
+ lease_until = ${TS("$3")}, lease_gen = r.lease_gen + 1
91
+ WHERE r.instance_id = (
92
+ SELECT instance_id FROM ${this.run}
93
+ WHERE status IN ${LIVE} AND wake_at <= ${TS("$2")}
94
+ AND (lease_until IS NULL OR lease_until < ${TS("$2")})
95
+ ORDER BY wake_at LIMIT 1 FOR UPDATE SKIP LOCKED
96
+ )
97
+ RETURNING r.instance_id, r.params, ${MS("r.entered_at")} AS entered_at, r.lease_gen,
98
+ (SELECT jsonb_agg(jsonb_build_object('key', s.key, 'kind', s.kind, 'done', s.done,
99
+ 'result', s.result, 'attempts', s.attempts))
100
+ FROM ${this.step} s WHERE s.instance_id = r.instance_id) AS steps`, [
101
+ owner,
102
+ now,
103
+ now + leaseMs
104
+ ])).at(0);
105
+ if (row === void 0) return void 0;
106
+ return {
107
+ instanceId: row.instance_id,
108
+ params: typeof row.params === "string" ? JSON.parse(row.params) : row.params,
109
+ enteredAtMs: Number(row.entered_at),
110
+ gen: row.lease_gen,
111
+ steps: new Map(((typeof row.steps === "string" ? JSON.parse(row.steps) : row.steps) ?? []).map(({ key, kind, done, result, attempts }) => [key, {
112
+ kind,
113
+ done,
114
+ result,
115
+ attempts
116
+ }]))
117
+ };
118
+ }
119
+ /** A turn still running holds on to its run. False when it no longer does. */
120
+ async extend(run, until) {
121
+ return (await this.write(`UPDATE ${this.run} SET lease_until = ${TS("$3")}
122
+ WHERE instance_id = $1 AND lease_gen = $2 AND status = 'running' RETURNING instance_id`, [
123
+ run.instanceId,
124
+ run.gen,
125
+ until
126
+ ])).length > 0;
127
+ }
128
+ /** The counter a wait compares against, read fresh. */
129
+ async signals(id) {
130
+ return (await this.sql.transaction((tx) => tx.query(`SELECT signals FROM ${this.run} WHERE instance_id = $1`, [id]))).at(0)?.signals ?? 0;
131
+ }
132
+ /**
133
+ * The checkpoints as one insert, behind the fence: `$1` the instance, `$2` its `lease_gen`,
134
+ * and the two parameters named for the records (JSON) and the time. Nothing is written when
135
+ * the turn no longer holds the run.
136
+ */
137
+ insertSteps(records, at) {
138
+ return `INSERT INTO ${this.step} (instance_id, key, kind, done, result, attempts, created_at)
139
+ SELECT $1, s.key, s.kind, s.done, s.result, s.attempts, ${TS(at)}
140
+ FROM jsonb_to_recordset(${records}::text::jsonb)
141
+ AS s(key text, kind text, done boolean, result jsonb, attempts integer)
142
+ WHERE EXISTS (SELECT 1 FROM ${this.run}
143
+ WHERE instance_id = $1 AND lease_gen = $2 AND status = 'running')
144
+ ON CONFLICT (instance_id, key) DO UPDATE
145
+ SET done = EXCLUDED.done, result = EXCLUDED.result, attempts = EXCLUDED.attempts
146
+ RETURNING key`;
147
+ }
148
+ static encode(writes) {
149
+ return JSON.stringify(writes.map(([key, record]) => ({
150
+ key,
151
+ ...record,
152
+ result: record.result ?? null
153
+ })));
154
+ }
155
+ /**
156
+ * Write checkpoints, behind the fence, in one statement: all of them or none. False when the
157
+ * turn no longer holds the run.
158
+ */
159
+ async checkpoint(run, writes, now) {
160
+ if (writes.length === 0) return true;
161
+ return (await this.write(this.insertSteps("$3", "$4"), [
162
+ run.instanceId,
163
+ run.gen,
164
+ RunStore.encode(writes),
165
+ now
166
+ ])).length > 0;
167
+ }
168
+ /**
169
+ * End a turn that did not end the run, releasing it — with the checkpoints the turn still
170
+ * holds, in the same statement. A wait's park is conditional on no wake having arrived since
171
+ * it subscribed; when one has, the run is queued again at once.
172
+ */
173
+ async suspend(run, suspension, now, writes = []) {
174
+ const { status, wakeAt, ifSignals } = suspension;
175
+ const held = writes.length > 0;
176
+ await this.write(`${held ? `WITH saved AS (${this.insertSteps("$7", "$6")}) ` : ""}UPDATE ${this.run} SET
177
+ status = CASE WHEN $5::int IS NULL OR signals = $5::int THEN $3 ELSE 'queued' END,
178
+ wake_at = CASE WHEN $5::int IS NULL OR signals = $5::int THEN ${TS("$4")} ELSE ${TS("$6")} END,
179
+ lease_owner = NULL, lease_until = NULL
180
+ WHERE instance_id = $1 AND lease_gen = $2 AND status = 'running'`, [
181
+ run.instanceId,
182
+ run.gen,
183
+ status,
184
+ wakeAt,
185
+ ifSignals ?? null,
186
+ now,
187
+ ...held ? [RunStore.encode(writes)] : []
188
+ ]);
189
+ }
190
+ /** The run is over: it returned, or it threw. Its last checkpoints go in the same statement. */
191
+ async finish(run, status, now, error, writes = []) {
192
+ const held = writes.length > 0;
193
+ await this.write(`${held ? `WITH saved AS (${this.insertSteps("$6", "$4")}) ` : ""}UPDATE ${this.run}
194
+ SET status = $3, wake_at = NULL, finished_at = ${TS("$4")}, error = $5,
195
+ lease_owner = NULL, lease_until = NULL
196
+ WHERE instance_id = $1 AND lease_gen = $2 AND status = 'running'`, [
197
+ run.instanceId,
198
+ run.gen,
199
+ status,
200
+ now,
201
+ error ?? null,
202
+ ...held ? [RunStore.encode(writes)] : []
203
+ ]);
204
+ }
205
+ /** Whether anything is due at `now`: what an idle worker asks before it sleeps. */
206
+ async nextWake() {
207
+ const at = (await this.sql.query(`SELECT ${MS("min(wake_at)")} AS at FROM ${this.run} WHERE status IN ${LIVE}`)).at(0)?.at;
208
+ return at === null || at === void 0 ? void 0 : Number(at);
209
+ }
210
+ /** Runs that ended before `before`, and their checkpoints: how many were removed. */
211
+ async prune(before) {
212
+ return this.sql.transaction(async (tx) => {
213
+ const old = `SELECT instance_id FROM ${this.run} WHERE finished_at < ${TS("$1")}`;
214
+ await tx.query(`DELETE FROM ${this.step} WHERE instance_id IN (${old})`, [before]);
215
+ return (await tx.query(`DELETE FROM ${this.run} WHERE finished_at < ${TS("$1")} RETURNING instance_id`, [before])).length;
216
+ });
217
+ }
218
+ };
219
+ export { RunStore };
220
+
221
+ //# sourceMappingURL=runs.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runs.mjs","names":[],"sources":["../../src/node/runs.ts"],"sourcesContent":["import type { JourneyParams } from '../host/platform';\nimport type { SqlClientLike } from '../store/sql';\nimport { DEFAULT_SCHEMA, TABLES } from '../store/tables';\nimport { beginReadCommitted } from '../store/user-lock';\n\n/**\n * The self-hosted runtime's own tables, `run` and `run_step`: every statement the runtime issues\n * is here, so the rules that make it safe are in one place.\n *\n * Two of them carry everything:\n *\n * - **The claim** picks one due run with `FOR UPDATE SKIP LOCKED` and increments its\n * `lease_gen`. Any number of workers, in any number of processes, can run it at once and no\n * run is handed to two of them.\n * - **The fence**: every write a turn makes names the `lease_gen` it claimed with and requires\n * the run to be `running` still. A worker whose lease expired and was taken over, or whose run\n * was terminated under it, finds its write refused (`false`) and drops the turn — it was only\n * slow, and its successor's state is the one that counts.\n *\n * Time is always the caller's clock, passed in: the runtime is driven by an injected clock in\n * tests, and one clock for the claim, the wake instants and the leases keeps them comparable.\n */\n\nconst TS = (param: string) => `to_timestamp(${param}::double precision / 1000)`;\nconst MS = (column: string) => `(extract(epoch FROM ${column}) * 1000)::double precision`;\n\n/** The states a run is in while it can still be picked up. */\nconst LIVE = `('queued', 'running', 'sleeping', 'waiting')`;\n\nexport type RunStatus =\n | 'queued'\n | 'running'\n | 'sleeping'\n | 'waiting'\n | 'complete'\n | 'errored'\n | 'terminated';\n\n/** A run a worker holds for one turn. */\nexport interface ClaimedRun {\n instanceId: string;\n params: JourneyParams;\n enteredAtMs: number;\n /** The fencing token: what every write of this turn is checked against. */\n gen: number;\n /** Its checkpoints so far, read by the claim itself. */\n steps: Map<string, StepRecord>;\n}\n\n/** Checkpoints written together: each key and its record. */\nexport type StepWrites = readonly (readonly [key: string, record: StepRecord])[];\n\n/** One checkpoint, as a turn reads it back. */\nexport interface StepRecord {\n kind: 'do' | 'sleep' | 'wait';\n /** False while a step that threw waits for its retry. */\n done: boolean;\n result: unknown;\n attempts: number;\n}\n\n/** How a turn that did not end the run leaves it. */\nexport interface Suspension {\n status: 'sleeping' | 'waiting' | 'queued';\n wakeAt: number;\n /**\n * A wait parks only while no wake has arrived since it subscribed: the `signals` value it saw.\n * When the counter has moved, the run is queued again at once instead of parked.\n */\n ifSignals?: number | undefined;\n}\n\nexport class RunStore {\n private readonly run: string;\n private readonly step: string;\n\n constructor(\n private readonly sql: SqlClientLike,\n schema: string = DEFAULT_SCHEMA\n ) {\n this.run = `\"${schema}\".\"${TABLES.run.name}\"`;\n this.step = `\"${schema}\".\"${TABLES.runStep.name}\"`;\n }\n\n /**\n * One statement that may meet another worker's write to the same row. Each is a transaction\n * of its own, so under READ COMMITTED (the server's default) it simply sees the row as the\n * other left it. A pool that defaults to REPEATABLE READ or SERIALIZABLE gets a serialization\n * failure there instead (40001), with nothing written: the statement is then run again in a\n * transaction pinned to READ COMMITTED, where it cannot fail that way. The default pays\n * nothing for it.\n */\n private async write<T = Record<string, unknown>>(\n text: string,\n params: readonly unknown[]\n ): Promise<T[]> {\n try {\n return await this.sql.query<T>(text, params);\n } catch (error) {\n if ((error as { code?: unknown } | null)?.code !== '40001') throw error;\n return this.sql.transaction(async (tx) => {\n await beginReadCommitted(tx);\n return tx.query<T>(text, params);\n });\n }\n }\n\n /** A new run, due at once. False when the id is taken: an instance id names one run for good. */\n async create(\n id: string,\n params: JourneyParams,\n enteredAt: number,\n now: number\n ): Promise<boolean> {\n const rows = await this.sql.query(\n `INSERT INTO ${this.run}\n (instance_id, params, entered_at, status, wake_at, signals, lease_gen, created_at)\n VALUES ($1, $2::text::jsonb, ${TS('$3')}, 'queued', ${TS('$4')}, 0, 0, ${TS('$4')})\n ON CONFLICT DO NOTHING RETURNING instance_id`,\n [id, JSON.stringify(params), enteredAt, now]\n );\n return rows.length > 0;\n }\n\n async status(id: string): Promise<RunStatus | undefined> {\n // In a transaction, so a pooler that caches reads answers from the database\n const rows = await this.sql.transaction((tx) =>\n tx.query<{ status: RunStatus }>(`SELECT status FROM ${this.run} WHERE instance_id = $1`, [id])\n );\n return rows.at(0)?.status;\n }\n\n /**\n * A wake: the counter moves, and a run that is parked or asleep becomes due now. A run in the\n * middle of a turn only gets the counter — its park is conditional on it (`Suspension`).\n * False when the run is unknown or over.\n */\n async signal(id: string, now: number): Promise<boolean> {\n const rows = await this.write(\n `UPDATE ${this.run} SET signals = signals + 1,\n wake_at = CASE WHEN status = 'running' THEN wake_at ELSE LEAST(wake_at, ${TS('$2')}) END\n WHERE instance_id = $1 AND status IN ${LIVE} RETURNING instance_id`,\n [id, now]\n );\n return rows.length > 0;\n }\n\n /** Stop a run for good. False when it is unknown or had already ended. */\n async terminate(id: string, now: number): Promise<boolean> {\n const rows = await this.write(\n `UPDATE ${this.run} SET status = 'terminated', wake_at = NULL, finished_at = ${TS('$2')},\n lease_owner = NULL, lease_until = NULL\n WHERE instance_id = $1 AND status IN ${LIVE} RETURNING instance_id`,\n [id, now]\n );\n return rows.length > 0;\n }\n\n /**\n * The earliest due run nobody holds — one whose lease ran out included, which is how a run\n * outlives the worker that died with it.\n */\n async claim(owner: string, now: number, leaseMs: number): Promise<ClaimedRun | undefined> {\n const rows = await this.write<{\n instance_id: string;\n params: unknown;\n entered_at: number | string;\n lease_gen: number;\n steps: unknown;\n }>(\n // The checkpoints come back with the claim: one round trip, not a second one to read them\n `UPDATE ${this.run} AS r SET status = 'running', lease_owner = $1,\n lease_until = ${TS('$3')}, lease_gen = r.lease_gen + 1\n WHERE r.instance_id = (\n SELECT instance_id FROM ${this.run}\n WHERE status IN ${LIVE} AND wake_at <= ${TS('$2')}\n AND (lease_until IS NULL OR lease_until < ${TS('$2')})\n ORDER BY wake_at LIMIT 1 FOR UPDATE SKIP LOCKED\n )\n RETURNING r.instance_id, r.params, ${MS('r.entered_at')} AS entered_at, r.lease_gen,\n (SELECT jsonb_agg(jsonb_build_object('key', s.key, 'kind', s.kind, 'done', s.done,\n 'result', s.result, 'attempts', s.attempts))\n FROM ${this.step} s WHERE s.instance_id = r.instance_id) AS steps`,\n [owner, now, now + leaseMs]\n );\n const row = rows.at(0);\n if (row === undefined) return undefined;\n return {\n instanceId: row.instance_id,\n params: (typeof row.params === 'string'\n ? JSON.parse(row.params)\n : row.params) as JourneyParams,\n enteredAtMs: Number(row.entered_at),\n gen: row.lease_gen,\n steps: new Map(\n (\n ((typeof row.steps === 'string' ? JSON.parse(row.steps) : row.steps) ?? []) as ({\n key: string;\n } & StepRecord)[]\n ).map(({ key, kind, done, result, attempts }) => [key, { kind, done, result, attempts }])\n ),\n };\n }\n\n /** A turn still running holds on to its run. False when it no longer does. */\n async extend(run: ClaimedRun, until: number): Promise<boolean> {\n const rows = await this.write(\n `UPDATE ${this.run} SET lease_until = ${TS('$3')}\n WHERE instance_id = $1 AND lease_gen = $2 AND status = 'running' RETURNING instance_id`,\n [run.instanceId, run.gen, until]\n );\n return rows.length > 0;\n }\n\n /** The counter a wait compares against, read fresh. */\n async signals(id: string): Promise<number> {\n const rows = await this.sql.transaction((tx) =>\n tx.query<{ signals: number }>(`SELECT signals FROM ${this.run} WHERE instance_id = $1`, [id])\n );\n return rows.at(0)?.signals ?? 0;\n }\n\n /**\n * The checkpoints as one insert, behind the fence: `$1` the instance, `$2` its `lease_gen`,\n * and the two parameters named for the records (JSON) and the time. Nothing is written when\n * the turn no longer holds the run.\n */\n private insertSteps(records: string, at: string): string {\n return `INSERT INTO ${this.step} (instance_id, key, kind, done, result, attempts, created_at)\n SELECT $1, s.key, s.kind, s.done, s.result, s.attempts, ${TS(at)}\n FROM jsonb_to_recordset(${records}::text::jsonb)\n AS s(key text, kind text, done boolean, result jsonb, attempts integer)\n WHERE EXISTS (SELECT 1 FROM ${this.run}\n WHERE instance_id = $1 AND lease_gen = $2 AND status = 'running')\n ON CONFLICT (instance_id, key) DO UPDATE\n SET done = EXCLUDED.done, result = EXCLUDED.result, attempts = EXCLUDED.attempts\n RETURNING key`;\n }\n\n private static encode(writes: StepWrites): string {\n return JSON.stringify(\n // undefined has no JSON: a step that returns nothing is stored as null\n writes.map(([key, record]) => ({ key, ...record, result: record.result ?? null }))\n );\n }\n\n /**\n * Write checkpoints, behind the fence, in one statement: all of them or none. False when the\n * turn no longer holds the run.\n */\n async checkpoint(run: ClaimedRun, writes: StepWrites, now: number): Promise<boolean> {\n if (writes.length === 0) return true;\n const rows = await this.write(this.insertSteps('$3', '$4'), [\n run.instanceId,\n run.gen,\n RunStore.encode(writes),\n now,\n ]);\n return rows.length > 0;\n }\n\n /**\n * End a turn that did not end the run, releasing it — with the checkpoints the turn still\n * holds, in the same statement. A wait's park is conditional on no wake having arrived since\n * it subscribed; when one has, the run is queued again at once.\n */\n async suspend(\n run: ClaimedRun,\n suspension: Suspension,\n now: number,\n writes: StepWrites = []\n ): Promise<void> {\n const { status, wakeAt, ifSignals } = suspension;\n const held = writes.length > 0;\n await this.write(\n `${held ? `WITH saved AS (${this.insertSteps('$7', '$6')}) ` : ''}UPDATE ${this.run} SET\n status = CASE WHEN $5::int IS NULL OR signals = $5::int THEN $3 ELSE 'queued' END,\n wake_at = CASE WHEN $5::int IS NULL OR signals = $5::int THEN ${TS('$4')} ELSE ${TS('$6')} END,\n lease_owner = NULL, lease_until = NULL\n WHERE instance_id = $1 AND lease_gen = $2 AND status = 'running'`,\n [\n run.instanceId,\n run.gen,\n status,\n wakeAt,\n ifSignals ?? null,\n now,\n ...(held ? [RunStore.encode(writes)] : []),\n ]\n );\n }\n\n /** The run is over: it returned, or it threw. Its last checkpoints go in the same statement. */\n async finish(\n run: ClaimedRun,\n status: 'complete' | 'errored',\n now: number,\n error?: string,\n writes: StepWrites = []\n ): Promise<void> {\n const held = writes.length > 0;\n await this.write(\n `${held ? `WITH saved AS (${this.insertSteps('$6', '$4')}) ` : ''}UPDATE ${this.run}\n SET status = $3, wake_at = NULL, finished_at = ${TS('$4')}, error = $5,\n lease_owner = NULL, lease_until = NULL\n WHERE instance_id = $1 AND lease_gen = $2 AND status = 'running'`,\n [\n run.instanceId,\n run.gen,\n status,\n now,\n error ?? null,\n ...(held ? [RunStore.encode(writes)] : []),\n ]\n );\n }\n\n /** Whether anything is due at `now`: what an idle worker asks before it sleeps. */\n async nextWake(): Promise<number | undefined> {\n const rows = await this.sql.query<{ at: number | string | null }>(\n `SELECT ${MS('min(wake_at)')} AS at FROM ${this.run} WHERE status IN ${LIVE}`\n );\n const at = rows.at(0)?.at;\n return at === null || at === undefined ? undefined : Number(at);\n }\n\n /** Runs that ended before `before`, and their checkpoints: how many were removed. */\n async prune(before: number): Promise<number> {\n return this.sql.transaction(async (tx) => {\n const old = `SELECT instance_id FROM ${this.run} WHERE finished_at < ${TS('$1')}`;\n await tx.query(`DELETE FROM ${this.step} WHERE instance_id IN (${old})`, [before]);\n const rows = await tx.query(\n `DELETE FROM ${this.run} WHERE finished_at < ${TS('$1')} RETURNING instance_id`,\n [before]\n );\n return rows.length;\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuBA,MAAM,MAAM,UAAkB,gBAAgB,MAAM;AACpD,MAAM,MAAM,WAAmB,uBAAuB,OAAO;;AAG7D,MAAM,OAAO;AA6Cb,IAAa,WAAb,MAAa,SAAS;CAKD;CAJF;CACA;CAEjB,YACmB,KACjB,SAAiB,gBACjB;EAFiB,KAAA,MAAA;EAGjB,KAAK,MAAM,IAAI,OAAO,KAAK,OAAO,IAAI,KAAK;EAC3C,KAAK,OAAO,IAAI,OAAO,KAAK,OAAO,QAAQ,KAAK;CAClD;;;;;;;;;CAUA,MAAc,MACZ,MACA,QACc;EACd,IAAI;GACF,OAAO,MAAM,KAAK,IAAI,MAAS,MAAM,MAAM;EAC7C,SAAS,OAAO;GACd,IAAK,OAAqC,SAAS,SAAS,MAAM;GAClE,OAAO,KAAK,IAAI,YAAY,OAAO,OAAO;IACxC,MAAM,mBAAmB,EAAE;IAC3B,OAAO,GAAG,MAAS,MAAM,MAAM;GACjC,CAAC;EACH;CACF;;CAGA,MAAM,OACJ,IACA,QACA,WACA,KACkB;EA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EACd,CAAC;CACH;AACF"}
@@ -0,0 +1,351 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_engine_retry = require("../engine/retry.cjs");
3
+ const require_store_identity = require("../store/identity.cjs");
4
+ const require_host_platform = require("../host/platform.cjs");
5
+ require("../store/index.cjs");
6
+ // src/node/runtime.ts
7
+ const DEFAULT_STEP_RETRY = {
8
+ limit: 5,
9
+ delayMs: 1e4,
10
+ timeoutMs: 6e5
11
+ };
12
+ /**
13
+ * How long a claim holds before another worker may take the run; a running turn keeps extending
14
+ * it. Leases are told by each process's own clock, so the processes' clocks must agree to well
15
+ * within this (NTP does): one far ahead takes runs that are still being run.
16
+ */
17
+ const DEFAULT_LEASE_MS = 6e4;
18
+ /** A promise nothing settles: where a suspended turn's journey stays parked. */
19
+ const never = () => new Promise(() => {});
20
+ const messageOf = (error) => error instanceof Error ? `${error.name}: ${error.message}` : String(error);
21
+ /**
22
+ * One turn's `EngineStep`. A call with a checkpoint answers from it; the first call without one
23
+ * does the work. A call that has to wait does not throw through the interpreter — a `catch`
24
+ * there would swallow it and the journey would run on past its own sleep. It reports the
25
+ * suspension to the driver and returns a promise nothing settles, so the journey simply stops
26
+ * where it stands.
27
+ */
28
+ var TurnStep = class {
29
+ run;
30
+ records;
31
+ runs;
32
+ store;
33
+ userId;
34
+ now;
35
+ retry;
36
+ stop;
37
+ seen = /* @__PURE__ */ new Map();
38
+ /**
39
+ * Checkpoints not written yet: the engine's bookkeeping steps, a sleep's instant, a retry's
40
+ * backoff. They go with the next checkpoint that cannot wait, or with the statement that ends
41
+ * the turn — always together with what follows them, so a replay never finds a later step
42
+ * recorded and an earlier one missing.
43
+ */
44
+ held = /* @__PURE__ */ new Map();
45
+ inFlight = /* @__PURE__ */ new Set();
46
+ /** The wake counter as the latest `subscribe` read it: what the next wait compares against. */
47
+ baseline = 0;
48
+ stopped = false;
49
+ /** The run is no longer this turn's: a write was refused, or the runtime's store failed. */
50
+ lost = false;
51
+ /** The store's failure, when that is why: the driver throws it, and the run is replayed. */
52
+ fault;
53
+ constructor(run, records, runs, store, userId, now, retry, stop) {
54
+ this.run = run;
55
+ this.records = records;
56
+ this.runs = runs;
57
+ this.store = store;
58
+ this.userId = userId;
59
+ this.now = now;
60
+ this.retry = retry;
61
+ this.stop = stop;
62
+ }
63
+ /** The step bodies still running: the driver lets them finish before it releases the run. */
64
+ settled() {
65
+ return Promise.allSettled(this.inFlight);
66
+ }
67
+ /** A name used twice in one run is two steps: the key carries which occurrence this is. */
68
+ key(name) {
69
+ const n = (this.seen.get(name) ?? 0) + 1;
70
+ this.seen.set(name, n);
71
+ return n === 1 ? name : `${name}#${n}`;
72
+ }
73
+ halt(how) {
74
+ if (!this.stopped) {
75
+ this.stopped = true;
76
+ this.stop(how);
77
+ }
78
+ return never();
79
+ }
80
+ abandon() {
81
+ this.lost = true;
82
+ return this.halt("abandoned");
83
+ }
84
+ /**
85
+ * The runtime's own store failed (the connection, a failover). That is not the journey
86
+ * failing: thrown to the interpreter it would end the run as errored, for a database that is
87
+ * back a second later. The turn is dropped instead and the run replayed from its checkpoints.
88
+ */
89
+ fail(error) {
90
+ this.fault ??= { error };
91
+ return this.abandon();
92
+ }
93
+ /**
94
+ * Write a checkpoint; a write the fence refuses ends the turn, with nothing more written. A
95
+ * turn that was only suspended still holds its run: a step finishing beside the one that
96
+ * suspended it is recorded.
97
+ */
98
+ async save(key, record, later = false) {
99
+ if (this.lost) return false;
100
+ this.held.set(key, record);
101
+ this.records.set(key, record);
102
+ if (later) return true;
103
+ const writes = Array.from(this.held);
104
+ let kept;
105
+ try {
106
+ kept = await this.runs.checkpoint(this.run, writes, this.now());
107
+ } catch (error) {
108
+ this.fail(error);
109
+ return false;
110
+ }
111
+ if (kept) for (const [written] of writes) this.held.delete(written);
112
+ else this.abandon();
113
+ return kept;
114
+ }
115
+ /** The checkpoints still held, for the statement that ends the turn. */
116
+ take() {
117
+ return Array.from(this.held);
118
+ }
119
+ async do(name, fn, options) {
120
+ const key = this.key(name);
121
+ const record = this.records.get(key);
122
+ if (record?.done === true) return record.result;
123
+ if (this.stopped) return never();
124
+ const failed = record?.attempts ?? 0;
125
+ const retryAt = record?.result;
126
+ if (failed > 0 && retryAt !== void 0 && this.now() < retryAt) return this.halt({
127
+ status: "sleeping",
128
+ wakeAt: retryAt
129
+ });
130
+ const attempt = this.attempt(fn);
131
+ this.inFlight.add(attempt);
132
+ let result;
133
+ try {
134
+ result = await attempt;
135
+ } catch (error) {
136
+ this.inFlight.delete(attempt);
137
+ if (!require_engine_retry.isRetryable(error) || failed >= this.retry.limit) throw error;
138
+ const wakeAt = this.now() + this.retry.delayMs * 2 ** failed;
139
+ if (await this.save(key, {
140
+ kind: "do",
141
+ done: false,
142
+ result: wakeAt,
143
+ attempts: failed + 1
144
+ }, true)) console.warn(`[workflow] step ${name} of ${this.run.instanceId} failed (attempt ${failed + 1}), retrying: ${messageOf(error)}`);
145
+ return this.halt({
146
+ status: "sleeping",
147
+ wakeAt
148
+ });
149
+ }
150
+ this.inFlight.delete(attempt);
151
+ return await this.save(key, {
152
+ kind: "do",
153
+ done: true,
154
+ result,
155
+ attempts: failed + 1
156
+ }, options?.idempotent === true) ? result : never();
157
+ }
158
+ /**
159
+ * One attempt, given up on after the step timeout. Nothing can stop the body itself: a call
160
+ * that answers after its step was given up on has still happened, and the retry repeats it
161
+ * (steps are at least once).
162
+ */
163
+ attempt(fn) {
164
+ let timer;
165
+ const timeout = new Promise((_resolve, reject) => {
166
+ timer = setTimeout(() => {
167
+ reject(/* @__PURE__ */ new Error(`step timed out after ${this.retry.timeoutMs} ms`));
168
+ }, this.retry.timeoutMs);
169
+ });
170
+ return Promise.race([fn(), timeout]).finally(() => {
171
+ clearTimeout(timer);
172
+ });
173
+ }
174
+ async sleep(name, ms) {
175
+ const key = this.key(name);
176
+ let until = this.records.get(key)?.result;
177
+ if (until === void 0) {
178
+ if (this.stopped) return never();
179
+ until = this.now() + ms;
180
+ if (!await this.save(key, {
181
+ kind: "sleep",
182
+ done: true,
183
+ result: until,
184
+ attempts: 0
185
+ }, true)) return never();
186
+ }
187
+ if (this.now() >= until) return;
188
+ return this.halt({
189
+ status: "sleeping",
190
+ wakeAt: until
191
+ });
192
+ }
193
+ async subscribe(name, events) {
194
+ this.baseline = await this.do(name, async () => {
195
+ const signals = await this.runs.signals(this.run.instanceId);
196
+ const owner = await require_store_identity.instanceOwner(this.store, this.run.instanceId, this.userId);
197
+ await this.store.subscribe(this.run.instanceId, owner, events, this.now());
198
+ return signals;
199
+ });
200
+ }
201
+ unsubscribe(name) {
202
+ return this.do(name, () => this.store.unsubscribe(this.run.instanceId));
203
+ }
204
+ async waitForWake(name, { deadlineMs }) {
205
+ const key = this.key(name);
206
+ const record = this.records.get(key);
207
+ if (record?.done === true) return record.result;
208
+ if (this.stopped) return never();
209
+ const answer = async (verdict) => await this.save(key, {
210
+ kind: "wait",
211
+ done: true,
212
+ result: verdict,
213
+ attempts: 0
214
+ }) ? verdict : never();
215
+ let signals;
216
+ try {
217
+ signals = await this.runs.signals(this.run.instanceId);
218
+ } catch (error) {
219
+ return this.fail(error);
220
+ }
221
+ if (signals > this.baseline) return answer("event");
222
+ if (this.now() >= deadlineMs) return answer("timeout");
223
+ return this.halt({
224
+ status: "waiting",
225
+ wakeAt: deadlineMs,
226
+ ifSignals: this.baseline
227
+ });
228
+ }
229
+ };
230
+ var NodeRuntime = class {
231
+ options;
232
+ runs;
233
+ owner;
234
+ now;
235
+ leaseMs;
236
+ retry;
237
+ constructor(options) {
238
+ this.options = options;
239
+ this.runs = options.runs;
240
+ this.owner = options.owner ?? `node-${crypto.randomUUID()}`;
241
+ this.now = options.now ?? (() => Date.now());
242
+ this.leaseMs = options.leaseMs ?? 6e4;
243
+ this.retry = {
244
+ ...DEFAULT_STEP_RETRY,
245
+ ...options.retry
246
+ };
247
+ }
248
+ /** The runtime port the rest of the host starts, wakes and stops instances through. */
249
+ binding = {
250
+ create: async ({ id, params }) => {
251
+ const journey = params;
252
+ if (!await this.runs.create(id, journey, journey.trigger.ts ?? this.now(), this.now())) throw new Error(`instance ${id} already exists`);
253
+ this.options.onDue?.();
254
+ return this.instance(id);
255
+ },
256
+ get: async (id) => {
257
+ if (await this.runs.status(id) === void 0) throw new require_host_platform.InstanceNotFoundError(id);
258
+ return this.instance(id);
259
+ }
260
+ };
261
+ instance(id) {
262
+ return {
263
+ id,
264
+ sendEvent: async () => {
265
+ if (await this.runs.signal(id, this.now())) this.options.onDue?.();
266
+ },
267
+ status: async () => {
268
+ const status = await this.runs.status(id);
269
+ if (status === void 0) throw new require_host_platform.InstanceNotFoundError(id);
270
+ return { status: status === "queued" || status === "sleeping" || status === "waiting" ? "running" : status };
271
+ },
272
+ terminate: async () => {
273
+ await this.runs.terminate(id, this.now());
274
+ }
275
+ };
276
+ }
277
+ /**
278
+ * Claim the earliest due run and take it one turn further. Undefined when nothing is due.
279
+ */
280
+ async turn() {
281
+ const run = await this.runs.claim(this.owner, this.now(), this.leaseMs);
282
+ if (run === void 0) return void 0;
283
+ const { instanceId } = run;
284
+ const beat = setInterval(() => {
285
+ this.runs.extend(run, this.now() + this.leaseMs).catch(() => {});
286
+ }, Math.max(50, this.leaseMs / 3));
287
+ const parts = this.options.open(run);
288
+ try {
289
+ let stop;
290
+ const stopped = new Promise((resolve) => {
291
+ stop = resolve;
292
+ });
293
+ const step = new TurnStep(run, run.steps, this.runs, parts.store, run.params.userId, this.now, this.retry, stop);
294
+ const end = await Promise.race([parts.execute(step).then((outcome) => ({ outcome }), (error) => ({ error })), stopped.then((how) => ({ how }))]);
295
+ if ("how" in end) {
296
+ await step.settled();
297
+ if (step.fault !== void 0) throw step.fault.error;
298
+ if (end.how === "abandoned" || step.lost) return {
299
+ instanceId,
300
+ ended: "abandoned"
301
+ };
302
+ await this.runs.suspend(run, end.how, this.now(), step.take());
303
+ return {
304
+ instanceId,
305
+ ended: "suspended",
306
+ wakeAt: end.how.wakeAt
307
+ };
308
+ }
309
+ if ("error" in end) {
310
+ await this.runs.finish(run, "errored", this.now(), messageOf(end.error), step.take());
311
+ return {
312
+ instanceId,
313
+ ended: "errored",
314
+ error: end.error
315
+ };
316
+ }
317
+ await this.runs.finish(run, "complete", this.now(), void 0, step.take());
318
+ return {
319
+ instanceId,
320
+ ended: "complete",
321
+ outcome: end.outcome
322
+ };
323
+ } finally {
324
+ clearInterval(beat);
325
+ await parts.close();
326
+ }
327
+ }
328
+ /** Every run that is due now, one after another; what each turn came to. */
329
+ async drain(limit = Number.POSITIVE_INFINITY) {
330
+ const results = [];
331
+ while (results.length < limit) {
332
+ const result = await this.turn();
333
+ if (result === void 0) break;
334
+ results.push(result);
335
+ }
336
+ return results;
337
+ }
338
+ /** When the next run is due, if any is waiting on the clock. */
339
+ nextWake() {
340
+ return this.runs.nextWake();
341
+ }
342
+ /** Remove the runs that ended more than `olderThanMs` ago. */
343
+ prune(olderThanMs) {
344
+ return this.runs.prune(this.now() - olderThanMs);
345
+ }
346
+ };
347
+ exports.DEFAULT_LEASE_MS = DEFAULT_LEASE_MS;
348
+ exports.DEFAULT_STEP_RETRY = DEFAULT_STEP_RETRY;
349
+ exports.NodeRuntime = NodeRuntime;
350
+
351
+ //# sourceMappingURL=runtime.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.cjs","names":["isRetryable","instanceOwner","InstanceNotFoundError"],"sources":["../../src/node/runtime.ts"],"sourcesContent":["import type { EngineStep, JourneyOutcome, StepOptions } from '../engine/ports';\nimport { isRetryable } from '../engine/retry';\nimport {\n InstanceNotFoundError,\n type JourneyParams,\n type WorkflowBindingLike,\n type WorkflowInstanceLike,\n} from '../host/platform';\nimport { type JourneyStore, instanceOwner } from '../store/index';\nimport type { ClaimedRun, RunStore, StepRecord, StepWrites, Suspension } from './runs';\n\n/**\n * The self-hosted runtime: journeys as rows, run a turn at a time.\n *\n * A turn claims one due run, replays the journey from the top with the run's checkpoints in\n * memory, and ends in one of three ways: the journey returned, it threw, or it reached something\n * that has to wait (a sleep, a retry's backoff, a wait for a wake) and was **suspended** — its\n * state written, its lease released, to be claimed again when that is due.\n *\n * This is the model both other hosts run on (Cloudflare Workflows, Lambda durable functions);\n * here the process is the runtime and Postgres its only state.\n */\n\n/** A step's retries, as Cloudflare Workflows defaults them. */\nexport interface StepRetryPolicy {\n /** Retries after the first attempt. */\n limit: number;\n /** The wait before the first retry; doubled before each one after. */\n delayMs: number;\n /** How long one attempt may run before it counts as failed. */\n timeoutMs: number;\n}\n\nexport const DEFAULT_STEP_RETRY: StepRetryPolicy = {\n limit: 5,\n delayMs: 10_000,\n timeoutMs: 10 * 60_000,\n};\n\n/**\n * How long a claim holds before another worker may take the run; a running turn keeps extending\n * it. Leases are told by each process's own clock, so the processes' clocks must agree to well\n * within this (NTP does): one far ahead takes runs that are still being run.\n */\nexport const DEFAULT_LEASE_MS = 60_000;\n\n/** What one run of the journey is given: the store it reads and writes, and how to close it. */\nexport interface TurnParts {\n store: JourneyStore;\n /** Run the journey once over `step`: `executeJourney` with the host's outlets. */\n execute(step: EngineStep): Promise<JourneyOutcome>;\n close(): Promise<void>;\n}\n\nexport interface NodeRuntimeOptions {\n runs: RunStore;\n /** Everything one turn of `instanceId` needs. Called once per turn. */\n open(run: { instanceId: string; params: JourneyParams; enteredAtMs: number }): TurnParts;\n /** This worker's name on the leases it holds. */\n owner?: string;\n now?: () => number;\n leaseMs?: number;\n retry?: Partial<StepRetryPolicy>;\n /** Told when a run becomes due at once (a create, a wake), so an idle worker need not poll for it. */\n onDue?: () => void;\n}\n\n/** How a turn ended. */\nexport type TurnResult =\n | { instanceId: string; ended: 'complete'; outcome: JourneyOutcome }\n | { instanceId: string; ended: 'errored'; error: unknown }\n | { instanceId: string; ended: 'suspended'; wakeAt: number }\n /** The run was taken from this turn (its lease ran out, or it was terminated): nothing was written. */\n | { instanceId: string; ended: 'abandoned' };\n\n/** A promise nothing settles: where a suspended turn's journey stays parked. */\nconst never = <T>(): Promise<T> => new Promise<T>(() => {});\n\nconst messageOf = (error: unknown): string =>\n error instanceof Error ? `${error.name}: ${error.message}` : String(error);\n\n/**\n * One turn's `EngineStep`. A call with a checkpoint answers from it; the first call without one\n * does the work. A call that has to wait does not throw through the interpreter — a `catch`\n * there would swallow it and the journey would run on past its own sleep. It reports the\n * suspension to the driver and returns a promise nothing settles, so the journey simply stops\n * where it stands.\n */\nclass TurnStep implements EngineStep {\n private readonly seen = new Map<string, number>();\n /**\n * Checkpoints not written yet: the engine's bookkeeping steps, a sleep's instant, a retry's\n * backoff. They go with the next checkpoint that cannot wait, or with the statement that ends\n * the turn — always together with what follows them, so a replay never finds a later step\n * recorded and an earlier one missing.\n */\n private readonly held = new Map<string, StepRecord>();\n private readonly inFlight = new Set<Promise<unknown>>();\n /** The wake counter as the latest `subscribe` read it: what the next wait compares against. */\n private baseline = 0;\n private stopped = false;\n /** The run is no longer this turn's: a write was refused, or the runtime's store failed. */\n lost = false;\n /** The store's failure, when that is why: the driver throws it, and the run is replayed. */\n fault: { error: unknown } | undefined;\n\n constructor(\n private readonly run: ClaimedRun,\n private readonly records: Map<string, StepRecord>,\n private readonly runs: RunStore,\n private readonly store: JourneyStore,\n private readonly userId: string,\n private readonly now: () => number,\n private readonly retry: StepRetryPolicy,\n private readonly stop: (how: Suspension | 'abandoned') => void\n ) {}\n\n /** The step bodies still running: the driver lets them finish before it releases the run. */\n settled(): Promise<unknown> {\n return Promise.allSettled(this.inFlight);\n }\n\n /** A name used twice in one run is two steps: the key carries which occurrence this is. */\n private key(name: string): string {\n const n = (this.seen.get(name) ?? 0) + 1;\n this.seen.set(name, n);\n return n === 1 ? name : `${name}#${n}`;\n }\n\n private halt<T>(how: Suspension | 'abandoned'): Promise<T> {\n if (!this.stopped) {\n this.stopped = true;\n this.stop(how);\n }\n return never<T>();\n }\n\n private abandon<T>(): Promise<T> {\n this.lost = true;\n return this.halt('abandoned');\n }\n\n /**\n * The runtime's own store failed (the connection, a failover). That is not the journey\n * failing: thrown to the interpreter it would end the run as errored, for a database that is\n * back a second later. The turn is dropped instead and the run replayed from its checkpoints.\n */\n private fail<T>(error: unknown): Promise<T> {\n this.fault ??= { error };\n return this.abandon();\n }\n\n /**\n * Write a checkpoint; a write the fence refuses ends the turn, with nothing more written. A\n * turn that was only suspended still holds its run: a step finishing beside the one that\n * suspended it is recorded.\n */\n private async save(key: string, record: StepRecord, later = false): Promise<boolean> {\n if (this.lost) return false;\n this.held.set(key, record);\n this.records.set(key, record);\n if (later) return true;\n const writes = Array.from(this.held);\n let kept: boolean;\n try {\n kept = await this.runs.checkpoint(this.run, writes, this.now());\n } catch (error) {\n void this.fail(error);\n return false;\n }\n // Only what was sent: a step finishing meanwhile holds its own\n if (kept) for (const [written] of writes) this.held.delete(written);\n else void this.abandon();\n return kept;\n }\n\n /** The checkpoints still held, for the statement that ends the turn. */\n take(): StepWrites {\n return Array.from(this.held);\n }\n\n async do<T>(name: string, fn: () => Promise<T>, options?: StepOptions): Promise<T> {\n const key = this.key(name);\n const record = this.records.get(key);\n if (record?.done === true) return record.result as T;\n if (this.stopped) return never<T>();\n\n const failed = record?.attempts ?? 0;\n // Woken before its backoff was over (a wake meant for a later wait): not yet\n const retryAt = record?.result as number | undefined;\n if (failed > 0 && retryAt !== undefined && this.now() < retryAt) {\n return this.halt({ status: 'sleeping', wakeAt: retryAt });\n }\n\n const attempt = this.attempt(fn);\n this.inFlight.add(attempt);\n let result: T;\n try {\n result = await attempt;\n } catch (error) {\n this.inFlight.delete(attempt);\n // The same on every attempt (a template refusing its props, a provider's 4xx), or out of\n // retries: the journey gets the error, as on the other runtimes\n if (!isRetryable(error) || failed >= this.retry.limit) throw error;\n const wakeAt = this.now() + this.retry.delayMs * 2 ** failed;\n // Held: the suspension that follows writes it\n const kept = await this.save(\n key,\n { kind: 'do', done: false, result: wakeAt, attempts: failed + 1 },\n true\n );\n if (kept) {\n console.warn(\n `[workflow] step ${name} of ${this.run.instanceId} failed (attempt ${failed + 1}), retrying: ${messageOf(error)}`\n );\n }\n return this.halt({ status: 'sleeping', wakeAt });\n }\n this.inFlight.delete(attempt);\n const kept = await this.save(\n key,\n { kind: 'do', done: true, result, attempts: failed + 1 },\n options?.idempotent === true\n );\n return kept ? result : never<T>();\n }\n\n /**\n * One attempt, given up on after the step timeout. Nothing can stop the body itself: a call\n * that answers after its step was given up on has still happened, and the retry repeats it\n * (steps are at least once).\n */\n private attempt<T>(fn: () => Promise<T>): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n reject(new Error(`step timed out after ${this.retry.timeoutMs} ms`));\n }, this.retry.timeoutMs);\n });\n return Promise.race([fn(), timeout]).finally(() => {\n clearTimeout(timer);\n });\n }\n\n async sleep(name: string, ms: number): Promise<void> {\n const key = this.key(name);\n let until = this.records.get(key)?.result as number | undefined;\n if (until === undefined) {\n if (this.stopped) return never();\n // The instant is fixed the first time the sleep is reached: a replay sleeps to the same one\n until = this.now() + ms;\n // Held: the suspension that follows writes it (a sleep of no length has nothing to lose)\n if (\n !(await this.save(key, { kind: 'sleep', done: true, result: until, attempts: 0 }, true))\n ) {\n return never();\n }\n }\n if (this.now() >= until) return;\n return this.halt({ status: 'sleeping', wakeAt: until });\n }\n\n async subscribe(name: string, events: readonly string[]): Promise<void> {\n // The counter is read before the registration is written and kept with the step: a wake\n // that lands any time after this — before the wait is even reached — has moved it\n this.baseline = await this.do(name, async () => {\n const signals = await this.runs.signals(this.run.instanceId);\n // The instance may have changed hands (a visitor who signed in): its wakes follow the owner\n const owner = await instanceOwner(this.store, this.run.instanceId, this.userId);\n await this.store.subscribe(this.run.instanceId, owner, events, this.now());\n return signals;\n });\n }\n\n unsubscribe(name: string): Promise<void> {\n return this.do(name, () => this.store.unsubscribe(this.run.instanceId));\n }\n\n async waitForWake(\n name: string,\n { deadlineMs }: { timeoutMs: number; deadlineMs: number }\n ): Promise<'event' | 'timeout'> {\n const key = this.key(name);\n const record = this.records.get(key);\n if (record?.done === true) return record.result as 'event' | 'timeout';\n if (this.stopped) return never();\n\n const answer = async (verdict: 'event' | 'timeout') =>\n (await this.save(key, { kind: 'wait', done: true, result: verdict, attempts: 0 }))\n ? verdict\n : never<'event' | 'timeout'>();\n let signals: number;\n try {\n signals = await this.runs.signals(this.run.instanceId);\n } catch (error) {\n return this.fail(error);\n }\n // A wake first: one that arrived at the deadline is still a wake\n if (signals > this.baseline) return answer('event');\n if (this.now() >= deadlineMs) return answer('timeout');\n // Parked only if the counter is still where the subscribe found it; otherwise the run is\n // queued again at once and the replay answers 'event' above\n return this.halt({ status: 'waiting', wakeAt: deadlineMs, ifSignals: this.baseline });\n }\n}\n\nexport class NodeRuntime {\n private readonly runs: RunStore;\n private readonly owner: string;\n private readonly now: () => number;\n private readonly leaseMs: number;\n private readonly retry: StepRetryPolicy;\n\n constructor(private readonly options: NodeRuntimeOptions) {\n this.runs = options.runs;\n this.owner = options.owner ?? `node-${crypto.randomUUID()}`;\n // Read through `Date` at each call, not captured: a test that fakes the clock later is followed\n this.now = options.now ?? (() => Date.now());\n this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS;\n this.retry = { ...DEFAULT_STEP_RETRY, ...options.retry };\n }\n\n /** The runtime port the rest of the host starts, wakes and stops instances through. */\n readonly binding: WorkflowBindingLike = {\n create: async ({ id, params }) => {\n const journey = params as JourneyParams;\n // The trigger's time is the entry anchor, as Cloudflare's event timestamp is for its runner\n const created = await this.runs.create(\n id,\n journey,\n journey.trigger.ts ?? this.now(),\n this.now()\n );\n if (!created) throw new Error(`instance ${id} already exists`);\n this.options.onDue?.();\n return this.instance(id);\n },\n get: async (id) => {\n if ((await this.runs.status(id)) === undefined) throw new InstanceNotFoundError(id);\n return this.instance(id);\n },\n };\n\n private instance(id: string): WorkflowInstanceLike {\n return {\n id,\n sendEvent: async () => {\n // A run that is over takes no wake: the host reads its status and drops the subscription\n if (await this.runs.signal(id, this.now())) this.options.onDue?.();\n },\n status: async () => {\n const status = await this.runs.status(id);\n if (status === undefined) throw new InstanceNotFoundError(id);\n // The states between turns are all \"it is running\", as far as the host is concerned\n const live = status === 'queued' || status === 'sleeping' || status === 'waiting';\n return { status: live ? 'running' : status };\n },\n terminate: async () => {\n await this.runs.terminate(id, this.now());\n },\n };\n }\n\n /**\n * Claim the earliest due run and take it one turn further. Undefined when nothing is due.\n */\n async turn(): Promise<TurnResult | undefined> {\n const run = await this.runs.claim(this.owner, this.now(), this.leaseMs);\n if (run === undefined) return undefined;\n const { instanceId } = run;\n\n // Held for as long as the turn runs: a slow action is not a dead worker\n const beat = setInterval(\n () => {\n void this.runs.extend(run, this.now() + this.leaseMs).catch(() => {});\n },\n // Three chances a lease, however short the lease\n Math.max(50, this.leaseMs / 3)\n );\n const parts = this.options.open(run);\n try {\n let stop!: (how: Suspension | 'abandoned') => void;\n const stopped = new Promise<Suspension | 'abandoned'>((resolve) => {\n stop = resolve;\n });\n const step = new TurnStep(\n run,\n run.steps,\n this.runs,\n parts.store,\n run.params.userId,\n this.now,\n this.retry,\n stop\n );\n const end = await Promise.race([\n parts.execute(step).then(\n (outcome) => ({ outcome }),\n (error: unknown) => ({ error })\n ),\n stopped.then((how) => ({ how })),\n ]);\n\n if ('how' in end) {\n // Steps running beside the one that stopped the turn (a push to several devices) get\n // to their own checkpoints before the run is let go\n await step.settled();\n // The store failed under the turn: the caller hears of it, the lease runs out, and the\n // run is taken again\n if (step.fault !== undefined) throw step.fault.error;\n if (end.how === 'abandoned' || step.lost) return { instanceId, ended: 'abandoned' };\n await this.runs.suspend(run, end.how, this.now(), step.take());\n return { instanceId, ended: 'suspended', wakeAt: end.how.wakeAt };\n }\n if ('error' in end) {\n await this.runs.finish(run, 'errored', this.now(), messageOf(end.error), step.take());\n return { instanceId, ended: 'errored', error: end.error };\n }\n await this.runs.finish(run, 'complete', this.now(), undefined, step.take());\n return { instanceId, ended: 'complete', outcome: end.outcome };\n } finally {\n clearInterval(beat);\n await parts.close();\n }\n }\n\n /** Every run that is due now, one after another; what each turn came to. */\n async drain(limit = Number.POSITIVE_INFINITY): Promise<TurnResult[]> {\n const results: TurnResult[] = [];\n while (results.length < limit) {\n const result = await this.turn();\n if (result === undefined) break;\n results.push(result);\n }\n return results;\n }\n\n /** When the next run is due, if any is waiting on the clock. */\n nextWake(): Promise<number | undefined> {\n return this.runs.nextWake();\n }\n\n /** Remove the runs that ended more than `olderThanMs` ago. */\n prune(olderThanMs: number): Promise<number> {\n return this.runs.prune(this.now() - olderThanMs);\n }\n}\n"],"mappings":";;;;;;AAiCA,MAAa,qBAAsC;CACjD,OAAO;CACP,SAAS;CACT,WAAW;AACb;;;;;;AAOA,MAAa,mBAAmB;;AAgChC,MAAM,cAA6B,IAAI,cAAiB,CAAC,CAAC;AAE1D,MAAM,aAAa,UACjB,iBAAiB,QAAQ,GAAG,MAAM,KAAK,IAAI,MAAM,YAAY,OAAO,KAAK;;;;;;;;AAS3E,IAAM,WAAN,MAAqC;CAmBhB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAzBF,uBAAO,IAAI,IAAoB;;;;;;;CAO/B,uBAAO,IAAI,IAAwB;CACnC,2BAAW,IAAI,IAAsB;;CAE9C,WAAW;CACX,UAAU;;CAElB,OAAO;;CAEP;CAEA,YACmB,KACA,SACA,MACA,OACA,QACA,KACA,OACA,MACjB;EARiB,KAAA,MAAA;EACA,KAAA,UAAA;EACA,KAAA,OAAA;EACA,KAAA,QAAA;EACA,KAAA,SAAA;EACA,KAAA,MAAA;EACA,KAAA,QAAA;EACA,KAAA,OAAA;CAChB;;CAGH,UAA4B;EAC1B,OAAO,QAAQ,WAAW,KAAK,QAAQ;CACzC;;CAGQ,IAAI,MAAsB;EAChC,MAAM,KAAK,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK;EACvC,KAAK,KAAK,IAAI,MAAM,CAAC;EACrB,OAAO,MAAM,IAAI,OAAO,GAAG,KAAK,GAAG;CACrC;CAEQ,KAAQ,KAA2C;EACzD,IAAI,CAAC,KAAK,SAAS;GACjB,KAAK,UAAU;GACf,KAAK,K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