@demlik/tea 0.12.0 → 0.14.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 (368) hide show
  1. package/README.md +11 -9
  2. package/dist/agent/index.d.ts +638 -45
  3. package/dist/agent/index.js +9 -19
  4. package/dist/{chunk-25LBDCBC.js → chunk-6IQPODUF.js} +2 -2
  5. package/dist/{chunk-25LBDCBC.js.map → chunk-6IQPODUF.js.map} +1 -1
  6. package/dist/chunk-AQ6ZIMEA.js +421 -0
  7. package/dist/chunk-AQ6ZIMEA.js.map +1 -0
  8. package/dist/{chunk-MUUROGIH.js → chunk-BLJ2JQSH.js} +62 -12
  9. package/dist/chunk-BLJ2JQSH.js.map +1 -0
  10. package/dist/{chunk-7SVIRMC6.js → chunk-F2US5BW6.js} +25 -5
  11. package/dist/chunk-F2US5BW6.js.map +1 -0
  12. package/dist/{batch-window/index.js → chunk-F7FMAWLA.js} +4 -8
  13. package/dist/chunk-F7FMAWLA.js.map +1 -0
  14. package/dist/{chunk-7V4EVLZA.js → chunk-HUKZQX6U.js} +20 -16
  15. package/dist/chunk-HUKZQX6U.js.map +1 -0
  16. package/dist/{chunk-EWJP3YYP.js → chunk-HWVW4AXC.js} +3 -3
  17. package/dist/chunk-HWVW4AXC.js.map +1 -0
  18. package/dist/{chunk-WLGO64WC.js → chunk-HYDWG35Q.js} +23 -6
  19. package/dist/chunk-HYDWG35Q.js.map +1 -0
  20. package/dist/{chunk-I5OV65MS.js → chunk-I5MQMJDW.js} +57 -7
  21. package/dist/chunk-I5MQMJDW.js.map +1 -0
  22. package/dist/{chunk-J6527VRQ.js → chunk-LFZUK6J2.js} +3 -3
  23. package/dist/chunk-LFZUK6J2.js.map +1 -0
  24. package/dist/{chunk-ZVJZ72HY.js → chunk-LYLTKJWM.js} +25 -11
  25. package/dist/chunk-LYLTKJWM.js.map +1 -0
  26. package/dist/{chunk-D736QUGF.js → chunk-MYXFNWAJ.js} +4 -5
  27. package/dist/chunk-MYXFNWAJ.js.map +1 -0
  28. package/dist/{chunk-K575PT4S.js → chunk-PR6TB3BL.js} +15 -4
  29. package/dist/chunk-PR6TB3BL.js.map +1 -0
  30. package/dist/chunk-RQULHGYH.js +1804 -0
  31. package/dist/chunk-RQULHGYH.js.map +1 -0
  32. package/dist/{chunk-FV3Z5MBE.js → chunk-TXN2KFHF.js} +14 -4
  33. package/dist/chunk-TXN2KFHF.js.map +1 -0
  34. package/dist/{chunk-Q2UM7BXU.js → chunk-VBDU4JL6.js} +2 -2
  35. package/dist/chunk-VBDU4JL6.js.map +1 -0
  36. package/dist/chunk-Z2L3LSNV.js +1470 -0
  37. package/dist/chunk-Z2L3LSNV.js.map +1 -0
  38. package/dist/core-CTzMJ82M.d.ts +562 -0
  39. package/dist/devtools/index.d.ts +2 -2
  40. package/dist/devtools/index.js +207 -2
  41. package/dist/devtools/index.js.map +1 -1
  42. package/dist/do/index.d.ts +48 -31
  43. package/dist/do/index.js +36 -25
  44. package/dist/do/index.js.map +1 -1
  45. package/dist/{durable-effects-D8SqU_if.d.ts → durable-effects-B0-qGQDy.d.ts} +2 -2
  46. package/dist/extension/index.d.ts +301 -3
  47. package/dist/extension/index.js +596 -5
  48. package/dist/extension/index.js.map +1 -1
  49. package/dist/flow/index.d.ts +1295 -0
  50. package/dist/flow/index.js +732 -0
  51. package/dist/flow/index.js.map +1 -0
  52. package/dist/idempotency/index.d.ts +90 -116
  53. package/dist/idempotency/index.js +4 -1
  54. package/dist/{batch-window/index.d.ts → index-4vZzljCD.d.ts} +7 -11
  55. package/dist/{fan-out/index.d.ts → index-6A7dB8f6.d.ts} +7 -8
  56. package/dist/index-B5BZ-_cT.d.ts +616 -0
  57. package/dist/index-Bc40JWVl.d.ts +131 -0
  58. package/dist/{debounce/index.d.ts → index-DHSUmQTR.d.ts} +7 -7
  59. package/dist/index-DJWIER_3.d.ts +69 -0
  60. package/dist/{snapshot/index.d.ts → index-DMCeMPMJ.d.ts} +15 -77
  61. package/dist/{monitored-run/index.d.ts → index-NjrT3fL2.d.ts} +37 -12
  62. package/dist/{recorder/index.d.ts → index-TvRb1KVf.d.ts} +4 -6
  63. package/dist/{deadline/index.d.ts → index-q0hXFeZ0.d.ts} +155 -8
  64. package/dist/index.d.ts +719 -6
  65. package/dist/index.js +1 -2
  66. package/dist/jev/index.d.ts +634 -0
  67. package/dist/jev/index.js +433 -0
  68. package/dist/jev/index.js.map +1 -0
  69. package/dist/machine-CdIcN2Xm.d.ts +1773 -0
  70. package/dist/machine-viz/index.d.ts +2 -1
  71. package/dist/machine-viz/index.js +12 -5
  72. package/dist/machine-viz/index.js.map +1 -1
  73. package/dist/mem/index.d.ts +19 -3
  74. package/dist/mem/index.js +22 -2
  75. package/dist/mem/index.js.map +1 -1
  76. package/dist/node/index.d.ts +130 -4
  77. package/dist/node/index.js +222 -10
  78. package/dist/node/index.js.map +1 -1
  79. package/dist/{paginator → paginate}/index.d.ts +151 -6
  80. package/dist/paginate/index.js +7 -0
  81. package/dist/parity/index.d.ts +5 -10
  82. package/dist/parity/index.js +4 -7
  83. package/dist/parity/index.js.map +1 -1
  84. package/dist/pbt/index.d.ts +248 -5
  85. package/dist/pbt/index.js +124 -5
  86. package/dist/pbt/index.js.map +1 -1
  87. package/dist/{trace-replay → persistence}/index.d.ts +7 -4
  88. package/dist/persistence/index.js +6 -0
  89. package/dist/react/index.d.ts +4 -3
  90. package/dist/react/index.js +1 -2
  91. package/dist/react/index.js.map +1 -1
  92. package/dist/resilience/index.d.ts +743 -0
  93. package/dist/resilience/index.js +657 -0
  94. package/dist/resilience/index.js.map +1 -0
  95. package/dist/retry-backoff/index.d.ts +3 -2
  96. package/dist/retry-backoff/index.js +1 -1
  97. package/dist/runtime-types-LWDoi943.d.ts +998 -0
  98. package/dist/testing/index.d.ts +3 -2
  99. package/dist/testing/index.js +1 -2
  100. package/dist/testing/index.js.map +1 -1
  101. package/dist/{throttled-input → timing}/index.d.ts +144 -12
  102. package/dist/{throttled-input → timing}/index.js +57 -12
  103. package/dist/timing/index.js.map +1 -0
  104. package/dist/{types-D7u9DkH7.d.ts → types-DP3f5NIl.d.ts} +1 -1
  105. package/dist/work-queue/index.d.ts +131 -54
  106. package/dist/work-queue/index.js +3 -2
  107. package/dist/work-queue/index.js.map +1 -1
  108. package/package.json +50 -216
  109. package/dist/authed-call/index.d.ts +0 -119
  110. package/dist/authed-call/index.js +0 -134
  111. package/dist/authed-call/index.js.map +0 -1
  112. package/dist/await-terminal/index.d.ts +0 -100
  113. package/dist/await-terminal/index.js +0 -76
  114. package/dist/await-terminal/index.js.map +0 -1
  115. package/dist/batch-window/index.js.map +0 -1
  116. package/dist/cache/index.d.ts +0 -151
  117. package/dist/cache/index.js +0 -8
  118. package/dist/chart/index.d.ts +0 -217
  119. package/dist/chart/index.js +0 -16
  120. package/dist/chart/index.js.map +0 -1
  121. package/dist/chart/inspect/index.d.ts +0 -85
  122. package/dist/chart/inspect/index.js +0 -5
  123. package/dist/chart/inspect/react.d.ts +0 -112
  124. package/dist/chart/inspect/react.js +0 -11
  125. package/dist/chart/inspect/react.js.map +0 -1
  126. package/dist/chart/inspect/styles.css +0 -286
  127. package/dist/chart/lane/index.d.ts +0 -361
  128. package/dist/chart/lane/index.js +0 -9
  129. package/dist/chart/lane/index.js.map +0 -1
  130. package/dist/chart/lane/react.d.ts +0 -83
  131. package/dist/chart/lane/react.js +0 -559
  132. package/dist/chart/lane/react.js.map +0 -1
  133. package/dist/chart/lane/server.d.ts +0 -148
  134. package/dist/chart/lane/server.js +0 -209
  135. package/dist/chart/lane/server.js.map +0 -1
  136. package/dist/chart/lane/styles.css +0 -498
  137. package/dist/chart/lane/viewer/assets/abnfDiagram-N423BO3Z-C729LI31.js +0 -1
  138. package/dist/chart/lane/viewer/assets/architectureDiagram-T3A2C74G-C729LI31.js +0 -1
  139. package/dist/chart/lane/viewer/assets/blockDiagram-VBNYF7ZC-C729LI31.js +0 -1
  140. package/dist/chart/lane/viewer/assets/c4Diagram-5PPSVZJV-C729LI31.js +0 -1
  141. package/dist/chart/lane/viewer/assets/chunk-2GRJ4B5K-HdDf8SI3.js +0 -1
  142. package/dist/chart/lane/viewer/assets/chunk-5RXB4S5H-CcNtpUd7.js +0 -231
  143. package/dist/chart/lane/viewer/assets/chunk-5VM5RSS4-BP4fRS_5.js +0 -15
  144. package/dist/chart/lane/viewer/assets/chunk-KBJHAD2P-DZOw7xU6.js +0 -1
  145. package/dist/chart/lane/viewer/assets/chunk-NSK5VX7P-CBCyTZMs.js +0 -128
  146. package/dist/chart/lane/viewer/assets/classDiagram-JCYQIIEL-C729LI31.js +0 -1
  147. package/dist/chart/lane/viewer/assets/classDiagram-v2-OCEON4UE-D4uAiFr8.js +0 -206
  148. package/dist/chart/lane/viewer/assets/cose-bilkent-JH36ORCC-DOwCrGXH.js +0 -1
  149. package/dist/chart/lane/viewer/assets/cynefinDiagram-MW4NZA55-C729LI31.js +0 -1
  150. package/dist/chart/lane/viewer/assets/dagre-K_PewWfS.js +0 -1
  151. package/dist/chart/lane/viewer/assets/dagre-VZM6K2ZE-831qZcA8.js +0 -4
  152. package/dist/chart/lane/viewer/assets/diagram-7IWD3JNH-C729LI31.js +0 -1
  153. package/dist/chart/lane/viewer/assets/diagram-B4RE2ZJO-C729LI31.js +0 -1
  154. package/dist/chart/lane/viewer/assets/diagram-LBJQPF4R-C729LI31.js +0 -1
  155. package/dist/chart/lane/viewer/assets/diagram-Q27KOJAE-C729LI31.js +0 -1
  156. package/dist/chart/lane/viewer/assets/diagram-UB23O5K3-C729LI31.js +0 -1
  157. package/dist/chart/lane/viewer/assets/ebnfDiagram-BXEA7PRR-C729LI31.js +0 -1
  158. package/dist/chart/lane/viewer/assets/erDiagram-JOGREHBK-C729LI31.js +0 -1
  159. package/dist/chart/lane/viewer/assets/flowDiagram-UKHOOZJN-C729LI31.js +0 -1
  160. package/dist/chart/lane/viewer/assets/ganttDiagram-PKOTCBZU-C729LI31.js +0 -1
  161. package/dist/chart/lane/viewer/assets/gitGraphDiagram-DS77QQ5N-C729LI31.js +0 -1
  162. package/dist/chart/lane/viewer/assets/index-9SkH5NA3.css +0 -1
  163. package/dist/chart/lane/viewer/assets/index-Bgt4sXpW.js +0 -195
  164. package/dist/chart/lane/viewer/assets/infoDiagram-6WML65LV-C729LI31.js +0 -1
  165. package/dist/chart/lane/viewer/assets/ishikawaDiagram-WSZJBQD7-C729LI31.js +0 -1
  166. package/dist/chart/lane/viewer/assets/journeyDiagram-NVQOT4AX-C729LI31.js +0 -1
  167. package/dist/chart/lane/viewer/assets/kanban-definition-27J2QSJJ-G7PaPzy-.js +0 -89
  168. package/dist/chart/lane/viewer/assets/katex-DOwCrGXH.js +0 -1
  169. package/dist/chart/lane/viewer/assets/mindmap-definition-FAOFIHXS-CGj9nrVk.js +0 -96
  170. package/dist/chart/lane/viewer/assets/path-fybaL0A-.js +0 -1
  171. package/dist/chart/lane/viewer/assets/pegDiagram-VL7TDLO6-C729LI31.js +0 -1
  172. package/dist/chart/lane/viewer/assets/pieDiagram-7S7Q4E2Y-C729LI31.js +0 -1
  173. package/dist/chart/lane/viewer/assets/quadrantDiagram-CIZ2JOQS-C729LI31.js +0 -1
  174. package/dist/chart/lane/viewer/assets/railroadDiagram-AXF67PYL-C729LI31.js +0 -1
  175. package/dist/chart/lane/viewer/assets/requirementDiagram-LRYGKXZP-C729LI31.js +0 -1
  176. package/dist/chart/lane/viewer/assets/sankeyDiagram-W5VNT64P-C729LI31.js +0 -1
  177. package/dist/chart/lane/viewer/assets/sequenceDiagram-SI44F4Z6-C729LI31.js +0 -1
  178. package/dist/chart/lane/viewer/assets/stateDiagram-OKZ733FA-B_88AzBS.js +0 -1
  179. package/dist/chart/lane/viewer/assets/stateDiagram-v2-UEYNNEHI-CR5gcgq6.js +0 -1
  180. package/dist/chart/lane/viewer/assets/swimlanes-SLNWSIFB-B4xK-rwg.js +0 -1
  181. package/dist/chart/lane/viewer/assets/swimlanesDiagram-ULZ7WXOC-C729LI31.js +0 -1
  182. package/dist/chart/lane/viewer/assets/timeline-definition-Z64GVDOM-CCv52MfY.js +0 -120
  183. package/dist/chart/lane/viewer/assets/vennDiagram-T6HMQDX7-C729LI31.js +0 -1
  184. package/dist/chart/lane/viewer/assets/wardleyDiagram-T6FBY63Y-C729LI31.js +0 -1
  185. package/dist/chart/lane/viewer/assets/xychartDiagram-ELKLHX3M-C729LI31.js +0 -1
  186. package/dist/chart/lane/viewer/index.html +0 -15
  187. package/dist/chart/report/index.d.ts +0 -116
  188. package/dist/chart/report/index.js +0 -32
  189. package/dist/chart/report/index.js.map +0 -1
  190. package/dist/chunk-2YFLOCWX.js +0 -15
  191. package/dist/chunk-2YFLOCWX.js.map +0 -1
  192. package/dist/chunk-3JU6657S.js +0 -372
  193. package/dist/chunk-3JU6657S.js.map +0 -1
  194. package/dist/chunk-4KTWLPL5.js +0 -33
  195. package/dist/chunk-4KTWLPL5.js.map +0 -1
  196. package/dist/chunk-5EHLEUTL.js +0 -686
  197. package/dist/chunk-5EHLEUTL.js.map +0 -1
  198. package/dist/chunk-5KJKJOFC.js +0 -758
  199. package/dist/chunk-5KJKJOFC.js.map +0 -1
  200. package/dist/chunk-7SVIRMC6.js.map +0 -1
  201. package/dist/chunk-7V4EVLZA.js.map +0 -1
  202. package/dist/chunk-A56OR5RF.js +0 -184
  203. package/dist/chunk-A56OR5RF.js.map +0 -1
  204. package/dist/chunk-AZZLE7XR.js +0 -62
  205. package/dist/chunk-AZZLE7XR.js.map +0 -1
  206. package/dist/chunk-B5VXOFMZ.js +0 -266
  207. package/dist/chunk-B5VXOFMZ.js.map +0 -1
  208. package/dist/chunk-BYQUGDD3.js +0 -16
  209. package/dist/chunk-BYQUGDD3.js.map +0 -1
  210. package/dist/chunk-D736QUGF.js.map +0 -1
  211. package/dist/chunk-E6GEDSF4.js +0 -307
  212. package/dist/chunk-E6GEDSF4.js.map +0 -1
  213. package/dist/chunk-EUF7XOEE.js +0 -223
  214. package/dist/chunk-EUF7XOEE.js.map +0 -1
  215. package/dist/chunk-EWJP3YYP.js.map +0 -1
  216. package/dist/chunk-FV3Z5MBE.js.map +0 -1
  217. package/dist/chunk-HCEVHFJ7.js +0 -54
  218. package/dist/chunk-HCEVHFJ7.js.map +0 -1
  219. package/dist/chunk-I5OV65MS.js.map +0 -1
  220. package/dist/chunk-J6527VRQ.js.map +0 -1
  221. package/dist/chunk-JELSZN25.js +0 -47
  222. package/dist/chunk-JELSZN25.js.map +0 -1
  223. package/dist/chunk-JER5O7PQ.js +0 -416
  224. package/dist/chunk-JER5O7PQ.js.map +0 -1
  225. package/dist/chunk-JGVL3WPL.js +0 -26
  226. package/dist/chunk-JGVL3WPL.js.map +0 -1
  227. package/dist/chunk-JP5D6GSL.js +0 -71
  228. package/dist/chunk-JP5D6GSL.js.map +0 -1
  229. package/dist/chunk-K575PT4S.js.map +0 -1
  230. package/dist/chunk-MU6MCIAC.js +0 -15
  231. package/dist/chunk-MU6MCIAC.js.map +0 -1
  232. package/dist/chunk-MUUROGIH.js.map +0 -1
  233. package/dist/chunk-ND3DH6KM.js +0 -88
  234. package/dist/chunk-ND3DH6KM.js.map +0 -1
  235. package/dist/chunk-Q2UM7BXU.js.map +0 -1
  236. package/dist/chunk-S2EGRPCM.js +0 -47
  237. package/dist/chunk-S2EGRPCM.js.map +0 -1
  238. package/dist/chunk-SINXE47Y.js +0 -55
  239. package/dist/chunk-SINXE47Y.js.map +0 -1
  240. package/dist/chunk-SUST46KO.js +0 -53
  241. package/dist/chunk-SUST46KO.js.map +0 -1
  242. package/dist/chunk-TP5UPGLY.js +0 -61
  243. package/dist/chunk-TP5UPGLY.js.map +0 -1
  244. package/dist/chunk-UF4MZSLT.js +0 -53
  245. package/dist/chunk-UF4MZSLT.js.map +0 -1
  246. package/dist/chunk-UOC2PL46.js +0 -13
  247. package/dist/chunk-UOC2PL46.js.map +0 -1
  248. package/dist/chunk-WLGO64WC.js.map +0 -1
  249. package/dist/chunk-WRAA7GVZ.js +0 -209
  250. package/dist/chunk-WRAA7GVZ.js.map +0 -1
  251. package/dist/chunk-ZCL7SCBK.js +0 -685
  252. package/dist/chunk-ZCL7SCBK.js.map +0 -1
  253. package/dist/chunk-ZD6PNZBK.js +0 -457
  254. package/dist/chunk-ZD6PNZBK.js.map +0 -1
  255. package/dist/chunk-ZF6WDK2D.js +0 -519
  256. package/dist/chunk-ZF6WDK2D.js.map +0 -1
  257. package/dist/chunk-ZJ5AOYBH.js +0 -8
  258. package/dist/chunk-ZJ5AOYBH.js.map +0 -1
  259. package/dist/chunk-ZVJZ72HY.js.map +0 -1
  260. package/dist/circuit-breaker/index.d.ts +0 -197
  261. package/dist/circuit-breaker/index.js +0 -3
  262. package/dist/circuit-breaker/index.js.map +0 -1
  263. package/dist/core-Bjc0bS8j.d.ts +0 -326
  264. package/dist/deadline/index.js +0 -6
  265. package/dist/deadline/index.js.map +0 -1
  266. package/dist/debounce/index.js +0 -3
  267. package/dist/debounce/index.js.map +0 -1
  268. package/dist/extension/react.d.ts +0 -121
  269. package/dist/extension/react.js +0 -75
  270. package/dist/extension/react.js.map +0 -1
  271. package/dist/extension/subs/index.d.ts +0 -44
  272. package/dist/extension/subs/index.js +0 -80
  273. package/dist/extension/subs/index.js.map +0 -1
  274. package/dist/extension/test-utils.d.ts +0 -128
  275. package/dist/extension/test-utils.js +0 -277
  276. package/dist/extension/test-utils.js.map +0 -1
  277. package/dist/fan-out/index.js +0 -5
  278. package/dist/fan-out/index.js.map +0 -1
  279. package/dist/fold-Blbhru48.d.ts +0 -435
  280. package/dist/graph-CcjWZVrd.d.ts +0 -923
  281. package/dist/idempotency/adapter.d.ts +0 -62
  282. package/dist/idempotency/adapter.js +0 -4
  283. package/dist/idempotency/adapter.js.map +0 -1
  284. package/dist/idempotent-intake/index.d.ts +0 -187
  285. package/dist/idempotent-intake/index.js +0 -7
  286. package/dist/idempotent-intake/index.js.map +0 -1
  287. package/dist/llm-call/index.d.ts +0 -310
  288. package/dist/llm-call/index.js +0 -16
  289. package/dist/llm-call/index.js.map +0 -1
  290. package/dist/machine-0OmPvsy_.d.ts +0 -804
  291. package/dist/monitored-run/index.js +0 -10
  292. package/dist/monitored-run/index.js.map +0 -1
  293. package/dist/paginated-walk/index.d.ts +0 -234
  294. package/dist/paginated-walk/index.js +0 -16
  295. package/dist/paginated-walk/index.js.map +0 -1
  296. package/dist/paginator/index.js +0 -3
  297. package/dist/paginator/index.js.map +0 -1
  298. package/dist/pbt/arbitraries/index.d.ts +0 -135
  299. package/dist/pbt/arbitraries/index.js +0 -3
  300. package/dist/pbt/arbitraries/index.js.map +0 -1
  301. package/dist/pbt/runners/index.d.ts +0 -117
  302. package/dist/pbt/runners/index.js +0 -5
  303. package/dist/pbt/runners/index.js.map +0 -1
  304. package/dist/poller/index.d.ts +0 -351
  305. package/dist/poller/index.js +0 -115
  306. package/dist/poller/index.js.map +0 -1
  307. package/dist/prediction/index.d.ts +0 -130
  308. package/dist/prediction/index.js +0 -4
  309. package/dist/prediction/index.js.map +0 -1
  310. package/dist/protocol-B5YmJr0d.d.ts +0 -45
  311. package/dist/pure/index.d.ts +0 -2
  312. package/dist/pure/index.js +0 -4
  313. package/dist/pure/index.js.map +0 -1
  314. package/dist/rate-limit/index.d.ts +0 -115
  315. package/dist/rate-limit/index.js +0 -3
  316. package/dist/rate-limit/index.js.map +0 -1
  317. package/dist/reconciler/index.d.ts +0 -192
  318. package/dist/reconciler/index.js +0 -164
  319. package/dist/reconciler/index.js.map +0 -1
  320. package/dist/recorder/index.js +0 -3
  321. package/dist/recorder/index.js.map +0 -1
  322. package/dist/reducer-BqyoVyBG.d.ts +0 -447
  323. package/dist/resilient-call/index.d.ts +0 -319
  324. package/dist/resilient-call/index.js +0 -14
  325. package/dist/resilient-call/index.js.map +0 -1
  326. package/dist/retry-to-success/index.d.ts +0 -109
  327. package/dist/retry-to-success/index.js +0 -37
  328. package/dist/retry-to-success/index.js.map +0 -1
  329. package/dist/run-BVeqJDBF.d.ts +0 -713
  330. package/dist/runtime-types-Bxc637bp.d.ts +0 -502
  331. package/dist/saga/index.d.ts +0 -240
  332. package/dist/saga/index.js +0 -150
  333. package/dist/saga/index.js.map +0 -1
  334. package/dist/samples-DCt6nF8H.d.ts +0 -59
  335. package/dist/snapshot/index.js +0 -5
  336. package/dist/snapshot/index.js.map +0 -1
  337. package/dist/subs/index.d.ts +0 -471
  338. package/dist/subs/index.js +0 -7
  339. package/dist/subs/index.js.map +0 -1
  340. package/dist/throttle/index.d.ts +0 -134
  341. package/dist/throttle/index.js +0 -3
  342. package/dist/throttle/index.js.map +0 -1
  343. package/dist/throttled-input/index.js.map +0 -1
  344. package/dist/token-refresh/index.d.ts +0 -215
  345. package/dist/token-refresh/index.js +0 -6
  346. package/dist/token-refresh/index.js.map +0 -1
  347. package/dist/trace-replay/index.js +0 -6
  348. package/dist/trace-replay/index.js.map +0 -1
  349. package/dist/with-deadline/index.d.ts +0 -196
  350. package/dist/with-deadline/index.js +0 -111
  351. package/dist/with-deadline/index.js.map +0 -1
  352. package/dist/with-resilience/index.d.ts +0 -224
  353. package/dist/with-resilience/index.js +0 -240
  354. package/dist/with-resilience/index.js.map +0 -1
  355. package/dist/with-telemetry/index.d.ts +0 -149
  356. package/dist/with-telemetry/index.js +0 -70
  357. package/dist/with-telemetry/index.js.map +0 -1
  358. package/dist/work-queue/adapter.d.ts +0 -83
  359. package/dist/work-queue/adapter.js +0 -4
  360. package/dist/work-queue/adapter.js.map +0 -1
  361. package/dist/work-queue/ops.d.ts +0 -70
  362. package/dist/work-queue/ops.js +0 -3
  363. package/dist/work-queue/ops.js.map +0 -1
  364. package/dist/workflow/index.d.ts +0 -484
  365. package/dist/workflow/index.js +0 -244
  366. package/dist/workflow/index.js.map +0 -1
  367. /package/dist/{cache → paginate}/index.js.map +0 -0
  368. /package/dist/{chart/inspect → persistence}/index.js.map +0 -0
@@ -1,62 +0,0 @@
1
- import * as fc from 'fast-check';
2
-
3
- // src/pbt/arbitraries/ctx.ts
4
- function stubCtxThrowingProxy() {
5
- const handler = {
6
- get(_target, prop) {
7
- if (typeof prop === "symbol") return void 0;
8
- if (prop === "toJSON" || prop === "toString" || prop === "valueOf" || prop === "then") {
9
- return void 0;
10
- }
11
- throw new Error(
12
- `@demlik/tea/pbt: ctx access denied (PBT operates on the pure reducer; ctx field '${prop}' was read). Pass a real ctx value if the reducer's init reads from ctx.`
13
- );
14
- },
15
- has() {
16
- return false;
17
- },
18
- ownKeys() {
19
- return [];
20
- }
21
- };
22
- return new Proxy({}, handler);
23
- }
24
- function arbMsg(table, opts) {
25
- const weights = opts?.weights;
26
- const entries = Object.entries(table);
27
- if (entries.length === 0) {
28
- throw new Error("@demlik/tea/pbt: arbMsg table is empty");
29
- }
30
- const weighted = entries.map(([key, arb]) => ({
31
- arbitrary: arb,
32
- weight: weights?.[key] ?? 1
33
- }));
34
- return fc.oneof(...weighted);
35
- }
36
- function arbConstantMsg(type) {
37
- return fc.constant({ type });
38
- }
39
- function arbRecordMsg(type, fields) {
40
- const recordArbitraries = {
41
- type: fc.constant(type),
42
- ...fields
43
- };
44
- return fc.record(recordArbitraries);
45
- }
46
- function arbMsgSequence(msgArb, opts) {
47
- const minLength = opts?.minLength ?? 0;
48
- const maxLength = opts?.maxLength ?? 30;
49
- const prefix = opts?.prefix ?? [];
50
- const tail = fc.array(msgArb, { minLength, maxLength });
51
- if (prefix.length === 0) return tail;
52
- return tail.map((arr) => [...prefix, ...arr]);
53
- }
54
- function arbGuidedSequence(_machine, _ctx, _cells, _opts) {
55
- throw new Error(
56
- "@demlik/tea/pbt: arbGuidedSequence is not implemented in v1. Use arbMsgSequence with an unguided arbMsg table for now; states that don't accept a given msg should noop in the reducer (mapped-type discipline)."
57
- );
58
- }
59
-
60
- export { arbConstantMsg, arbGuidedSequence, arbMsg, arbMsgSequence, arbRecordMsg, stubCtxThrowingProxy };
61
- //# sourceMappingURL=chunk-AZZLE7XR.js.map
62
- //# sourceMappingURL=chunk-AZZLE7XR.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/pbt/arbitraries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AU,EAAA,CAAA,QAAA,CAAS,EAAE,IAAA,EAAM,CAAA;AAC7B;AAWO,SAAS,YAAA,CACd,MACA,MAAA,EAC+B;AAa/B,EAAA,MAAM,iBAAA,GAA2D;AAAA,IAC/D,IAAA,EAAS,YAAS,IAAI,CAAA;AAAA,IACtB,GAAI;AAAA,GACN;AACA,EAAA,OAAU,UAAO,iBAAiB,CAAA;AAGpC;ACvFO,SAAS,cAAA,CACd,QACA,IAAA,EAK4B;AAC5B,EAAA,MAAM,SAAA,GAAY,MAAM,SAAA,IAAa,CAAA;AACrC,EAAA,MAAM,SAAA,GAAY,MAAM,SAAA,IAAa,EAAA;AACrC,EAAA,MAAM,MAAA,GAAS,IAAA,EAAM,MAAA,IAAU,EAAC;AAChC,EAAA,MAAM,OAAUA,EAAA,CAAA,KAAA,CAAM,MAAA,EAAQ,EAAE,SAAA,EAAW,WAAW,CAAA;AACtD,EAAA,IAAI,MAAA,CAAO,MAAA,KAAW,CAAA,EAAG,OAAO,IAAA;AAChC,EAAA,OAAO,IAAA,CAAK,IAAI,CAAC,GAAA,KAAQ,CAAC,GAAG,MAAA,EAAQ,GAAG,GAAG,CAAC,CAAA;AAC9C;AAWO,SAAS,iBAAA,CAOd,QAAA,EACA,IAAA,EACA,MAAA,EAKA,KAAA,EAC4B;AAC5B,EAAA,MAAM,IAAI,KAAA;AAAA,IACR;AAAA,GAIF;AACF","file":"chunk-AZZLE7XR.js","sourcesContent":["// ---------------------------------------------------------------------------\n// `stubCtxThrowingProxy<Ctx>()` — a Proxy that satisfies the Ctx type-shape\n// at compile time but throws on every property access at runtime.\n//\n// Why this exists: PBT runs the pure reducer surface ONLY — `replay` never\n// invokes `interpret` and never starts a Sub, so Ctx should never be\n// dereferenced during property generation. But the substrate's `replay`\n// signature requires a `ctx: Ctx` value at compile time (it forwards ctx\n// into `init`, which on some machines IS pure but on others reads ctx). A\n// hand-rolled `{} as Ctx` would silently pass through any accidental ctx\n// access — exactly the silent footgun this proxy catches.\n//\n// Open question 2 (design doc): we ship this as the default. Tests that\n// genuinely need a working ctx (because their `init` reads from it) can\n// pass a real ctx value instead — the proxy is opt-in, not load-bearing.\n//\n// Strengthens invariant 6 (no silent failures — accidental ctx reads\n// produce a useful error, not a `undefined.foo` confusion later).\n// ---------------------------------------------------------------------------\n\n/**\n * Build a Ctx value whose every property access throws. Use as the `ctx`\n * argument to PBT runners when the reducer under test is pure (does not\n * read from ctx). Accidental ctx access during property generation\n * surfaces as a labelled error instead of a silent `undefined` or\n * downstream type-error.\n *\n * Returns a typed `Ctx` (via `as unknown as Ctx`) — the proxy satisfies the\n * type-shape requirement at the call site; the runtime contract is\n * \"throw on first read.\" The `as unknown` cast is the one boundary cast\n * this helper requires; the proxy is structurally a `Ctx` for every\n * property accessor.\n *\n * @example\n * import { stubCtxThrowingProxy } from \"../index\";\n * const ctx = stubCtxThrowingProxy<MyCtx>();\n * propertyTerminates(machine, ctx, ...);\n * // If anything reads ctx.someField during the run, an Error throws:\n * // \"@demlik/tea/pbt: ctx access denied (PBT operates on the pure\n * // reducer; ctx field 'someField' was read)\"\n */\nexport function stubCtxThrowingProxy<Ctx>(): Ctx {\n const handler: ProxyHandler<object> = {\n get(_target, prop: string | symbol): unknown {\n // Allow vitest / fast-check internals to introspect via Symbol-keyed\n // checks (e.g. Symbol.toStringTag, Symbol.iterator). Returning\n // undefined on symbol keys keeps property-tree walks cheap; the\n // throw fires on real domain field reads.\n if (typeof prop === \"symbol\") return undefined;\n // Some shrinkers / pretty-printers in fast-check probe a small set\n // of conventional field names (`toJSON`, `toString`, `valueOf`,\n // `then` — the last for thenable-check). Return undefined for those\n // so the proxy doesn't fail a probe before the property body runs.\n if (\n prop === \"toJSON\" ||\n prop === \"toString\" ||\n prop === \"valueOf\" ||\n prop === \"then\"\n ) {\n return undefined;\n }\n throw new Error(\n `@demlik/tea/pbt: ctx access denied (PBT operates on the pure reducer; ` +\n `ctx field '${prop}' was read). Pass a real ctx value if the reducer's ` +\n `init reads from ctx.`,\n );\n },\n has(): boolean {\n return false;\n },\n ownKeys(): ArrayLike<string | symbol> {\n return [];\n },\n };\n return new Proxy({}, handler) as unknown as Ctx;\n}\n","// ---------------------------------------------------------------------------\n// Msg arbitrary builders.\n//\n// `MsgArbitraryTable<M>` is a strict mapped type — every Msg variant must\n// have an arbitrary entry, keyed by `M[\"type\"]`, narrowing the arbitrary's\n// `T` to `Extract<M, { type: K }>`. This mirrors the load-bearing discipline\n// of `Reducer<S, M, C>` and `Transitions<S, M, C>` in the substrate: adding\n// a Msg variant without an arbitrary fails to compile, not at runtime.\n//\n// `arbMsg(table, opts?)` collapses the table into a single `fc.Arbitrary<M>`\n// via `fc.oneof`. Optional per-variant weighting for sequence-skew tests.\n//\n// `arbConstantMsg(type)` / `arbRecordMsg(type, fields)` are sugar over\n// `fc.constant({ type })` / `fc.record({ type: fc.constant(type), ...fields })`.\n// They exist because every Msg variant arbitrary either (a) carries no\n// payload — `arbConstantMsg(\"stop\")` — or (b) carries a record of fields —\n// `arbRecordMsg(\"tick\", { now: fc.integer() })`. Naming the two shapes\n// prevents callers from hand-rolling `fc.record({ type: fc.constant(\"...\") })`\n// inconsistently across test files.\n//\n// Open question 1 from the design doc (strict vs Partial table): strict by\n// default. The mapped type catches drift at compile time; `arbMsgPartial`\n// sugar is a future addition iff friction becomes real.\n// ---------------------------------------------------------------------------\n\nimport * as fc from \"fast-check\";\n\n/**\n * Strict per-variant Msg arbitrary table. Mapped type: every key in\n * `M[\"type\"]` MUST have an arbitrary entry whose `T` is the narrowed\n * variant. Adding a new Msg variant without an entry is a compile error\n * (same load-bearing discipline as `Reducer<S, M, C>` in the substrate).\n *\n * @example\n * type Msg = { type: \"start\" } | { type: \"tick\"; now: number };\n * const table: MsgArbitraryTable<Msg> = {\n * start: arbConstantMsg(\"start\"),\n * tick: arbRecordMsg(\"tick\", { now: fc.integer({ min: 0 }) }),\n * };\n */\nexport type MsgArbitraryTable<M extends { type: string }> = {\n [K in M[\"type\"]]: fc.Arbitrary<Extract<M, { type: K }>>;\n};\n\n/**\n * Build a single `fc.Arbitrary<M>` from a `MsgArbitraryTable<M>`. Picks one\n * variant per generation via `fc.oneof`; optional per-variant `weights`\n * bias the distribution (default uniform).\n *\n * @param table Per-variant arbitrary table (strict — every variant required).\n * @param opts Optional bias: `weights` is a `Partial<Record<M[\"type\"], number>>`.\n * Variants without an explicit weight default to 1.\n *\n * @example\n * const msgArb = arbMsg<Msg>({\n * start: arbConstantMsg(\"start\"),\n * tick: arbRecordMsg(\"tick\", { now: fc.integer() }),\n * stop: arbConstantMsg(\"stop\"),\n * }, { weights: { tick: 5, start: 1, stop: 1 } });\n */\nexport function arbMsg<M extends { type: string }>(\n table: MsgArbitraryTable<M>,\n opts?: { weights?: Partial<Record<M[\"type\"], number>> },\n): fc.Arbitrary<M> {\n const weights = opts?.weights;\n const entries = Object.entries(table) as [M[\"type\"], fc.Arbitrary<M>][];\n if (entries.length === 0) {\n throw new Error(\"@demlik/tea/pbt: arbMsg table is empty\");\n }\n const weighted = entries.map(([key, arb]) => ({\n arbitrary: arb,\n weight: weights?.[key] ?? 1,\n }));\n return fc.oneof(...weighted);\n}\n\n/**\n * Build a payload-free Msg variant arbitrary. Sugar for\n * `fc.constant({ type })` that narrows the result to `{ type: T }` literal.\n *\n * @example\n * arbConstantMsg(\"stop\") // fc.Arbitrary<{ type: \"stop\" }>\n */\nexport function arbConstantMsg<T extends string>(\n type: T,\n): fc.Arbitrary<{ type: T }> {\n return fc.constant({ type });\n}\n\n/**\n * Build a record-shaped Msg variant arbitrary. Sugar for\n * `fc.record({ type: fc.constant(type), ...fields })` that stamps the\n * discriminator literal and combines with the per-field arbitraries.\n *\n * @example\n * arbRecordMsg(\"tick\", { now: fc.integer({ min: 0 }) })\n * // fc.Arbitrary<{ type: \"tick\"; now: number }>\n */\nexport function arbRecordMsg<T extends string, R>(\n type: T,\n fields: { [K in keyof R]: fc.Arbitrary<R[K]> },\n): fc.Arbitrary<{ type: T } & R> {\n // `fc.record` builds an arbitrary of the merged-shape record. The\n // `type: fc.constant(type)` field stamps the literal discriminator;\n // the spread of `fields` provides every payload field's arbitrary.\n //\n // The intermediate `as Record<string, fc.Arbitrary<unknown>>` is the\n // single load-bearing cast — fc.record's parameter type is invariant in\n // its inferred field shape, and the merged literal-and-generic spread\n // doesn't unify with the strict `{ [K in keyof R]: Arbitrary<R[K]> }`\n // shape TS computes for us. The outer cast to `fc.Arbitrary<{ type: T }\n // & R>` restates the result shape we know to be correct at this\n // boundary. Mirrors the same discipline `fc.record` callers use\n // throughout the prior-art branch.\n const recordArbitraries: Record<string, fc.Arbitrary<unknown>> = {\n type: fc.constant(type),\n ...(fields as Record<string, fc.Arbitrary<unknown>>),\n };\n return fc.record(recordArbitraries) as unknown as fc.Arbitrary<\n { type: T } & R\n >;\n}\n","// ---------------------------------------------------------------------------\n// Msg-sequence arbitraries.\n//\n// `arbMsgSequence(msgArb, opts)` produces `fc.Arbitrary<readonly M[]>` —\n// fast-check's default-shrinker handles the array; the per-element shrinker\n// inside `msgArb` shrinks each variant. Optional `prefix` is prepended\n// verbatim (used by Test A: \"the bug-triggering Msg leads the sequence\").\n//\n// `arbGuidedSequence` is the state-aware sequence builder. In v1 it throws\n// — Phase 6 of the design doc lands the `fc.commands`-backed implementation.\n// The export exists today so the surface is forward-compatible: consumers\n// that need state-aware generation get a useful error pointing at the\n// design doc instead of \"is not a function.\"\n// ---------------------------------------------------------------------------\n\nimport * as fc from \"fast-check\";\nimport type { Cmd, Machine, Sub } from \"../../index\";\n\n/**\n * Build an arbitrary of Msg sequences over a per-Msg arbitrary. Optionally\n * bounded in length and / or prefixed with a fixed sequence.\n *\n * - `minLength` (default 0) and `maxLength` (default 30) bound the random\n * array length. `prefix` is prepended AFTER the random tail is built; the\n * final length is `prefix.length + tail.length`.\n * - `prefix` is the load-bearing escape hatch for \"the first msg is the\n * one that exercises the cell I care about\" (e.g. Test A's\n * `[{ type: \"ws:client:hello\" }]` prefix to land in the\n * `auditing.ws:client:hello` cell on the first transition).\n *\n * @example\n * arbMsgSequence(msgArb, { minLength: 1, maxLength: 30 });\n * arbMsgSequence(msgArb, { prefix: [{ type: \"ws:client:hello\" }], maxLength: 20 });\n */\nexport function arbMsgSequence<M extends { type: string }>(\n msgArb: fc.Arbitrary<M>,\n opts?: {\n readonly minLength?: number;\n readonly maxLength?: number;\n readonly prefix?: readonly NoInfer<M>[];\n },\n): fc.Arbitrary<readonly M[]> {\n const minLength = opts?.minLength ?? 0;\n const maxLength = opts?.maxLength ?? 30;\n const prefix = opts?.prefix ?? [];\n const tail = fc.array(msgArb, { minLength, maxLength });\n if (prefix.length === 0) return tail;\n return tail.map((arr) => [...prefix, ...arr]);\n}\n\n/**\n * State-aware Msg sequence arbitrary — generates only msgs whose\n * precondition holds in the current state. Backed by `fc.commands`\n * internally. Planned for a later phase.\n *\n * **NOT IMPLEMENTED IN v1.** The export exists today so the surface is\n * forward-compatible; this ships in a later phase alongside\n * shrinkers. Calling it throws.\n */\nexport function arbGuidedSequence<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n _machine: Machine<S, M, C, U, Ctx>,\n _ctx: Ctx,\n _cells: {\n [K in M[\"type\"]]?: (\n state: S,\n ) => fc.Arbitrary<Extract<M, { type: K }>> | null;\n },\n _opts?: { maxLength?: number },\n): fc.Arbitrary<readonly M[]> {\n throw new Error(\n \"@demlik/tea/pbt: arbGuidedSequence is not implemented in v1. \" +\n \"Use arbMsgSequence with \" +\n \"an unguided arbMsg table for now; states that don't accept a given \" +\n \"msg should noop in the reducer (mapped-type discipline).\",\n );\n}\n"]}
@@ -1,266 +0,0 @@
1
- // src/pure/core.ts
2
- var __DEV__ = (() => {
3
- try {
4
- const meta = import.meta;
5
- if (meta.env?.DEV !== void 0) {
6
- return meta.env.DEV;
7
- }
8
- } catch {
9
- }
10
- try {
11
- return typeof process !== "undefined" && process.env?.NODE_ENV !== "production";
12
- } catch {
13
- return false;
14
- }
15
- })();
16
- function deepFreeze(obj, seen) {
17
- if (obj === null || typeof obj !== "object") return obj;
18
- const proto = Object.getPrototypeOf(obj);
19
- if (proto !== Object.prototype && proto !== Array.prototype && proto !== null)
20
- return obj;
21
- const visited = seen ?? /* @__PURE__ */ new WeakSet();
22
- if (visited.has(obj)) return obj;
23
- visited.add(obj);
24
- Object.freeze(obj);
25
- for (const v of Object.values(obj))
26
- deepFreeze(v, visited);
27
- return obj;
28
- }
29
- function hasFunctionValues(obj) {
30
- if (obj === null || typeof obj !== "object") return null;
31
- for (const [key, value] of Object.entries(obj)) {
32
- if (typeof value === "function") return key;
33
- }
34
- return null;
35
- }
36
- function assertPureResult(result, msgType) {
37
- if (result && typeof result.then === "function") {
38
- throw new Error(
39
- `@demlik/tea: update cell "${msgType}" returned a Promise. update must be synchronous. Move async work to interpret.`
40
- );
41
- }
42
- if (!Array.isArray(result) || result.length < 2 || !Array.isArray(result[1])) {
43
- throw new Error(
44
- `@demlik/tea: update cell "${msgType}" returned a non-tuple. Expected [State, Cmd[]], got ${typeof result}.`
45
- );
46
- }
47
- const cmds = result[1];
48
- for (const cmd of cmds) {
49
- const fnField = hasFunctionValues(cmd);
50
- if (fnField !== null) {
51
- throw new Error(
52
- `@demlik/tea: Cmd "${cmd.type}" has function field "${fnField}". Cmds must be plain data, not closures.`
53
- );
54
- }
55
- }
56
- }
57
- function without(rec, key) {
58
- const { [key]: _dropped, ...rest } = rec;
59
- return rest;
60
- }
61
- function detectUpdateForm(update) {
62
- const firstKey = Object.keys(update)[0];
63
- if (firstKey === void 0) return "reducer";
64
- const firstValue = update[firstKey];
65
- return typeof firstValue === "function" ? "reducer" : "transitions";
66
- }
67
- function formOf(machine) {
68
- return machine.__form ?? detectUpdateForm(machine.update);
69
- }
70
- var NoCellError = class extends Error {
71
- constructor(msgType, stateName) {
72
- super(
73
- `@demlik/tea: no update cell for msg.type "${msgType}" in state "${stateName}" \u2014 the machine's update does not handle this Msg (an unknown wire msg.type, or a missing cell reached by bypassing the mapped types).`
74
- );
75
- this.msgType = msgType;
76
- this.stateName = stateName;
77
- }
78
- msgType;
79
- stateName;
80
- name = "NoCellError";
81
- _tag = "NoCellError";
82
- };
83
- function stateNameOf(state) {
84
- if (typeof state === "object" && state !== null && "type" in state) {
85
- const t = state.type;
86
- if (typeof t === "string") return t;
87
- }
88
- return "(untagged state)";
89
- }
90
- function lookupCell(machine, state, msg) {
91
- if (formOf(machine) === "reducer") {
92
- const record = machine.update;
93
- const cell2 = record[msg.type];
94
- return {
95
- cell: typeof cell2 === "function" ? cell2 : void 0,
96
- stateName: stateNameOf(state)
97
- };
98
- }
99
- const table = machine.update;
100
- const stateKey = state.type;
101
- const cell = table[stateKey]?.[msg.type];
102
- return {
103
- cell: typeof cell === "function" ? cell : void 0,
104
- stateName: String(stateKey)
105
- };
106
- }
107
- function applyCell(machine, state, msg) {
108
- const { cell, stateName } = lookupCell(machine, state, msg);
109
- if (cell === void 0) throw new NoCellError(msg.type, stateName);
110
- return cell(state, msg);
111
- }
112
- function applyCellChecked(machine, state, msg) {
113
- if (__DEV__) deepFreeze(state);
114
- const result = applyCell(machine, state, msg);
115
- if (__DEV__) assertPureResult(result, msg.type);
116
- return result;
117
- }
118
- function msgKeysOf(machine) {
119
- const keys = Object.keys(machine.update);
120
- if (keys.length === 0) return [];
121
- if (formOf(machine) === "reducer") return keys;
122
- const table = machine.update;
123
- const seen = /* @__PURE__ */ new Set();
124
- const union = [];
125
- for (const stateKey of keys) {
126
- const row = table[stateKey];
127
- if (row === null || row === void 0) continue;
128
- for (const msgKey of Object.keys(row)) {
129
- if (seen.has(msgKey)) continue;
130
- seen.add(msgKey);
131
- union.push(msgKey);
132
- }
133
- }
134
- return union;
135
- }
136
- function describeMachine(machine) {
137
- const msgs = msgKeysOf(machine);
138
- if (formOf(machine) === "reducer") return { form: "reducer", msgs };
139
- const table = machine.update;
140
- const states = Object.keys(table);
141
- const accepts = {};
142
- for (const stateKey of states) {
143
- const row = table[stateKey];
144
- accepts[stateKey] = row === null || row === void 0 ? [] : Object.keys(row);
145
- }
146
- return { form: "transitions", msgs, states, accepts };
147
- }
148
- function acceptsOf(machine, stateType) {
149
- const shape = describeMachine(machine);
150
- if (shape.form === "reducer") return shape.msgs;
151
- return shape.accepts[stateType] ?? [];
152
- }
153
- var Cmd = {
154
- /**
155
- * The empty Cmd array. Typed `readonly never[]` so it's assignable to any
156
- * `readonly C[]` for any `C extends Cmd`. Use in `init` returns and
157
- * Transitions cells that emit zero effects:
158
- *
159
- * init: (loaded) => [loaded ?? initial, Cmd.none],
160
- * tick: (state) => [state, Cmd.none],
161
- *
162
- * Elm's `Cmd.none` analogue. Cultural signal alongside the runtime help:
163
- * `[state, Cmd.none]` reads as intent ("this transition emits nothing"),
164
- * `[state, []]` reads as "empty array of what".
165
- *
166
- * Frozen at runtime so a downstream consumer can't `.push()` into the
167
- * shared reference.
168
- */
169
- none: Object.freeze([]),
170
- /**
171
- * Flat concat of cmd arrays. Use when a cell composes effects from
172
- * multiple conditional sources:
173
- *
174
- * return [next, Cmd.batch(
175
- * Cmd.whenDefined(state.queueItemId, (id) => ({ type: "complete", id })),
176
- * Cmd.when(state.windowId !== undefined, { type: "close_window", windowId }),
177
- * [{ type: "detach_debugger", tabId: state.tabId }],
178
- * )];
179
- *
180
- * `<const C>` keeps inline cmd literals' discriminants narrow (same
181
- * rationale as `when` / `whenDefined` above).
182
- */
183
- batch: (...arrs) => {
184
- const out = [];
185
- for (const arr of arrs) out.push(...arr);
186
- return out;
187
- },
188
- /**
189
- * Emit `cmd` wrapped in a single-element array iff `cond` is true.
190
- * Otherwise return the empty array. Spreads cleanly into the cmds array
191
- * returned by a Transitions cell.
192
- *
193
- * `const C` (TypeScript 5.0+) keeps the inferred `type:` discriminator
194
- * literal narrow when called with an object literal — so `Cmd.when(b,
195
- * { type: "x", ... })` infers as `{ type: "x", ... }`, not `{ type:
196
- * string, ... }`, and stays assignable to a discriminated-union arm
197
- * without `as const` at the call site.
198
- */
199
- when: (cond, cmd) => cond ? [cmd] : [],
200
- /**
201
- * If `value` is defined, call `build(value)` and emit the resulting cmd
202
- * wrapped in a single-element array. If `value` is `undefined`, return
203
- * the empty array. `value` is narrowed to `T` inside `build`.
204
- *
205
- * `const C` on the return type keeps the callback's object-literal
206
- * `type:` field narrow (see `when` above for the full rationale).
207
- */
208
- whenDefined: (value, build) => value !== void 0 ? [build(value)] : []
209
- };
210
- function subId(s) {
211
- return s;
212
- }
213
- function depsInactive(deps) {
214
- return deps === null || deps === void 0;
215
- }
216
- function structuralHash(deps) {
217
- return stableStringify(deps);
218
- }
219
- function stableStringify(value) {
220
- if (value === null) return "null";
221
- const t = typeof value;
222
- if (t === "string") return JSON.stringify(value);
223
- if (t === "number" || t === "boolean") return String(value);
224
- if (t === "undefined") return "undefined";
225
- if (t === "function") {
226
- throw new Error(
227
- "@demlik/tea: structuralHash received a function in `deps`. A dep-keyed Sub's `deps` must be a plain state slice (string / number / boolean / null / array / object), not a closure \u2014 see invariant 1."
228
- );
229
- }
230
- if (Array.isArray(value)) {
231
- return `[${value.map(stableStringify).join(",")}]`;
232
- }
233
- if (t === "object") {
234
- const proto = Object.getPrototypeOf(value);
235
- if (proto !== Object.prototype && proto !== null) {
236
- const ctor = value.constructor;
237
- const label = ctor?.name ?? "object";
238
- throw new Error(
239
- `@demlik/tea: structuralHash received a non-plain object (${label}) in \`deps\`. A \`Date\`, \`Map\`, \`Set\`, \`Error\` or class instance carries no own enumerable properties, so every one of them would hash to the same id as \`{}\` \u2014 a silent collision, not a wrong-looking key. Project it to plain data first (e.g. \`startedAt.toISOString()\`, \`[...set].sort()\`) \u2014 see invariant 1.`
240
- );
241
- }
242
- const obj = value;
243
- const keys = Object.keys(obj).sort();
244
- return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(",")}}`;
245
- }
246
- throw new Error(
247
- `@demlik/tea: structuralHash received an unsupported \`deps\` value of type "${t}". Use plain JSON-compatible data for a dep-keyed Sub's \`deps\`.`
248
- );
249
- }
250
- function foldUpdates(machine, initialState, msgs) {
251
- let state = initialState;
252
- const cmds = [];
253
- for (const msg of msgs) {
254
- const [next, emitted] = applyCellChecked(machine, state, msg);
255
- state = next;
256
- cmds.push(...emitted);
257
- }
258
- return { state, cmds };
259
- }
260
- function foldMsgs(machine, base, msgs) {
261
- return foldUpdates(machine, base, msgs).state;
262
- }
263
-
264
- export { Cmd, NoCellError, __DEV__, acceptsOf, applyCell, applyCellChecked, assertPureResult, deepFreeze, depsInactive, describeMachine, detectUpdateForm, foldMsgs, foldUpdates, formOf, lookupCell, msgKeysOf, structuralHash, subId, without };
265
- //# sourceMappingURL=chunk-B5VXOFMZ.js.map
266
- //# sourceMappingURL=chunk-B5VXOFMZ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/pure/core.ts"],"names":["cell"],"mappings":";AA4BO,IAAM,WAAoB,MAAM;AACrC,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,MAAA,CAAA,IAAA;AACb,IAAA,IAAI,IAAA,CAAK,GAAA,EAAK,GAAA,KAAQ,KAAA,CAAA,EAAW;AAC/B,MAAA,OAAO,KAAK,GAAA,CAAI,GAAA;AAAA,IAClB;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAA,IAAI;AACF,IAAA,OACE,OAAO,OAAA,KAAY,WAAA,IAAe,OAAA,CAAQ,KAAK,QAAA,KAAa,YAAA;AAAA,EAEhE,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF,CAAA;AAEO,SAAS,UAAA,CAAc,KAAQ,IAAA,EAA2B;AAC/D,EAAA,IAAI,GAAA,KAAQ,IAAA,IAAQ,OAAO,GAAA,KAAQ,UAAU,OAAO,GAAA;AACpD,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,cAAA,CAAe,GAAG,CAAA;AACvC,EAAA,IAAI,UAAU,MAAA,CAAO,SAAA,IAAa,KAAA,KAAU,KAAA,CAAM,aAAa,KAAA,KAAU,IAAA;A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AA,EAAmC,IAAA,EAAS,IAAA,EAAuB;AACnE,EAAA,OAAO,WAAA,CAAqB,OAAA,EAAS,IAAA,EAAM,IAAI,CAAA,CAAE,KAAA;AACnD","file":"chunk-B5VXOFMZ.js","sourcesContent":["/**\n * @demlik/tea — pure-core leaf (ADR 0006).\n *\n * This is the runtime-free pure core of the substrate. It holds the\n * client-prediction fold seam (`foldMsgs`), the form reader\n * (`formOf`/`detectUpdateForm`), and the pure type vocabulary (`Machine`,\n * `Reducer`, `Transitions`, `Cmd`, `Sub`, `Port`, …).\n *\n * **Dependency direction (the actual decoupling):** this module imports\n * NOTHING from the runtime — no `better-result`, no `run`/host/`Store`. The\n * runtime (`run`, the host, interpret, `Store`, subscribe — all in\n * `../index.ts`) imports *from* here; never the reverse. The\n * `@demlik/tea/pure` subpath re-exports this surface, and\n * `pure/import-graph.test.ts` is the regression fence asserting the pure\n * entrypoint's import graph never reaches `run`.\n */\n\n// === Dev-mode invariant enforcement ===\n//\n// Three runtime guards that catch TEA invariant violations during development.\n// Dead-code-eliminated in production by any bundler that replaces\n// `import.meta.env.DEV` (Vite) or `process.env.NODE_ENV` (webpack/esbuild).\n//\n// 1. deepFreeze(state) before passing to update — catches mutation\n// 2. Thenable check on return value — catches async update\n// 3. Walk cmd fields for function types — catches closures-as-data\n//\n// These enforce invariants 1 and 2 at runtime where the type system cannot.\nexport const __DEV__: boolean = (() => {\n try {\n const meta = import.meta as unknown as { env?: { DEV?: boolean } };\n if (meta.env?.DEV !== undefined) {\n return meta.env.DEV;\n }\n } catch {\n // import.meta not available (Node CJS, service workers)\n }\n try {\n return (\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\"\n );\n } catch {\n return false;\n }\n})();\n\nexport function deepFreeze<T>(obj: T, seen?: WeakSet<object>): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const proto = Object.getPrototypeOf(obj);\n if (proto !== Object.prototype && proto !== Array.prototype && proto !== null)\n return obj;\n const visited = seen ?? new WeakSet();\n if (visited.has(obj as object)) return obj;\n visited.add(obj as object);\n Object.freeze(obj);\n for (const v of Object.values(obj as Record<string, unknown>))\n deepFreeze(v, visited);\n return obj;\n}\n\nexport function hasFunctionValues(obj: unknown): string | null {\n if (obj === null || typeof obj !== \"object\") return null;\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n if (typeof value === \"function\") return key;\n }\n return null;\n}\n\nexport function assertPureResult(result: unknown, msgType: string): void {\n if (result && typeof (result as { then?: unknown }).then === \"function\") {\n throw new Error(\n `@demlik/tea: update cell \"${msgType}\" returned a Promise. ` +\n `update must be synchronous. Move async work to interpret.`,\n );\n }\n if (\n !Array.isArray(result) ||\n result.length < 2 ||\n !Array.isArray(result[1])\n ) {\n throw new Error(\n `@demlik/tea: update cell \"${msgType}\" returned a non-tuple. ` +\n `Expected [State, Cmd[]], got ${typeof result}.`,\n );\n }\n const cmds = result[1] as readonly { type: string }[];\n for (const cmd of cmds) {\n const fnField = hasFunctionValues(cmd);\n if (fnField !== null) {\n throw new Error(\n `@demlik/tea: Cmd \"${cmd.type}\" has function field \"${fnField}\". ` +\n `Cmds must be plain data, not closures.`,\n );\n }\n }\n}\n\n/**\n * Drop one `key` from a `Record` immutably — returns a new record with `key`\n * omitted, leaving the input untouched. The immutable-record-key-drop the L2\n * resilience bricks reach for whenever a settled/restarted call must forget its\n * per-key bookkeeping (a retry counter, a parked input). A plain\n * object-rest spread, lifted here so `resilient-call` and `authed-call` share\n * one definition instead of open-coding `const { [key]: _drop, ...rest } = rec`\n * at each site.\n */\nexport function without<V>(\n rec: Readonly<Record<string, V>>,\n key: string,\n): Readonly<Record<string, V>> {\n const { [key]: _dropped, ...rest } = rec;\n return rest;\n}\n\n// === Cmd: tagged-union, one-shot effect ===\nexport type Cmd<T extends string = string> = { readonly type: T };\n\n// === SyncReturn<S, C>: the compile-time reentrancy guard (ADR 0003 #5) ===\n//\n// The canon rule (`.patterns/tea-do/reentrancy.md`,\n// `.patterns/tea-do/reentrancy-deadlock.md`): a reducer must never\n// inline-`await` a re-entrant result. \"Non-reentrant by default\" ≡ \"the reducer\n// is pure AND synchronous\": a reducer that returns a `Promise` (because it is\n// `async`, or inline-`await`s) is the suspended-but-still-blocking turn Orleans\n// serializes against — it occupies the single-writer slot across a suspension\n// point and can be re-entered mid-flight → deadlock.\n//\n// So the guard is purely type-level: every reducer/transition cell returns\n// `SyncReturn<S, C>` — the synchronous result tuple, intersected with `{ then?:\n// never }` to make it *non-thenable*. A `Promise<readonly [S, readonly C[]]>`\n// is an object with a `then` method, so it fails to satisfy `then?: never`; an\n// `async (s, m) => [...]` (or one that inline-`await`s) is therefore\n// unrepresentable at compile time — `tsc` rejects it *at the cell*, not at a\n// runtime hang. A plain synchronous tuple `[next, cmds]` has no `then` property,\n// so the optional-absent `then?: never` is satisfied and existing pure reducers\n// compile unchanged. `SyncReturn<S, C>` is also assignable *to* `readonly [S,\n// readonly C[]]` (the intersection is narrower), so the runtime dispatch in\n// `run`/`replay` consumes a cell result exactly as before.\n//\n// This mirrors `retry-backoff`'s `Rng` brand (#63): the obligation lives in the\n// type at the construction boundary (\"parse, don't validate\"), not in a comment.\nexport type SyncReturn<S, C extends Cmd> = readonly [S, readonly C[]] & {\n // A thenable carries a callable `then`; forbidding it rejects every Promise.\n // Optional + `never` means \"absent on a sync tuple, impossible on a Promise\".\n readonly then?: never;\n};\n\n// === update form: Reducer vs Transitions, tagged once ===\n//\n// The substrate accepts two `update` shapes (see the `Machine.update` union and\n// the `defineMachine` overloads):\n//\n// - \"reducer\" — flat record keyed by Msg.type, every cell a function.\n// - \"transitions\" — 2D table keyed by State.type then Msg.type, every cell a\n// record of functions.\n//\n// Which one a given machine is must be known at runtime by `run`, `replay`, and\n// the `withX` wrappers (their dispatch / key-enumeration / reserved-namespace\n// scans differ per form). Rather than re-derive it structurally at every reader\n// — a `typeof update[firstKey] === \"function\"` heuristic that breaks the day a\n// reducer cell is itself an object-with-a-call — `defineMachine` computes the\n// form ONCE at construction and stamps it on the machine as a non-enumerable\n// `__form` (so it never serializes, never collides with a Msg.type key, never\n// shows up in `Object.keys(machine)`). Every reader calls `formOf(machine)`.\nexport type UpdateForm = \"reducer\" | \"transitions\";\n\n// The single structural heuristic, defined ONCE. Used only by `defineMachine`\n// (and `formOf`'s fallback for machines built without it, e.g. a plain object\n// literal annotated as `Machine`). A Reducer's first own value is a function; a\n// Transitions table's first own value is a record (of functions). An empty\n// record (`M` is `never`) can never dispatch a Msg, so the form is irrelevant —\n// \"reducer\" is returned arbitrarily.\nexport function detectUpdateForm(update: object): UpdateForm {\n const firstKey = Object.keys(update)[0];\n if (firstKey === undefined) return \"reducer\";\n const firstValue = (update as Record<string, unknown>)[firstKey];\n return typeof firstValue === \"function\" ? \"reducer\" : \"transitions\";\n}\n\n// The single reader every form-sensitive site goes through. Prefers the\n// `__form` tag stamped by `defineMachine` (authoritative — computed once at the\n// typed construction boundary); falls back to `detectUpdateForm` only for a\n// machine that never passed through `defineMachine`. No reader re-implements the\n// heuristic.\nexport function formOf(machine: {\n update: object;\n __form?: UpdateForm;\n}): UpdateForm {\n return machine.__form ?? detectUpdateForm(machine.update);\n}\n\n// === NoCellError: the named cell-lookup failure (#276) ===\n//\n// An unknown `msg.type` (wire data reaching dispatch) or a type-bypassed\n// missing cell used to surface as a bare `TypeError: ... is not a function`\n// deep inside dispatch — no msg.type, no state name, nothing actionable. The\n// guard lives in `applyCell` because it is the single dispatch primitive\n// every stepping site goes through (#275), so one guard covers `run`,\n// replay/foldMsgs, the PBT fold runner, and the withX wrappers.\nexport class NoCellError extends Error {\n override readonly name = \"NoCellError\";\n readonly _tag = \"NoCellError\" as const;\n constructor(\n public readonly msgType: string,\n public readonly stateName: string,\n ) {\n super(\n `@demlik/tea: no update cell for msg.type \"${msgType}\" in state ` +\n `\"${stateName}\" — the machine's update does not handle this Msg ` +\n `(an unknown wire msg.type, or a missing cell reached by bypassing ` +\n `the mapped types).`,\n );\n }\n}\n\n// Reducer-form State carries no mandatory discriminant; best-effort read of a\n// string `state.type` for the error, else a placeholder.\nfunction stateNameOf(state: unknown): string {\n if (typeof state === \"object\" && state !== null && \"type\" in state) {\n const t = (state as { type: unknown }).type;\n if (typeof t === \"string\") return t;\n }\n return \"(untagged state)\";\n}\n\n// === lookupCell: THE single cell SELECTION, split from the invocation ===\n//\n// The form-branching (`reducer` → flat `update[msg.type]`; `transitions` →\n// `update[state.type][msg.type]`) lives here and NOWHERE else. `applyCell`\n// (throwing) and `tryApplyCell` (`Result`-returning, in `../runtime-types`)\n// are both thin skins over this one selection, so the two error disciplines\n// can never disagree about WHICH cell a `(machine, state, msg)` triple picks\n// — the failure mode a second hand-written copy of the branching would have.\n//\n// Returns the selected cell (or `undefined` when there is none) together with\n// the `stateName` the `NoCellError` message needs — the caller decides whether\n// that absence becomes a throw or an `Err`.\n//\n// Pure and allocation-light: one small record per lookup, never a closure.\nexport function lookupCell<S, M extends { type: string }, C extends Cmd>(\n machine: { update: object; __form?: UpdateForm },\n state: S,\n msg: M,\n): {\n readonly cell: ((state: S, msg: M) => readonly [S, readonly C[]]) | undefined;\n readonly stateName: string;\n} {\n type CellFn = (state: S, msg: M) => readonly [S, readonly C[]];\n if (formOf(machine) === \"reducer\") {\n const record = machine.update as Record<string, CellFn | undefined>;\n const cell = record[msg.type];\n return {\n cell: typeof cell === \"function\" ? cell : undefined,\n stateName: stateNameOf(state),\n };\n }\n const table = machine.update as Record<\n string,\n Record<string, CellFn | undefined> | undefined\n >;\n // The ONE sanctioned `state as unknown as { type }` read: the Transitions\n // overload constrains S to `{ type: string }` at the `defineMachine`\n // boundary, but that constraint is erased on the runtime-facing `object`\n // here — every former per-site copy of this double-cast collapsed into\n // this line (#275).\n const stateKey = (state as unknown as { type: string }).type;\n const cell = table[stateKey]?.[msg.type];\n return {\n cell: typeof cell === \"function\" ? cell : undefined,\n stateName: String(stateKey),\n };\n}\n\n// === applyCell: THE single reducer-vs-transitions dispatch primitive ===\n//\n// Applies the one update cell selected by `lookupCell(machine, state, msg)` and\n// returns its `[nextState, cmds]` verbatim. Every site that steps a machine —\n// `run`'s applyUpdate, `foldUpdates` (replay/foldMsgs), the PBT fold runner,\n// and the withX wrappers — dispatches through THIS function, so production and\n// the verification tools agree on the update form by construction (#275).\n// Pure and dev-check-free: `deepFreeze`/`assertPureResult` stay at the call\n// sites that want them. A missing cell throws `NoCellError` (#276), never a\n// bare TypeError.\n//\n// The `Result`-returning twin is `tryApplyCell` (`@demlik/tea` root; it needs\n// `better-result`, which this pure leaf must not import). Both read the SAME\n// `lookupCell`, so \"which cell\" is decided once.\nexport function applyCell<S, M extends { type: string }, C extends Cmd>(\n machine: { update: object; __form?: UpdateForm },\n state: S,\n msg: M,\n): readonly [S, readonly C[]] {\n const { cell, stateName } = lookupCell<S, M, C>(machine, state, msg);\n if (cell === undefined) throw new NoCellError(msg.type, stateName);\n return cell(state, msg);\n}\n\n// === applyCellChecked: `applyCell` wrapped in the DEV pre/post invariant pair ===\n//\n// The dev-mode discipline every fold site shares: `deepFreeze` the input `state`\n// so a reducer that mutates it in place trips synchronously, then\n// `assertPureResult` the returned `[state, cmds]` shape. Both guards compile out\n// of production (`__DEV__`). `run`'s dispatch loop and `foldUpdates` both step\n// through THIS wrapper so the invariant enforcement lives in exactly one place\n// and cannot drift between the runtime and the pure fold.\nexport function applyCellChecked<S, M extends { type: string }, C extends Cmd>(\n machine: { update: object; __form?: UpdateForm },\n state: S,\n msg: M,\n): readonly [S, readonly C[]] {\n if (__DEV__) deepFreeze(state);\n const result = applyCell<S, M, C>(machine, state, msg);\n if (__DEV__) assertPureResult(result, msg.type);\n return result;\n}\n\n// === msgKeysOf: recover the Msg.type set from either update form ===\n//\n// A Reducer's own keys ARE the Msg.type set. A Transitions table's keys are\n// state.type; its INNER keys are the Msg.type set, so the UNION of every row's\n// inner keys is read — first-seen order, deduped. An empty update (`M` is\n// `never`) yields `[]`. Keyed on `formOf` — the withX wrappers and the PBT\n// `msgTypeKeys` all read through this one helper (#275).\n//\n// Why the union and not the first row's keys (the former reading): the\n// mapped-type `Transitions<S, M, C>` contract makes the Msg key set uniform\n// across phases, so for a hand-written TOTAL table the first row already IS\n// the union and this is a no-op. But the contract only binds where the types\n// bind. A table assembled DYNAMICALLY — the discriminants widened to plain\n// `string`, rows pushed in a loop — is structurally ragged, and reading row\n// zero then under-reports the Msg union. That under-report is not cosmetic:\n// all three withX wrappers build their flat merged Reducer by iterating\n// `msgKeysOf(base)`, so a Msg missing from row zero got NO cell in the wrapped\n// machine and threw `NoCellError` at dispatch for a Msg the base handles\n// perfectly well; and `withDeadline`'s reserved-namespace scan silently missed\n// a `$deadline:`-prefixed base Msg that appeared only in a later row.\n//\n// The widening is pure: for any total table the returned array is identical\n// (same keys, same order). Cost goes from O(msgs) to O(states × msgs), paid\n// ONCE per wrapper construction — never inside the dispatch loop.\nexport function msgKeysOf(machine: {\n update: object;\n __form?: UpdateForm;\n}): readonly string[] {\n const keys = Object.keys(machine.update);\n if (keys.length === 0) return [];\n if (formOf(machine) === \"reducer\") return keys;\n const table = machine.update as Record<string, object | undefined>;\n const seen = new Set<string>();\n const union: string[] = [];\n for (const stateKey of keys) {\n const row = table[stateKey];\n if (row === null || row === undefined) continue;\n for (const msgKey of Object.keys(row)) {\n if (seen.has(msgKey)) continue;\n seen.add(msgKey);\n union.push(msgKey);\n }\n }\n return union;\n}\n\n// === describeMachine / acceptsOf: the per-state accept-sets, as a reading ===\n//\n// \"Which Msgs does this machine accept, and in which state?\" — the question a\n// tool asks when it drives a machine ITSELF instead of through `run`: a CLI\n// rendering the legal next moves, a doc generator, a log validator. Before\n// this the only answer was to cast `machine.update as Record<string,\n// Record<string, unknown>>` at the call site and hand-branch the form — one\n// private copy of the form-branching per consumer, drifting from the kernel's.\n//\n// This is a DERIVED READING over the table, deliberately NOT a property on the\n// machine. It has to be: every `withX` wrapper builds a fresh flat\n// `Record<string, Cell>`, casts it to `Reducer`, and returns a NEW object\n// literal carrying only `init`/`update`/`subscriptions`/`subscribe`/\n// `interpret`. Any property hung on a machine is therefore destroyed by the\n// first wrap, and the wrapped table is reducer-form regardless of the base's.\n// A function over `(update, formOf)` survives wrapping and tells the truth\n// about the machine it is actually handed.\n//\n// The return type is a DISCRIMINATED union on `form` because the two forms\n// genuinely answer different questions, and faking the missing one would be a\n// lie the type system would then propagate:\n// - `transitions` — carries `states` and `accepts` (state.type → Msg.types).\n// - `reducer` — has NO per-state accept-sets AT ALL. Its dispatch does\n// not consult the state, so `msgs` is the whole answer and there is no\n// `accepts` field to read. Reaching for one is a compile error, not an\n// empty object.\nexport type MachineShape =\n | {\n readonly form: \"reducer\";\n /** Every `Msg.type` the flat reducer has a cell for. */\n readonly msgs: readonly string[];\n }\n | {\n readonly form: \"transitions\";\n /** The union of every row's `Msg.type` keys (see `msgKeysOf`). */\n readonly msgs: readonly string[];\n /** Every `state.type` the table has a row for, in table order. */\n readonly states: readonly string[];\n /** `state.type` → the `Msg.type`s that state has a cell for. */\n readonly accepts: Readonly<Record<string, readonly string[]>>;\n };\n\nexport function describeMachine(machine: {\n update: object;\n __form?: UpdateForm;\n}): MachineShape {\n const msgs = msgKeysOf(machine);\n if (formOf(machine) === \"reducer\") return { form: \"reducer\", msgs };\n const table = machine.update as Record<string, object | undefined>;\n const states = Object.keys(table);\n const accepts: Record<string, readonly string[]> = {};\n for (const stateKey of states) {\n const row = table[stateKey];\n accepts[stateKey] =\n row === null || row === undefined ? [] : Object.keys(row);\n }\n return { form: \"transitions\", msgs, states, accepts };\n}\n\n// The one-state shorthand over `describeMachine`. Reducer-form is not a\n// special case being papered over: a flat reducer's dispatch never reads the\n// state, so EVERY state accepts the full Msg set and returning it is the true\n// answer, not a stand-in. A `stateType` with no row in a Transitions table\n// accepts nothing, so `[]` — equally true.\nexport function acceptsOf(\n machine: { update: object; __form?: UpdateForm },\n stateType: string,\n): readonly string[] {\n const shape = describeMachine(machine);\n if (shape.form === \"reducer\") return shape.msgs;\n return shape.accepts[stateType] ?? [];\n}\n\n// === Reducer<S, M, C>: record-of-handlers form of `update` ===\n//\n// Flat dispatch table keyed by `Msg.type`. Each cell is a pure transition for\n// a single Msg variant, narrowed via `Extract<M, { type: K }>`. The mapped type\n// is *load-bearing*: adding a Msg variant without a matching key in the\n// Reducer record is a compile error — no `absurd()` helper at call sites, no\n// silent fall-through, no default branch hiding impurity.\n//\n// Strengthens invariant 2 (pure transitions — the record form has no\n// fall-through default to hide impurity behind) and invariant 7 (identity is\n// explicit — the Msg variant set is load-bearing at the type level).\n//\n// `defineMachine` accepts the Reducer record form via overload. The runtime\n// dispatches via `update[msg.type](state, msg)`.\nexport type Reducer<S, M extends { type: string }, C extends Cmd> = {\n [K in M[\"type\"]]: (\n state: S,\n msg: Extract<M, { type: K }>,\n // `SyncReturn<S, C>` (not `readonly [S, readonly C[]]`) is the reentrancy\n // guard: a non-thenable return type, so an `async`/inline-`await`ing cell —\n // which returns `Promise<...>` — fails to compile at the cell. See the\n // `SyncReturn` doc above.\n ) => SyncReturn<S, C>;\n};\n\n// === Transitions<S, M, C>: table form of `update` for state-machine-shaped machines ===\n//\n// When `State` is itself a discriminated union (`State.type` is the active\n// phase), the table form makes every (state.type × msg.type) cell explicit at\n// the type level. Missing a cell — e.g. forgetting how `phase: \"settling\"`\n// handles `msg.type: \"tab_stepped\"` — fails to compile. No nested switch, no\n// fall-through, no `_ -> (state, [])` default branch hiding regressions.\n//\n// Each cell receives the narrowed `State` for its phase and the narrowed\n// `Msg` for its variant via two `Extract` lookups. Phantom-narrow at the\n// type level; pure data at runtime.\n//\n// `defineMachine` accepts a third `update` form for `Transitions<S, M, C>` —\n// the runtime dispatches via `update[state.type][msg.type](state, msg)`.\n//\n// Strengthens invariant 2 (table form has no fall-through default),\n// invariant 6 (runtime walks the table predictably, no hidden dispatch\n// fallback), and invariant 7 (both state.type and msg.type are load-bearing\n// at the type level).\nexport type Transitions<\n S extends { type: string },\n M extends { type: string },\n C extends Cmd,\n> = {\n [P in S[\"type\"]]: {\n [K in M[\"type\"]]: (\n state: Extract<S, { type: P }>,\n msg: Extract<M, { type: K }>,\n // Same reentrancy guard as `Reducer`: a transition cell that returns a\n // Promise (async / inline-await) is the suspended-blocking turn the canon\n // forbids, so its return is the non-thenable `SyncReturn<S, C>`.\n ) => SyncReturn<S, C>;\n };\n};\n\n// === Cmd: namespace for conditional Cmd emission ===\n//\n// Two recurring frictions in reducer cells:\n//\n// 1. \"Emit cmd X only when condition Y holds.\"\n// Hand-rolled: `cond ? [{ type: \"x\", ... }] : []`\n// With Cmd: `Cmd.when(cond, { type: \"x\", ... })`\n//\n// 2. \"Emit cmd X carrying a value that may be undefined; if undefined,\n// emit nothing.\"\n// Hand-rolled: `value !== undefined ? [{ type: \"x\", value }] : []`\n// With Cmd: `Cmd.whenDefined(value, (v) => ({ type: \"x\", value: v }))`\n//\n// Both forms return `readonly C[]` so they spread cleanly into the cmds\n// array returned by a Transitions cell:\n//\n// return [next, [\n// ...Cmd.when(state.tabId !== undefined, { type: \"detach_debugger\", tabId: state.tabId }),\n// ...Cmd.whenDefined(state.queueItemId, (id) => ({\n// type: \"queue:complete\", queueItemId: id, status: \"done\",\n// })),\n// ]];\n//\n// `Cmd` as a value namespace coexists with `Cmd<T>` as a type — TypeScript's\n// declaration merging puts them in different name spaces (type vs. value).\n// The reader sees `Cmd<...>` in type position and `Cmd.when(...)` in\n// expression position; no ambiguity at use sites.\n//\n// Why a namespace and not top-level `when` / `whenDefined`: `when` at module\n// scope reads as a generic conditional, but these helpers are specifically\n// for *Cmd emission* (return `readonly C[]`, the cmds-array contract of\n// every Transitions cell). The namespace pins that intent at the call site.\nexport const Cmd = {\n /**\n * The empty Cmd array. Typed `readonly never[]` so it's assignable to any\n * `readonly C[]` for any `C extends Cmd`. Use in `init` returns and\n * Transitions cells that emit zero effects:\n *\n * init: (loaded) => [loaded ?? initial, Cmd.none],\n * tick: (state) => [state, Cmd.none],\n *\n * Elm's `Cmd.none` analogue. Cultural signal alongside the runtime help:\n * `[state, Cmd.none]` reads as intent (\"this transition emits nothing\"),\n * `[state, []]` reads as \"empty array of what\".\n *\n * Frozen at runtime so a downstream consumer can't `.push()` into the\n * shared reference.\n */\n none: Object.freeze([]) as readonly never[],\n\n /**\n * Flat concat of cmd arrays. Use when a cell composes effects from\n * multiple conditional sources:\n *\n * return [next, Cmd.batch(\n * Cmd.whenDefined(state.queueItemId, (id) => ({ type: \"complete\", id })),\n * Cmd.when(state.windowId !== undefined, { type: \"close_window\", windowId }),\n * [{ type: \"detach_debugger\", tabId: state.tabId }],\n * )];\n *\n * `<const C>` keeps inline cmd literals' discriminants narrow (same\n * rationale as `when` / `whenDefined` above).\n */\n batch: <const C extends Cmd>(\n ...arrs: readonly (readonly C[])[]\n ): readonly C[] => {\n const out: C[] = [];\n for (const arr of arrs) out.push(...arr);\n return out;\n },\n\n /**\n * Emit `cmd` wrapped in a single-element array iff `cond` is true.\n * Otherwise return the empty array. Spreads cleanly into the cmds array\n * returned by a Transitions cell.\n *\n * `const C` (TypeScript 5.0+) keeps the inferred `type:` discriminator\n * literal narrow when called with an object literal — so `Cmd.when(b,\n * { type: \"x\", ... })` infers as `{ type: \"x\", ... }`, not `{ type:\n * string, ... }`, and stays assignable to a discriminated-union arm\n * without `as const` at the call site.\n */\n when: <const C extends Cmd>(cond: boolean, cmd: C): readonly C[] =>\n cond ? [cmd] : [],\n\n /**\n * If `value` is defined, call `build(value)` and emit the resulting cmd\n * wrapped in a single-element array. If `value` is `undefined`, return\n * the empty array. `value` is narrowed to `T` inside `build`.\n *\n * `const C` on the return type keeps the callback's object-literal\n * `type:` field narrow (see `when` above for the full rationale).\n */\n whenDefined: <T, const C extends Cmd>(\n value: T | undefined,\n build: (value: T) => C,\n ): readonly C[] => (value !== undefined ? [build(value)] : []),\n} as const;\n\n// === SubId: branded string for Sub identity ===\n//\n// Subs are reconciled by id on every transition (canon §2.5, invariant 7).\n// Before branding, `Sub.id` was a raw `string` — a typo at one call site and a\n// different typo at another would silently produce two distinct subs that\n// looked identical to a human reader. The brand makes id construction explicit\n// (`subId(\"...\")`) and catches accidental string-where-SubId at the type\n// level.\n//\n// The brand is structural: `string & { __brand: \"SubId\" }`. The `subId(s)`\n// constructor is the ONE permitted cast in the substrate — every other call\n// site must go through it.\nexport type SubId = string & { readonly __brand: \"SubId\" };\n\n/**\n * Construct a `SubId` from a string. Use this everywhere a Sub literal is\n * built — including ids derived from runtime data (`subId(\\`ws:${auditId}\\`)`).\n * The brand is structural, not nominal, so dynamic ids are permitted; the\n * constructor's job is to make the identity decision explicit at every call\n * site so the type system can catch accidental raw-string drift.\n *\n * Strengthens invariant 7 (identity is explicit).\n */\nexport function subId(s: string): SubId {\n return s as SubId;\n}\n\n// === Sub: tagged-union, continuous source of msgs; stable id used for diff/reconcile ===\nexport type Sub<T extends string = string> = {\n readonly id: SubId;\n readonly type: T;\n};\n\n// === Dispose: the cleanup a dep-keyed Sub's source returns ===\n//\n// A `source` opens a resource and returns the function that closes it. The\n// substrate's reconcile calls it when the Sub's `deps` go null (torn down) or\n// change (re-armed: old `Dispose` then a fresh `source`). Same contract as the\n// `() => void` cleanup every `subscribe[type]` handler returns — named so a\n// dep-keyed Sub's `source` reads as \"open → returns close\".\nexport type Dispose = () => void | Promise<void>;\n\n// === depsInactive: the dep-keyed gate, defined ONCE ===\n//\n// \"This Sub has no slice in this state\" is one fact read by two places — the\n// runtime's `reconcileDepSubs` and `replay`'s desired-set projection — so it\n// gets one definition rather than a `deps === null` written twice.\n//\n// It reads NULLISH, not `null`. `(s) => s.runId` over an optional field is the\n// natural projection an author writes, and it yields `undefined` on the states\n// that mean \"inactive\"; a `=== null` gate armed the Sub there and hashed the\n// slice to the string `\"undefined\"` — one shared key under which a resource\n// was acquired for a state that had none. The typed alternative (`deps: (s) =>\n// {} | null`) would reject that projection at compile time, but it also rejects\n// every battery's `(state) => TKey | null` for an unconstrained `TKey`, so the\n// gate is widened instead of the type narrowed.\nexport function depsInactive(deps: unknown): boolean {\n return deps === null || deps === undefined;\n}\n\n// === structuralHash: deterministic, order-independent id from a deps value ===\n//\n// The id of a dep-keyed Sub (invariant 7 — identity is explicit) is DERIVED\n// from the slice of state the Sub depends on, never hand-authored. So adding a\n// field to `deps` changes the id exactly when that field changes, and a\n// churning id — the named #1 Sub bug (a Sub that remounts every tick, so its\n// timer never fires) — becomes impossible by construction: the author cannot\n// build the id wrong because the author does not build it.\n//\n// Determinism is load-bearing (invariant 2 — the reconcile pass runs inside\n// the pure-transition path's reconcile step; the same `deps` must always hash\n// to the same id). So: NO `Date`, NO random, NO insertion-order dependence.\n// Object keys are sorted so `{ runId, phase }` and `{ phase, runId }` hash\n// identically — the canonical \"name the slice → stable key\" adaptation FoldKit\n// makes for TS (its `modelToDependencies`), which Elm gets free from its\n// structural compare.\n//\n// The supported `deps` shape is plain JSON-compatible data (string / number /\n// boolean / null / array / plain object). A function, class instance, symbol,\n// or bigint in `deps` is a programming error — `deps` names a state SLICE, and\n// state is a value (invariant 1); such a value would also break the\n// determinism this hash promises. The walk throws on all of them to surface\n// that loudly rather than silently producing an unstable — or, worse, a\n// COLLIDING — id.\n//\n// The non-plain OBJECT case is the one that bites: `Object.keys` reports no own\n// enumerable property on a `Date`, `Map`, `Set`, `Error`, or a typical class\n// instance, so a walk that trusts it renders every one of them — and `{}` —\n// as `\"{}\"`. That is not an unstable id, it is ONE id for every value, which\n// defeats the identity filter (a foreign run's message compares equal), pins a\n// dep-keyed Sub to its first slice forever, and makes a battery's handle table\n// return the previous key's handle. The guard is therefore on the PROTOTYPE\n// (`Object.prototype` or `null`), not on a list of known classes: a\n// user-defined `RunKey` is refused by the same rule as `Date`, and no future\n// exotic builtin slips through.\n//\n// Rendering `Date`/`Map`/`Set` structurally was the alternative. It was\n// rejected: it buys a second rule to remember for a value the author can\n// project in one call (`startedAt.toISOString()`), and `Map`/`Set` iteration is\n// INSERTION-ordered, so any faithful rendering is order-sensitive — exactly the\n// churn this hash exists to prevent. One rule, stated once: plain data only.\n//\n// It is also the ONE \"turn this key value into a stable string\" primitive the\n// `@demlik/tea/subs` batteries address their interpret-local handle tables\n// with, so a battery's key rendering and the kernel's Sub identity can never\n// drift into two hashes for one fact.\nexport function structuralHash(deps: unknown): string {\n return stableStringify(deps);\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null) return \"null\";\n const t = typeof value;\n if (t === \"string\") return JSON.stringify(value);\n if (t === \"number\" || t === \"boolean\") return String(value);\n if (t === \"undefined\") return \"undefined\";\n if (t === \"function\") {\n throw new Error(\n \"@demlik/tea: structuralHash received a function in `deps`. \" +\n \"A dep-keyed Sub's `deps` must be a plain state slice (string / number / \" +\n \"boolean / null / array / object), not a closure — see invariant 1.\",\n );\n }\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(\",\")}]`;\n }\n if (t === \"object\") {\n // Plain-object gate. `Object.keys` is only a faithful reading of a value\n // whose prototype is `Object.prototype` (or `null` — a bag built with\n // `Object.create(null)` is plain by every measure that matters here).\n // Anything else keeps its data somewhere `Object.keys` cannot see, and\n // would render as `\"{}\"` — one id for every such value.\n const proto = Object.getPrototypeOf(value) as object | null;\n if (proto !== Object.prototype && proto !== null) {\n const ctor = (value as { constructor?: { name?: string } }).constructor;\n const label = ctor?.name ?? \"object\";\n throw new Error(\n `@demlik/tea: structuralHash received a non-plain object (${label}) in \\`deps\\`. ` +\n \"A `Date`, `Map`, `Set`, `Error` or class instance carries no own enumerable \" +\n \"properties, so every one of them would hash to the same id as `{}` — a silent \" +\n \"collision, not a wrong-looking key. Project it to plain data first \" +\n \"(e.g. `startedAt.toISOString()`, `[...set].sort()`) — see invariant 1.\",\n );\n }\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(\",\")}}`;\n }\n // bigint / symbol — not JSON-representable; same class of error as function.\n throw new Error(\n `@demlik/tea: structuralHash received an unsupported \\`deps\\` value of type \"${t}\". ` +\n \"Use plain JSON-compatible data for a dep-keyed Sub's `deps`.\",\n );\n}\n\n// === DepKeyedSub<S, M, Ctx>: a Sub whose identity AND gate fall out of `deps` ===\n//\n// The author declares the slice of state the Sub depends on (`deps`) and how\n// to open the resource for that slice (`source`). The substrate derives BOTH:\n//\n// - the **id** = `structuralHash(deps(state))` — changes exactly when the\n// slice changes (re-arm), stable otherwise (no churn). The author never\n// writes `subId(...)` — the hand-written subId was the drift away from\n// Elm's structural identity, which this restores.\n// - the **gate** = `deps(state)` returning `null` ⇒ inactive in this state\n// (dispose if running); non-null ⇒ active. The substrate folds every\n// `DepKeyedSub` into its own active set, so the author deletes the central\n// `subscriptions(state)` aggregate — there is no list to forget to edit\n// when a new phase is added (a per-Sub gate travels with the Sub).\n//\n// This is the FoldKit `modelToDependencies` shape: a Sub names the state slice\n// it depends on, the kernel keys on that slice. The manual `subscriptions?:`\n// field stays as the documented escape hatch (see `Machine`).\n//\n// `source` returns a `Dispose`. On a `deps` change the substrate runs the old\n// `Dispose` then re-runs `source` with the new deps (re-arm); on `deps` going\n// null it runs `Dispose` (teardown). The same reconcile machinery the manual\n// `Sub` path uses (`reconcileSubs` in `../run.ts`) — no second loop.\n//\n// Strengthens invariant 4 (external lifecycle owned by the substrate — the\n// dep-keyed Sub is reconciled, never hand-driven) and invariant 7 (identity is\n// explicit — derived deterministically from `deps`, never an ad-hoc string).\nexport interface DepKeyedSub<S, M, Ctx = unknown> {\n /**\n * The slice of state this Sub depends on. `null` OR `undefined` ⇒ the Sub is\n * inactive in this state (the substrate disposes it if it was running) — see\n * `depsInactive`, so `(s) => s.optionalRunId` gates correctly. Otherwise the\n * Sub is active, keyed on `structuralHash(deps)`.\n *\n * Pure (invariant 2). Plain JSON-compatible data only (invariant 1) — the\n * structural hash walks it deterministically and THROWS on a `Date`, `Map`,\n * `Set`, `Error` or class instance rather than collapsing them all onto one\n * id. Project such a value first (`startedAt.toISOString()`).\n */\n readonly deps: (state: S) => unknown;\n /**\n * Open the resource for the current `state` (whose `deps` the kernel just\n * found non-null). Receives `dispatch` to fire follow-up Msgs (a timer's\n * fire, an inbound frame) and the machine's `ctx` (the host's transport\n * factory, storage handles). Returns the `Dispose` the substrate runs on\n * teardown / re-arm. Same role as a `subscribe[type]` handler's returned\n * cleanup.\n *\n * `source` takes `state` (not the deps slice) so the slice type `D` never\n * escapes the entry — each battery's `.depKeyed` closes over its own typed\n * deps internally (cast-free existential: the entry that produced the deps\n * is the entry that consumes them).\n */\n readonly source: (state: S, dispatch: (msg: M) => void, ctx: Ctx) => Dispose;\n}\n\n// === Identity<S, M>: declare the instance's identity once; the kernel drops\n// mis-addressed messages before they reach `update` ===\n//\n// Without this: the substrate dispatches EVERY message to `update`, so an\n// author who needs \"this message is for THIS run\" must repeat\n// `if (msg.runId !== state.runId) return [state, []]` in every reducer cell.\n// Forget one cell and a stale or foreign run's message is applied → silent\n// corruption. That per-cell check is a rung-4 runtime stand-in for invariant 7\n// (identity is explicit): the identity invariant the host already holds (one\n// instance per run — `idFromName(runId)`) is re-asserted, cell by cell, where\n// it can be forgotten.\n//\n// `Identity<S, M>` lifts that to ONE declaration the kernel enforces. The\n// machine names two projections:\n//\n// - `ofState(state)` → the identity THIS instance owns, derived from state.\n// - `ofMsg(msg)` → the identity a message is ADDRESSED to, or\n// `undefined` when the message carries no identity\n// (lifecycle messages like `boot`, or `start_audit`\n// before the run exists — those are never dropped).\n//\n// Per transition the kernel compares `ofMsg(msg)` to `ofState(state)` by\n// `structuralHash` (so the identity can be any plain value, same machinery the\n// dep-keyed Sub id uses). A message addressed to a DIFFERENT identity is\n// dropped BEFORE `update` runs — the reducer never sees it, so no cell needs a\n// guard. A message with `ofMsg === undefined` is identity-agnostic and always\n// reaches `update`.\n//\n// Two projections rather than a single `(state) => state.runId`: the kernel\n// needs BOTH the state's identity AND the message's to compare, and splitting\n// them keeps the comparison `K`-to-`K` with no `as` cast (a message union\n// carries its identity field on only SOME arms — `ofMsg` narrows per arm in\n// author-land, returning `undefined` on the arms that have none, instead of\n// the substrate reaching into `msg.runId` it cannot type).\n//\n// Opt-in (escape hatch): a machine that declares no `identity` skips the filter\n// entirely — every message reaches `update`, exactly as before.\n//\n// Strengthens invariant 7 (identity is explicit — declared once, derived\n// deterministically, kernel-enforced rather than re-checked per cell) and\n// invariant 6 (the runtime is small and inspectable — a mis-addressed message\n// is dropped at ONE observable point, not silently mishandled in N cells).\nexport interface Identity<S, M> {\n /** The identity THIS instance owns. Pure (invariant 2); plain value. */\n readonly ofState: (state: S) => unknown;\n /**\n * The identity a message is addressed to, or `undefined` when the message\n * carries no identity (lifecycle / pre-identity messages — never dropped).\n * Pure (invariant 2); plain value when defined.\n */\n readonly ofMsg: (msg: M) => unknown;\n}\n\n// === Port<T>: typed escape hatch for \"data leaving the runtime\" ===\n//\n// A Port is a named, typed channel that Cmd handlers can `emit` to via the\n// augmented `ctx.emit(port, value)`. Subscribers attach via\n// `runtime.subscribePort(port, listener)` and receive every emitted value\n// synchronously (same fanout discipline as `runtime.observe`).\n//\n// Why Ports are a substrate primitive, distinct from State and Observe:\n// - **State** is \"the world as the program sees it.\" Folding outgoing\n// announcements into State turns ephemeral signals into persisted facts —\n// the classic anti-pattern that motivated this primitive.\n// - **Observe** sees every transition `(msg, state)`. That's the right channel\n// for devtools and logging, but it forces every consumer to filter the\n// entire firehose for a single signal.\n// - **Ports** are typed and selective: one channel per concept, subscribers\n// only see what the handler chose to emit. Mirrors Elm's outgoing-port\n// semantics — a typed declaration with `port` keyword whose values flow\n// out of the program to the host.\n//\n// Port identity is **by reference** — the returned object IS the identity.\n// Name is metadata for debugging. To prevent the \"two modules definePort the\n// same name expecting to share a channel, silently get distinct ports\" class\n// of bug, `definePort` asserts the name has not been seen in this process —\n// the symmetric runtime check to `SubId` (canon §2.12, invariant 7). Each\n// definePort call must use a unique name; if two modules need the same port,\n// one module exports it and the other imports it.\nexport interface Port<T> {\n readonly __brand: \"port\";\n readonly name: string;\n // Phantom field — never assigned, never read at runtime. Carries `T` for\n // inference at `ctx.emit` and `subscribePort` call sites. Using `?` so\n // `definePort` can produce a Port without constructing a value of `T`.\n readonly __t?: T;\n}\n\n/**\n * Augmentation injected onto `ctx` inside Cmd handlers. Handlers receive\n * `ctx & PortEmitter` so they can call `ctx.emit(port, value)` synchronously.\n * Subscribers registered via `runtime.subscribePort(port, listener)` receive\n * the value immediately.\n *\n * Emitting to a port with no subscribers is a no-op (does not throw).\n */\nexport interface PortEmitter {\n emit<T>(port: Port<T>, value: T): void;\n}\n\n// === NoCtx: the context-free marker ===\n//\n// A handler, Sub, or machine that reads NOTHING from `ctx` says so by using\n// `NoCtx` for its Ctx slot. This is the DELIBERATE absence of context — not\n// the accidental `unknown` looseness that erodes a boundary (see issue #64).\n//\n// `unknown` at a Ctx seam is ambiguous: it can mean \"I intentionally need no\n// context\" OR \"I gave up tightening this type.\" `NoCtx` resolves that\n// ambiguity at the type level. A reader (and the next agent) sees `NoCtx` and\n// knows the context-free-ness is a choice the author made, not a hole.\n//\n// Shape: an empty readonly record. A `Ctx & PortEmitter` is-a `NoCtx`, so a\n// context-free handler still composes at a richer call site. It carries no\n// own fields, so the name's claim (\"reads nothing from ctx\") is what callers\n// read at the seam.\n//\n// Strengthens invariant 6 (no silent looseness — a context-free seam is named,\n// not inferred) and invariant 8 (the boundary is legible; `unknown` stays\n// reserved for genuine wire-edge erasure, not for \"didn't bother\").\nexport type NoCtx = Readonly<Record<never, never>>;\n\n/**\n * Spelled-out alias for `NoCtx`.\n *\n * @deprecated Use {@link NoCtx}. One Way to Do Each Thing — `NoCtx` is the\n * single non-deprecated name for the context-free-ctx marker (this alias has\n * no in-tree uses). Kept as a re-export for one minor per the deprecate-don't-\n * delete policy in `MAINTAINING.md`, then removed.\n */\nexport type ContextFree = NoCtx;\n\n// === Interpret<M, C, Ctx>: record-of-handlers form of `interpret` ===\n//\n// Flat dispatch table keyed by `Cmd.type`. Each cell receives the narrowed Cmd\n// and the runtime-augmented Ctx (`Ctx & PortEmitter`) and resolves to a\n// follow-up Msg or `void` (fire-and-forget). The mapped type makes a missing\n// handler a compile error — `defineMachine` cannot accept the dictionary until\n// every Cmd variant has one.\n//\n// **The injected `dispatch` — the typed Cmd→Msg edge.** A leaf handler that\n// resolves on its own returns its follow-up Msg (`Promise<M | void>`) and\n// IGNORES the third argument. A DETACHED handler (one that hands long-running\n// work to `ctx.waitUntil` and CANNOT return its terminal Msg inline — awaiting\n// it would deadlock the serial dispatch tail) fires its terminal Msg through\n// this injected `dispatch` instead. Today such a handler reaches for a\n// host-wired `ctx.dispatch` typed to the FULL Msg union — so a typo'd or wrong\n// terminal Msg from a detached site compiles silently (rung 5: the allowed set\n// lives only in a comment). `wrapDetached<C, Allowed>` (in `../runtime-types`)\n// narrows THIS injected `dispatch` to the Cmd's declared result-Msg set, so a\n// wrong terminal Msg fails to compile (rung 2).\n//\n// Additive: the third arg is OPTIONAL (`dispatch?: (msg: M) => void`), so a\n// handler declaring only `(cmd, ctx)` stays assignable, and a unit test that\n// invokes a handler directly with two args still typechecks. The kernel ALWAYS\n// passes the dispatch (see `runInterpret` in `../run.ts`); the optionality is\n// purely a backward-compatibility affordance on the TYPE, not a runtime \"maybe\n// absent\". A handler authored via `wrapDetached` receives a NARROWER view of\n// this dispatch (only its declared result-Msg set).\n//\n// Hoisted out of `Machine.interpret` so consumers can type a free-standing\n// handler dictionary with `Interpret<MyMsg, MyCmd, MyCtx>` instead of\n// re-declaring the mapped type at every effects module.\n//\n// Strengthens invariant 2 (the record form has no fall-through default to\n// hide impurity behind) and invariant 7 (identity is explicit — the Cmd\n// variant set is load-bearing at the type level).\nexport type Interpret<M extends { type: string }, C extends Cmd, Ctx> = {\n [K in C[\"type\"]]: (\n cmd: Extract<C, { type: K }>,\n ctx: Ctx & PortEmitter,\n dispatch?: (msg: M) => void,\n // biome-ignore lint/suspicious/noConfusingVoidType: an interpret handler returns a follow-up Msg or nothing; `void` permits no-return bodies that `M | undefined` would reject\n ) => Promise<M | void>;\n};\n\n// === InterpretDetached<C, Allowed, Ctx>: a detached interpret handler ===\n//\n// A handler that detaches long-running work (`ctx.waitUntil(...)`) and therefore\n// CANNOT return its terminal Msg inline (awaiting it would deadlock the serial\n// dispatch tail). It returns `Promise<void>` and fires its terminal Msg through\n// the kernel-injected `dispatch`, which is NARROWED to `Allowed` — the subset\n// of the Msg union this Cmd is permitted to produce. A wrong / typo'd terminal\n// Msg then fails to compile.\n//\n// `Allowed extends { type: string }` is the declared result-Msg set (e.g.\n// `GraphFinished | GraphFailed`). `dispatch: (msg: Allowed) => void` is the\n// narrowed edge. The handler still receives `ctx` (carrying `waitUntil`).\n//\n// Authored via `wrapDetached` (in `../runtime-types`), which adapts this shape\n// back into a plain `Interpret` cell so it drops into the existing `interpret`\n// dictionary with no kernel change at the call site.\nexport type InterpretDetached<\n C extends Cmd,\n Allowed extends { type: string },\n Ctx,\n> = (\n cmd: C,\n ctx: Ctx & PortEmitter,\n dispatch: (msg: Allowed) => void,\n) => Promise<void>;\n\n// === Subscribe<M, U, Ctx>: record-of-handlers form of `subscribe` ===\n//\n// Flat dispatch table keyed by `Sub.type`. Each cell receives the narrowed\n// Sub, the Ctx, and a `dispatch` to fire follow-up Msgs. Returns a cleanup\n// function the substrate calls when the Sub is reconciled out (state\n// transitioned away). The mapped type guarantees every Sub variant has a\n// handler at the type level; runtime dispatch is a single property lookup.\n//\n// The cleanup shares `Dispose`'s shape: a returned Promise is AWAITED by\n// `stop()` (bounded), so an async teardown a host relies on before evicting the\n// isolate actually completes. Mid-run reconcile does not await it — the\n// reconcile pass is synchronous by construction (invariant 2) — but the promise\n// is tracked from the moment it exists, so `stop()` catches it either way.\n//\n// Hoisted out of `Machine.subscribe` so consumers can type a free-standing\n// handler dictionary with `Subscribe<MyMsg, MySub, MyCtx>` instead of\n// re-declaring the mapped type at every subs module.\n//\n// Strengthens invariant 7 (identity is explicit — the Sub variant set is\n// load-bearing at the type level).\nexport type Subscribe<M extends { type: string }, U extends Sub, Ctx> = {\n [K in U[\"type\"]]: (\n sub: Extract<U, { type: K }>,\n ctx: Ctx,\n dispatch: (msg: M) => void,\n ) => Dispose;\n};\n\n// === Machine: pure data, host-agnostic ===\n//\n// `update` is stored as a union of the two record forms — the runtime branches\n// on shape at dispatch time. The public `defineMachine` overloads enforce one\n// shape per call so consumers never see the union themselves.\n//\n// - Reducer form: `Reducer<S, M, C>` — flat record keyed by Msg.type;\n// exhaustiveness enforced by the mapped type.\n// - Transitions form: `Transitions<S, M, C>` — 2D table keyed by\n// `state.type` then `msg.type`; only available when `S extends { type:\n// string }`. Conditional in the union so machines without a discriminated\n// State don't widen to include this branch.\n//\n// `M` is constrained to `{ type: string }` because both record forms require\n// a string discriminant.\n//\n// `interpret` is conditionally optional: when `C` is `Cmd<never>` the\n// interpret map is keyed by `never`, so the only valid value is `{}`. Forcing\n// every cmdless machine to write `interpret: {} as never` is ceremony for a\n// shape the type already pins. The tuple-wrap (`[C] extends [Cmd<never>]`)\n// disables distributive conditional so a real cmd union (e.g.\n// `Cmd<\"a\"> | Cmd<\"b\">`) doesn't degrade to optional just because one arm\n// happens to be `Cmd<never>`. Same trick the `update` field uses.\nexport type Machine<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n> = {\n /**\n * Boot the runtime. Called once by `run(...)` with whatever `Store.load()`\n * returned: `null` on fresh boot, the persisted state on rehydrate.\n *\n * **Contract:** when `loaded !== null`, init MUST return `[loaded, []]` —\n * no Cmds. Init's rehydrate branch is the migration / parse boundary, not\n * the boot-effect hook. See Invariant 2 in `.patterns/tea/tea-invariants.md`.\n *\n * Boot effects routes:\n * - Stateless infrastructure → host module top, outside TEA.\n * - State-conditional resume → a `boot` Msg the host dispatches once\n * after `run(...)` returns.\n *\n * Violations are caught at runtime by `replay` (which throws with a\n * pointer to the alternatives).\n */\n init: (loaded: S | null, ctx: Ctx) => readonly [S, readonly C[]];\n update:\n | Reducer<S, M, C>\n // Wrap in tuple to disable distributive conditional behavior. Without\n // `[S]`, TS distributes the conditional across `S`'s union members,\n // producing `Transitions<A,...> | Transitions<B,...>` instead of the\n // desired `Transitions<A|B,...>` — the table form needs a single\n // mapping over the full union of state types, not separate tables per\n // member.\n | ([S] extends [{ type: string }] ? Transitions<S, M, C> : never);\n /**\n * Dep-keyed Subs. Each declares the state slice it depends on; the substrate\n * derives the id (`structuralHash(deps)`) and the gate (`deps` non-null) and\n * folds them into the SAME reconcile loop `subscriptions` feeds. The author\n * never writes `subId(...)` and never lists Subs in a central\n * `subscriptions(state)` aggregate — a per-Sub gate travels with the Sub, so\n * a new phase can't silently forget to arm it.\n *\n * The deps slice type is erased to `unknown` per entry — each Sub's slice\n * differs, but the slice type never crosses this field (the kernel only needs\n * to hash it and pass `state` back to that same entry's `source`).\n *\n * Optional and independent of `subscriptions` / `subscribe`: a machine that\n * omits `subs` reconciles exactly as before.\n *\n * Strengthens invariant 4 (lifecycle owned by the substrate) and invariant 7\n * (identity derived, not hand-authored).\n */\n subs?: ReadonlyArray<DepKeyedSub<S, M, Ctx>>;\n /**\n * Instance-identity filter. Declares THIS instance's identity once; the\n * substrate drops any message addressed to a DIFFERENT identity before it\n * reaches `update`. Replaces the per-cell `if (msg.runId !== state.runId)`\n * guard entirely — the reducer never sees a foreign-instance message, so no\n * cell needs to check.\n *\n * Opt-in: a machine that omits `identity` skips the filter (every message\n * reaches `update`, exactly as before). A message whose `ofMsg` returns\n * `undefined` is identity-agnostic and always reaches `update` (lifecycle /\n * pre-identity messages).\n *\n * Strengthens invariant 7 (identity is explicit — declared once, enforced by\n * the substrate) and invariant 6 (mis-addressed messages dropped at one\n * observable point, not per cell).\n */\n identity?: Identity<S, M>;\n /**\n * Manual Sub aggregate — the documented escape hatch, KEPT alongside `subs`.\n * The machine that needs cross-Sub logic the per-Sub `deps` fold can't\n * express lists Subs here; the substrate reconciles them via `subscribe`.\n * Both paths feed ONE reconcile pass.\n */\n subscriptions?: (state: S) => readonly U[];\n subscribe?: Subscribe<M, U, Ctx>;\n /**\n * The update form (\"reducer\" | \"transitions\"), stamped non-enumerably by\n * `defineMachine` at construction (see `UpdateForm` / `formOf`). Optional in\n * the type so the structural `Machine` annotation form keeps accepting plain\n * object literals; readers go through `formOf`, which falls back to\n * `detectUpdateForm` when the tag is absent. Never written by hand.\n */\n readonly __form?: UpdateForm;\n} & ([C] extends [Cmd<never>]\n ? { interpret?: Interpret<M, C, Ctx> }\n : { interpret: Interpret<M, C, Ctx> }) &\n // `subscribe`/`subscriptions` are conditionally REQUIRED the same way\n // `interpret` is (#276): a machine declaring a real Sub union without a\n // subscribe map compiled and silently wired no subs (`reconcileSubs` skips\n // undefined handlers) — the exact silent-failure class the `interpret`\n // conditional prevents. The optional declarations above stay as U's\n // inference sites (a conditional type is not an inference site); this\n // intersection only adds requiredness when U is a real union. Same\n // tuple-wrap trick as `interpret` to disable distribution.\n ([U] extends [Sub<never>]\n ? unknown\n : {\n subscriptions: (state: S) => readonly U[];\n subscribe: Subscribe<M, U, Ctx>;\n });\n\n// === foldUpdates: the single internal fold `replay` and `foldMsgs` share ===\n//\n// Folds `machine.update` over `msgs` from `initialState`, dispatching each\n// Msg through `applyCell` — the same primitive `run` uses — so every fold site\n// agrees on the reducer-vs-transitions form by construction (no second copy of\n// the dispatch to drift). Returns the final state plus the Cmds the cells emitted\n// along the way; the caller keeps them (`replay`) or discards them (`foldMsgs`).\n//\n// Touches no `Store`, no `interpret` handler, and starts no subscription — it\n// only calls `update` cells. The two public folds differ only in how they\n// enter and what they return: `replay` enters via `init` and returns\n// `{ state, cmds, subs }`; `foldMsgs` enters from a base state and returns `S`.\nexport function foldUpdates<S, M extends { type: string }, C extends Cmd>(\n machine: { update: object; __form?: UpdateForm },\n initialState: S,\n msgs: readonly M[],\n): { state: S; cmds: C[] } {\n let state: S = initialState;\n const cmds: C[] = [];\n\n for (const msg of msgs) {\n const [next, emitted] = applyCellChecked<S, M, C>(machine, state, msg);\n state = next;\n cmds.push(...emitted);\n }\n\n return { state, cmds };\n}\n\n// === foldMsgs: runtime-free client-prediction fold seam (ADR 0006, #211) ===\n//\n// Folds `machine.update` over an ordered `Msg[]` starting from a caller-supplied\n// `base` state and returns the resulting state ONLY. This is the client-side\n// replay primitive a prediction loop needs (the Gambetta/Valve\n// authoritative-server reconcile step): re-simulate a queue of un-acked inputs\n// on top of an authoritative snapshot —\n// `foldMsgs(machine, snapshot, pendingInputs)`.\n//\n// Distinct from `replay` (the test idiom), by design (ADR 0006):\n// - Enters from a direct `base` parameter, NOT via `init`/`loaded` — so\n// reconciliation correctness never depends on the machine author's `init`\n// rehydrate discipline. Takes no `ctx` (the fold calls `update` only).\n// - Returns just the final `S` — not `{ state, cmds, subs }`. During prediction\n// the inputs' effects were already sent to the server; re-emitting their Cmds\n// on the client would double-fire, and `subs` are a runtime concern. Returning\n// only `S` makes \"replay fires no effects\" structural, not caller discipline.\n// A caller that wants the emitted Cmds for assertions uses `replay`.\n//\n// Invokes no `Store`, no `interpret` handler, and starts no subscription — it\n// shares `replay`'s `foldUpdates` fold, which only calls `update` cells, and\n// reads the reducer-vs-transitions form via the same `formOf(machine)` reader\n// `run`/`replay` use, so it agrees with them by construction.\n//\n// Per ADR 0006 the runtime-free *guarantee* lives on a dedicated\n// `@demlik/tea/pure` subpath whose module graph never reaches `run`; that\n// subpath export + import-graph guard are #213's scope. Here `foldMsgs` ships\n// as a reachable public API from root; #213 formalizes the boundary.\nexport function foldMsgs<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(machine: Machine<S, M, C, U, Ctx>, base: S, msgs: readonly M[]): S {\n return foldUpdates<S, M, C>(machine, base, msgs).state;\n}\n"]}
@@ -1,16 +0,0 @@
1
- import { evictExpired, remember, recall, seen, initStore } from './chunk-K575PT4S.js';
2
-
3
- // src/idempotency/adapter.ts
4
- function idempotencyMemory() {
5
- return {
6
- init: (opts) => initStore(opts),
7
- isSeen: (store, key, now) => seen(store, key, now),
8
- recall: (store, key, now) => recall(store, key, now),
9
- remember: (store, key, value, now) => remember(store, key, value, now),
10
- evict: (store, now) => evictExpired(store, now)
11
- };
12
- }
13
-
14
- export { idempotencyMemory };
15
- //# sourceMappingURL=chunk-BYQUGDD3.js.map
16
- //# sourceMappingURL=chunk-BYQUGDD3.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/idempotency/adapter.ts"],"names":[],"mappings":";;;AAyEO,SAAS,iBAAA,GAA6C;AAC3D,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,CAAC,IAAA,KAAS,SAAA,CAAa,IAAI,CAAA;AAAA,IACjC,MAAA,EAAQ,CAAC,KAAA,EAAO,GAAA,EAAK,QAAQ,IAAA,CAAQ,KAAA,EAAO,KAAK,GAAG,CAAA;AAAA,IACpD,MAAA,EAAQ,CAAC,KAAA,EAAO,GAAA,EAAK,QAAQ,MAAA,CAAU,KAAA,EAAO,KAAK,GAAG,CAAA;AAAA,IACtD,QAAA,EAAU,CAAC,KAAA,EAAO,GAAA,EAAK,KAAA,EAAO,QAAQ,QAAA,CAAY,KAAA,EAAO,GAAA,EAAK,KAAA,EAAO,GAAG,CAAA;AAAA,IACxE,OAAO,CAAC,KAAA,EAAO,GAAA,KAAQ,YAAA,CAAgB,OAAO,GAAG;AAAA,GACnD;AACF","file":"chunk-BYQUGDD3.js","sourcesContent":["/**\n * @demlik/tea/idempotency/adapter — the verb seam over the pure idempotency ops.\n *\n * The functions in `./index` (`seen` / `recall` / `remember` / `evictExpired`\n * / `initStore`) are the BLESSED transitions, but their names and the\n * `IdempotencyStore<V>` shape they read/return are the STORE's vocabulary. A\n * consumer that owns an `IdempotencyStore<V>` slice (`idempotent-intake`,\n * `poller`) used to import those functions by name and call them directly, so\n * a change to the op surface — or to `IdempotencyStore`'s fields — cascaded to\n * every call site.\n *\n * `IdempotencyMemory<V>` is the insulating interface: five VERBS (`isSeen` /\n * `recall` / `remember` / `evict` / `init`) consumers depend on instead of the\n * raw functions. The verbs keep the ops' pure contract — no I/O, no `Date.now`\n * (the clock is injected as `now`) — so a consumer folding the adapter through\n * its reducer stays inside invariant 2 (pure transitions). `isSeen` renames the\n * blessed `seen` predicate (a noun-y `seen` reads ambiguously as a slice field;\n * the verb form states the question it answers), and `evict` is the verb form\n * of `evictExpired`.\n *\n * `idempotencyMemory<V>()` is the canonical implementation, a thin binding of\n * the blessed ops. Because the verbs are the only surface consumers touch, an\n * `IdempotencyStore` shape change is absorbed HERE rather than at the consumer\n * call sites.\n *\n * INTERNAL seam (no public-API port): consumers import the adapter from this\n * subpath the same way they imported the ops. The ops remain exported from\n * `./index` for any call site that genuinely wants a function directly.\n */\n\nimport {\n evictExpired,\n type IdempotencyStore,\n initStore,\n recall,\n remember,\n seen,\n} from \"./index\";\n\n/**\n * The verb interface over an `IdempotencyStore<V>`. Each verb mirrors a blessed\n * op's pure contract but speaks the consumer's dedupe vocabulary, so the\n * consumer never names a store function or reaches into an `IdempotencyStore`\n * field it did not put there.\n */\nexport interface IdempotencyMemory<V> {\n /** Create an empty store, optionally bounded by `capacity` and/or `ttlMs`. */\n init(opts?: { capacity?: number; ttlMs?: number }): IdempotencyStore<V>;\n\n /** True iff `key` is present AND not expired at `now`. Read-only. */\n isSeen(store: IdempotencyStore<V>, key: string, now: number): boolean;\n\n /** The cached value for `key` if present and unexpired at `now`. Read-only. */\n recall(store: IdempotencyStore<V>, key: string, now: number): V | undefined;\n\n /** Record `key → value` at `now`, enforcing the store's bounds. Returns a new store. */\n remember(\n store: IdempotencyStore<V>,\n key: string,\n value: V,\n now: number,\n ): IdempotencyStore<V>;\n\n /** Drop every entry expired at `now`. Returns a new store. */\n evict(store: IdempotencyStore<V>, now: number): IdempotencyStore<V>;\n}\n\n/**\n * The canonical `IdempotencyMemory<V>`, binding each verb to its blessed op.\n * Pure and stateless — call once at module scope in a consumer and fold its\n * verbs through the reducer. An `IdempotencyStore` shape change is absorbed by\n * re-binding a verb here, not at the consumers.\n */\nexport function idempotencyMemory<V>(): IdempotencyMemory<V> {\n return {\n init: (opts) => initStore<V>(opts),\n isSeen: (store, key, now) => seen<V>(store, key, now),\n recall: (store, key, now) => recall<V>(store, key, now),\n remember: (store, key, value, now) => remember<V>(store, key, value, now),\n evict: (store, now) => evictExpired<V>(store, now),\n };\n}\n"]}