@graphrefly/graphrefly 0.44.0 → 0.46.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 (720) hide show
  1. package/README.md +22 -19
  2. package/dist/_internal-B23BagFd.d.cts +33 -0
  3. package/dist/_internal-B23BagFd.d.ts +33 -0
  4. package/dist/adaptive-rate-limiter-Dch_xYIi.d.cts +111 -0
  5. package/dist/adaptive-rate-limiter-Dch_xYIi.d.ts +111 -0
  6. package/dist/agents-C0Ji9ldU.d.cts +629 -0
  7. package/dist/agents-C9zexT7I.d.ts +629 -0
  8. package/dist/audit-BAXb3VOg.d.ts +246 -0
  9. package/dist/audit-C_bPfkqS.d.cts +246 -0
  10. package/dist/backoff-7KIK3WQW.js +24 -0
  11. package/dist/backoff-7KIK3WQW.js.map +1 -0
  12. package/dist/backoff-Bnb9OoPh.d.cts +6 -0
  13. package/dist/backoff-Bnb9OoPh.d.ts +6 -0
  14. package/dist/base/composition/index.cjs +811 -0
  15. package/dist/base/composition/index.cjs.map +1 -0
  16. package/dist/base/composition/index.d.cts +469 -0
  17. package/dist/base/composition/index.d.ts +469 -0
  18. package/dist/base/composition/index.js +40 -0
  19. package/dist/base/composition/index.js.map +1 -0
  20. package/dist/base/index.cjs +6336 -0
  21. package/dist/base/index.cjs.map +1 -0
  22. package/dist/base/index.d.cts +22 -0
  23. package/dist/base/index.d.ts +22 -0
  24. package/dist/base/index.js +259 -0
  25. package/dist/base/index.js.map +1 -0
  26. package/dist/base/io/index.cjs +3270 -0
  27. package/dist/base/io/index.cjs.map +1 -0
  28. package/dist/base/io/index.d.cts +2245 -0
  29. package/dist/base/io/index.d.ts +2245 -0
  30. package/dist/base/io/index.js +117 -0
  31. package/dist/base/io/index.js.map +1 -0
  32. package/dist/base/meta/index.cjs +43 -0
  33. package/dist/base/meta/index.cjs.map +1 -0
  34. package/dist/base/meta/index.d.cts +45 -0
  35. package/dist/base/meta/index.d.ts +45 -0
  36. package/dist/base/meta/index.js +13 -0
  37. package/dist/base/meta/index.js.map +1 -0
  38. package/dist/base/mutation/index.cjs +200 -0
  39. package/dist/base/mutation/index.cjs.map +1 -0
  40. package/dist/base/mutation/index.d.cts +177 -0
  41. package/dist/base/mutation/index.d.ts +177 -0
  42. package/dist/base/mutation/index.js +22 -0
  43. package/dist/base/mutation/index.js.map +1 -0
  44. package/dist/base/render/index.cjs +1120 -0
  45. package/dist/base/render/index.cjs.map +1 -0
  46. package/dist/{extra/render/index.d.ts → base/render/index.d.cts} +75 -31
  47. package/dist/{extra/render/index.d.cts → base/render/index.d.ts} +75 -31
  48. package/dist/base/render/index.js +24 -0
  49. package/dist/base/render/index.js.map +1 -0
  50. package/dist/base/sources/browser/index.cjs +172 -0
  51. package/dist/base/sources/browser/index.cjs.map +1 -0
  52. package/dist/base/sources/browser/index.d.cts +84 -0
  53. package/dist/base/sources/browser/index.d.ts +84 -0
  54. package/dist/base/sources/browser/index.js +151 -0
  55. package/dist/base/sources/browser/index.js.map +1 -0
  56. package/dist/base/sources/event/index.cjs +98 -0
  57. package/dist/base/sources/event/index.cjs.map +1 -0
  58. package/dist/base/sources/event/index.d.cts +91 -0
  59. package/dist/base/sources/event/index.d.ts +91 -0
  60. package/dist/base/sources/event/index.js +13 -0
  61. package/dist/base/sources/event/index.js.map +1 -0
  62. package/dist/base/sources/index.cjs +755 -0
  63. package/dist/base/sources/index.cjs.map +1 -0
  64. package/dist/{extra/sources.d.ts → base/sources/index.d.cts} +74 -301
  65. package/dist/{extra/sources.d.cts → base/sources/index.d.ts} +74 -301
  66. package/dist/base/sources/index.js +42 -0
  67. package/dist/base/sources/index.js.map +1 -0
  68. package/dist/base/sources/node/index.cjs +320 -0
  69. package/dist/base/sources/node/index.cjs.map +1 -0
  70. package/dist/{extra/node.d.ts → base/sources/node/index.d.cts} +35 -37
  71. package/dist/{extra/node.d.cts → base/sources/node/index.d.ts} +35 -37
  72. package/dist/base/sources/node/index.js +306 -0
  73. package/dist/base/sources/node/index.js.map +1 -0
  74. package/dist/base/utils/index.cjs +37 -0
  75. package/dist/base/utils/index.cjs.map +1 -0
  76. package/dist/base/utils/index.d.cts +37 -0
  77. package/dist/base/utils/index.d.ts +37 -0
  78. package/dist/base/utils/index.js +11 -0
  79. package/dist/base/utils/index.js.map +1 -0
  80. package/dist/base/worker/index.cjs +548 -0
  81. package/dist/base/worker/index.cjs.map +1 -0
  82. package/dist/base/worker/index.d.cts +207 -0
  83. package/dist/base/worker/index.d.ts +207 -0
  84. package/dist/base/worker/index.js +20 -0
  85. package/dist/base/worker/index.js.map +1 -0
  86. package/dist/breaker-C9skL3d8.d.ts +175 -0
  87. package/dist/breaker-ugSdq54q.d.cts +175 -0
  88. package/dist/{cascading-BglDkMdX.d.cts → cascading-CSSbKGrJ.d.ts} +3 -3
  89. package/dist/{cascading-MFgxu7Yo.d.ts → cascading-baGkiihI.d.cts} +3 -3
  90. package/dist/chunk-255UCBG4.js +58 -0
  91. package/dist/chunk-255UCBG4.js.map +1 -0
  92. package/dist/chunk-2LO3EL4W.js +1 -0
  93. package/dist/chunk-2LO3EL4W.js.map +1 -0
  94. package/dist/chunk-2OB3CEJS.js +1065 -0
  95. package/dist/chunk-2OB3CEJS.js.map +1 -0
  96. package/dist/chunk-36NMM65U.js +144 -0
  97. package/dist/chunk-36NMM65U.js.map +1 -0
  98. package/dist/chunk-3CEXCBN6.js +1 -0
  99. package/dist/chunk-3CEXCBN6.js.map +1 -0
  100. package/dist/chunk-3MUSLI6E.js +105 -0
  101. package/dist/chunk-3MUSLI6E.js.map +1 -0
  102. package/dist/chunk-3PSLNJDU.js +884 -0
  103. package/dist/chunk-3PSLNJDU.js.map +1 -0
  104. package/dist/chunk-3QZY5BI7.js +92 -0
  105. package/dist/chunk-3QZY5BI7.js.map +1 -0
  106. package/dist/chunk-42FQ27MQ.js +594 -0
  107. package/dist/chunk-42FQ27MQ.js.map +1 -0
  108. package/dist/chunk-4GYMCUDZ.js +1085 -0
  109. package/dist/chunk-4GYMCUDZ.js.map +1 -0
  110. package/dist/chunk-4S53H2KR.js +382 -0
  111. package/dist/chunk-4S53H2KR.js.map +1 -0
  112. package/dist/chunk-4XCHZRUJ.js +128 -0
  113. package/dist/chunk-4XCHZRUJ.js.map +1 -0
  114. package/dist/chunk-5THCXDWY.js +725 -0
  115. package/dist/chunk-5THCXDWY.js.map +1 -0
  116. package/dist/chunk-6XZYT4SW.js +256 -0
  117. package/dist/chunk-6XZYT4SW.js.map +1 -0
  118. package/dist/chunk-7EGRP2VX.js +76 -0
  119. package/dist/chunk-7EGRP2VX.js.map +1 -0
  120. package/dist/chunk-A7KV5UK4.js +150 -0
  121. package/dist/chunk-A7KV5UK4.js.map +1 -0
  122. package/dist/chunk-APY2SS5X.js +156 -0
  123. package/dist/chunk-APY2SS5X.js.map +1 -0
  124. package/dist/chunk-AZDQPQ3V.js +66 -0
  125. package/dist/chunk-AZDQPQ3V.js.map +1 -0
  126. package/dist/chunk-BU3SEFA5.js +90 -0
  127. package/dist/chunk-BU3SEFA5.js.map +1 -0
  128. package/dist/chunk-BXGZFGZ4.js +189 -0
  129. package/dist/chunk-BXGZFGZ4.js.map +1 -0
  130. package/dist/chunk-CGHORL6G.js +579 -0
  131. package/dist/chunk-CGHORL6G.js.map +1 -0
  132. package/dist/chunk-CXANAIZU.js +530 -0
  133. package/dist/chunk-CXANAIZU.js.map +1 -0
  134. package/dist/chunk-CZQHCKKG.js +1 -0
  135. package/dist/chunk-CZQHCKKG.js.map +1 -0
  136. package/dist/chunk-DKNHAICT.js +133 -0
  137. package/dist/chunk-DKNHAICT.js.map +1 -0
  138. package/dist/chunk-DM4OMPWK.js +584 -0
  139. package/dist/chunk-DM4OMPWK.js.map +1 -0
  140. package/dist/chunk-DMSNO6ZB.js +452 -0
  141. package/dist/chunk-DMSNO6ZB.js.map +1 -0
  142. package/dist/chunk-E5OZPDIW.js +229 -0
  143. package/dist/chunk-E5OZPDIW.js.map +1 -0
  144. package/dist/chunk-EVYY4X5A.js +509 -0
  145. package/dist/chunk-EVYY4X5A.js.map +1 -0
  146. package/dist/chunk-FDFD67UO.js +1 -0
  147. package/dist/chunk-FDFD67UO.js.map +1 -0
  148. package/dist/chunk-FMPF42Q4.js +13 -0
  149. package/dist/chunk-FMPF42Q4.js.map +1 -0
  150. package/dist/chunk-FR6RGA3B.js +1277 -0
  151. package/dist/chunk-FR6RGA3B.js.map +1 -0
  152. package/dist/chunk-FW23JYNQ.js +454 -0
  153. package/dist/chunk-FW23JYNQ.js.map +1 -0
  154. package/dist/chunk-GBCENOLN.js +1575 -0
  155. package/dist/chunk-GBCENOLN.js.map +1 -0
  156. package/dist/chunk-HL7HUJIX.js +1 -0
  157. package/dist/chunk-HL7HUJIX.js.map +1 -0
  158. package/dist/chunk-HULCUY35.js +2508 -0
  159. package/dist/chunk-HULCUY35.js.map +1 -0
  160. package/dist/chunk-IHTWQEDR.js +169 -0
  161. package/dist/chunk-IHTWQEDR.js.map +1 -0
  162. package/dist/chunk-IJRR6YAI.js +128 -0
  163. package/dist/chunk-IJRR6YAI.js.map +1 -0
  164. package/dist/chunk-JGFRAFDL.js +221 -0
  165. package/dist/chunk-JGFRAFDL.js.map +1 -0
  166. package/dist/chunk-KIIXR252.js +211 -0
  167. package/dist/chunk-KIIXR252.js.map +1 -0
  168. package/dist/chunk-KN3H5CNT.js +11 -0
  169. package/dist/chunk-KN3H5CNT.js.map +1 -0
  170. package/dist/chunk-KPG3DGLA.js +1 -0
  171. package/dist/chunk-KPG3DGLA.js.map +1 -0
  172. package/dist/chunk-KRNQ6RGQ.js +1 -0
  173. package/dist/chunk-KRNQ6RGQ.js.map +1 -0
  174. package/dist/chunk-LBAJK24K.js +1071 -0
  175. package/dist/chunk-LBAJK24K.js.map +1 -0
  176. package/dist/chunk-MLTPJMH6.js +417 -0
  177. package/dist/chunk-MLTPJMH6.js.map +1 -0
  178. package/dist/chunk-N3SZ7BMH.js +95 -0
  179. package/dist/chunk-N3SZ7BMH.js.map +1 -0
  180. package/dist/chunk-NDUD3IMO.js +540 -0
  181. package/dist/chunk-NDUD3IMO.js.map +1 -0
  182. package/dist/chunk-NY2PYHNC.js +873 -0
  183. package/dist/chunk-NY2PYHNC.js.map +1 -0
  184. package/dist/chunk-O3MT7DYI.js +225 -0
  185. package/dist/chunk-O3MT7DYI.js.map +1 -0
  186. package/dist/chunk-OCUDSN63.js +2386 -0
  187. package/dist/chunk-OCUDSN63.js.map +1 -0
  188. package/dist/chunk-OIWU3NYV.js +199 -0
  189. package/dist/chunk-OIWU3NYV.js.map +1 -0
  190. package/dist/chunk-OO5BM6CJ.js +1153 -0
  191. package/dist/chunk-OO5BM6CJ.js.map +1 -0
  192. package/dist/chunk-OQUIJT7A.js +1 -0
  193. package/dist/chunk-OQUIJT7A.js.map +1 -0
  194. package/dist/chunk-P5LBT622.js +105 -0
  195. package/dist/chunk-P5LBT622.js.map +1 -0
  196. package/dist/chunk-PKGQG5QQ.js +519 -0
  197. package/dist/chunk-PKGQG5QQ.js.map +1 -0
  198. package/dist/chunk-PKPO3JTZ.js +561 -0
  199. package/dist/chunk-PKPO3JTZ.js.map +1 -0
  200. package/dist/chunk-PL5UDIQ5.js +118 -0
  201. package/dist/chunk-PL5UDIQ5.js.map +1 -0
  202. package/dist/chunk-PZWISPIQ.js +432 -0
  203. package/dist/chunk-PZWISPIQ.js.map +1 -0
  204. package/dist/chunk-Q3EYOCZB.js +510 -0
  205. package/dist/chunk-Q3EYOCZB.js.map +1 -0
  206. package/dist/chunk-QMBYUVRL.js +15 -0
  207. package/dist/chunk-QMBYUVRL.js.map +1 -0
  208. package/dist/chunk-RAGGHLCV.js +200 -0
  209. package/dist/chunk-RAGGHLCV.js.map +1 -0
  210. package/dist/chunk-RGL53X5G.js +574 -0
  211. package/dist/chunk-RGL53X5G.js.map +1 -0
  212. package/dist/chunk-RJOG4IJU.js +1039 -0
  213. package/dist/chunk-RJOG4IJU.js.map +1 -0
  214. package/dist/chunk-SOOKUYVM.js +403 -0
  215. package/dist/chunk-SOOKUYVM.js.map +1 -0
  216. package/dist/chunk-T5BN5KG7.js +1 -0
  217. package/dist/chunk-T5BN5KG7.js.map +1 -0
  218. package/dist/chunk-TP7244Y6.js +207 -0
  219. package/dist/chunk-TP7244Y6.js.map +1 -0
  220. package/dist/chunk-TSBFTJKM.js +57 -0
  221. package/dist/chunk-TSBFTJKM.js.map +1 -0
  222. package/dist/chunk-URQ2CBBF.js +143 -0
  223. package/dist/chunk-URQ2CBBF.js.map +1 -0
  224. package/dist/chunk-W2BOPXTI.js +1 -0
  225. package/dist/chunk-W2BOPXTI.js.map +1 -0
  226. package/dist/chunk-WKSWLSCX.js +207 -0
  227. package/dist/chunk-WKSWLSCX.js.map +1 -0
  228. package/dist/chunk-Y52CS6YA.js +88 -0
  229. package/dist/chunk-Y52CS6YA.js.map +1 -0
  230. package/dist/chunk-YCBUWK77.js +92 -0
  231. package/dist/chunk-YCBUWK77.js.map +1 -0
  232. package/dist/chunk-YJ4U2D2C.js +314 -0
  233. package/dist/chunk-YJ4U2D2C.js.map +1 -0
  234. package/dist/chunk-Z4YXAUDN.js +239 -0
  235. package/dist/chunk-Z4YXAUDN.js.map +1 -0
  236. package/dist/chunk-Z6EGP5D7.js +92 -0
  237. package/dist/chunk-Z6EGP5D7.js.map +1 -0
  238. package/dist/compat/index.cjs +3100 -9
  239. package/dist/compat/index.cjs.map +1 -0
  240. package/dist/compat/index.d.cts +112 -18
  241. package/dist/compat/index.d.ts +112 -18
  242. package/dist/compat/index.js +176 -1
  243. package/dist/compat/index.js.map +1 -0
  244. package/dist/compat/jotai/index.cjs +149 -1
  245. package/dist/compat/jotai/index.cjs.map +1 -0
  246. package/dist/compat/jotai/index.d.cts +2 -2
  247. package/dist/compat/jotai/index.d.ts +2 -2
  248. package/dist/compat/jotai/index.js +8 -1
  249. package/dist/compat/jotai/index.js.map +1 -0
  250. package/dist/compat/nanostores/index.cjs +205 -1
  251. package/dist/compat/nanostores/index.cjs.map +1 -0
  252. package/dist/compat/nanostores/index.d.cts +2 -2
  253. package/dist/compat/nanostores/index.d.ts +2 -2
  254. package/dist/compat/nanostores/index.js +22 -1
  255. package/dist/compat/nanostores/index.js.map +1 -0
  256. package/dist/compat/nestjs/index.cjs +2241 -9
  257. package/dist/compat/nestjs/index.cjs.map +1 -0
  258. package/dist/compat/nestjs/index.d.cts +7 -10
  259. package/dist/compat/nestjs/index.d.ts +7 -10
  260. package/dist/compat/nestjs/index.js +78 -1
  261. package/dist/compat/nestjs/index.js.map +1 -0
  262. package/dist/compat/react/index.cjs +114 -1
  263. package/dist/compat/react/index.cjs.map +1 -0
  264. package/dist/compat/react/index.d.cts +2 -2
  265. package/dist/compat/react/index.d.ts +2 -2
  266. package/dist/compat/react/index.js +12 -1
  267. package/dist/compat/react/index.js.map +1 -0
  268. package/dist/compat/solid/index.cjs +101 -1
  269. package/dist/compat/solid/index.cjs.map +1 -0
  270. package/dist/compat/solid/index.d.cts +2 -2
  271. package/dist/compat/solid/index.d.ts +2 -2
  272. package/dist/compat/solid/index.js +12 -1
  273. package/dist/compat/solid/index.js.map +1 -0
  274. package/dist/compat/svelte/index.cjs +104 -1
  275. package/dist/compat/svelte/index.cjs.map +1 -0
  276. package/dist/compat/svelte/index.d.cts +2 -2
  277. package/dist/compat/svelte/index.d.ts +2 -2
  278. package/dist/compat/svelte/index.js +12 -1
  279. package/dist/compat/svelte/index.js.map +1 -0
  280. package/dist/compat/vue/index.cjs +119 -1
  281. package/dist/compat/vue/index.cjs.map +1 -0
  282. package/dist/compat/vue/index.d.cts +2 -2
  283. package/dist/compat/vue/index.d.ts +2 -2
  284. package/dist/compat/vue/index.js +12 -1
  285. package/dist/compat/vue/index.js.map +1 -0
  286. package/dist/compat/zustand/index.cjs +69 -3
  287. package/dist/compat/zustand/index.cjs.map +1 -0
  288. package/dist/compat/zustand/index.d.cts +2 -6
  289. package/dist/compat/zustand/index.d.ts +2 -6
  290. package/dist/compat/zustand/index.js +8 -1
  291. package/dist/compat/zustand/index.js.map +1 -0
  292. package/dist/distill-De6Rnn15.d.cts +48 -0
  293. package/dist/distill-De6Rnn15.d.ts +48 -0
  294. package/dist/external-register-CWyroXb_.d.cts +138 -0
  295. package/dist/external-register-CWyroXb_.d.ts +138 -0
  296. package/dist/{fallback-74oxi34l.d.cts → fallback-Bx46zqky.d.cts} +3 -10
  297. package/dist/{fallback-DUyyBTBK.d.ts → fallback-pIWW8A2d.d.ts} +3 -10
  298. package/dist/guarded-execution-BcdtxeBk.d.ts +207 -0
  299. package/dist/guarded-execution-C-3hnP6A.d.cts +207 -0
  300. package/dist/{index-CBGUK09R.d.ts → index-5SU_O78r.d.cts} +5 -5
  301. package/dist/{index-BmZXHqkE.d.ts → index-B6pxYJzO.d.cts} +1 -1
  302. package/dist/{index-hcDJ8PSI.d.cts → index-B6pxYJzO.d.ts} +1 -1
  303. package/dist/{index-C5stwKcw.d.cts → index-BFsng6v1.d.cts} +1 -1
  304. package/dist/{index-CdAlHFEt.d.ts → index-BFsng6v1.d.ts} +1 -1
  305. package/dist/{index-_6ODbuOu.d.cts → index-Bg-LwEt-.d.cts} +1 -1
  306. package/dist/{index-CviRnE4K.d.ts → index-Bg-LwEt-.d.ts} +1 -1
  307. package/dist/{index-CBBLl_rc.d.ts → index-Brp888t0.d.cts} +1 -1
  308. package/dist/{index-BQSKmbuG.d.cts → index-Brp888t0.d.ts} +1 -1
  309. package/dist/{index-sqkqlb1p.d.ts → index-CDfk6jHN.d.cts} +1 -1
  310. package/dist/{index-ZVQhLa2i.d.cts → index-CDfk6jHN.d.ts} +1 -1
  311. package/dist/{index-Climxqsu.d.cts → index-CEXCtYYJ.d.ts} +5 -5
  312. package/dist/index-DLAxYaN5.d.cts +169 -0
  313. package/dist/index-DLAxYaN5.d.ts +169 -0
  314. package/dist/{index-CK29LV56.d.cts → index-DeWbQzMe.d.cts} +1 -1
  315. package/dist/{index-CPQlGA29.d.ts → index-DeWbQzMe.d.ts} +1 -1
  316. package/dist/{index-BrPrLl4e.d.cts → index-dX9IzPqj.d.cts} +1 -1
  317. package/dist/{index-Dgl1HpPn.d.ts → index-dX9IzPqj.d.ts} +1 -1
  318. package/dist/index.cjs +25934 -191
  319. package/dist/index.cjs.map +1 -0
  320. package/dist/index.d.cts +58 -94
  321. package/dist/index.d.ts +58 -94
  322. package/dist/index.js +852 -1
  323. package/dist/index.js.map +1 -0
  324. package/dist/layout-types-B5aiHYgk.d.cts +72 -0
  325. package/dist/layout-types-B5aiHYgk.d.ts +72 -0
  326. package/dist/memory-composers-BryDrRBX.d.cts +529 -0
  327. package/dist/memory-composers-CVQqPYEV.d.ts +529 -0
  328. package/dist/{observable-DWjNfLvC.d.ts → observable-BXQoW1P-.d.cts} +1 -1
  329. package/dist/{observable-e3eiPPFy.d.cts → observable-BXQoW1P-.d.ts} +1 -1
  330. package/dist/{pipeline-graph-Sgj0gCwn.d.ts → pipeline-graph-Ce47CB6Y.d.cts} +13 -10
  331. package/dist/{pipeline-graph-CIKhynsF.d.cts → pipeline-graph-DXCwY9vG.d.ts} +13 -10
  332. package/dist/presets/ai/index.cjs +4377 -0
  333. package/dist/presets/ai/index.cjs.map +1 -0
  334. package/dist/presets/ai/index.d.cts +98 -0
  335. package/dist/presets/ai/index.d.ts +98 -0
  336. package/dist/presets/ai/index.js +54 -0
  337. package/dist/presets/ai/index.js.map +1 -0
  338. package/dist/presets/harness/index.cjs +5929 -0
  339. package/dist/presets/harness/index.cjs.map +1 -0
  340. package/dist/presets/harness/index.d.cts +566 -0
  341. package/dist/presets/harness/index.d.ts +566 -0
  342. package/dist/presets/harness/index.js +71 -0
  343. package/dist/presets/harness/index.js.map +1 -0
  344. package/dist/presets/index.cjs +9782 -0
  345. package/dist/presets/index.cjs.map +1 -0
  346. package/dist/presets/index.d.cts +28 -0
  347. package/dist/presets/index.d.ts +28 -0
  348. package/dist/presets/index.js +129 -0
  349. package/dist/presets/index.js.map +1 -0
  350. package/dist/presets/inspect/index.cjs +1087 -0
  351. package/dist/presets/inspect/index.cjs.map +1 -0
  352. package/dist/presets/inspect/index.d.cts +172 -0
  353. package/dist/presets/inspect/index.d.ts +172 -0
  354. package/dist/presets/inspect/index.js +21 -0
  355. package/dist/presets/inspect/index.js.map +1 -0
  356. package/dist/presets/resilience/index.cjs +1593 -0
  357. package/dist/presets/resilience/index.cjs.map +1 -0
  358. package/dist/presets/resilience/index.d.cts +205 -0
  359. package/dist/presets/resilience/index.d.ts +205 -0
  360. package/dist/presets/resilience/index.js +18 -0
  361. package/dist/presets/resilience/index.js.map +1 -0
  362. package/dist/rate-limiter-CEALq4N1.d.ts +559 -0
  363. package/dist/rate-limiter-DpVbSYdH.d.cts +559 -0
  364. package/dist/{reactive-layout-DOTs9P3X.d.ts → reactive-layout-fswlBUvX.d.cts} +19 -7
  365. package/dist/{reactive-layout-DgctbqZo.d.cts → reactive-layout-fswlBUvX.d.ts} +19 -7
  366. package/dist/retry-BDbRZ_gx.d.ts +125 -0
  367. package/dist/retry-DWuhjvsA.d.cts +125 -0
  368. package/dist/solutions/index.cjs +8200 -0
  369. package/dist/solutions/index.cjs.map +1 -0
  370. package/dist/solutions/index.d.cts +23 -0
  371. package/dist/solutions/index.d.ts +23 -0
  372. package/dist/solutions/index.js +55 -0
  373. package/dist/solutions/index.js.map +1 -0
  374. package/dist/spawnable-5mDY501F.d.cts +746 -0
  375. package/dist/spawnable-D3lR0oQu.d.ts +746 -0
  376. package/dist/status-U-rUI79b.d.cts +84 -0
  377. package/dist/status-U-rUI79b.d.ts +84 -0
  378. package/dist/timeout-U5O4ESK3.js +12 -0
  379. package/dist/timeout-U5O4ESK3.js.map +1 -0
  380. package/dist/{types-CWFysE9E.d.ts → types-BB5Lw-pB.d.cts} +3 -3
  381. package/dist/{types-C0_yquda.d.cts → types-BB5Lw-pB.d.ts} +3 -3
  382. package/dist/types-CJWIMJiZ.d.ts +548 -0
  383. package/dist/types-vCq7ShIm.d.cts +548 -0
  384. package/dist/utils/ai/browser.cjs +2169 -0
  385. package/dist/utils/ai/browser.cjs.map +1 -0
  386. package/dist/{patterns → utils}/ai/browser.d.cts +7 -5
  387. package/dist/{patterns → utils}/ai/browser.d.ts +7 -5
  388. package/dist/utils/ai/browser.js +255 -0
  389. package/dist/utils/ai/browser.js.map +1 -0
  390. package/dist/utils/ai/index.cjs +8468 -0
  391. package/dist/utils/ai/index.cjs.map +1 -0
  392. package/dist/{index-CR8QpwX8.d.ts → utils/ai/index.d.cts} +73 -976
  393. package/dist/{index-UPSiS-X7.d.cts → utils/ai/index.d.ts} +73 -976
  394. package/dist/utils/ai/index.js +173 -0
  395. package/dist/utils/ai/index.js.map +1 -0
  396. package/dist/utils/ai/node.cjs +648 -0
  397. package/dist/utils/ai/node.cjs.map +1 -0
  398. package/dist/{patterns → utils}/ai/node.d.cts +5 -7
  399. package/dist/{patterns → utils}/ai/node.d.ts +5 -7
  400. package/dist/utils/ai/node.js +84 -0
  401. package/dist/utils/ai/node.js.map +1 -0
  402. package/dist/utils/cqrs/index.cjs +1036 -0
  403. package/dist/utils/cqrs/index.cjs.map +1 -0
  404. package/dist/{index-CeFiHtAg.d.ts → utils/cqrs/index.d.cts} +7 -37
  405. package/dist/{index-B-_tFaqV.d.cts → utils/cqrs/index.d.ts} +7 -37
  406. package/dist/utils/cqrs/index.js +18 -0
  407. package/dist/utils/cqrs/index.js.map +1 -0
  408. package/dist/utils/demo-shell/index.cjs +865 -0
  409. package/dist/utils/demo-shell/index.cjs.map +1 -0
  410. package/dist/{index-B8YnZpIR.d.ts → utils/demo-shell/index.d.cts} +4 -16
  411. package/dist/{index-Cwv0KWcU.d.cts → utils/demo-shell/index.d.ts} +4 -16
  412. package/dist/utils/demo-shell/index.js +13 -0
  413. package/dist/utils/demo-shell/index.js.map +1 -0
  414. package/dist/utils/domain-templates/index.cjs +732 -0
  415. package/dist/utils/domain-templates/index.cjs.map +1 -0
  416. package/dist/{index-CzLVrjxn.d.ts → utils/domain-templates/index.d.cts} +3 -20
  417. package/dist/{index-BaQaY_IQ.d.cts → utils/domain-templates/index.d.ts} +3 -20
  418. package/dist/utils/domain-templates/index.js +17 -0
  419. package/dist/utils/domain-templates/index.js.map +1 -0
  420. package/dist/utils/graphspec/index.cjs +1174 -0
  421. package/dist/utils/graphspec/index.cjs.map +1 -0
  422. package/dist/{index-CMh5Rz1y.d.ts → utils/graphspec/index.d.cts} +106 -42
  423. package/dist/{index-CS0LTlB8.d.cts → utils/graphspec/index.d.ts} +106 -42
  424. package/dist/utils/graphspec/index.js +35 -0
  425. package/dist/utils/graphspec/index.js.map +1 -0
  426. package/dist/utils/harness/index.cjs +656 -0
  427. package/dist/utils/harness/index.cjs.map +1 -0
  428. package/dist/utils/harness/index.d.cts +542 -0
  429. package/dist/utils/harness/index.d.ts +542 -0
  430. package/dist/utils/harness/index.js +56 -0
  431. package/dist/utils/harness/index.js.map +1 -0
  432. package/dist/utils/index.cjs +17609 -0
  433. package/dist/utils/index.cjs.map +1 -0
  434. package/dist/utils/index.d.cts +96 -0
  435. package/dist/utils/index.d.ts +96 -0
  436. package/dist/utils/index.js +514 -0
  437. package/dist/utils/index.js.map +1 -0
  438. package/dist/utils/inspect/index.cjs +807 -0
  439. package/dist/utils/inspect/index.cjs.map +1 -0
  440. package/dist/utils/inspect/index.d.cts +123 -0
  441. package/dist/utils/inspect/index.d.ts +123 -0
  442. package/dist/utils/inspect/index.js +30 -0
  443. package/dist/utils/inspect/index.js.map +1 -0
  444. package/dist/utils/job-queue/index.cjs +717 -0
  445. package/dist/utils/job-queue/index.cjs.map +1 -0
  446. package/dist/{index-DisjX8a-.d.ts → utils/job-queue/index.d.cts} +5 -26
  447. package/dist/{index-DV_1YuVk.d.cts → utils/job-queue/index.d.ts} +5 -26
  448. package/dist/utils/job-queue/index.js +18 -0
  449. package/dist/utils/job-queue/index.js.map +1 -0
  450. package/dist/utils/memory/index.cjs +1451 -0
  451. package/dist/utils/memory/index.cjs.map +1 -0
  452. package/dist/{index-CZ3r5Rxp.d.ts → utils/memory/index.d.cts} +242 -34
  453. package/dist/{index-B17QddL1.d.cts → utils/memory/index.d.ts} +242 -34
  454. package/dist/utils/memory/index.js +19 -0
  455. package/dist/utils/memory/index.js.map +1 -0
  456. package/dist/utils/messaging/index.cjs +666 -0
  457. package/dist/utils/messaging/index.cjs.map +1 -0
  458. package/dist/utils/messaging/index.d.cts +562 -0
  459. package/dist/utils/messaging/index.d.ts +562 -0
  460. package/dist/utils/messaging/index.js +50 -0
  461. package/dist/utils/messaging/index.js.map +1 -0
  462. package/dist/utils/orchestration/index.cjs +876 -0
  463. package/dist/utils/orchestration/index.cjs.map +1 -0
  464. package/dist/utils/orchestration/index.d.cts +233 -0
  465. package/dist/utils/orchestration/index.d.ts +233 -0
  466. package/dist/utils/orchestration/index.js +19 -0
  467. package/dist/utils/orchestration/index.js.map +1 -0
  468. package/dist/utils/process/index.cjs +743 -0
  469. package/dist/utils/process/index.cjs.map +1 -0
  470. package/dist/{index-p09KSrTN.d.ts → utils/process/index.d.cts} +97 -44
  471. package/dist/{index-CasX6Pfq.d.cts → utils/process/index.d.ts} +97 -44
  472. package/dist/utils/process/index.js +14 -0
  473. package/dist/utils/process/index.js.map +1 -0
  474. package/dist/utils/reactive-layout/index.cjs +1607 -0
  475. package/dist/utils/reactive-layout/index.cjs.map +1 -0
  476. package/dist/{index-B5S8ULbU.d.ts → utils/reactive-layout/index.d.cts} +58 -81
  477. package/dist/{index-Dc4AYqrJ.d.cts → utils/reactive-layout/index.d.ts} +58 -81
  478. package/dist/utils/reactive-layout/index.js +52 -0
  479. package/dist/utils/reactive-layout/index.js.map +1 -0
  480. package/dist/utils/reduction/index.cjs +203 -0
  481. package/dist/utils/reduction/index.cjs.map +1 -0
  482. package/dist/{index-Byu-OpX_.d.ts → utils/reduction/index.d.cts} +6 -17
  483. package/dist/{index-tRCxuAXF.d.cts → utils/reduction/index.d.ts} +6 -17
  484. package/dist/utils/reduction/index.js +14 -0
  485. package/dist/utils/reduction/index.js.map +1 -0
  486. package/dist/utils/resilience/index.cjs +1617 -0
  487. package/dist/utils/resilience/index.cjs.map +1 -0
  488. package/dist/utils/resilience/index.d.cts +9 -0
  489. package/dist/utils/resilience/index.d.ts +9 -0
  490. package/dist/utils/resilience/index.js +44 -0
  491. package/dist/utils/resilience/index.js.map +1 -0
  492. package/dist/utils/surface/index.cjs +1070 -0
  493. package/dist/utils/surface/index.cjs.map +1 -0
  494. package/dist/{index-CYq8vAyV.d.ts → utils/surface/index.d.cts} +7 -58
  495. package/dist/{index-CSOmP7xT.d.cts → utils/surface/index.d.ts} +7 -58
  496. package/dist/utils/surface/index.js +30 -0
  497. package/dist/utils/surface/index.js.map +1 -0
  498. package/dist/utils/topology-view/index.cjs +620 -0
  499. package/dist/utils/topology-view/index.cjs.map +1 -0
  500. package/dist/utils/topology-view/index.d.cts +68 -0
  501. package/dist/utils/topology-view/index.d.ts +68 -0
  502. package/dist/utils/topology-view/index.js +11 -0
  503. package/dist/utils/topology-view/index.js.map +1 -0
  504. package/package.json +664 -584
  505. package/dist/backoff-HPZMEZNF.js +0 -1
  506. package/dist/chunk-2T7U5EU6.js +0 -1
  507. package/dist/chunk-3G5U5QNE.js +0 -5
  508. package/dist/chunk-4VVTGLXJ.js +0 -1
  509. package/dist/chunk-5M4CCMMD.js +0 -45
  510. package/dist/chunk-5QDBSZBV.js +0 -1
  511. package/dist/chunk-5XJ6B66J.js +0 -1
  512. package/dist/chunk-6QZNQS5B.js +0 -1
  513. package/dist/chunk-6X7AFUJV.js +0 -9
  514. package/dist/chunk-7K6PWTDQ.js +0 -1
  515. package/dist/chunk-7LIAPXJB.js +0 -1
  516. package/dist/chunk-7WPU3UHQ.js +0 -1
  517. package/dist/chunk-A5WCQ5NO.js +0 -1
  518. package/dist/chunk-APPIWSGD.js +0 -84
  519. package/dist/chunk-BEZWM2SY.js +0 -1
  520. package/dist/chunk-C72GO4IZ.js +0 -1
  521. package/dist/chunk-CB676TKJ.js +0 -1
  522. package/dist/chunk-CE6TI2TL.js +0 -1
  523. package/dist/chunk-CE72X3WO.js +0 -1
  524. package/dist/chunk-CK2E7BTU.js +0 -1
  525. package/dist/chunk-CLVB32RD.js +0 -1
  526. package/dist/chunk-CRVT7D2P.js +0 -1
  527. package/dist/chunk-D5RFJOZ2.js +0 -1
  528. package/dist/chunk-D7GPHKFH.js +0 -1
  529. package/dist/chunk-DHRX7JX4.js +0 -2
  530. package/dist/chunk-ESMPEKEV.js +0 -1
  531. package/dist/chunk-F672GV32.js +0 -1
  532. package/dist/chunk-FZMYDOWV.js +0 -1
  533. package/dist/chunk-GHBWHMRZ.js +0 -1
  534. package/dist/chunk-GLERH466.js +0 -1
  535. package/dist/chunk-GPW2V3RE.js +0 -1
  536. package/dist/chunk-HIDYF36O.js +0 -1
  537. package/dist/chunk-HITNVN6B.js +0 -3
  538. package/dist/chunk-HY4DJBA7.js +0 -5
  539. package/dist/chunk-KZIEYVXN.js +0 -1
  540. package/dist/chunk-L6NSJVJZ.js +0 -1
  541. package/dist/chunk-N4MQX6JU.js +0 -18
  542. package/dist/chunk-N7FHEL4D.js +0 -1
  543. package/dist/chunk-NTEURFZH.js +0 -1
  544. package/dist/chunk-OIVP6KFV.js +0 -1
  545. package/dist/chunk-OPHBU3LG.js +0 -1
  546. package/dist/chunk-OYQOZP2F.js +0 -5
  547. package/dist/chunk-PTZK576G.js +0 -1
  548. package/dist/chunk-QYADASLV.js +0 -1
  549. package/dist/chunk-ST7UXLWR.js +0 -1
  550. package/dist/chunk-SVY7VUYU.js +0 -1
  551. package/dist/chunk-TK3NWWD4.js +0 -1
  552. package/dist/chunk-TSOYJ743.js +0 -1
  553. package/dist/chunk-UNGSTR4X.js +0 -61
  554. package/dist/chunk-VIMF6LGM.js +0 -1
  555. package/dist/chunk-VJLMUKOI.js +0 -1
  556. package/dist/chunk-VN6RDSK2.js +0 -1
  557. package/dist/chunk-VV4N5P64.js +0 -1
  558. package/dist/chunk-W3I423PS.js +0 -1
  559. package/dist/chunk-WJR24TAG.js +0 -1
  560. package/dist/chunk-XTGKMHSW.js +0 -1
  561. package/dist/chunk-YBB7ZGTY.js +0 -1
  562. package/dist/chunk-Z4NPUARF.js +0 -1
  563. package/dist/chunk-ZGNQRPDT.js +0 -1
  564. package/dist/chunk-ZKPSFFKU.js +0 -1
  565. package/dist/chunk-ZLV5SQSX.js +0 -1
  566. package/dist/content-addressed-storage-4-ST1tYk.d.cts +0 -124
  567. package/dist/content-addressed-storage-DuYMjV7o.d.ts +0 -124
  568. package/dist/core/index.cjs +0 -1
  569. package/dist/core/index.d.cts +0 -3
  570. package/dist/core/index.d.ts +0 -3
  571. package/dist/core/index.js +0 -1
  572. package/dist/decay-BvOWTZ00.d.ts +0 -112
  573. package/dist/decay-CFlLvXUT.d.cts +0 -112
  574. package/dist/extra/browser.cjs +0 -1
  575. package/dist/extra/browser.d.cts +0 -4
  576. package/dist/extra/browser.d.ts +0 -4
  577. package/dist/extra/browser.js +0 -1
  578. package/dist/extra/index.cjs +0 -20
  579. package/dist/extra/index.d.cts +0 -17
  580. package/dist/extra/index.d.ts +0 -17
  581. package/dist/extra/index.js +0 -1
  582. package/dist/extra/node.cjs +0 -2
  583. package/dist/extra/node.js +0 -2
  584. package/dist/extra/operators.cjs +0 -1
  585. package/dist/extra/operators.d.cts +0 -958
  586. package/dist/extra/operators.d.ts +0 -958
  587. package/dist/extra/operators.js +0 -1
  588. package/dist/extra/reactive.cjs +0 -1
  589. package/dist/extra/reactive.d.cts +0 -353
  590. package/dist/extra/reactive.d.ts +0 -353
  591. package/dist/extra/reactive.js +0 -1
  592. package/dist/extra/render/index.cjs +0 -5
  593. package/dist/extra/render/index.js +0 -1
  594. package/dist/extra/sources.cjs +0 -3
  595. package/dist/extra/sources.js +0 -1
  596. package/dist/extra/storage-browser.cjs +0 -1
  597. package/dist/extra/storage-browser.d.cts +0 -37
  598. package/dist/extra/storage-browser.d.ts +0 -37
  599. package/dist/extra/storage-browser.js +0 -1
  600. package/dist/extra/storage-core.cjs +0 -1
  601. package/dist/extra/storage-core.d.cts +0 -28
  602. package/dist/extra/storage-core.d.ts +0 -28
  603. package/dist/extra/storage-core.js +0 -1
  604. package/dist/extra/storage-node.cjs +0 -1
  605. package/dist/extra/storage-node.d.cts +0 -2
  606. package/dist/extra/storage-node.d.ts +0 -2
  607. package/dist/extra/storage-node.js +0 -0
  608. package/dist/extra/storage-tiers-browser.cjs +0 -1
  609. package/dist/extra/storage-tiers-browser.d.cts +0 -120
  610. package/dist/extra/storage-tiers-browser.d.ts +0 -120
  611. package/dist/extra/storage-tiers-browser.js +0 -1
  612. package/dist/extra/storage-tiers-node.cjs +0 -1
  613. package/dist/extra/storage-tiers-node.d.cts +0 -210
  614. package/dist/extra/storage-tiers-node.d.ts +0 -210
  615. package/dist/extra/storage-tiers-node.js +0 -1
  616. package/dist/extra/storage-tiers.cjs +0 -1
  617. package/dist/extra/storage-tiers.d.cts +0 -412
  618. package/dist/extra/storage-tiers.d.ts +0 -412
  619. package/dist/extra/storage-tiers.js +0 -1
  620. package/dist/graph/index.cjs +0 -7
  621. package/dist/graph/index.d.cts +0 -7
  622. package/dist/graph/index.d.ts +0 -7
  623. package/dist/graph/index.js +0 -1
  624. package/dist/graph-CWvEUQAq.d.cts +0 -1861
  625. package/dist/graph-D9LFnda9.d.ts +0 -1861
  626. package/dist/index-5k1T6jl0.d.cts +0 -121
  627. package/dist/index-9770hRuQ.d.cts +0 -779
  628. package/dist/index-B1F8Enjf.d.ts +0 -704
  629. package/dist/index-BHskSB8v.d.ts +0 -3413
  630. package/dist/index-BIYAkbAi.d.cts +0 -26
  631. package/dist/index-BoJ5JHxI.d.ts +0 -557
  632. package/dist/index-BocU7pqs.d.ts +0 -779
  633. package/dist/index-BxNs2HB9.d.cts +0 -1858
  634. package/dist/index-C1T3d7V-.d.cts +0 -704
  635. package/dist/index-C5ri2Axc.d.cts +0 -301
  636. package/dist/index-C9l6OEBL.d.ts +0 -26
  637. package/dist/index-CC-AvFTy.d.cts +0 -557
  638. package/dist/index-CJF1URuX.d.ts +0 -121
  639. package/dist/index-CdTelp1M.d.ts +0 -202
  640. package/dist/index-Cj3WohTd.d.cts +0 -202
  641. package/dist/index-Co7uli2l.d.cts +0 -3413
  642. package/dist/index-D0aciIex.d.cts +0 -209
  643. package/dist/index-DHen9Klo.d.ts +0 -1858
  644. package/dist/index-Yq60JP3s.d.ts +0 -209
  645. package/dist/index-nozs3fFC.d.ts +0 -301
  646. package/dist/node-kK3CvTrR.d.cts +0 -1347
  647. package/dist/node-kK3CvTrR.d.ts +0 -1347
  648. package/dist/patterns/ai/browser.cjs +0 -8
  649. package/dist/patterns/ai/browser.js +0 -3
  650. package/dist/patterns/ai/index.cjs +0 -74
  651. package/dist/patterns/ai/index.d.cts +0 -20
  652. package/dist/patterns/ai/index.d.ts +0 -20
  653. package/dist/patterns/ai/index.js +0 -1
  654. package/dist/patterns/ai/node.cjs +0 -1
  655. package/dist/patterns/ai/node.js +0 -1
  656. package/dist/patterns/cqrs/index.cjs +0 -3
  657. package/dist/patterns/cqrs/index.d.cts +0 -8
  658. package/dist/patterns/cqrs/index.d.ts +0 -8
  659. package/dist/patterns/cqrs/index.js +0 -1
  660. package/dist/patterns/demo-shell/index.cjs +0 -5
  661. package/dist/patterns/demo-shell/index.d.cts +0 -7
  662. package/dist/patterns/demo-shell/index.d.ts +0 -7
  663. package/dist/patterns/demo-shell/index.js +0 -1
  664. package/dist/patterns/domain-templates/index.cjs +0 -3
  665. package/dist/patterns/domain-templates/index.d.cts +0 -6
  666. package/dist/patterns/domain-templates/index.d.ts +0 -6
  667. package/dist/patterns/domain-templates/index.js +0 -1
  668. package/dist/patterns/graphspec/index.cjs +0 -86
  669. package/dist/patterns/graphspec/index.d.cts +0 -8
  670. package/dist/patterns/graphspec/index.d.ts +0 -8
  671. package/dist/patterns/graphspec/index.js +0 -1
  672. package/dist/patterns/harness/index.cjs +0 -48
  673. package/dist/patterns/harness/index.d.cts +0 -13
  674. package/dist/patterns/harness/index.d.ts +0 -13
  675. package/dist/patterns/harness/index.js +0 -1
  676. package/dist/patterns/inspect/index.cjs +0 -3
  677. package/dist/patterns/inspect/index.d.cts +0 -9
  678. package/dist/patterns/inspect/index.d.ts +0 -9
  679. package/dist/patterns/inspect/index.js +0 -1
  680. package/dist/patterns/job-queue/index.cjs +0 -3
  681. package/dist/patterns/job-queue/index.d.cts +0 -9
  682. package/dist/patterns/job-queue/index.d.ts +0 -9
  683. package/dist/patterns/job-queue/index.js +0 -1
  684. package/dist/patterns/memory/index.cjs +0 -3
  685. package/dist/patterns/memory/index.d.cts +0 -8
  686. package/dist/patterns/memory/index.d.ts +0 -8
  687. package/dist/patterns/memory/index.js +0 -1
  688. package/dist/patterns/messaging/index.cjs +0 -3
  689. package/dist/patterns/messaging/index.d.cts +0 -7
  690. package/dist/patterns/messaging/index.d.ts +0 -7
  691. package/dist/patterns/messaging/index.js +0 -1
  692. package/dist/patterns/orchestration/index.cjs +0 -3
  693. package/dist/patterns/orchestration/index.d.cts +0 -8
  694. package/dist/patterns/orchestration/index.d.ts +0 -8
  695. package/dist/patterns/orchestration/index.js +0 -1
  696. package/dist/patterns/process/index.cjs +0 -3
  697. package/dist/patterns/process/index.d.cts +0 -10
  698. package/dist/patterns/process/index.d.ts +0 -10
  699. package/dist/patterns/process/index.js +0 -1
  700. package/dist/patterns/reactive-layout/index.cjs +0 -4
  701. package/dist/patterns/reactive-layout/index.d.cts +0 -7
  702. package/dist/patterns/reactive-layout/index.d.ts +0 -7
  703. package/dist/patterns/reactive-layout/index.js +0 -1
  704. package/dist/patterns/reduction/index.cjs +0 -3
  705. package/dist/patterns/reduction/index.d.cts +0 -6
  706. package/dist/patterns/reduction/index.d.ts +0 -6
  707. package/dist/patterns/reduction/index.js +0 -1
  708. package/dist/patterns/surface/index.cjs +0 -13
  709. package/dist/patterns/surface/index.d.cts +0 -9
  710. package/dist/patterns/surface/index.d.ts +0 -9
  711. package/dist/patterns/surface/index.js +0 -1
  712. package/dist/reactive-log-BKALbfal.d.ts +0 -223
  713. package/dist/reactive-log-DIGdYqQ6.d.cts +0 -223
  714. package/dist/reactive-map-CEFGp8TK.d.cts +0 -296
  715. package/dist/reactive-map-DS_SIAxv.d.ts +0 -296
  716. package/dist/resilience-6LYQJAC5.js +0 -1
  717. package/dist/sugar-DQjFmVqb.d.cts +0 -399
  718. package/dist/sugar-fhLIE7TT.d.ts +0 -399
  719. package/dist/topology-tree-Bcz27hpF.d.cts +0 -25
  720. package/dist/topology-tree-xvaD0fOX.d.ts +0 -25
@@ -1,11 +1,3102 @@
1
- "use strict";var Mo=Object.create;var Fe=Object.defineProperty;var Yn=Object.getOwnPropertyDescriptor;var Do=Object.getOwnPropertyNames;var Go=Object.prototype.hasOwnProperty;var Jn=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),nt=r=>{throw TypeError(r)};var Io=(r,e,t)=>e in r?Fe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Bn=(r,e)=>Fe(r,"name",{value:e,configurable:!0});var F=(r,e)=>()=>(r&&(e=r(r=0)),e);var le=(r,e)=>{for(var t in e)Fe(r,t,{get:e[t],enumerable:!0})},Po=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Do(e))!Go.call(r,o)&&o!==t&&Fe(r,o,{get:()=>e[o],enumerable:!(n=Yn(e,o))||n.enumerable});return r};var Lo=r=>Po(Fe({},"__esModule",{value:!0}),r);var Qn=r=>[,,,Mo(r?.[Jn("metadata")]??null)],Zn=["class","method","getter","setter","accessor","field","value","get","set"],tt=r=>r!==void 0&&typeof r!="function"?nt("Function expected"):r,$o=(r,e,t,n,o)=>({kind:Zn[r],name:e,metadata:n,addInitializer:s=>t._?nt("Already initialized"):o.push(tt(s||null))}),Fo=(r,e)=>Io(e,Jn("metadata"),r[3]),Xn=(r,e,t,n)=>{for(var o=0,s=r[e>>1],a=s&&s.length;o<a;o++)e&1?s[o].call(t):n=s[o].call(t,n);return n},er=(r,e,t,n,o,s)=>{var a,i,d,u,c,l=e&7,p=!!(e&8),h=!!(e&16),f=l>3?r.length+1:l?p?1:2:0,m=Zn[l+5],g=l>3&&(r[f-1]=[]),x=r[f]||(r[f]=[]),v=l&&(!h&&!p&&(o=o.prototype),l<5&&(l>3||!h)&&Yn(l<4?o:{get[t](){return Kn(this,s)},set[t](b){return Un(this,s,b)}},t));l?h&&l<4&&Bn(s,(l>2?"set ":l>1?"get ":"")+t):Bn(o,t);for(var _=n.length-1;_>=0;_--)u=$o(l,t,d={},r[3],x),l&&(u.static=p,u.private=h,c=u.access={has:h?b=>Vo(o,b):b=>t in b},l^3&&(c.get=h?b=>(l^1?Kn:qo)(b,o,l^4?s:v.get):b=>b[t]),l>2&&(c.set=h?(b,T)=>Un(b,o,T,l^4?s:v.set):(b,T)=>b[t]=T)),i=(0,n[_])(l?l<4?h?s:v[m]:l>4?void 0:{get:v.get,set:v.set}:o,u),d._=1,l^4||i===void 0?tt(i)&&(l>4?g.unshift(i):l?h?s=i:v[m]=i:o=i):typeof i!="object"||i===null?nt("Object expected"):(tt(a=i.get)&&(v.get=a),tt(a=i.set)&&(v.set=a),tt(a=i.init)&&g.unshift(a));return l||Fo(r,o),v&&Fe(o,t,v),h?l^4?s:v:o};var Xt=(r,e,t)=>e.has(r)||nt("Cannot "+t),Vo=(r,e)=>Object(e)!==e?nt('Cannot use the "in" operator on this value'):r.has(e),Kn=(r,e,t)=>(Xt(r,e,"read from private field"),t?t.call(r):e.get(r));var Un=(r,e,t,n)=>(Xt(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t),qo=(r,e,t)=>(Xt(r,e,"access private method"),t);var xe,E,P,W,re,ee,oe,V,G,M,Re,Tt,tr,wt,nr,rr,xt,en,tn,nn,Rt,B=F(()=>{"use strict";xe=Symbol.for("graphrefly/START"),E=Symbol.for("graphrefly/DATA"),P=Symbol.for("graphrefly/DIRTY"),W=Symbol.for("graphrefly/RESOLVED"),re=Symbol.for("graphrefly/INVALIDATE"),ee=Symbol.for("graphrefly/PAUSE"),oe=Symbol.for("graphrefly/RESUME"),V=Symbol.for("graphrefly/TEARDOWN"),G=Symbol.for("graphrefly/COMPLETE"),M=Symbol.for("graphrefly/ERROR"),Re=Object.freeze([P]),Tt=Object.freeze([W]),tr=Object.freeze([re]),wt=Object.freeze([xe]),nr=Object.freeze([G]),rr=Object.freeze([V]),xt=Object.freeze([Re]),en=Object.freeze([Tt]),tn=Object.freeze([tr]),nn=Object.freeze([nr]),Rt=Object.freeze([rr])});function sr(r,e){let t=new TextEncoder().encode(r.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${r.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let n=r.version;if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`encodeEnvelope: codec.version ${n} out of u16 range (expected integer 0\u201365535)`);let o=2+t.length+2+e.length;if(o>4294967295)throw new Error(`encodeEnvelope: total envelope size ${o} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let s=new Uint8Array(o),a=0;return s[a++]=rn,s[a++]=t.length,s.set(t,a),a+=t.length,s[a++]=n>>>8&255,s[a++]=n&255,s.set(e,a),s}function ir(r,e){if(r.length<or)throw new Error(`decodeEnvelope: bytes too short (${r.length} < ${or})`);let t=0,n=r[t++];if(n!==rn)throw new Error(`decodeEnvelope: unsupported envelope version ${n} (expected ${rn})`);let o=r[t++];if(o===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+o+2>r.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+o+2} bytes, have ${r.length})`);let s=new TextDecoder().decode(r.subarray(t,t+o));t+=o;let a=(r[t]<<8|r[t+1])>>>0;t+=2;let i=r.subarray(t),d=e.lookupCodec(s);if(d==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${a})`);return{codec:d,codecVersion:a,payload:i}}function ar(r){r.registerCodec(Ho)}var Ho,rn,or,on=F(()=>{"use strict";Ho={name:"json",version:1,contentType:"application/json",encode(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)},decode(r,e){let t=new TextDecoder().decode(r);return JSON.parse(t)}},rn=1,or=4});function Ne(r){if(r==null)return ve;let{type:e,id:t,...n}=r;return{type:e??"system",id:t??"",...n}}var ve,rt=F(()=>{"use strict";ve={type:"system",id:""}});function Nt(){return Ve>0||ot}function dr(){return Ve>0}function He(r){Ve>0?st.push(r):r()}function ue(r){Ve+=1;let e=!1;try{r()}catch(t){throw e=!0,t}finally{if(Ve-=1,Ve===0)if(e){if(!ot){let t=st.splice(0);for(let n of t)try{n()}catch{}Ee.length=0,Oe.length=0,qe.length=0}}else jo()}}function jo(){let r=!ot;r&&(ot=!0);let e=[],t=0;try{for(;Ee.length>0||Oe.length>0||qe.length>0||r&&st.length>0;){if(r&&st.length>0){let s=st.splice(0);for(let a of s)try{a()}catch(i){e.push(i)}continue}if(t+=1,t>1e3)throw Ee.length=0,Oe.length=0,qe.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(Ee.length>0?Ee:Oe.length>0?Oe:qe).splice(0);for(let s of o)try{s()}catch(a){e.push(a)}}}finally{r&&(ot=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Et(r,e,t){if(e.length===0)return;if(e.length===1){let u=t(e[0][0]);if(u<3||!Nt()){r(e);return}(u>=5?qe:u===4?Oe:Ee).push(()=>r(e));return}let n=e.length,o=n,s=n,a=n,i=0;for(;i<n&&t(e[i][0])<3;)i++;for(o=i;i<n&&t(e[i][0])===3;)i++;for(s=i;i<n&&t(e[i][0])===4;)i++;a=i;let d=Nt();if(o>0){let u=e.slice(0,o);r(u)}if(s>o){let u=e.slice(o,s);d?Ee.push(()=>r(u)):r(u)}if(a>s){let u=e.slice(s,a);d?Oe.push(()=>r(u)):r(u)}if(n>a){let u=e.slice(a,n);d?qe.push(()=>r(u)):r(u)}}var Ve,ot,Ee,Oe,qe,st,ke=F(()=>{"use strict";Ve=0,ot=!1,Ee=[],Oe=[],qe=[],st=[]});function ge(){return Math.trunc(performance.now()*1e6)}function se(){return Date.now()*1e6}var Se=F(()=>{"use strict"});function ur(r){r.registerMessageType(xe,{tier:0,wireCrossing:!1}),r.registerMessageType(P,{tier:1,wireCrossing:!1}),r.registerMessageType(re,{tier:1,wireCrossing:!1,metaPassthrough:!1}),r.registerMessageType(ee,{tier:2,wireCrossing:!1}),r.registerMessageType(oe,{tier:2,wireCrossing:!1}),r.registerMessageType(E,{tier:3,wireCrossing:!0}),r.registerMessageType(W,{tier:3,wireCrossing:!0}),r.registerMessageType(G,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(M,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(V,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Ot,cr=F(()=>{"use strict";B();Ot=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=t=>{let n=this._messageTypes.get(t);return n!=null?n.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function lr(r){return Array.isArray(r)?[...r]:[r]}function zo(r,e){return r.has(e)||r.has("*")}function je(r){let e=[];return r((o,s)=>{e.push({kind:"allow",actions:new Set(lr(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(lr(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let a=!1,i=!1;for(let d of e)zo(d.actions,s)&&d.where(o)&&(d.kind==="deny"?a=!0:i=!0);return a?!1:i}}function sn(r){let e=Wo.filter(t=>r({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}var ie,Wo,Ae=F(()=>{"use strict";ie=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};Wo=["human","llm","wallet","system"]});function an(r){if(r===void 0)return null;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError(`Cannot hash non-finite number: ${r}`);if(Number.isInteger(r)&&!Number.isSafeInteger(r))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${r}. Cross-language cid parity is not guaranteed for unsafe integers.`);return r}if(typeof r=="string"||typeof r=="boolean"||r===null)return r;if(Array.isArray(r))return r.map(an);if(typeof r=="object"&&r!==null){let e={};for(let t of Object.keys(r).sort())e[t]=an(r[t]);return e}return null}function Uo(r){let e=Ko.encode(r),t=e.length,n=t*8,o=t+9+63&-64,s=new Uint8Array(o);s.set(e),s[t]=128;let a=new DataView(s.buffer);a.setUint32(o-4,n>>>0,!1),a.setUint32(o-8,Math.floor(n/4294967296)>>>0,!1);let i=1779033703,d=3144134277,u=1013904242,c=2773480762,l=1359893119,p=2600822924,h=528734635,f=1541459225,m=new Uint32Array(64),g=(v,_)=>v>>>_|v<<32-_;for(let v=0;v<o;v+=64){for(let w=0;w<16;w++)m[w]=a.getUint32(v+w*4,!1);for(let w=16;w<64;w++){let S=m[w-15],D=m[w-2],A=g(S,7)^g(S,18)^S>>>3,j=g(D,17)^g(D,19)^D>>>10;m[w]=m[w-16]+A+m[w-7]+j>>>0}let _=i,b=d,T=u,O=c,y=l,R=p,k=h,N=f;for(let w=0;w<64;w++){let S=g(y,6)^g(y,11)^g(y,25),D=y&R^~y&k,A=N+S+D+Bo[w]+m[w]>>>0,j=g(_,2)^g(_,13)^g(_,22),U=_&b^_&T^b&T,X=j+U>>>0;N=k,k=R,R=y,y=O+A>>>0,O=T,T=b,b=_,_=A+X>>>0}i=i+_>>>0,d=d+b>>>0,u=u+T>>>0,c=c+O>>>0,l=l+y>>>0,p=p+R>>>0,h=h+k>>>0,f=f+N>>>0}let x=v=>v.toString(16).padStart(8,"0");return x(i)+x(d)+x(u)+x(c)+x(l)+x(p)+x(h)+x(f)}function dn(r){let e=an(r??null),t=JSON.stringify(e);return Uo(t).slice(0,16)}function Yo(){let r=globalThis.crypto;if(r?.randomUUID)return r.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function un(r,e,t){let n=t?.id??Yo();if(r===0)return{id:n,version:0};let s=(t?.hash??dn)(e);return{id:n,version:0,cid:s,prev:null}}function fr(r,e,t){r.version+=1,"cid"in r&&(r.prev=r.cid,r.cid=t(e))}var Bo,Ko,pr=F(()=>{"use strict";Bo=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ko=new TextEncoder});function mr(r){return{node:r,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function cn(r){r.prevData=void 0,r.dirty=!1,r.involvedThisWave=!1,r.dataBatch.length=0,r.terminal=void 0}function kt(r){return r.length===0?r:typeof r[0]=="symbol"?[r]:r}function fe(r,e,t){let n=yr(r)?r:[],o=typeof r=="function"?r:typeof e=="function"?e:void 0,s={};return yr(r)?s=(ln(e)?e:t)??{}:ln(r)?s=r:s=(ln(e)?e:t)??{},new H(n,o,s)}var hr,gr,Jo,Qo,Ce,H,yr,ln,Me=F(()=>{"use strict";on();rt();ke();Se();cr();Ae();B();pr();hr=()=>{},gr=100;Jo=(r,e,t,n)=>{t.direction==="down-in"&&r._onDepMessage(t.depIndex,e)},Qo=(r,e,t,n)=>{let o=r;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,a=s===void 0?[wt]:[wt,[E,s]];o._status==="dirty"&&a.push(Re),Et(e,a,o._config.tierOf)},Ce=new Ot({onMessage:Jo,onSubscribe:Qo});ur(Ce);ar(Ce);H=class r{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,t,n){this._config=n.config??Ce,this._config.onMessage,this._optsName=n.name,this._describeKind=n.describeKind,this._equals=n.equals??Object.is,this._resubscribable=n.resubscribable??!1,this._resetOnTeardown=n.resetOnTeardown??!1,this._autoComplete=n.completeWhenDepsComplete??!0,this._autoError=n.errorWhenDepsError??!0,this._pausable=n.pausable??!0,this._guard=n.guard,this._fn=t,this._partial=n.partial??!1,this._cached=n.initial!==void 0?n.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=n.versioningHash??this._config.defaultHashFn??dn;let o=n.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?un(o,this._cached===void 0?void 0:this._cached,{id:n.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(mr);let s={};for(let[i,d]of Object.entries(n.meta??{})){let u={initial:d,name:`${n.name??"node"}:meta:${i}`,describeKind:"state",config:this._config};n.guard!=null&&(u.guard=n.guard),n.resubscribable===!0&&(u.resubscribable=!0),s[i]=new r([],void 0,u)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let a=this;this._actions={emit(i){a._emit([[E,i]])},down(i){a._emit(kt(i))},up(i){a._emitUp(kt(i))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,t){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let n=this._versioningLevel;if(n!=null&&e<=n)return;let o=t?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,a=this._versioning,i=a?.id??t?.id,d=a?.version??0,u=un(e,s,{id:i,hash:o});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let t=Ne(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let n of this._extraGuards)if(!n(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,n=e?.actor!=null;if(!t&&!n)return;let o=Ne(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new ie({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let a of this._extraGuards)if(!a(o,s))throw new ie({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:se()}}down(e,t){let n=kt(e);n.length!==0&&(this._checkGuard(t),this._emit(n))}emit(e,t){this._checkGuard(t),this._emit([[E,e]])}up(e,t){if(this._deps.length===0)return;let n=kt(e);if(n.length===0)return;this._checkGuard(t);let o=t??{internal:!0};this._validateUpTiers(n);for(let s of this._deps)s.node.up?.(n,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let n of e){let o=t(n[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,t){if(t!=null&&this._guard!=null){let d=Ne(t);if(!this._guard(d,"observe"))throw new ie({actor:d,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)cn(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let a=this._isTerminal;if(this._sinkCount===1&&!a)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let i=!1;return()=>{i||(i=!0,this._sinkCount-=1,this._removeSink(e),typeof s=="function"&&s(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[t]=this._sinks;this._sinks=t}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,t=0;try{for(let n=0;n<e;n++){let o=n,s=this._deps[n];s.unsub=hr,s.unsub=s.node.subscribe(a=>{if(s.unsub===null)return;let i=this._config.tierOf,d=!1;for(let u of a)i(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:o},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(n){this._deps[t].unsub=null;for(let o=0;o<t;o++){let s=this._deps[o];if(s.unsub!=null){let a=s.unsub;s.unsub=null;try{a()}catch{}cn(s)}}throw this._dirtyDepCount=0,n}}_addDep(e){for(let o=0;o<this._deps.length;o++)if(this._deps[o].node===e)return o;let t=this._deps.length,n=mr(e);if(this._deps.push(n),this._sinks==null)return t;n.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(xt),n.unsub=hr;try{n.unsub=e.subscribe(o=>{if(n.unsub===null)return;let s=this._config.tierOf,a=!1;for(let i of o)s(i[0])>=3&&(a=!0),this._config.onMessage(this,i,{direction:"down-in",depIndex:t},this._actions);a&&this._maybeRunFnOnSettlement()})}catch(o){throw n.unsub=null,this._deps.pop(),this._dirtyDepCount--,o}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(n){this._emit([[M,this._wrapFnError("cleanup threw",n)]])}else if(t!=null&&typeof t=="object"){let n=t.deactivate;if(typeof n=="function")try{n()}catch(o){this._emit([[M,this._wrapFnError("cleanup.deactivate threw",o)]])}}for(let n of this._deps){if(n.unsub!=null){let o=n.unsub;n.unsub=null;try{o()}catch{}}cn(n)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,t){let n=this._deps[e],o=t[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:t};for(let a of this._inspectorHooks)a(s)}if(o!==xe){if(o===P){this._depDirtied(n);return}if(o===re){if(this._depInvalidated(n),this._cached===void 0)return;this._emit(tn);return}if(o===ee||o===oe){this._emit([t]);return}if(o===V){this._emit(Rt);return}if(o===E)this._depSettledAsData(n,t[1]);else if(o===W)this._depSettledAsResolved(n);else if(o===G)this._depSettledAsTerminal(n,!0);else if(o===M)this._depSettledAsTerminal(n,t[1]);else{this._emit([t]);return}if(!this._fn){(o===E||o===W)&&this._emit([t]),(o===G||o===M)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(xt))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(en),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[M,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(nn)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(a){this._emit([[M,this._wrapFnError("cleanup threw",a)]]);return}}else if(e!=null&&typeof e=="object"){let a=e.beforeRun;if(typeof a=="function"){e.beforeRun=void 0;try{a()}catch(i){this._emit([[M,this._wrapFnError("cleanup.beforeRun threw",i)]]);return}}}let t=this._deps.map(a=>a.involvedThisWave?a.dataBatch.length>0?[...a.dataBatch]:[]:void 0),n=this._deps.map(a=>a.prevData);for(let a=0;a<this._deps.length;a++){let i=t[a];i!=null&&i.length>0&&(this._deps[a].prevData=i[i.length-1])}let o=this._deps.map(a=>a.terminal),s={prevData:n,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let a={kind:"run",batchData:t,prevData:n};for(let i of this._inspectorHooks)i(a)}this._isExecutingFn=!0;try{let a=this._fn(t,this._actions,s);if(typeof a=="function")this._cleanup=a;else if(a!=null&&typeof a=="object"){let i=a;(typeof i.beforeRun=="function"||typeof i.deactivate=="function"||typeof i.invalidate=="function")&&(this._cleanup=a)}}catch(a){this._emit([[M,this._wrapFnError("fn threw",a)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>gr?(this._rerunDepth=0,this._emit([[M,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${gr} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,t){let n=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${n}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[Re,e[0]]:e;let n=!0,o=!1,s=!1,a=-1;for(let d of e){let u=t(d[0]);u<a&&(n=!1),u===3&&(o=!0),d[0]===P&&(s=!0),a=u}let i=e;if(!n){let d=e.map((u,c)=>({m:u,i:c,tier:t(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),i=d.map(u=>u.m)}if(o&&!s&&this._status!=="dirty"){let d=0;for(;d<i.length&&t(i[d][0])===0;)d++;return d===0?[Re,...i]:[...i.slice(0,d),Re,...i.slice(d)]}return i}_emit(e){if(e.length===0)return;for(let i=0;i<e.length;i++){let d=e[i];if(d[0]===M&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let t=e;if(this._isTerminal&&!this._resubscribable){let i=e.filter(d=>d[0]===V||d[0]===re);if(i.length===0)return;t=i}t=this._frameBatch(t);let o=null;for(let i=0;i<t.length;i++){let d=t[i],u=d[0];if(u!==ee&&u!==oe){o?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===ee?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let l=d[1];if(u===ee)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))c=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?o?.push(d):o==null&&(o=t.slice(0,i))}if(o!=null){if(o.length===0)return;t=o}if(this._hasMeta&&t.some(i=>i[0]===V))for(let i of Object.keys(this.meta))try{this.meta[i]._emit(Rt)}catch{}let{finalMessages:s,equalsError:a}=this._updateState(t);if(s.length>0&&this._config.inspectorEnabled){let i=this._config.globalInspector;if(i!=null)try{i({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let i=this._config.tierOf,d=[];for(let u of s)i(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(s);a!=null&&this._emit([[M,a]])}_updateState(e){let t=this._config.tierOf,n,o,s=-1,a=0;for(let c of e)t(c[0])===3&&a++;let i=a<=1,d=-1;if(this._versioning!=null&&a>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===E){d=c;break}}for(let c=0;c<e.length;c++){let l=e[c],p=l[0];if(p===E){if(l.length>=2){let h=!1;if(i&&this._cached!==void 0)try{h=this._equals(this._cached,l[1])}catch(f){o=this._wrapFnError("equals threw",f),s=c;break}if(h){n==null&&(n=e.slice(0,c)),n.push(Tt),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(d<0||c===d)&&fr(this._versioning,l[1],this._hashFn)}this._status="settled",n?.push(l)}else if(n?.push(l),p===P)this._status="dirty";else if(p===W)this._status="resolved";else if(p===G){this._status="completed";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===M){this._status="errored";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===re){if(this._cached!==void 0){let f=this._config.rigorRecorder;if(f!=null)try{f.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let f=h.invalidate;if(typeof f=="function")try{f()}catch{}}}else p===V&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=s>=0?n??e.slice(0,s):n??e;return o!=null?{finalMessages:u,equalsError:o}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let n of t)n(e)};_dispatchOrAccumulate(e){if(dr()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],He(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}Et(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);Et(this._deliverToSinks,t,this._config.tierOf)}},yr=r=>Array.isArray(r),ln=r=>typeof r=="object"&&r!=null&&!Array.isArray(r)});function q(r,e){return fe([],{...e,initial:r})}function pe(r,e){return fe((n,o,s)=>r(o,s)??void 0,{describeKind:"producer",...e})}function Y(r,e,t){return fe(r,(o,s,a)=>{let i=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):a.prevData[u]);s.emit(e(i,a))},{describeKind:"derived",...t})}function fn(r,e,t){return fe(r,(o,s,a)=>{let i=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):a.prevData[u]);return e(i,s,a)??void 0},{describeKind:"effect",...t})}function pn(r,e,t){let n=new Map;return r.forEach((o,s)=>{n.set(o,s)}),Y(r,(o,s)=>e(i=>{let d=n.get(i);if(d==null)throw new Error(`dynamicNode: untracked dep "${i.name??"<unnamed>"}"`);return o[d]},s),t)}function it(r,e){let t,n=new Map,o=(s,a,i)=>{let d=!1,u=c=>{let l=n.get(c);if(l!==void 0){if(l<s.length){let h=s[l];return h!=null&&h.length>0?h.at(-1):i.prevData[l]}return c.cache}d=!0;let p=t._addDep(c);return n.set(c,p),c.cache};try{let c=r(u,i);d||(a.emit(c),i.store.__autoTrackLastDiscoveryError!=null&&delete i.store.__autoTrackLastDiscoveryError)}catch(c){if(!d)throw c;i.store.__autoTrackLastDiscoveryError=c}};return t=new H([],o,{describeKind:"derived",...e}),t}var he=F(()=>{"use strict";Me()});function ut(r,e,t){let n=new Set;for(let o of r.split(",")){let[s,a]=o.split("/"),i=a?Number.parseInt(a,10):1;if(Number.isNaN(i)||i<1)throw new Error(`Invalid cron step: ${o}`);let d,u;if(s==="*")d=e,u=t;else if(s.includes("-")){let[c,l]=s.split("-");d=Number.parseInt(c,10),u=Number.parseInt(l,10)}else d=Number.parseInt(s,10),u=d;if(Number.isNaN(d)||Number.isNaN(u))throw new Error(`Invalid cron field: ${r}`);if(d<e||u>t)throw new Error(`Cron field out of range: ${r} (${e}-${t})`);if(d>u)throw new Error(`Invalid cron range: ${d}-${u} in ${r}`);for(let c=d;c<=u;c+=i)n.add(c)}return n}function Gr(r){let e=r.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:ut(e[0],0,59),hours:ut(e[1],0,23),daysOfMonth:ut(e[2],1,31),months:ut(e[3],1,12),daysOfWeek:ut(e[4],0,6)}}function Ir(r,e){return r.minutes.has(e.getMinutes())&&r.hours.has(e.getHours())&&r.daysOfMonth.has(e.getDate())&&r.months.has(e.getMonth()+1)&&r.daysOfWeek.has(e.getDay())}var Pr=F(()=>{"use strict"});function ct(r){return{describeKind:"producer",...r}}function Lr(r,e){let{signal:t,period:n,...o}=e??{};return pe(s=>{let a=!1,i=0,d,u,c=()=>{a=!0,d!==void 0&&clearTimeout(d),u!==void 0&&clearInterval(u),t?.removeEventListener("abort",p)},l=()=>{a||(n!=null?(s.emit(i++),u=setInterval(()=>{a||s.emit(i++)},n)):(a=!0,t?.removeEventListener("abort",p),s.emit(i++),s.down([[G]])))},p=()=>{a||(c(),s.down([[M,t.reason]]))};if(t?.aborted){p();return}return d=setTimeout(l,r),t?.addEventListener("abort",p,{once:!0}),c},ct(o))}function $r(r,e){let t=Gr(r),{tickMs:n,output:o,...s}=e??{},a=n??6e4,i=o==="date";return pe(d=>{let u=-1,c=()=>{let p=new Date,h=p.getFullYear()*1e8+(p.getMonth()+1)*1e6+p.getDate()*1e4+p.getHours()*100+p.getMinutes();h!==u&&Ir(t,p)&&(u=h,d.emit(i?p:se()))};c();let l=setInterval(c,a);return()=>clearInterval(l)},{...ct(s),name:s.name??`cron:${r}`})}function Fr(r,e){return pe(t=>{let n=!1;try{for(let o of r){if(n)return;t.emit(o)}n||t.down([[G]])}catch(o){n||t.down([[M,o]])}return()=>{n=!0}},ct(e))}function is(r){return r!=null&&typeof r.then=="function"}function as(r,e){let{signal:t,...n}=e??{};return pe(o=>{let s=!1,a=()=>{s||(s=!0,o.down([[M,t.reason]]))};if(t?.aborted){a();return}return t?.addEventListener("abort",a,{once:!0}),Promise.resolve(r).then(i=>{s||(s=!0,t?.removeEventListener("abort",a),o.emit(i),o.down([[G]]))},i=>{s||(s=!0,t?.removeEventListener("abort",a),o.down([[M,i]]))}),()=>{s=!0,t?.removeEventListener("abort",a)}},ct(n))}function ds(r,e){let{signal:t,...n}=e??{};return pe(o=>{let s=new AbortController,a=()=>s.abort(t?.reason);t?.aborted?s.abort(t.reason):t?.addEventListener("abort",a,{once:!0});let i=t??s.signal,d=!1,u=r[Symbol.asyncIterator](),c=()=>{d||i.aborted||Promise.resolve(u.next()).then(l=>{if(!(d||i.aborted)){if(l.done){o.down([[G]]);return}o.emit(l.value),c()}},l=>{!d&&!i.aborted&&o.down([[M,l]])})};return c(),()=>{d=!0,t?.removeEventListener("abort",a),s.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},ct(n))}function us(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"}function Vr(r,e){if(us(r))return r;if(is(r))return as(r,e);if(r!=null){let t=r;if(typeof t[Symbol.asyncIterator]=="function")return ds(r,e);if(typeof t[Symbol.iterator]=="function")return Fr(r,e)}return cs(r)}function cs(...r){return Fr(r,void 0)}function me(r){return r.subscribe(()=>{})}var qr=F(()=>{"use strict";Se();B();he();Pr()});var Mt=F(()=>{"use strict";qr()});function Pt(r,e){if(e!=null&&e.length>0)return new Set(e);switch(r){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta","value"]);default:return new Set(["type","deps"])}}function gs(r){return r._describeKind!=null?r._describeKind:r._deps.length>0?"derived":r._fn!=null?"producer":"state"}function wn(r){let e=new WeakSet,t={};for(let[n,o]of Ur(r))t[n]=Tn(o,e);return t}function Tn(r,e){if(r==null)return r;let t=typeof r;if(t==="boolean"||t==="number"||t==="string")return r;if(t==="function")return"<function>";if(Array.isArray(r))return e.has(r)?"<cycle>":(e.add(r),r.map(n=>Tn(n,e)));if(t==="object"){let n=r;if(e.has(n))return"<cycle>";e.add(n);try{if(typeof n.subscribe=="function"&&"cache"in n)return"<Node>"}catch{return"<unserializable>"}let o={};for(let[s,a]of Ur(n))o[s]=Tn(a,e);return o}return"<unserializable>"}function Ur(r){let e=[],t;try{t=Object.keys(r)}catch{return e}for(let n of t)try{e.push([n,r[n]])}catch{e.push([n,"<unserializable>"])}return e}function ms(r){let e={};for(let[t,n]of Object.entries(r.meta))try{e[t]=n.cache}catch{}return e}function xn(r,e,t){let n=e==null,o=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,s=n||e.has("meta")||o!=null&&o.length>0,a="state",i=[];r instanceof H&&(a=gs(r),i=r._deps.map(c=>c.node.name??""));let d={type:a,deps:i};(n||e.has("status"))&&(d.status=r.status);let u=r instanceof H?r._guard:void 0;if(s){let c={...ms(r)};if(u!=null&&c.access===void 0&&(c.access=sn(u)),o!=null&&o.length>0&&!e.has("meta")){let l={};for(let p of o)p in c&&(l[p]=c[p]);d.meta=l}else d.meta=c}if(r.name!=null&&(d.name=r.name),(n||e.has("value"))&&(!t||a==="state")){r.status==="sentinel"&&(d.sentinel=!0);try{d.value=r.cache}catch{}}if((n||e.has("v"))&&r.v!=null){let c={id:r.v.id,version:r.v.version};"cid"in r.v&&(c.cid=r.v.cid,c.prev=r.v.prev),d.v=c}return(n||e.has("guard"))&&u!=null&&(d.guard=sn(u)),(n||e.has("lastMutation"))&&r.lastMutation!=null&&(d.lastMutation=r.lastMutation),d}var Rn=F(()=>{"use strict";Ae();Me()});function Nn(r,e){if(Object.is(r,e))return!0;if(r==null||e==null||typeof r!="object"||typeof e!="object")return!1;if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let s=0;s<r.length;s++)if(!Nn(r[s],e[s]))return!1;return!0}if(Array.isArray(e))return!1;let t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;let o=new Set(n);for(let s of t)if(!o.has(s)||!Nn(r[s],e[s]))return!1;return!0}function Yr(r,e){return`${r}\0${e}`}function En(r,e){let t=[],n=new Set(r.subgraphs),o=new Set(e.subgraphs),s=[];for(let g of o)n.has(g)||s.push(g);s.sort();for(let g of s)t.push({type:"subgraph-mounted",path:g});let a=new Set(Object.keys(r.nodes)),i=new Set(Object.keys(e.nodes)),d=[];for(let g of i)a.has(g)||d.push(g);d.sort();for(let g of d)t.push({type:"node-added",path:g,node:{...e.nodes[g]}});let u=[];for(let g of i){if(!a.has(g))continue;let x=r.nodes[g]?.meta,v=e.nodes[g]?.meta;x==null&&v==null||Nn(x??{},v??{})||u.push(g)}u.sort();for(let g of u)t.push({type:"node-meta-changed",path:g,prevMeta:r.nodes[g]?.meta??{},nextMeta:e.nodes[g]?.meta??{}});let c=new Map;for(let g of r.edges)c.set(Yr(g.from,g.to),g);let l=new Map;for(let g of e.edges)l.set(Yr(g.from,g.to),g);let p=[];for(let[g,x]of l)c.has(g)||p.push(x);p.sort((g,x)=>g.from<x.from?-1:g.from>x.from?1:g.to<x.to?-1:g.to>x.to?1:0);for(let g of p)t.push({type:"edge-added",from:g.from,to:g.to});let h=[];for(let[g,x]of c)l.has(g)||h.push(x);h.sort((g,x)=>g.from<x.from?-1:g.from>x.from?1:g.to<x.to?-1:g.to>x.to?1:0);for(let g of h)t.push({type:"edge-removed",from:g.from,to:g.to});let f=[];for(let g of a)i.has(g)||f.push(g);f.sort();for(let g of f)t.push({type:"node-removed",path:g});let m=[];for(let g of n)o.has(g)||m.push(g);m.sort();for(let g of m)t.push({type:"subgraph-unmounted",path:g});return{events:t,flushedAt_ns:ge()}}var Jr=F(()=>{"use strict";Se()});var Lt,Qr=F(()=>{"use strict";Lt=class{_timer;_gen=0;start(e,t){this.cancel(),this._gen+=1;let n=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,n===this._gen&&t()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var ft,Zr=F(()=>{"use strict";ft=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let t=(this.head+this._size)%this.capacity;this.buf[t]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let t=e<0?this._size+e:e;if(!(t<0||t>=this._size))return this.buf[(this.head+t)%this.capacity]}toArray(){let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this.buf[(this.head+t)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}}});function Xr(r,e,t,n={}){let o=e in r.nodes,s=t in r.nodes;if(!o)return $t(e,t,"no-such-from");if(!s)return $t(e,t,"no-such-to");let a=n.maxDepth;if(a!=null&&(!Number.isInteger(a)||a<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===t){if(n.findCycle===!0){let u=ys(r,e,n);if(u!=null)return u}let d=Ft(e,r.nodes[e],0,n);return Vt(e,t,[d])}if(a===0)return $t(e,t,"no-path");let i=eo(r,e,t,a);return i.found?Vt(e,t,to(r,i.pathOrder,n)):$t(e,t,i.truncated?"max-depth-exceeded":"no-path")}function eo(r,e,t,n){let o=new Map,s=[{path:t,depth:0}],a=new Set([t]),i=0,d=!1;for(;i<s.length;){let l=s[i++];if(l.path===e)break;if(n!=null&&l.depth>=n){let m=r.nodes[l.path];m?.deps&&m.deps.length>0&&(d=!0);continue}let p=r.nodes[l.path];if(p==null)continue;let h=p.deps??[],f=new Map;for(let m=0;m<h.length;m++){let g=h[m];if(!g)continue;let x=f.get(g);x==null&&(x=[],f.set(g,x)),x.push(m)}for(let[m,g]of f)a.has(m)||(a.add(m),o.set(m,{from:l.path,depIndices:g}),s.push({path:m,depth:l.depth+1}))}if(!o.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==t;){let l=o.get(c);if(l==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=l.depIndices,u.push({path:l.from}),c=l.from}return{found:!0,pathOrder:u,truncated:!1}}function ys(r,e,t){let n=r.nodes[e];if(n==null)return null;let o=n.deps??[],s=[];for(let i=0;i<o.length;i++)o[i]===e&&s.push(i);if(s.length>0){let i=Ft(e,n,0,t);i.dep_index=s[0];let d=Ft(e,n,1,t);return Vt(e,e,[i,d])}let a=null;for(let i=0;i<o.length;i++){let d=o[i];if(!d||d===e)continue;let u=eo(r,d,e,t.maxDepth);u.found&&(a==null||u.pathOrder.length<a.pathOrder.length)&&(a=u,a={found:!0,pathOrder:[{path:e,depIndices:[i]},...u.pathOrder],truncated:!1})}return a==null?null:Vt(e,e,to(r,a.pathOrder,t))}function to(r,e,t){return e.map((n,o)=>{let s=r.nodes[n.path],a=Ft(n.path,s,o,t);return n.depIndices!=null&&n.depIndices.length>0&&(a.dep_index=n.depIndices[0],n.depIndices.length>1&&(a.dep_indices=[...n.depIndices])),a})}function Ft(r,e,t,n){let o={path:r,type:e.type,hop:t};e.status!==void 0&&(o.status=e.status),"value"in e&&(o.value=e.value),e.v!=null&&(o.v=e.v);let s=n.annotations?.get(r)??e.annotation;s!=null&&(o.annotation=s);let a=n.lastMutations?.get(r)??e.lastMutation;return a!=null&&(o.lastMutation=a),o}function Vt(r,e,t){return no(r,e,!0,"ok",t)}function $t(r,e,t){return no(r,e,!1,t,[])}function no(r,e,t,n,o){let s=bs(r,e,t,n,o);return{from:r,to:e,found:t,reason:n,steps:o,text:s,toJSON(){return{from:r,to:e,found:t,reason:n,steps:o}}}}function bs(r,e,t,n,o){if(!t)switch(n){case"no-such-from":return`explainPath: no node named "${r}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${r}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${r}" to "${e}"`}let s=[`Causal path: ${r} \u2192 ${e} (${o.length} step(s))`];for(let a of o){let d=` ${a.hop===0?"\xB7":"\u2193"} ${a.path} (${a.type}${a.status?`/${a.status}`:""})`;if(s.push(d),"value"in a&&s.push(` value: ${vs(a.value)}`),a.annotation!=null&&s.push(` annotation: ${a.annotation}`),a.lastMutation!=null){let u=a.lastMutation.actor;s.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return s.join(`
2
- `)}function vs(r){if(r===void 0)return"<sentinel>";if(r===null)return"null";if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return String(r);try{let e=JSON.stringify(r);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(r)}}var ro=F(()=>{"use strict"});function oo(r){let e=new WeakSet,t=new WeakSet,n=[r],o=0;for(;n.length>0;){let s=n.pop();o+=Ts(s,e,t,n)}return o}function Ts(r,e,t,n){if(r==null)return 0;switch(typeof r){case"number":return K.number;case"boolean":return K.boolean;case"string":return K.string+r.length*2;case"bigint":return K.bigint+ws(r);case"symbol":return K.symbol;case"function":return e.has(r)?0:(e.add(r),K.function);case"undefined":return 0}let s=r;if(e.has(s))return 0;e.add(s);let a=s[_s];if(typeof a=="function")try{let u=a.call(s);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(s instanceof Date)return K.date;if(s instanceof RegExp)return K.regexp+s.source.length*2;if(s instanceof Error){let u=s.message?s.message.length*2:0,c=s.stack?s.stack.length*2:0;return K.error+u+c}if(typeof URL<"u"&&s instanceof URL)return K.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return K.promise;if(s instanceof WeakMap)return K.weakmap;if(s instanceof WeakSet)return K.weakset;if(s instanceof Map){let u=K.map;for(let[c,l]of s)u+=K.mapEntry,n.push(c),n.push(l);return u}if(s instanceof Set){let u=K.set;for(let c of s)u+=K.setEntry,n.push(c);return u}if(Array.isArray(s)){let u=K.array+s.length*8;for(let c of s)n.push(c);return u}if(s instanceof ArrayBuffer)return t.has(s)?0:(t.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let u=s;return t.has(u.buffer)?48:(t.add(u.buffer),u.buffer.byteLength+48)}let i=K.object,d=Object.keys(s);for(let u of d){i+=K.string+u.length*2;try{n.push(s[u])}catch{}}return i}function ws(r){let e=r<0n?-r:r;if(e===0n)return 0;let t=e.toString(2).length;return Math.ceil(t/32)*8}var K,_s,so=F(()=>{"use strict";K={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},_s=Symbol.for("sizeof")});function io(r,e){let t=e?.topN??10,n=r.describe({detail:"standard"}),o=[],s=r._collectObserveTargets;typeof s=="function"&&s.call(r,"",o);let a=new Map;for(let[p,h]of o)a.set(p,h);let i=[];for(let[p,h]of Object.entries(n.nodes)){let f=a.get(p),m=f instanceof H?f:null,g=m?oo(m.cache):0,x=m?m._sinkCount:0,v=h.deps?.length??0,_=h.type==="effect"&&x===0,b=x===0?h.type==="effect"?"orphan-effect":h.type==="derived"?"idle-derived":h.type==="producer"?"idle-producer":null:null;i.push({path:p,type:h.type,status:h.status??"unknown",valueSizeBytes:g,subscriberCount:x,depCount:v,isOrphanEffect:_,orphanKind:b})}let d=i.reduce((p,h)=>p+h.valueSizeBytes,0),u=(p,h)=>[...i].sort(h??((f,m)=>m[p]-f[p])).slice(0,t),c=i.filter(p=>p.orphanKind!=null),l=i.filter(p=>p.isOrphanEffect);return{nodeCount:i.length,edgeCount:n.edges.length,subgraphCount:n.subgraphs.length,nodes:i,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:c,orphanEffects:l}}var ao=F(()=>{"use strict";Me();so()});function qt(r,e){let t=Math.max(16,r.size*4),n=0;for(;r.size>0;){if(n++>=t){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${t}); ${r.size} disposer(s) discarded`),r.clear();return}let o=r.values().next();if(o.done)return;let s=o.value;r.delete(s);try{s()}catch(a){console.error(`[Graph "${e}".destroy] disposer threw:`,a)}}}function po(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function xs(r){if(r!=null)return po(r)?r.cache:r}function Pe(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function _e(r){return Pe(r)?r.cache??"":r}function uo(r){return Pe(r)?r.cache??0:r}function co(r){return Pe(r)?r.cache??!1:r}function Rs(r){let e=[];for(let t of Object.keys(r).sort()){let n=r[t].v;n!=null&&e.push(`${t} ${n.id} ${n.version}`)}return e.join(`
3
- `)}function lo(r){if(r.version!==Ie)throw new Error(`unsupported snapshot version ${String(r.version)} (expected ${Ie})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in r))throw new Error(`snapshot missing required key "${e}"`);if(typeof r.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof r.nodes!="object"||r.nodes===null||Array.isArray(r.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(r.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(r.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function Ns(r,e){let t=new WeakMap,n=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let a=t.get(o);if(a==null&&(a=new WeakSet,t.set(o,a)),a.has(s))return!0;a.add(s);let i=o.constructor,d=s.constructor;if(i!==d)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let p=s;if(o.length!==p.length)return!1;for(let h=0;h<o.length;h++)if(!n(o[h],p[h]))return!1;return!0}if(o instanceof Map){let p=s;if(o.size!==p.size)return!1;for(let[h,f]of o)if(!p.has(h)||!n(f,p.get(h)))return!1;return!0}if(o instanceof Set){let p=s;if(o.size!==p.size)return!1;for(let h of o){let f=!1;for(let m of p)if(n(h,m)){f=!0;break}if(!f)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,h=s;if(p.length!==h.length)return!1;for(let f=0;f<p.length;f++)if(p[f]!==h[f])return!1;return!0}let u=Object.keys(o),c=Object.keys(s);if(u.length!==c.length)return!1;let l=new Set(c);for(let p of u)if(!l.has(p)||!n(o[p],s[p]))return!1;return!0};return n(r,e)}function Es(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ht(r){let e="^";for(let t=0;t<r.length;t+=1){let n=r[t];if(n==="*"){e+=".*";continue}if(n==="?"){e+=".";continue}if(n==="["){let o=r.indexOf("]",t+1);if(o<=t+1){e+="\\[";continue}let s=r.slice(t+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),e+=`[${s}]`,t=o;continue}e+=Es(n)}return e+="$",new RegExp(e)}function On(r){if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||r==null)return String(r);try{return JSON.stringify(r)}catch{return"[unserializable]"}}function Ss(r){return r==="none"?ks:r==="ansi"||r==null?Os:{data:r.data??"",dirty:r.dirty??"",resolved:r.resolved??"",invalidate:r.invalidate??"",pause:r.pause??"",resume:r.resume??"",complete:r.complete??"",error:r.error??"",teardown:r.teardown??"",derived:r.derived??"",path:r.path??"",reset:r.reset??""}}function fo(r){if(r==null)return{};let e=r.detail;return e==="full"?{...r,structured:r.structured??!0,timeline:r.timeline??!0,causal:r.causal??!0,derived:r.derived??!0}:e==="minimal"?{...r,structured:r.structured??!0}:r.format==="stage-log"?{...r,structured:r.structured??!0,timeline:r.timeline??!0}:r}function As(r,e,t){for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);if(o<32||o===127)throw new Error(`Graph "${e}": ${t} "${r}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${n})`)}}function kn(r,e,t){if(r==="")throw new Error(`Graph "${e}": ${t} name must be non-empty`);if(r.includes($))throw new Error(`Graph "${e}": ${t} "${r}" must not contain '${$}' (path separator)`);if(r===de)throw new Error(`Graph "${e}": ${t} name "${de}" is reserved for meta companion paths`);As(r,e,t)}function Cs(r,e){if(r==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let t=r.split($);for(let n of t)if(n==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return t}function Ms(r,e){let t=!1;for(let o of r)if(!e.isMetaPassthrough(o[0])){t=!0;break}return t?r.filter(o=>e.isMetaPassthrough(o[0])):r}function ho(r){for(let e of r._mounts.values())ho(e);for(let e of r._nodes.values())try{e.down([[V]],{internal:!0})}catch{}}function go(r,e){let t=Z.diff(r,e),n={};for(let o of t.nodesAdded){let s=e.nodes[o];s!=null&&(n[o]=s)}return{...t,nodesAddedFull:n}}function Sn(r,e,t,n={}){let o={paths:[],depths:new Map,truncated:!1};if(!e)return n.withDetail?o:[];if(!n.both&&t!=="upstream"&&t!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=n.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return n.withDetail?o:[];let a=new Map,i=new Map,d=new Map,u=new Map,c=new Set;for(let[_,b]of Object.entries(r.nodes)){if(!_)continue;c.add(_);let T=b.deps??[];a.set(_,T);for(let O of T)O&&(c.add(O),i.has(O)||i.set(O,new Set),i.get(O).add(_))}for(let _ of r.edges){if(_==null||typeof _!="object")continue;let b=typeof _.from=="string"?_.from:"",T=typeof _.to=="string"?_.to:"";!b||!T||(c.add(b),c.add(T),u.has(b)||u.set(b,new Set),u.get(b).add(T),d.has(T)||d.set(T,new Set),d.get(T).add(b))}if(!c.has(e))return n.withDetail?o:[];let l=n.both===!0,p=_=>{if(l){let y=a.get(_)??[],R=d.get(_),k=i.get(_),N=u.get(_),w=[...y];return R&&w.push(...R),k&&w.push(...k),N&&w.push(...N),w}if(t==="upstream"){let y=a.get(_)??[],R=d.get(_);return R?[...y,...R]:y}let b=i.get(_),T=u.get(_),O=b?[...b]:[];return T&&O.push(...T),O},h=new Set([e]),f=new Map,m=[{path:e,depth:0}],g=0,x=!1;for(;g<m.length;){let _=m[g++];if(s!=null&&_.depth>=s){p(_.path).length>0&&(x=!0);continue}for(let b of p(_.path))!b||h.has(b)||(h.add(b),f.set(b,_.depth+1),m.push({path:b,depth:_.depth+1}))}let v=[...f.keys()].sort((_,b)=>_<b?-1:_>b?1:0);return n.withDetail?{paths:v,depths:f,truncated:x}:v}function Ds(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],o=e[t];if(n.path!==o.path||n.type!==o.type||n.status!==o.status||n.hop!==o.hop||n.dep_index!==o.dep_index||n.annotation!==o.annotation||n.value!==o.value||n.lastMutation!==o.lastMutation)return!1;let s=n.v,a=o.v;if(s!==a&&(s==null||a==null||s.id!==a.id||s.version!==a.version))return!1}return!0}var $,de,Ie,Os,ks,Z,pt=F(()=>{"use strict";rt();ke();Se();Ae();B();Rn();Me();he();Jr();Mt();Qr();Zr();on();ro();ao();$="::",de="__meta__",Ie=1;Os={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},ks={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};Z=class r{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;_factory;_factoryArgs;constructor(e,t){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes($))throw new Error(`Graph name must not contain '${$}' (got "${e}")`);if(e===de)throw new Error(`Graph name "${de}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...t??{}}),this.config=t?.config??Ce,this._traceRing=new ft(t?.traceCapacity??1e3),t?.versioning!=null&&this.setVersioning(t.versioning),typeof t?.factory=="string"&&(this._factory=t.factory,t.factoryArgs!==void 0&&(this._factoryArgs=t.factoryArgs))}tagFactory(e,t){return this._factory=e,this._factoryArgs=t,this}ancestors(e=!0){let t=[],n=e?this:this._parent;for(;n!=null;)t.push(n),n=n._parent;return t}get topology(){return this._topology==null&&(this._topology=pe(e=>{let t=n=>{e.emit(n)};return this._topologyEmitters.add(t),()=>{this._topologyEmitters.delete(t)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let t of this._topologyEmitters)t(e)}nameOf(e){return this._nodeToName.get(e)}add(e,t){let n=e.name,o=t?.name??n;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,a=t?.annotation;if(kn(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let i=this._nodeToName.get(e);if(i!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${i}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),a!=null&&(this._annotations.set(s,a),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:a,timestamp_ns:ge()})),e}setVersioning(e){if(e!=null)for(let t of this._nodes.values())t instanceof H&&t._applyVersioning(e)}remove(e){kn(e,this.name,"remove");let t=this._mounts.get(e);if(t){let s={kind:"mount",nodes:[],mounts:[]},a=[];t._collectObserveTargets("",a);for(let[i,d]of a)i.includes(`${$}${de}${$}`)||s.nodes.push(i);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...t._collectSubgraphs(`${e}${$}`)),this._mounts.delete(e),t._parent=void 0,ho(t),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(n),n.down([[V]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let t=typeof e=="function"?e:(()=>{let s=Ht(e);return a=>s.test(a)})(),n={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>t(s));for(let s of o){let a=this.remove(s);n.nodes.push(...a.nodes),n.mounts.push(...a.mounts)}return n.nodes.sort(),n.mounts.sort(),n}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),t=this._nodes,n=0;return{[Symbol.iterator](){return this},next(){if(n>=e.length)return{value:void 0,done:!0};let o=e[n++];return{value:[o,t.get(o)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes($))return this.resolve(e);let t=this._nodes.get(e);if(!t)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return t}get(e){return this.node(e).cache}set(e,t,n){let o=n?.internal===!0;this.node(e).down([[E,t]],{actor:n?.actor,internal:o,delivery:"write"})}setAll(e,t){let n=Symbol.iterator in e?e:Object.entries(e);ue(()=>{for(let[o,s]of n)this.set(o,s,t)})}invalidate(e,t){let n=t?.internal===!0;this.node(e).down([[re]],{actor:t?.actor,internal:n,delivery:"write"})}error(e,t,n){let o=n?.internal===!0;this.node(e).down([[M,t]],{actor:n?.actor,internal:o,delivery:"write"})}complete(e,t){let n=t?.internal===!0;this.node(e).down([[G]],{actor:t?.actor,internal:n,delivery:"write"})}_registerSelfPruningKeepalive(e){let t,n,o=()=>{t?.(),t=void 0,n?.(),n=void 0};t=e.subscribe(s=>{for(let a of s){let i=a[0];if(i===V||i===G||i===M){o();return}}}),n=this.addDisposer(o)}_wireSignalToRemove(e,t){if(t==null)return;let n=()=>{try{this.remove(e)}catch{}};if(t.aborted){n();return}t.addEventListener("abort",n,{once:!0}),this.addDisposer(()=>t.removeEventListener("abort",n))}derived(e,t,n,o){let s=t.map(h=>this.resolve(h)),{keepAlive:a,annotation:i,equals:d,initial:u,meta:c,signal:l}=o??{},p=Y(s,n,{name:e,...d!=null?{equals:d}:{},...u!==void 0?{initial:u}:{},...c!=null?{meta:c}:{}});return this.add(p,{name:e,...i!=null?{annotation:i}:{}}),a===!0&&this._registerSelfPruningKeepalive(p),this._wireSignalToRemove(e,l),p}effect(e,t,n,o){let s=t.map(c=>this.resolve(c)),{annotation:a,meta:i,signal:d}=o??{},u=fn(s,n,{name:e,...i!=null?{meta:i}:{}});return this.add(u,{name:e,...a!=null?{annotation:a}:{}}),this._wireSignalToRemove(e,d),u}produce(e,t,n){if(t===void 0)throw new Error(`Graph "${this.name}".produce("${e}", \u2026): source must not be \`undefined\` \u2014 undefined is the global SENTINEL (spec \xA71.1). Pass \`null\` for nullary DATA, or a Promise/AsyncIterable/Iterable for async sources.`);if(t!==null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function")throw new Error(`Graph "${this.name}".produce("${e}", \u2026): Node sources are rejected. For Node\u2192Node, use graph.derived(name, [path], ([v]) => v, { keepAlive: true }) \u2014 fromAny passes Nodes through verbatim and silently drops opts.`);let{annotation:o,meta:s,equals:a,signal:i}=n??{},d=Vr(t,{name:e,...s!=null?{meta:s}:{},...a!=null?{equals:a}:{},...i!=null?{signal:i}:{}});return this.add(d,{name:e,...o!=null?{annotation:o}:{}}),this._wireSignalToRemove(e,i),d}batch(e){ue(e)}edges(e){let t=e?.recursive===!0,n=new Map;if(!t){for(let[d,u]of this._nodes)n.set(u,d);let i=[];for(let[d,u]of this._nodes)if(u instanceof H)for(let c of u._deps){let l=n.get(c.node);l!=null&&i.push([l,d])}return i.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),i}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[i,d]of o)s.set(d,i);let a=[];for(let[i,d]of o)if(d instanceof H)for(let u of d._deps){let c=s.get(u.node);c!=null&&a.push([c,i])}return a.sort((i,d)=>i[0]<d[0]?-1:i[0]>d[0]?1:i[1]<d[1]?-1:i[1]>d[1]?1:0),a}mount(e,t){if(t===void 0){let o=new r(e);return this.mount(e,o)}if(typeof t=="function"){let o=new r(e);return t(o),this.mount(e,o)}let n=t;if(kn(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let o=this;o!=null;o=o._parent)if(o===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let t=Cs(e,this.name);return this._resolveFromSegments(t)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let t=e;if(t[0]===this.name&&(t=t.slice(1),t.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let n=t[0],o=t.slice(1);if(o.length===0){let i=this._nodes.get(n);if(i)return i;throw this._mounts.has(n)?new Error(`Graph "${this.name}": path ends at subgraph "${n}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${n}"`)}let s=this._nodes.get(n);if(s&&o.length>0&&o[0]===de)return this._resolveMetaChainFromNode(s,o,t.join($));let a=this._mounts.get(n);if(!a)throw this._nodes.has(n)?new Error(`Graph "${this.name}": "${n}" is a node; trailing path "${o.join($)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${n}"`);return a.resolve(o.join($))}_resolveMetaChainFromNode(e,t,n){let o=e,s=0,a=[...t];for(;s<a.length;){if(a[s]!==de)throw new Error(`Graph "${this.name}": expected ${de} segment in meta path "${n}"`);if(s+1>=a.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${de} in "${n}"`);let i=a[s+1],d=o.meta[i];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${i}" in path "${n}"`);o=d,s+=2}return o}signal(e,t){if(t?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let n=[];if(this._signalDeliver(e,t??{},new Set,n),n.length>0)throw n[0]}_signalDeliver(e,t,n,o){for(let d of this._mounts.values())d._signalDeliver(e,t,n,o);let a=t.internal===!0?{internal:!0}:{actor:t.actor,delivery:"signal"},i=Ms(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!n.has(u)){n.add(u);try{u.down(e,a)}catch(c){if(c instanceof ie)throw c;o.push(c)}i.length!==0&&this._signalMetaSubtree(u,i,n,a,o)}}}_signalMetaSubtree(e,t,n,o,s){for(let a of Object.keys(e.meta).sort()){let i=e.meta[a];if(!n.has(i)){n.add(i);try{i.down(t,o)}catch(d){if(d instanceof ie)throw d;s.push(d)}this._signalMetaSubtree(i,t,n,o,s)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let t=xs(e?.actor),n=e?.filter;if(e?.detail!=null&&e?.fields!=null)throw new TypeError("Graph.describe(): pass either `detail` or `fields`, not both. `detail: 'spec'` is the canonical spec projection; use `fields` only when you need a custom subset.");let o=Pt(e?.detail,e?.fields),s=e?.detail==="spec",a=o,i=[];this._collectObserveTargets("",i);let d=new Map;for(let[b,T]of i)d.set(T,b);let u=[];{let b=i.map(([,y])=>y),T=new Set(d.values()),O=0;for(;b.length>0;){let y=b.shift();if(y instanceof H)for(let R of y._deps){let k=R.node;if(d.has(k))continue;let N=k.name??"",w=N;if(!w||T.has(w))if(N){let S=2;for(;T.has(`${N}#${S}`);)S++;w=`${N}#${S}`}else for(w=`__internal__/${O++}`;T.has(w);)w=`__internal__/${O++}`;d.set(k,w),T.add(w),u.push([w,k]),b.push(k)}}}let c=[...i,...u],l={};for(let[b,T]of c){if(t!=null&&!T.allowsObserve(t))continue;let O=xn(T,a,s),y=T instanceof H?T._deps.map(w=>d.get(w.node)??w.node.name??""):[],{name:R,...k}=O,N={...k,deps:y};if(!s){let w=this._annotations.get(b);w!=null&&(N.annotation=w)}if(n!=null)if(typeof n=="function"){let w=n;if(!(w.length>=2?w(b,N):w(N)))continue}else{let w=!0;for(let[S,D]of Object.entries(n)){let A=S==="deps_includes"?"depsIncludes":S==="meta_has"?"metaHas":S;if(A==="depsIncludes"){if(!N.deps.includes(String(D))){w=!1;break}continue}if(A==="metaHas"){if(!Object.hasOwn(N.meta??{},String(D))){w=!1;break}continue}if(N[A]!==D){w=!1;break}}if(!w)continue}l[b]=N}let p=new Set(Object.keys(l)),h=[];for(let[b,T]of c)if(T instanceof H)for(let O of T._deps){let y=d.get(O.node);y!=null&&h.push([y,b])}h.sort((b,T)=>b[0]<T[0]?-1:b[0]>T[0]?1:b[1]<T[1]?-1:b[1]>T[1]?1:0);let f=h.map(([b,T])=>({from:b,to:T}));(t!=null||n!=null)&&(f=f.filter(b=>p.has(b.from)&&p.has(b.to)));let m=this._collectSubgraphs(""),g=t!=null||n!=null?m.filter(b=>{let T=`${b}${$}`;return[...p].some(O=>O===b||O.startsWith(T))}):m,x=this,v=e;return{name:this.name,nodes:l,edges:f,subgraphs:g,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(b){let T={...v};return Array.isArray(b)?(T.fields=b,T.detail=void 0):(T.detail=b,T.fields=void 0),x.describe(T)}}}_collectSubgraphs(e){let t=[];for(let n of[...this._mounts.keys()].sort()){let o=e===""?n:`${e}${n}`;t.push(o),t.push(...this._mounts.get(n)._collectSubgraphs(`${o}${$}`))}return t}resourceProfile(e){return io(this,e)}reachable(e,t,n={}){return n.withDetail===!0?Sn(this.describe(),e,t,{...n,withDetail:!0}):Sn(this.describe(),e,t,n)}explain(e,t,n){return n?.reactive===!0?this._explainReactive(e,t,n):this._explainStatic(_e(e),_e(t),{...n?.maxDepth!==void 0?{maxDepth:uo(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:co(n.findCycle)}:{}})}_explainStatic(e,t,n){let o=this.describe({detail:"full"}),s=new Map(this._annotations),a=new Map;for(let[i,d]of Object.entries(o.nodes))d.lastMutation!=null&&a.set(i,d.lastMutation);return Xr(o,e,t,{...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:a})}_describeReactive(e){let t={...e,reactive:!1},n=e.reactiveName??"describe",o=0,s=q(o,{name:`${n}_version`}),a=this.observe({timeline:!0,structured:!0}),i=!1,d=!1,u=()=>{i||d||(i=!0,He(()=>{i=!1,!d&&(o+=1,s.emit(o))}))},c=a.onEvent(v=>{let _=v.type;_!=="data"&&_!=="error"&&_!=="complete"&&_!=="teardown"||u()}),l=[],p=new WeakSet,h=v=>{if(p.has(v)||d)return;p.add(v);let _=v.topology.subscribe(b=>{for(let T of b){if(T[0]!==E)continue;let O=T[1];if(u(),O.kind==="added"&&O.nodeKind==="mount"){let y=v._mounts.get(O.name);y!=null&&h(y)}}});l.push(_);for(let b of v._mounts.keys()){let T=v._mounts.get(b);T!=null&&h(T)}};h(this);let f,m=e.actor;po(m)&&(f=m.subscribe(v=>{let _=!1,b=!1;for(let T of v){let O=T[0];O===E?_=!0:(O===G||O===M||O===V)&&(b=!0)}_&&u(),b&&(f?.(),f=void 0,u())}));let g;try{g=Y([s],()=>this.describe(t),{name:n,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(v,_)=>v===_})}catch(v){c(),f?.();for(let _ of l)_();throw a.dispose(),v}let x=me(g);return{node:g,dispose(){d=!0,c(),f?.();for(let v of l)v();l.length=0,a.dispose(),x()}}}_describeReactiveDiff(e){let t={...e,reactive:!1},n=e.reactiveName??"describe-diff",o={name:this.name,nodes:{},edges:[],subgraphs:[]},s=this.describe(t),a=En(o,s),i=q(a,{name:n,meta:{domain:"audit",kind:"describe-diff"},equals:(p,h)=>p===h}),d=this._describeReactive({...e,reactiveName:void 0}),u=!1,c=d.node.subscribe(p=>{if(!u)for(let h of p){if(h[0]!==E)continue;let f=h[1],m=En(s,f);s=f,m.events.length!==0&&i.emit(m)}}),l=me(i);return{node:i,dispose(){u=!0,c(),d.dispose(),i.down([[V,"describe-diff disposed"]]),l()}}}_explainReactive(e,t,n){let o=0,s=q(o,{name:"explain_version"}),a=this.observe({timeline:!0,structured:!0}),i=!1,d=!1,u=()=>{i||d||(i=!0,He(()=>{i=!1,!d&&(o+=1,s.emit(o))}))},c=a.onEvent(v=>{let _=v.type;_!=="data"&&_!=="error"&&_!=="complete"&&_!=="teardown"||u()}),l=[];e!=null&&Pe(e)&&l.push(e),t!=null&&Pe(t)&&l.push(t),n?.maxDepth!=null&&Pe(n.maxDepth)&&l.push(n.maxDepth),n?.findCycle!=null&&Pe(n.findCycle)&&l.push(n.findCycle);let p=()=>{for(let v of l)if(v.cache===void 0)return!1;return!0},h=()=>{let v=_e(e),_=_e(t);return{from:v,to:_,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:v,to:_,found:!1,reason:"pending",steps:[]})}},f;try{f=Y([s],()=>{if(!p())return h();let v=_e(e),_=_e(t),b={...n?.maxDepth!==void 0?{maxDepth:uo(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:co(n.findCycle)}:{}};return this._explainStatic(v,_,b)},{name:n?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:_e(e),to:_e(t)},equals:(v,_)=>v.found===_.found&&v.reason===_.reason&&v.steps.length===_.steps.length&&Ds(v.steps,_.steps)})}catch(v){throw c(),a.dispose(),v}let m=me(f),g=[],x=v=>{let _;return _=v.subscribe(b=>{let T=!1,O=!1;for(let y of b){let R=y[0];R===E?T=!0:(R===G||R===M||R===V)&&(O=!0)}(T||O)&&u(),O&&_&&(_(),_=void 0)}),()=>{_&&(_(),_=void 0)}};for(let v of l)g.push(x(v));return{node:f,dispose(){d=!0,c();for(let v of g)v?.();g.length=0,a.dispose(),m()}}}_pathsMatching(e){let t=Ht(e),n=[];return this._collectObserveTargets("",n),n.map(([o])=>o).filter(o=>t.test(o))}_collectObserveTargets(e,t){for(let n of[...this._mounts.keys()].sort()){let o=e===""?n:`${e}${$}${n}`;this._mounts.get(n)._collectObserveTargets(o,t)}for(let n of[...this._nodes.keys()].sort()){let o=this._nodes.get(n),s=e===""?n:`${e}${$}${n}`;t.push([s,o]),this._appendMetaObserveTargets(s,o,t)}}_appendMetaObserveTargets(e,t,n){for(let o of Object.keys(t.meta).sort()){let s=t.meta[o],a=`${e}${$}${de}${$}${o}`;n.push([a,s]),this._appendMetaObserveTargets(a,s,n)}}observe(e,t){let n=typeof e=="string",s=fo(n?t:e);if(s.reactive===!0)return this._observeReactive(n?e:void 0,s);let a=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,i=s.actor;if(n){let c=e,l=this.resolve(c);if(i!=null&&!l.allowsObserve(i))throw new ie({actor:i,action:"observe",nodeName:c});return a?this._buildStructuredObserver([[c,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(h){if(h instanceof ie)return;throw h}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let u=i==null?d:d.filter(([,c])=>c.allowsObserve(i));return a?this._buildStructuredObserver(u,s,"all"):{subscribe:c=>{let l=u.map(([p,h])=>h.subscribe(f=>{c(p,f)}));return()=>{for(let p of l)p()}},up:(c,l)=>{try{this.resolve(c).up?.(l)}catch(p){if(p instanceof ie)return;throw p}}}}_observeReactive(e,t){let n=t.tiers,o=n!=null?new Set(n):null,s=t.reactiveName??"observe";return pe(a=>{let i=[],d=!1,u=!1,c=()=>{if(i.length===0||u)return;let m={events:i.slice(),flushedAt_ns:ge()};i.length=0,a.emit(m)},l={...t,reactive:!1,structured:!0,timeline:!0},p=e!=null?this.observe(e,l):this.observe(l),h=m=>{u||(i.push(m),!d&&(d=!0,He(()=>{d=!1,c()})))};for(let m of p.events)h(m);let f=p.onEvent(h);return()=>{u=!0,f(),p.dispose()}},{name:s,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,t,n){let o=n==="one"?e[0]?.[0]:void 0,s=a=>{if(n==="one"&&o!=null){let c=this.resolve(o);return this._buildStructuredObserver([[o,c]],a,"one")}let i=[];this._collectObserveTargets("",i),i.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let d=a.actor,u=d==null?i:i.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,a,"all")};return this._createObserveResult(e,t,s)}_createObserveResult(e,t,n){let o=t.timeline===!0,s=t.causal===!0,a=t.derived===!0,i=t.detail==="minimal",d=this.config.inspectorEnabled,u=(s||a)&&d,c=t.maxEvents,l=c!=null&&c>0?new ft(c):null,p=[],h=new Set,f=t.tiers!=null?new Set(t.tiers):null,m={},g=new Set,x=0,v=0,_=0,b=0,T=0,O=0,y=!1,R=!1,k=0,N=new Map,w=new Map,S=new Map,D=C=>{if(!(f!=null&&!f.has(C.type))){l?l.push(C):p.push(C);for(let L of h)L(C)}},A=C=>f==null||f.has(C),j=()=>o?{timestamp_ns:ge(),in_batch:Nt(),batch_id:k}:{},U=(C,L)=>{if(!(!u||!(C instanceof H)))return C._setInspectorHook(te=>{if(te.kind==="dep_message")N.set(C,te.depIndex);else if(te.kind==="run"){let et=te.batchData.map((I,J)=>I!=null&&I.length>0?I.at(-1):te.prevData[J]);w.set(C,et);let ne=te.batchData.map(I=>I!=null?[...I]:void 0);S.set(C,ne),a&&D({type:"derived",path:L,dep_values:et,dep_batches:ne,...j()})}})},X=C=>{let L=N.get(C),te=w.get(C);if(!s||te==null)return{};let ne=(L!=null&&L>=0&&C instanceof H?C._deps[L]:void 0)?.node,I=ne?.v,J=S.get(C);return{trigger_dep_index:L,trigger_dep_name:ne?.name,...I!=null?{trigger_version:{id:I.id,version:I.version}}:{},dep_values:[...te],...J!=null?{dep_batches:J}:{}}},Le=[],$e=[];for(let[C,L]of e){let te=U(L,C);te&&Le.push(te),$e.push(L.subscribe(et=>{k++;for(let ne of et){let I=ne[0],J=j();if(I===E){m[C]=ne[1];let Zt=L instanceof H?L.lastMutation?.actor??ve:ve;D({type:"data",path:C,data:ne[1],actor:Zt,...J,...X(L)})}else if(i)I===P?A("dirty")&&x++:I===W?A("resolved")&&v++:I===re?A("invalidate")&&_++:I===ee?A("pause")&&b++:I===oe?A("resume")&&T++:I===V?A("teardown")&&O++:I===G&&!g.has(C)?A("complete")&&(y=!0):I===M&&A("error")&&(R=!0,g.add(C));else if(I===P)A("dirty")&&x++,D({type:"dirty",path:C,...J});else if(I===W)A("resolved")&&v++,D({type:"resolved",path:C,...J,...X(L)});else if(I===re)A("invalidate")&&_++,D({type:"invalidate",path:C,...J});else if(I===ee)A("pause")&&b++,D({type:"pause",path:C,lockId:ne[1],...J});else if(I===oe)A("resume")&&T++,D({type:"resume",path:C,lockId:ne[1],...J});else if(I===G)A("complete")&&!g.has(C)&&(y=!0),D({type:"complete",path:C,...J});else if(I===M){A("error")&&(R=!0,g.add(C));let Zt=L instanceof H?L.lastMutation?.actor??ve:ve;D({type:"error",path:C,data:ne[1],actor:Zt,...J})}else I===V&&(A("teardown")&&O++,D({type:"teardown",path:C,...J}))}}))}let Ze=!1,Xe=()=>{if(!Ze){Ze=!0;for(let C of $e)C();for(let C of Le)C();for(let C of _t)C({value:void 0,done:!0});_t.length=0}},Qt=[],_t=[];h.add(C=>{let L=_t.shift();L?L({value:C,done:!1}):Qt.push(C)});let Wn={get values(){return m},get dirtyCount(){return x},get resolvedCount(){return v},get invalidateCount(){return _},get pauseCount(){return b},get resumeCount(){return T},get teardownCount(){return O},get events(){return l?l.toArray():[...p]},get anyCompletedCleanly(){return y},get anyErrored(){return R},get completedWithoutErrors(){return y&&!R},onEvent(C){return h.add(C),()=>h.delete(C)},dispose:Xe,expand(C){Xe();let L={...t};return typeof C=="string"?L.detail=C:Object.assign(L,C),n(fo(L))},[Symbol.asyncIterator](){return{next(){return Qt.length>0?Promise.resolve({value:Qt.shift(),done:!1}):Ze?Promise.resolve({value:void 0,done:!0}):new Promise(C=>_t.push(C))},return(){return Xe(),Promise.resolve({value:void 0,done:!0})}}}};return t.format!=null&&this._attachFormatLogger(Wn,t),Wn}_attachFormatLogger(e,t){let n=t.format;if(n==null)return;let o=t.logger??(f=>console.log(f)),s=t.includeTypes?new Set(t.includeTypes):null,a=t.excludeTypes?new Set(t.excludeTypes):null,i=s==null&&a==null?()=>!0:f=>(s==null||s.has(f))&&(a==null||!a.has(f)),d=Ss(t.theme),u=n==="stage-log"?ge():0,c=f=>f==null?"":t.stageLabels?.[f]??f,l=(f,m)=>f.length>m?`${f.slice(0,m-1)}\u2026`:f,p=f=>f.type==="data"||f.type==="error"?l(On(f.data),120):"",h=f=>{if(n==="stage-log"){let y=(ge()-u)/1e9,R=c(f.path).padEnd(9);if(f.type==="data"){let k=p(f);return`[${y.toFixed(3)}s] ${R} \u2190${k?` ${k}`:""}`}if(f.type==="error"){let k=p(f);return`[${y.toFixed(3)}s] ${R} \u2717${k?` ${k}`:""}`}return f.type==="complete"?`[${y.toFixed(3)}s] ${R} \u25A0 complete`:`[${y.toFixed(3)}s] ${R} ${f.type}`}if(n==="json")try{return JSON.stringify(f)}catch{return JSON.stringify({type:f.type,path:f.path,data:"[unserializable]"})}let m=d[f.type]??"",g=f.path?`${d.path}${f.path}${d.reset} `:"",x=f.type==="data"||f.type==="error",v=f.type==="pause"||f.type==="resume",_=x?` ${On(f.data)}`:v?` ${On(f.lockId)}`:"",b=f.type==="data"||f.type==="resolved"||f.type==="derived"?f:void 0,T=b?.trigger_dep_name!=null?` <- ${b.trigger_dep_name}`:b?.trigger_dep_index!=null?` <- #${b.trigger_dep_index}`:"",O=f.in_batch?" [batch]":"";return`${g}${m}${f.type.toUpperCase()}${d.reset}${_}${T}${O}`};e.onEvent(f=>{i(f.type)&&o(h(f),f)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){qt(this._disposers,this.name),this.signal([[V]],{internal:!0}),qt(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){qt(this._disposers,this.name),qt(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:t,...n}=this.describe({detail:"full"}),o={};for(let i of Object.keys(n.nodes).sort()){let{lastMutation:d,guard:u,...c}=n.nodes[i];o[i]=c}let s=[...n.subgraphs].sort(),a={...n,version:1,nodes:o,subgraphs:s};if(e?.format==null)return a;if(e.format==="json-string")return JSON.stringify(a);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let i=this.config.lookupCodec(e.codec);if(i==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return sr(i,i.encode(a))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,t){let n=t?.config??Ce,{codec:o,codecVersion:s,payload:a}=ir(e,n);return o.decode(a,s)}restore(e,t){if(lo(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let n=t?.only==null?null:(Array.isArray(t.only)?t.only:[t.only]).map(s=>Ht(s)),o=t?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(n!==null&&!n.some(i=>i.test(s)))continue;let a=e.nodes[s];if(a!==void 0){if(!("value"in a)||a.value===void 0){"value"in a&&a.value===void 0&&t?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(a.type==="derived"||a.type==="effect")&&!(a.type==="producer"&&!o)){if(a.v!=null){let d=this.tryResolve(s)?.v;if(d!=null&&d.id===a.v.id&&d.version===a.v.version)continue}try{this.set(s,a.value)}catch(i){t?.onError?.(s,i)}}}}}static fromSnapshot(e,t){lo(e);let n=typeof t=="function"?t:t?.build,o=typeof t=="function"?void 0:t?.factories,s=new r(e.name);if(n)return n(s),s.restore(e),s;for(let h of[...e.subgraphs].sort((f,m)=>{let g=f.split($).length,x=m.split($).length;return g!==x?g-x:f<m?-1:f>m?1:0})){let f=h.split($),m=s;for(let g of f)m._mounts.has(g)||m.mount(g,new r(g)),m=m._mounts.get(g)}let a=o?Object.entries(o).map(([h,f])=>({re:Ht(h),factory:f})):[],i=h=>{for(let f of a)if(f.re.test(h))return f.factory},d=h=>{let f=h.split($),m=f.pop();if(m==null||m.length===0)throw new Error(`invalid snapshot path "${h}"`);let g=s;for(let x of f){let v=g._mounts.get(x);if(!v)throw new Error(`unknown mount "${x}" in path "${h}"`);g=v}return[g,m]},u=Object.entries(e.nodes).filter(([h])=>!h.includes(`${$}${de}${$}`)).sort((h,f)=>h[0]<f[0]?-1:h[0]>f[0]?1:0),c=new Map(u),l=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[h,f]of[...c.entries()]){let m=f?.deps??[];if(!m.every(T=>l.has(T)))continue;let[g,x]=d(h),v={...f?.meta??{}},_=i(h),b;if(f?.type==="state")b=q(f.value,{meta:v});else{if(_==null)continue;b=_(x,{path:h,type:f.type,value:f.value,meta:v,deps:m,resolvedDeps:m.map(T=>l.get(T))})}g.add(b,{name:x}),l.set(h,b),c.delete(h),p=!0}}if(c.size>0){let h=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${h}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachSnapshotStorage(e,t={}){let n=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));t.autoRestore===!0&&this._cascadeRestore(e,t.onError);let o=(u,c)=>{if(u.disposed)return;let l=Rs(c.nodes);if(u.lastSnapshot!=null&&l!==""&&l===u.lastFingerprint)return;let p=u.seq+1,h=se(),g=u.lastSnapshot==null||p%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:h,format_version:Ie}:{name:this.name,mode:"diff",diff:go(u.lastSnapshot,c),seq:p,timestamp_ns:h,format_version:Ie};if(u.tier.filter&&!u.tier.filter(g))return;let x;try{x=u.tier.save(g)}catch(v){t.onError?.(v,u.tier);return}if(x&&typeof x.then=="function"){let b=(u.savePending??Promise.resolve()).then(()=>x,()=>x).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l)},T=>{t.onError?.(T,u.tier)});u.savePending=b.finally(()=>{u.savePending===b&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l},s=(u,c)=>{try{o(u,c)}catch(l){t.onError?.(l,u.tier)}},a=(u,c)=>{if(!c.some(f=>{let m=this.config.messageTier(f[0]);return m>=3&&m<5}))return;if(t.filter){let f=this.tryResolve(u);if(f==null)return;let m=xn(f,Pt("standard"));if(!t.filter(u,m))return}let p,h=()=>(p==null&&(p=this.snapshot()),p);for(let f of n)f.disposed||(f.debounceMs===0?s(f,h()):(f.timer==null&&(f.timer=new Lt),f.timer.start(f.debounceMs,()=>{f.disposed||s(f,this.snapshot())})))},i;if(t.paths!=null){let c=(typeof t.paths=="string"?this._pathsMatching(t.paths):t.paths).map(l=>{let p=this.tryResolve(l);return p==null?()=>{}:p.subscribe(h=>a(l,h))});i=()=>{for(let l of c)l()}}else i=this.observe().subscribe((u,c)=>a(u,c));let d=()=>{i();for(let u of n)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,t){for(let n of e){let o;try{o=await n.load?.()}catch(a){t?.(a,n);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===Ie&&s.nodes!=null)return this.restore(s),!0}catch(a){t?.(a,n)}}return!1}static async fromStorage(e,t,n){for(let o of t){let s;try{s=await o.load?.()}catch(d){n?.onError?.(d,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let a=s,i=a.mode==="full"&&a.snapshot!=null?a.snapshot:a.version===Ie&&a.nodes!=null?a:void 0;if(i!=null)try{return r.fromSnapshot(i,n)}catch(d){n?.onError?.(d,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${t.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,t,n){if(e!=null&&t!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,t),this.config.inspectorEnabled){let o={path:e,annotation:t,timestamp_ns:ge(),...n?.actor!=null?{actor:n.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let t=this._traceRing.toArray().filter(o=>!e(o)),n=this._traceRing.size-t.length;this._traceRing.clear();for(let o of t)this._traceRing.push(o);return n}static diff(e,t){let n=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(t.nodes)),s=[...o].filter(v=>!n.has(v)).sort(),a=[...n].filter(v=>!o.has(v)).sort(),i=[],d=[];for(let v of n){if(!o.has(v))continue;let _=e.nodes[v],b=t.nodes[v],T=_.v,O=b.v;T!=null&&O!=null&&T.id===O.id&&T.version!==O.version&&d.push({path:v,id:T.id,from:T.version,to:O.version});let y=T!=null&&O!=null&&T.id===O.id&&T.version===O.version;for(let R of["type","status","sentinel"]){let k=_[R],N=b[R];k!==N&&i.push({path:v,field:R,from:k,to:N})}if(!y)for(let R of["value","meta"]){let k=_[R],N=b[R];Ns(k,N)||i.push({path:v,field:R,from:k,to:N})}}let u=v=>`${v.from} ${v.to}`,c=new Set(e.edges.map(u)),l=new Set(t.edges.map(u)),p=t.edges.filter(v=>!c.has(u(v))),h=e.edges.filter(v=>!l.has(u(v))),f=new Set(e.subgraphs),m=new Set(t.subgraphs),g=[...m].filter(v=>!f.has(v)).sort(),x=[...f].filter(v=>!m.has(v)).sort();return{nodesAdded:s,nodesRemoved:a,nodesChanged:i,versionChanges:d,edgesAdded:p,edgesRemoved:h,subgraphsAdded:g,subgraphsRemoved:x}}}});var wo=F(()=>{"use strict";pt()});function xo(r,e,t){return{[r]:!0,[`${r}_type`]:e,...t??{}}}var Ro=F(()=>{"use strict"});var Qs={};le(Qs,{jotai:()=>hn,nanostores:()=>mn,nestjs:()=>Pn,react:()=>Ln,signals:()=>Vn,solid:()=>qn,svelte:()=>Hn,vue:()=>jn,zustand:()=>zn});module.exports=Lo(Qs);var hn={};le(hn,{atom:()=>Zo});B();he();function Zo(r,e,t){if(typeof r=="function"){let n=r;return typeof e=="function"?br(n,e,t):br(n,void 0,e)}return Xo(r,e)}function at(r){let e=r.cache,t;if(r.subscribe(o=>{for(let[s,a]of o)s===E&&(e=a),s===M&&(t=a)})(),t)throw t;return e}function Xo(r,e){let t=q(r,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>t.status==="sentinel"?at(t):t.cache,set:n=>t.emit(n),update:n=>{let o=t.status==="sentinel"?at(t):t.cache;t.emit(n(o))},subscribe:n=>{let o=!0;return t.subscribe(s=>{for(let[a,i]of s)if(a===E){if(o){o=!1;continue}n(i)}})},meta:t.meta,_node:t}}function br(r,e,t){let n=it(s=>r(a=>{let i=a._node;return i.status==="sentinel"&&at(i),s(i)}),{...t,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>n.status==="sentinel"?at(n):n.cache,subscribe:s=>{let a=!0;return n.subscribe(i=>{for(let[d,u]of i)if(d===E){if(a){a=!1;continue}s(u)}})},meta:n.meta,_node:n};if(e){let s=d=>d.get(),a=(d,u)=>d.set(u),i=o;return i.set=d=>e(s,a,d),i.update=d=>{let u=n.status==="sentinel"?at(n):n.cache;return e(s,a,d(u))},i}return o}var mn={};le(mn,{action:()=>ss,atom:()=>es,computed:()=>ts,getValue:()=>rs,map:()=>ns,onMount:()=>os,onStart:()=>Tr,onStop:()=>wr});ke();B();he();var At=new WeakMap,Ct=new WeakMap;function St(r,e){let t=e.get(r);if(t)for(let n of t)n()}function gn(r,e={}){let t=0;return{...e,get:()=>_r(r),subscribe:o=>{t===0&&St(r,At),t++;let s=r.subscribe(a=>{for(let[i,d]of a)i===E&&o(d)});return()=>{s(),t--,t===0&&St(r,Ct)}},listen:o=>{t===0&&St(r,At),t++;let s=!0,a=r.subscribe(i=>{for(let[d,u]of i)if(d===E){if(s){s=!1;continue}o(u)}});return()=>{a(),t--,t===0&&St(r,Ct)}},_node:r}}function vr(r){let e=r.cache,t;if(r.subscribe(o=>{for(let[s,a]of o)s===E&&(e=a),s===M&&(t=a)})(),t)throw t;return e}function _r(r){return r.status==="sentinel"?vr(r):r.cache}function es(r){let e=q(r,{resubscribable:!0,resetOnTeardown:!0});return gn(e,{set:t=>e.emit(t)})}function ts(r,e){let t=Array.isArray(r)?r:[r],n=t.map(s=>s._node),o=pn(n,s=>{let a=t.map(i=>{let d=i._node;return d.status==="sentinel"&&vr(d),s(d)});return e(...a)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return gn(o)}function ns(r){let e=q(r,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return gn(e,{set:t=>e.emit(t),setKey:(t,n)=>{let o=_r(e);e.emit({...o,[t]:n})}})}function rs(r){return r.get()}function Tr(r,e){let t=r._node,n=At.get(t);n||(n=new Set,At.set(t,n)),n.add(e)}function wr(r,e){let t=r._node,n=Ct.get(t);n||(n=new Set,Ct.set(t,n)),n.add(e)}function os(r,e){Tr(r,()=>{let t=e();typeof t=="function"&&wr(r,t)})}function ss(r,e,t){return(...n)=>{let o;return ue(()=>{o=t(...n)}),o}}var Pn={};le(Pn,{ACTOR_KEY:()=>It,COMMAND_HANDLERS:()=>Ke,CQRS_EVENT_HANDLERS:()=>Ue,CRON_HANDLERS:()=>Be,CommandHandler:()=>Ar,EVENT_HANDLERS:()=>ze,EventHandler:()=>Cr,GRAPHREFLY_REQUEST_GRAPH:()=>De,GRAPHREFLY_ROOT_GRAPH:()=>ae,GraphCron:()=>Sr,GraphInterval:()=>kr,GraphReflyEventExplorer:()=>Ge,GraphReflyGuard:()=>Kr,GraphReflyGuardImpl:()=>lt,GraphReflyModule:()=>Yt,INTERVAL_HANDLERS:()=>We,InjectCqrsGraph:()=>Nr,InjectGraph:()=>Rr,InjectNode:()=>Er,ObserveGateway:()=>Gt,OnGraphEvent:()=>Or,QUERY_HANDLERS:()=>Ye,QueryHandler:()=>Mr,SAGA_HANDLERS:()=>Je,SagaHandler:()=>Dr,fromHeader:()=>Wr,fromJwtPayload:()=>_n,getActor:()=>Br,getGraphToken:()=>Q,getNodeToken:()=>ce,observeSSE:()=>jr,observeSubscription:()=>zr,toObservable:()=>xr});var yn=require("rxjs");B();function xr(r,e){return e?.raw?new yn.Observable(t=>r.subscribe(o=>{if(!t.closed){t.next(o);for(let s of o){if(s[0]===M){t.error(s[1]);return}if(s[0]===G){t.complete();return}}}})):new yn.Observable(t=>r.subscribe(o=>{for(let s of o){if(t.closed)return;if(s[0]===E)t.next(s[1]);else if(s[0]===M){t.error(s[1]);return}else if(s[0]===G){t.complete();return}}}))}var dt=require("@nestjs/common");var ae=Symbol.for("graphrefly:root-graph");var De=Symbol.for("graphrefly:request-graph");function Q(r){return Symbol.for(`graphrefly:graph:${r}`)}function ce(r){return Symbol.for(`graphrefly:node:${r}`)}var ze=new Map,We=new Map,Be=new Map,Ke=new Map,Ue=new Map,Ye=new Map,Je=new Map;function Rr(r){return r==="request"?(0,dt.Inject)(De):(0,dt.Inject)(r?Q(r):ae)}function Nr(r){return(0,dt.Inject)(Q(r))}function Er(r){return(0,dt.Inject)(ce(r))}function Or(r){return(e,t)=>{let n=t.name;t.addInitializer(function(){let o=this.constructor,s=ze.get(o)??[];s.push({nodeName:r,methodKey:n}),ze.set(o,s)})}}function kr(r){return(e,t)=>{let n=t.name;t.addInitializer(function(){let o=this.constructor,s=We.get(o)??[];s.push({ms:r,methodKey:n}),We.set(o,s)})}}function Sr(r){return(e,t)=>{let n=t.name;t.addInitializer(function(){let o=this.constructor,s=Be.get(o)??[];s.push({expr:r,methodKey:n}),Be.set(o,s)})}}function Ar(r,e){return(t,n)=>{let o=n.name;n.addInitializer(function(){let s=this.constructor,a=Ke.get(s)??[];a.push({cqrsName:r,commandName:e,methodKey:o}),Ke.set(s,a)})}}function Cr(r,e){return(t,n)=>{let o=n.name;n.addInitializer(function(){let s=this.constructor,a=Ue.get(s)??[];a.push({cqrsName:r,eventName:e,methodKey:o}),Ue.set(s,a)})}}function Mr(r,e){return(t,n)=>{let o=n.name;n.addInitializer(function(){let s=this.constructor,a=Ye.get(s)??[];a.push({cqrsName:r,projectionName:e,methodKey:o}),Ye.set(s,a)})}}function Dr(r,e,t){return(n,o)=>{let s=o.name;o.addInitializer(function(){let a=this.constructor,i=Je.get(a)??[];i.push({cqrsName:r,eventNames:t,sagaName:e,methodKey:s}),Je.set(a,i)})}}B();Mt();var Hr=0,Ge=class{constructor(e,t){this.graph=e;this.moduleRef=t}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,t]of ze){let n=this.resolveInstance(e);if(n)for(let o of t)this.wireEventHandler(n,o)}}wireEventHandler(e,t){let n=e[t.methodKey];if(typeof n!="function")return;let o=n.bind(e),a=this.observeNode(t.nodeName).subscribe(i=>{for(let d of i)d[0]===E&&o(d[1])});this.disposers.push(a)}wireIntervals(){for(let[e,t]of We){let n=this.resolveInstance(e);if(n)for(let o of t)this.wireIntervalHandler(n,e,o)}}wireIntervalHandler(e,t,n){let o=e[n.methodKey];if(typeof o!="function")return;let s=o.bind(e),i=`__schedule__.${t.name??"anonymous"}.${String(n.methodKey)}.${Hr++}`,d=Lr(n.ms,{period:n.ms,name:i});this.graph.add(d),this.scheduleNodeNames.push(i);let c=this.observeNode(i).subscribe(l=>{for(let p of l)p[0]===E&&s(p[1])});this.disposers.push(c)}wireCrons(){for(let[e,t]of Be){let n=this.resolveInstance(e);if(n)for(let o of t)this.wireCronHandler(n,e,o)}}wireCronHandler(e,t,n){let o=e[n.methodKey];if(typeof o!="function")return;let s=o.bind(e),i=`__schedule__.${t.name??"anonymous"}.${String(n.methodKey)}.${Hr++}`,d=$r(n.expr,{name:i});this.graph.add(d),this.scheduleNodeNames.push(i);let c=this.observeNode(i).subscribe(l=>{for(let p of l)p[0]===E&&s(p[1])});this.disposers.push(c)}wireCqrsCommands(){for(let[e,t]of Ke){let n=this.resolveInstance(e);if(n)for(let o of t)this.wireCqrsCommand(n,o)}}wireCqrsCommand(e,t){let n=e[t.methodKey];if(typeof n!="function")return;let o=n.bind(e),s=this.resolveCqrsGraph(t.cqrsName);s&&s.command(t.commandName,o)}wireCqrsEvents(){for(let[e,t]of Ue){let n=this.resolveInstance(e);if(n)for(let o of t)this.wireCqrsEventHandler(n,o)}}wireCqrsEventHandler(e,t){let n=e[t.methodKey];if(typeof n!="function")return;let o=n.bind(e),s=this.resolveCqrsGraph(t.cqrsName);if(!s)return;s.event(t.eventName);let i=s.resolve(t.eventName).cache,d=i&&i.length>0?i[i.length-1].seq:0,c=this.observeNodeOn(s,t.eventName).subscribe(l=>{for(let p of l)if(p[0]===E){let h=p[1];for(let f of h)f.seq>d&&(o(f),d=f.seq)}});this.disposers.push(c)}wireCqrsQueries(){for(let[e,t]of Ye){let n=this.resolveInstance(e);if(n)for(let o of t)this.wireCqrsQuery(n,o)}}wireCqrsQuery(e,t){let n=e[t.methodKey];if(typeof n!="function")return;let o=n.bind(e),s=this.resolveCqrsGraph(t.cqrsName);if(!s)return;let i=this.observeNodeOn(s,t.projectionName).subscribe(d=>{for(let u of d)u[0]===E&&o(u[1])});this.disposers.push(i)}wireCqrsSagas(){for(let[e,t]of Je){let n=this.resolveInstance(e);if(n)for(let o of t)this.wireCqrsSaga(n,o)}}wireCqrsSaga(e,t){let n=e[t.methodKey];if(typeof n!="function")return;let o=n.bind(e),s=this.resolveCqrsGraph(t.cqrsName);s&&s.saga(t.sagaName,t.eventNames,o)}observeNode(e){return this.graph.observe(e)}observeNodeOn(e,t){return e.observe(t)}resolveCqrsGraph(e){try{return this.moduleRef.get(Q(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};B();B();var ls=0;function Dt(r,e){if(e.highWaterMark<1)throw new RangeError("highWaterMark must be >= 1");if(e.lowWaterMark<0)throw new RangeError("lowWaterMark must be >= 0");if(e.lowWaterMark>=e.highWaterMark)throw new RangeError("lowWaterMark must be < highWaterMark");let t=Symbol(`bp-${++ls}`),n=0,o=!1;return{onEnqueue(){return n+=1,!o&&n>=e.highWaterMark?(o=!0,r([[ee,t]]),!0):!1},onDequeue(){return n>0&&(n-=1),o&&n<=e.lowWaterMark?(o=!1,r([[oe,t]]),!0):!1},get pending(){return n},get paused(){return o},dispose(){o&&(o=!1,r([[oe,t]]))}}}function jr(r,e,t){let{actor:n,serialize:o=fs,keepAliveMs:s,signal:a}=t??{},i=new TextEncoder,d,u=t?.highWaterMark!=null,c,l,p=[],h=!1;return new ReadableStream({start(f){let m,g=()=>{},x=()=>{if(!h){h=!0,m!==void 0&&clearInterval(m),a?.removeEventListener("abort",v),g(),c?.dispose(),l?.(),l=void 0;for(let b of p)f.enqueue(b.frame);p.length=0,f.close()}};d=x;let v=()=>x(),_=r.observe(e,{actor:n});u&&(c=Dt(b=>_.up(b),{highWaterMark:t.highWaterMark,lowWaterMark:t.lowWaterMark??Math.floor(t.highWaterMark/2)})),g=_.subscribe(b=>{for(let T of b){if(h)return;let O=T[0];if(O===E){let y=i.encode(bn("data",o(T[1])));u?(p.push({frame:y,counted:!0}),c.onEnqueue(),l?.(),l=void 0):f.enqueue(y)}else if(O===M){let y=i.encode(bn("error",o(T[1])));u?(p.push({frame:y,counted:!1}),l?.(),l=void 0):f.enqueue(y),x();return}else if(O===G||O===V){if(O===G){let y=i.encode(bn("complete"));u?(p.push({frame:y,counted:!1}),l?.(),l=void 0):f.enqueue(y)}x();return}}}),s!==void 0&&s>0&&(m=setInterval(()=>{h||(u?(p.push({frame:i.encode(`: keepalive
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
8
+ var __typeError = (msg) => {
9
+ throw TypeError(msg);
10
+ };
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
27
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
28
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
29
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
30
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
31
+ var __runInitializers = (array, flags, self, value) => {
32
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
33
+ return value;
34
+ };
35
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
36
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
37
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
38
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
39
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
40
+ return __privateGet(this, extra);
41
+ }, set [name](x) {
42
+ return __privateSet(this, extra, x);
43
+ } }, name));
44
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
45
+ for (var i = decorators.length - 1; i >= 0; i--) {
46
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
47
+ if (k) {
48
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
49
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
50
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
51
+ }
52
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
53
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
54
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
55
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
56
+ }
57
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
58
+ };
59
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
60
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
61
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
62
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
63
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
4
64
 
5
- `),counted:!1}),l?.(),l=void 0):f.enqueue(i.encode(`: keepalive
65
+ // src/compat/index.ts
66
+ var compat_exports = {};
67
+ __export(compat_exports, {
68
+ jotai: () => jotai_exports,
69
+ nanostores: () => nanostores_exports,
70
+ nestjs: () => nestjs_exports,
71
+ react: () => react_exports,
72
+ signals: () => signals_exports,
73
+ solid: () => solid_exports,
74
+ svelte: () => svelte_exports,
75
+ vue: () => vue_exports,
76
+ zustand: () => zustand_exports
77
+ });
78
+ module.exports = __toCommonJS(compat_exports);
6
79
 
7
- `)))},s)),a?.aborted?v():a?.addEventListener("abort",v,{once:!0})},pull(f){if(u&&!h){if(p.length>0){let m=p.shift();f.enqueue(m.frame),m.counted&&c.onDequeue();return}return new Promise(m=>{l=m})}},cancel(){try{d?.()}catch{}}})}function zr(r,e,t){let{actor:n,filter:o}=t??{},s=[],a=[],i=!1,d=r.observe(e,{actor:n}),u=t?.highWaterMark!=null?Dt(f=>d.up(f),{highWaterMark:t.highWaterMark,lowWaterMark:t.lowWaterMark??Math.floor(t.highWaterMark/2)}):void 0,c=()=>{i||(i=!0,u?.dispose(),p())},l=f=>{if(!i)if(a.length>0){let m=a.shift();f.done&&f.error?m.reject(f.error):f.done?m.resolve({done:!0,value:void 0}):m.resolve({done:!1,value:f.value})}else s.push(f),f.done||u?.onEnqueue()},p=d.subscribe(f=>{for(let m of f){let g=m[0];if(g===E){let x=m[1];if(o&&!o(x))continue;l({done:!1,value:x})}else if(g===M){let x=m[1]instanceof Error?m[1]:new Error(String(m[1]));l({done:!0,error:x}),c();return}else if(g===G||g===V){l({done:!0}),c();return}}});return{next(){if(s.length>0){let f=s.shift();return f.done||u?.onDequeue(),f.done&&f.error?Promise.reject(f.error):Promise.resolve(f.done?{done:!0,value:void 0}:{done:!1,value:f.value})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((f,m)=>{a.push({resolve:f,reject:m})})},return(){c();for(let f of a)f.resolve({done:!0,value:void 0});return a.length=0,Promise.resolve({done:!0,value:void 0})},throw(f){return c(),Promise.reject(f)},[Symbol.asyncIterator](){return this}}}var Gt=class{constructor(e,t){this.graph=e;this.extractActor=t?.extractActor??(()=>{}),this.parse=t?.parse??ps,this.highWaterMark=t?.highWaterMark,this.lowWaterMark=t?.lowWaterMark}clients=new Map;extractActor;parse;highWaterMark;lowWaterMark;handleConnection(e){this.clients.has(e)||this.clients.set(e,new Map)}handleDisconnect(e){let t=this.clients.get(e);if(t){for(let n of t.values())n.wm?.dispose(),n.unsub();this.clients.delete(e)}}handleMessage(e,t,n){let o=n??hs.bind(null,e),s;try{s=typeof t=="string"?this.parse(t):t}catch{o({type:"err",message:"invalid command"});return}s.type==="subscribe"?this.subscribe(e,s.path,o):s.type==="unsubscribe"?this.unsubscribe(e,s.path,o):s.type==="ack"?this.ack(e,s.path,s.count??1):o({type:"err",message:`unknown command type: ${s.type}`})}subscriptionCount(e){return this.clients.get(e)?.size??0}destroy(){for(let[e]of this.clients)this.handleDisconnect(e)}subscribe(e,t,n){let o=this.clients.get(e);if(o||(o=new Map,this.clients.set(e,o)),o.has(t)){n({type:"subscribed",path:t});return}let s=this.extractActor(e),a;try{a=this.graph.observe(t,{actor:s})}catch(c){let l=c instanceof Error?c.message:String(c);n({type:"err",message:l});return}let i=this.highWaterMark!=null?Dt(c=>a.up(c),{highWaterMark:this.highWaterMark,lowWaterMark:this.lowWaterMark??Math.floor(this.highWaterMark/2)}):void 0,d=()=>{i?.dispose(),u(),o.delete(t)},u=a.subscribe(c=>{for(let l of c){let p=l[0];if(p===E)i?.onEnqueue(),vn(n,{type:"data",path:t,value:l[1]});else if(p===M){let h=l[1]instanceof Error?l[1].message:String(l[1]);vn(n,{type:"error",path:t,error:h}),d();return}else if(p===G||p===V){vn(n,{type:"complete",path:t}),d();return}}});o.set(t,{unsub:u,wm:i}),n({type:"subscribed",path:t})}unsubscribe(e,t,n){let o=this.clients.get(e),s=o?.get(t);s&&(s.wm?.dispose(),s.unsub(),o.delete(t)),n({type:"unsubscribed",path:t})}ack(e,t,n){let o=this.clients.get(e)?.get(t);if(!o?.wm)return;let s=Math.min(Math.max(0,Math.floor(n)),1024);for(let a=0;a<s;a++)o.wm.onDequeue()}};function fs(r){if(r instanceof Error)return r.message;try{return JSON.stringify(r)}catch{return String(r)}}function bn(r,e){let t=`event: ${r}
8
- `;if(e!==void 0)for(let n of e.split(`
9
- `))t+=`data: ${n}
10
- `;return t+=`
11
- `,t}function ps(r){return JSON.parse(r)}function hs(r,e){try{r.send(JSON.stringify(e))}catch{}}function vn(r,e){try{r(e)}catch{}}rt();var It="graphReflyActor";function _n(r){return e=>{let n=e.switchToHttp().getRequest()?.user;if(n!=null)return r?r(n):n}}function Wr(r="x-graphrefly-actor"){return e=>{let n=e.switchToHttp().getRequest()?.headers?.[r.toLowerCase()];if(!(typeof n!="string"||n.length===0))try{return JSON.parse(n)}catch{return}}}function Br(r){let e=r?.[It];return e!=null?Ne(e):ve}var lt=class{constructor(e){this.extractor=e}canActivate(e){let t=Ne(this.extractor(e)),n=e.switchToHttp().getRequest();return n!=null&&(n[It]=t),!0}};function Kr(r){return new lt(r??_n())}var vt=require("@nestjs/common"),So=require("@nestjs/core");pt();Se();Ae();rt();Ae();B();Rn();Me();he();ke();Se();Ae();B();he();pt();ke();B();Me();he();var An=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=t,t!==void 0){if(this._buf=new Array(t),e&&e.length>0){let n=Math.min(e.length,t),o=e.length-n;for(let s=0;s<n;s++)this._buf[s]=e[o+s];this._size=n}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let t=e>=0?e:this._size+e;if(!(t<0||t>=this._size))return this._maxSize!==void 0?this._buf[(this._head+t)%this._maxSize]:this._buf[t]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let n=t;n<e.length;n++)this._rawAppend(e[n]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let t=0;t<e;t++)this._buf[(this._head+t)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let t=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,t);else{for(let n=0;n<t;n++)this._buf[(this._head+n)%this._maxSize]=void 0;this._head=(this._head+t)%this._maxSize}return this._size-=t,this._version+=1,t}slice(e,t){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${t})`);let n=t===void 0?this._size:Math.min(Math.max(t,0),this._size),o=Math.min(e,this._size);if(o>=n)return[];let s=n-o;if(this._maxSize===void 0)return this._buf.slice(o,n);let a=new Array(s);for(let i=0;i<s;i++)a[i]=this._buf[(this._head+o+i)%this._maxSize];return a}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let t=Math.min(e,this._size);return this.slice(this._size-t,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this._buf[(this._head+t)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let t=0;t<e.length;t++)this._buf.push(e[t]);this._size=this._buf.length}else{let t=this._maxSize;for(let s=0;s<t;s++)this._buf[s]=void 0;this._head=0;let n=Math.min(e.length,t),o=e.length-n;for(let s=0;s<n;s++)this._buf[s]=e[o+s];this._size=n}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function ht(r){return r.subscribe(()=>{})}var Gs=64;function gt(r,e={}){let{name:t,maxSize:n,versioning:o,guard:s,backend:a}=e,i=a??new An(r,n),d=q(i.toArray(),{name:t,describeKind:"state",equals:(y,R)=>y===R,...o!=null?{versioning:o}:{},...s!=null?{guard:s}:{}});function u(){let y=i.toArray();ue(()=>{d.down([[P]],{internal:!0}),d.down([[E,y]],{internal:!0})})}let c=new Map,l=new Map,p=new Map;function h(y,R){return`${y}:${R===void 0?"END":R}`}function f(y){if(y.size<Gs)return;let R=y.keys().next();if(R.done)return;let k=y.get(R.value);k!==void 0&&k.dispose(),y.delete(R.value)}function m(y){let R=i.version;try{return y()}finally{i.version!==R&&u()}}function g(y){if(!Number.isInteger(y)||y<0)throw new RangeError(`tail: n must be a non-negative integer (got ${y})`);let R=c.get(y);if(R!==void 0)return c.delete(y),c.set(y,R),R.node;f(c);let k=Y([d],([w])=>{let S=w;return y===0||S.length===0?[]:S.slice(Math.max(0,S.length-y))},{initial:i.tail(y),describeKind:"derived"}),N=ht(k);return c.set(y,{node:k,dispose:N}),k}function x(y,R){if(!Number.isInteger(y)||y<0)throw new RangeError(`slice: start must be a non-negative integer (got ${y})`);if(R!==void 0&&(!Number.isInteger(R)||R<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${R})`);let k=h(y,R),N=l.get(k);if(N!==void 0)return l.delete(k),l.set(k,N),N.node;f(l);let w=Y([d],([D])=>{let A=D;return R===void 0?A.slice(y):A.slice(y,R)},{initial:i.slice(y,R),describeKind:"derived"}),S=ht(w);return l.set(k,{node:w,dispose:S}),w}function v(y){let R=p.get(y);if(R!==void 0)return R.node;let k=Y([d,y],([w,S])=>{let D=w,A=Math.max(0,Math.trunc(S??0));return D.slice(A)},{initial:[],describeKind:"derived"}),N=ht(k);return p.set(y,{node:k,dispose:N}),k}let _,b;function T(){_===void 0&&(_=fe([d],(y,R,k)=>{let N=y[0],S=N!=null&&N.length>0?N.at(-1):k.prevData[0];if(S==null||S.length===0){R.down([[W]]);return}R.emit(S[S.length-1])},{name:t!=null?`${t}::lastValue`:"lastValue",describeKind:"derived",initial:i.size===0?void 0:i.at(i.size-1)}),b=Y([d],([y])=>y.length>0,{name:t!=null?`${t}::hasLatest`:"hasLatest",describeKind:"derived",initial:i.size>0}),ht(_),ht(b))}let O={entries:d,get size(){return i.size},at(y){return i.at(y)},append(y){m(()=>i.append(y))},appendMany(y){y.length!==0&&m(()=>i.appendMany(y))},clear(){m(()=>i.clear())},trimHead(y){m(()=>i.trimHead(y))},withLatest(){return T(),d},get lastValue(){return T(),_},get hasLatest(){return T(),b},view(y){switch(y.kind){case"tail":return g(y.n);case"slice":return x(y.start,y.stop);case"fromCursor":return v(y.cursor)}},attach(y){let R=y.subscribe(k=>{for(let N of k)N[0]===E&&O.append(N[1])});return()=>R()},attachStorage(y){if(y.length===0)return()=>{};let R=new Map;for(let N of y)R.set(N,i.size);(async()=>{for(let N of y)if(typeof N.loadEntries=="function")try{let w=await Promise.resolve(N.loadEntries());w.entries.length>0&&i.size===0&&(i.restore(w.entries),R.set(N,w.entries.length),u());break}catch{}})();let k=d.subscribe(N=>{for(let w of N){if(w[0]!==E)continue;let S=w[1];for(let D of y){let A=R.get(D)??0;if(S.length<A){try{let U=D.appendEntries(S);U instanceof Promise&&U.catch(()=>{})}catch{}R.set(D,S.length);continue}if(S.length===A)continue;let j=S.slice(A);R.set(D,S.length);try{let U=D.appendEntries(j);U instanceof Promise&&U.catch(()=>{})}catch{}}}});return()=>k()},disposeAllViews(){for(let y of c.values())y.dispose();c.clear();for(let y of l.values())y.dispose();l.clear();for(let y of p.values())y.dispose();p.clear()},dispose(){for(let y of c.values())y.dispose();c.clear();for(let y of l.values())y.dispose();l.clear();for(let y of p.values())y.dispose();p.clear()}};return O}var Is=je((r,e)=>{r("observe"),r("signal"),e("write")});function zt(r){let e=gt([],{name:r.name,maxSize:r.retainedLimit??1024,guard:r.guard??Is,...r.versioning!=null?{versioning:r.versioning}:{}});return e.withLatest(),r.graph&&r.graph.add(e.entries,{name:r.name}),e}function Cn(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))Cn(r[e]);return Object.freeze(r)}var mo=new WeakSet;function yo(r){let e=r.cache,t=typeof e=="number"&&Number.isFinite(e);!t&&e!==void 0&&!mo.has(r)&&(mo.add(r),console.warn(`bumpCursor: cursor cache held a non-numeric value (${String(e)}); resetting to 0. Causes include: a snapshot codec round-tripping the cursor as a string / null / NaN, OR a malformed initial seed (e.g. state<number>(NaN)). Audit consumers may see colliding seq values after this point.`));let o=(t?e:0)+1;return r.down([[P],[E,o]]),o}function jt(r,e,t,n,o,s){let a=e(t,n,o);if(a===void 0)return;let i=s!=null?{...a,handlerVersion:s}:a;r.append(i)}function bo(r,e){let t=e.freeze??!0;return function(...o){let s=t?o.map(Cn):o,a=se(),i=e.seq?yo(e.seq):void 0;try{let d=r(...s);return e.audit&&e.onSuccess&&jt(e.audit,e.onSuccess,s,d,{t_ns:a,seq:i},e.handlerVersion),d}catch(d){if(e.audit&&e.onFailure){let u=d instanceof Error?d.name:typeof d;jt(e.audit,e.onFailure,s,d,{t_ns:a,seq:i,errorType:u},e.handlerVersion)}throw d}}}function vo(r,e){let t=e.freeze??!0;return function(...o){let s=t?o.map(Cn):o,a=se(),i,d,u=!1,c;try{ue(()=>{e.seq&&(c=yo(e.seq));try{i=r(...s),e.audit&&e.onSuccess&&jt(e.audit,e.onSuccess,s,i,{t_ns:a,seq:c},e.handlerVersion)}catch(l){throw d=l,u=!0,l}})}catch(l){if(u&&e.audit&&e.onFailure){let p=d instanceof Error?d.name:typeof d;jt(e.audit,e.onFailure,s,d,{t_ns:a,seq:c,errorType:p},e.handlerVersion)}throw u?d:l}return i}}function _o(r,e,t=0){let n=q(t,{name:e,describeKind:"state"});return r.add(n,{name:e}),n}function To(r,e,t,n=0){let o={},s=new Z(e);for(let a of t){let i=q(n,{name:a,describeKind:"state"});s.add(i,{name:a}),o[a]=i}return r.mount(e,s),o}wo();var Te=class extends Error{constructor(e,t){super(e,t),this.name=this.constructor.name}},Wt=class extends Te{constructor(t,n){super(`Duplicate ${t} registration: "${n}"`);this.kind=t;this.registrationName=n}},Bt=class extends Te{constructor(t,n,o){super(`Command "${t}" emitted undeclared event "${n}". Declared emits: [${o.join(", ")}]`);this.commandName=t;this.eventName=n;this.declaredEmits=o}},Kt=class extends Te{constructor(t,n,o){super(`Optimistic concurrency conflict on aggregate "${t}": expected version ${n}, got ${o}`);this.aggregateId=t;this.expected=n;this.actual=o}},Ut=class extends Te{constructor(t){super(`Unknown command: "${t}". Register with command() first.`);this.commandName=t}},mt=class extends Te{constructor(t,n){super(`Command handler "${t}" threw: ${n instanceof Error?n.message:String(n)}`,{cause:n});this.commandName=t}};var yt=class extends Te{constructor(t,n){super(`Projection "${t}" rebuild failed: ${n instanceof Error?n.message:String(n)}`,{cause:n});this.projectionName=t}};Ro();Mt();var Ps=je((r,e)=>{r("write"),r("signal"),e("observe")}),Ls=je((r,e)=>{r("observe"),r("signal"),e("write")}),No=je((r,e)=>{r("observe"),r("signal"),e("write")});function bt(r,e){return xo("cqrs",r,e)}function Eo(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))Eo(r[e]);return Object.freeze(r)}var Mn=class extends Z{_eventLogs=new Map;_eventLogsByAggregate=new Map;_aggregateVersions=new Map;_aggregateLru=new Map;_commandRegs=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_seq=0;_retainedLimit;_freezeCommandPayload;_freezeEventPayload;_maxAggregates;_dispatchSeqCursor;dispatches;audit;aggregateEvictions;constructor(e,t={}){super(e,t.graph),this._retainedLimit=t.retainedLimit??1024,this._freezeCommandPayload=t.freezeCommandPayload??!0,this._freezeEventPayload=t.freezeEventPayload??!0,this._maxAggregates=t.maxAggregates??1e4,this.dispatches=zt({name:"dispatches",retainedLimit:this._retainedLimit,graph:this}),this.audit=this.dispatches,this.aggregateEvictions=zt({name:"aggregateEvictions",retainedLimit:this._retainedLimit,graph:this}),this._dispatchSeqCursor=_o(this,"dispatch_seq",0)}aggregateVersion(e,t){return this._aggregateVersions.get(`${e}::${t}`)??0}_touchAggregate(e){this._aggregateLru.delete(e),this._aggregateLru.set(e,!0)}_enforceAggregateLru(){for(;this._aggregateLru.size>this._maxAggregates;){let e=this._aggregateLru.keys().next();if(e.done)break;let t=e.value;this._aggregateLru.delete(t);let n=t.indexOf("::");if(n<0)continue;let o=t.slice(0,n),s=t.slice(n+2),a=this._aggregateVersions.get(t)??0;this._aggregateVersions.delete(t);let i=this._eventLogsByAggregate.get(o);i&&(i.delete(s),i.size===0&&this._eventLogsByAggregate.delete(o)),this.aggregateEvictions.append({aggregateId:s,type:o,lastVersion:a,t_ns:se()})}}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}_attachedEventTiers=[];_attachedTierDisposers=new Map;attachEventStorage(e){this._attachedEventTiers.push(e);for(let[t,n]of this._eventLogs){let o=n.log.attachStorage(e),s=this._attachedTierDisposers.get(t);s||(s=[],this._attachedTierDisposers.set(t,s)),s.push(o)}for(let[t,n]of this._eventLogsByAggregate)for(let[o,s]of n){let a=`${t}::${o}`,i=s.log.attachStorage(e),d=this._attachedTierDisposers.get(a);d||(d=[],this._attachedTierDisposers.set(a,d)),d.push(i)}return()=>{let t=this._attachedEventTiers.indexOf(e);t>=0&&this._attachedEventTiers.splice(t,1)}}_autoWireStreamStorage(e,t){if(this._attachedEventTiers.length===0)return;let n=this._attachedTierDisposers.get(e);n||(n=[],this._attachedTierDisposers.set(e,n));for(let o of this._attachedEventTiers)n.push(t.attachStorage(o))}event(e,t){if(t!==void 0)return this._ensureAggregateStream(e,t).node;let n=this._eventLogs.get(e);if(n)return n.node;let o=gt([],{name:e,versioning:0,maxSize:this._retainedLimit});o.withLatest();let s=o.entries,a=Y([s],([i])=>i,{name:e,describeKind:"state",meta:bt("event",{event_name:e}),guard:No,initial:s.cache});return this.add(a,{name:e}),this._keepaliveDisposers.push(me(a)),this._eventLogs.set(e,{log:o,node:a}),this._autoWireStreamStorage(e,o),a}_ensureAggregateStream(e,t){this._eventLogs.has(e)||this.event(e);let n=this._eventLogsByAggregate.get(e);n||(n=new Map,this._eventLogsByAggregate.set(e,n));let o=`${e}::${t}`;this._touchAggregate(o);let s=n.get(t);if(s)return s;let a=`${e}_${t.replace(/[^a-zA-Z0-9_-]/g,"_")}`,i=gt([],{name:a,versioning:0,maxSize:this._retainedLimit});i.withLatest();let d=i.entries,u=Y([d],([h])=>h,{name:a,describeKind:"state",meta:bt("event_aggregate",{event_name:e,aggregate_id:t}),guard:No,initial:d.cache}),c=a,l=0;for(;this.nameOf(this.resolveOptional(c)??u)===c&&(l+=1,c=`${a}_${l}`,this.resolveOptional(c)!==void 0););try{this.add(u,{name:c})}catch{}this._keepaliveDisposers.push(me(u));let p={log:i,node:u};return n.set(t,p),this._autoWireStreamStorage(`${e}::${t}`,i),this._enforceAggregateLru(),p}resolveOptional(e){try{return this.resolve(e)}catch{return}}_appendEvent(e,t,n){let o=this._eventLogs.get(e);if(o||(this.event(e),o=this._eventLogs.get(e)),o.node.status==="completed"||o.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${o.node.status}).`);let s,a;if(n?.aggregateId!==void 0){let c=`${e}::${n.aggregateId}`;s=(this._aggregateVersions.get(c)??0)+1,this._aggregateVersions.set(c,s),a=this._ensureAggregateStream(e,n.aggregateId)}let i=o.log.entries.v,d=this._freezeEventPayload?Eo(t):t,u={type:e,payload:d,timestampNs:se(),seq:++this._seq,...n?.aggregateId!==void 0?{aggregateId:n.aggregateId}:{},...s!==void 0?{aggregateVersion:s}:{},...n?.correlationId!==void 0?{correlationId:n.correlationId}:{},...n?.causationId!==void 0?{causationId:n.causationId}:{},...n?.metadata!==void 0?{metadata:Object.freeze({...n.metadata})}:{},...n?.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},...i!=null?{v0:{id:i.id,version:i.version}}:{}};return o.log.append(u),a&&a.log.append(u),u}command(e,t){if(this._commandRegs.has(e))throw new Wt("command",e);let n=typeof t=="function"?{handler:t}:t,o=q(void 0,{name:e,describeKind:"state",meta:{...bt("command",{command_name:e}),error:null},guard:Ps});if(this.add(o,{name:e}),this._commandRegs.set(e,{handler:n.handler,...n.emits!==void 0?{emits:n.emits}:{},...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{}}),n.emits)for(let s of n.emits)this._eventLogs.has(s)||this.event(s);return o}dispatch(e,t,n){let o=this._commandRegs.get(e);if(!o)throw new Ut(e);if(n?.aggregateId!==void 0&&n.expectedAggregateVersion!==void 0&&o.emits!==void 0){let u=0;for(let c of o.emits){let l=this._aggregateVersions.get(`${c}::${n.aggregateId}`);l!==void 0&&l>u&&(u=l)}if(u!==n.expectedAggregateVersion)throw new Kt(n.aggregateId,n.expectedAggregateVersion,u)}let s=this.resolve(e),a=[],i=!1,d=u=>{s.emit(u,{internal:!0});try{o.handler(u,{emit:(c,l)=>{if(o.emits!==void 0&&!o.emits.includes(c))throw new Bt(e,c,o.emits);a.push(c),this._appendEvent(c,l,{...n?.aggregateId!==void 0?{aggregateId:n.aggregateId}:{},...n?.correlationId!==void 0?{correlationId:n.correlationId}:{},...n?.causationId!==void 0?{causationId:n.causationId}:{},...n?.metadata!==void 0?{metadata:Object.freeze({...n.metadata})}:{},...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}}),s.meta.error.emit(null,{internal:!0})}catch(c){throw i=!0,c}};try{vo(d,{audit:this.dispatches,seq:this._dispatchSeqCursor,freeze:this._freezeCommandPayload,onSuccess:([u],c,{t_ns:l,seq:p})=>({commandName:e,payload:u,outcome:"success",emittedEvents:[...a],t_ns:l,seq:p??0,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),onFailure:([u],c,{t_ns:l,seq:p,errorType:h})=>{let f=c instanceof mt?c:new mt(e,c);return{commandName:e,payload:u,outcome:"failure",error:f,errorType:h,emittedEvents:[...a],t_ns:l,seq:p??0,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}}})(t)}catch(u){throw i&&s.meta.error.emit(u,{internal:!0}),u}}projection(e){let{name:t,events:n,reducer:o,initial:s}=e,a=e.mode??"scan",i=e.freezeInputs??!0,d=e.snapshot,u=n.map(N=>(this._eventLogs.has(N)||this.event(N),this._eventLogs.get(N).node));function c(N){N.sort((w,S)=>w.timestampNs-S.timestampNs||w.seq-S.seq||(w.aggregateId??"").localeCompare(S.aggregateId??""))}function l(N){let w=[];for(let S of N)w.push(...S);return c(w),w}let p=u.map(N=>N.cache??[]),h=l(p),f=i?Object.freeze(h):h,m=0,g=s;a==="scan"&&h.length>0&&(g=o(s,f),m=h.length);let x=a==="replay"?o(s,f):g,v=d?.saveDebounceMs??1e3,_=d?.saveEvery??1e3,b,T=0;function O(N){if(d?.save){if(T+=1,T>=_){T=0,b!==void 0&&(clearTimeout(b),b=void 0);let w=d.save(N);w instanceof Promise&&w.catch(()=>{});return}b!==void 0&&clearTimeout(b),b=setTimeout(()=>{b=void 0,T=0;let w=d.save(N);w instanceof Promise&&w.catch(()=>{})},v)}}let y=Y(u,N=>{let w=l(N),S;if(a==="replay"){let D=i?Object.freeze(w):w;S=o(s,D)}else{let D=w.slice(m);m=w.length;let A=i?Object.freeze(D):D;S=o(g,A),g=S}return O(S),S},{name:t,describeKind:"derived",meta:bt("projection",{projection_name:t,source_events:n}),guard:Ls,initial:x});return this.add(y,{name:t}),this._keepaliveDisposers.push(me(y)),this._keepaliveDisposers.push(()=>{b!==void 0&&(clearTimeout(b),b=void 0)}),this._projections.add(t),{node:y,rebuild:async N=>{try{let w=N?.pageSize??1e3,S=N?.fromTier??this._attachedEventTiers[0]?.[0],D=l(u.map(j=>j.cache??[])).length,A=s;if(d?.load){let j=await d.load();j!==void 0&&(A=j)}if(!S||!S.loadEntries){let j=l(u.map(X=>X.cache??[])),U=i?Object.freeze(j):j;A=o(A,U)}else{let j=new Set(n),U,X=!1;for(;!X;){let Le=await S.loadEntries({cursor:U,pageSize:w}),$e=[...Le.entries].filter(Xe=>j.has(Xe.type));c($e);let Ze=i?Object.freeze($e):$e;A=o(A,Ze),U=Le.cursor,X=!U||Le.entries.length===0}}if(a==="scan"){let j=l(u.map(X=>X.cache??[])),U=j.slice(D);if(U.length>0){let X=i?Object.freeze(U):U;A=o(A,X)}g=A,m=j.length}return y.emit(A,{internal:!0}),A}catch(w){throw new yt(t,w)}},reset:async()=>{try{let N=s;if(d?.load){let A=await d.load();A!==void 0&&(N=A)}let w=l(u.map(A=>A.cache??[])),S=i?Object.freeze(w):w,D=o(N,S);return a==="scan"&&(g=D,m=w.length),y.emit(D,{internal:!0}),D}catch(N){throw new yt(t,N)}}}}saga(e,t,n,o={}){let s=t.map(f=>(this._eventLogs.has(f)||this.event(f),this._eventLogs.get(f).node)),a=To(this,`${e}_cursor`,t,0),i=zt({name:`${e}_invocations`,retainedLimit:this._retainedLimit,graph:this}),d=o.aggregateId,u=o.errorPolicy??"advance",c=new Map;for(let f of t){let m=a[f];c.set(f,m.cache??0);let g=m.subscribe(x=>{for(let v of x)v[0]===E&&c.set(f,v[1])});this._keepaliveDisposers.push(g)}let l=bo((f,m)=>{n(f)},{audit:i,freeze:!1,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{},onSuccess:([f,m],g,{t_ns:x})=>({eventType:m,outcome:"success",aggregateId:f.aggregateId,event:f,t_ns:x}),onFailure:([f,m],g,{t_ns:x,errorType:v})=>({eventType:m,outcome:"failure",error:g,errorType:v,aggregateId:f.aggregateId,event:f,t_ns:x})}),p={},h=fe(s,(f,m)=>{let g=p.n.meta.error;for(let x=0;x<f.length;x++){let v=f[x];if(v==null||v.length===0)continue;let _=v.at(-1);if(!_)continue;let b=t[x],T=a[b],O=c.get(b)??0;if(_.length>O){let y=_.slice(O),R=O;for(let k of y){let N=k;if(d!==void 0&&N.aggregateId!==d){R+=1;continue}try{l(N,b),g.emit(null,{internal:!0}),R+=1}catch(w){if(g.emit(w,{internal:!0}),u==="hold")break;R+=1}}T.emit(R)}}},{name:e,describeKind:"effect",meta:{...bt("saga",{saga_name:e,source_events:t}),error:null}});return p.n=h,this.add(h,{name:e}),this._keepaliveDisposers.push(me(h)),this._sagas.add(e),{node:h,invocations:i,audit:i,cursors:a}}};function Oo(r,e){let t=new Mn(r,e),{factory:n,factoryArgs:o,...s}=e??{};return t.tagFactory("cqrs",wn(s)),t}var Gn=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},In=class{graph=new Z("request");onModuleDestroy(){this.graph.destroy()}},ko,Dn;ko=[(0,vt.Module)({})];var we=class we{static forRoot(e){let t=e??{},n=t.name??"root",o=[{provide:ae,useFactory:()=>{let s=new Z(n);return t.build&&t.build(s),t.snapshot&&s.restore(t.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new Gn(s),inject:[ae]},{provide:Ge,useFactory:(s,a)=>new Ge(s,a),inject:[ae,So.ModuleRef]}];if(t.nodes)for(let s of t.nodes)o.push({provide:ce(s),useFactory:a=>a.resolve(s),inject:[ae]});return t.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new In,scope:vt.Scope.REQUEST},{provide:De,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:vt.Scope.REQUEST}),{module:we,global:!0,providers:o,exports:[ae,...(t.nodes??[]).map(ce),...t.requestScope?[De]:[]]}}static forFeature(e){let t=[{provide:Q(e.name),useFactory:n=>{let o=new Z(e.name);return e.build&&e.build(o),e.snapshot&&o.restore(e.snapshot),n.mount(e.name,o),o},inject:[ae]}];if(e.nodes)for(let n of e.nodes)t.push({provide:ce(`${e.name}::${n}`),useFactory:o=>o.resolve(n),inject:[Q(e.name)]});return{module:we,providers:t,exports:[Q(e.name),...(e.nodes??[]).map(n=>ce(`${e.name}::${n}`))]}}static forCqrs(e){let t=[{provide:Q(e.name),useFactory:n=>{let o=Oo(e.name,e.cqrs);return e.eventStorage&&o.attachEventStorage(e.eventStorage),e.build&&e.build(o),n.mount(e.name,o),o},inject:[ae]}];if(e.nodes)for(let n of e.nodes)t.push({provide:ce(`${e.name}::${n}`),useFactory:o=>o.resolve(n),inject:[Q(e.name)]});return{module:we,providers:t,exports:[Q(e.name),...(e.nodes??[]).map(n=>ce(`${e.name}::${n}`))]}}};Dn=Qn(null),we=er(Dn,0,"GraphReflyModule",ko,we),Xn(Dn,1,we);var Yt=we;var Ln={};le(Ln,{useStore:()=>$s,useSubscribe:()=>Ao,useSubscribeRecord:()=>Fs});var ye=require("react");B();function Ao(r){return(0,ye.useSyncExternalStore)(e=>{let t=!1,n=r.subscribe(()=>{t||e()});return()=>{t=!0,n()}},()=>r.cache,()=>r.cache)}function $s(r){let e=Ao(r),t=(0,ye.useCallback)(n=>{r.down([[P],[E,n]])},[r]);return[e,t]}function Fs(r,e){let t=(0,ye.useRef)(e);t.current=e;let n=(0,ye.useMemo)(()=>{let o=()=>{let a={},i=r.cache??[];for(let d of i){let u=t.current(d),c={};for(let l of Object.keys(u))c[l]=u[l].cache;a[d]=c}return a},s=o();return{subscribe:a=>{let i=!1,d=[],u=()=>{for(let p of d)p();d=[]},c=p=>{u();for(let h of p){let f=t.current(h);for(let m of Object.keys(f)){let g=f[m].subscribe(()=>{s=o(),i||a()});d.push(g)}}s=o(),i||a()},l=r.subscribe(p=>{let h=p.some(f=>f[0]===E||f[0]===W);!i&&h&&c(r.cache??[])});return c(r.cache??[]),()=>{i=!0,l(),u()}},getSnapshot:()=>s}},[r]);return(0,ye.useSyncExternalStore)(n.subscribe,n.getSnapshot,n.getSnapshot)}var Vn={};le(Vn,{Signal:()=>Vs});ke();B();he();var Qe=[];function Jt(r){let e=r.cache;return r.subscribe(n=>{for(let[o,s]of n)o===E&&(e=s)})(),e}var $n=class{_node;_equals;constructor(e,t){this._equals=t?.equals??Object.is,this._node=q(e,{...t,resubscribable:!0,resetOnTeardown:!0})}get(){let e=Qe[Qe.length-1];return e?(this._node.status==="sentinel"&&Jt(this._node),e(this._node)):this._node.status==="sentinel"?Jt(this._node):this._node.cache}set(e){this._equals(this.get(),e)||ue(()=>{this._node.down([[P],[E,e]])})}},Fn=class{_node;constructor(e,t){this._node=it(n=>{Qe.push(n);try{return e()}finally{Qe.pop()}},{...t,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=Qe[Qe.length-1];return e?(this._node.status==="sentinel"&&Jt(this._node),e(this._node)):this._node.status==="sentinel"?Jt(this._node):this._node.cache}},Vs={State:$n,Computed:Fn,sub:(r,e)=>{let t=typeof e=="function"?{data:e,error:void 0,complete:void 0}:e,n=!0;return r._node.subscribe(o=>{for(let[s,a]of o){if(s===E){if(n){n=!1;continue}t.data?.(a)}s===M&&t.error?.(a),s===G&&t.complete?.()}})}};var qn={};le(qn,{useStore:()=>qs,useSubscribe:()=>Co,useSubscribeRecord:()=>Hs});var be=require("solid-js");B();function Co(r){let[e,t]=(0,be.createSignal)(r.cache,{equals:!1}),n=r.subscribe(()=>{t(()=>r.cache)});return(0,be.getOwner)()?(0,be.onCleanup)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),e}function qs(r){return[Co(r),n=>{r.down([[P],[E,n]])}]}function Hs(r,e){let[t,n]=(0,be.createSignal)({},{equals:!1}),o=[],s=()=>{for(let u of o)u();o=[]},a=()=>{let u={};for(let c of r.cache??[]){let l=e(c),p={};for(let h of Object.keys(l))p[h]=l[h].cache;u[c]=p}return u},i=u=>{s();for(let c of u){let l=e(c);for(let p of Object.keys(l)){let h=l[p].subscribe(()=>{n(()=>a())});o.push(h)}}n(()=>a())},d=r.subscribe(u=>{u.some(c=>c[0]===E||c[0]===W)&&i(r.cache??[])});return i(r.cache??[]),(0,be.getOwner)()?(0,be.onCleanup)(()=>{d(),s()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),t}var Hn={};le(Hn,{useStore:()=>zs,useSubscribe:()=>js,useSubscribeRecord:()=>Ws});B();function js(r){return{subscribe(e){let t=r.subscribe(()=>{e(r.cache)});return e(r.cache),t}}}function zs(r){return{subscribe(e){let t=r.subscribe(()=>{e(r.cache)});return e(r.cache),t},set(e){r.down([[P],[E,e]])},update(e){let t=e(r.cache);r.down([[P],[E,t]])}}}function Ws(r,e){return{subscribe(t){let n=[],o=()=>{for(let d of n)d();n=[]},s=()=>{let d={};for(let u of r.cache??[]){let c=e(u),l={};for(let p of Object.keys(c))l[p]=c[p].cache;d[u]=l}return d},a=d=>{o();for(let u of d){let c=e(u);for(let l of Object.keys(c)){let p=c[l].subscribe(()=>{t(s())});n.push(p)}}t(s())},i=r.subscribe(d=>{d.some(u=>u[0]===E||u[0]===W)&&a(r.cache??[])});return a(r.cache??[]),()=>{i(),o()}}}}var jn={};le(jn,{useStore:()=>Ks,useSubscribe:()=>Bs,useSubscribeRecord:()=>Us});var z=require("vue");B();function Bs(r){let e=(0,z.shallowRef)(r.cache),t=r.subscribe(()=>{e.value=r.cache});return(0,z.getCurrentScope)()?(0,z.onScopeDispose)(()=>t()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,z.readonly)(e)}function Ks(r){let e=(0,z.shallowRef)(r.cache),t=r.subscribe(()=>{e.value=r.cache});return(0,z.getCurrentScope)()?(0,z.onScopeDispose)(()=>t()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,z.computed)({get:()=>e.value,set:n=>{r.down([[P],[E,n]])}})}function Us(r,e){let t=(0,z.shallowRef)({}),n=new Map;function o(){let i={};for(let[d,u]of n)i[d]={...u.values};t.value=i}function s(i){for(let u of n.values())for(let c of u.subs)c();n.clear();for(let u of i){let c=e(u),l=Object.keys(c),p={},h=[];for(let f of l){let m=c[f];p[f]=m.cache;let g=m.subscribe(()=>{p[f]=m.cache,o()});h.push(g)}n.set(u,{subs:h,values:p})}let d={};for(let[u,c]of n)d[u]={...c.values};t.value=d}return(0,z.watch)(()=>[...(typeof r=="function"?r():(0,z.isRef)(r)?r.value:r)??[]],i=>s(i??[]),{immediate:!0}),(0,z.getCurrentScope)()?(0,z.onScopeDispose)(()=>{for(let i of n.values())for(let d of i.subs)d();n.clear()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,z.readonly)(t)}var zn={};le(zn,{create:()=>Js});B();he();pt();var Ys=()=>!1;function Js(r){let e=new Z("zustand"),t=q(void 0,{name:"state",equals:Ys});e.add(t,{name:"state"});let n=()=>t.cache,o=(i,d)=>{let u=t.cache,c=typeof i=="function"?i(u):i;t.emit(d?c:{...u,...c})},s={getState:n,setState:o,getInitialState:()=>a,subscribe:i=>{let d=!0,u=t.cache;return t.subscribe(c=>{for(let[l,p]of c)if(l===E){if(d){d=!1;continue}i(p,u),u=p}})},destroy:e.destroy.bind(e)},a=r(o,n,s);return t.emit(a),Object.assign(e,s)}0&&(module.exports={jotai,nanostores,nestjs,react,signals,solid,svelte,vue,zustand});
80
+ // src/compat/jotai/index.ts
81
+ var jotai_exports = {};
82
+ __export(jotai_exports, {
83
+ atom: () => atom
84
+ });
85
+ var import_core = require("@graphrefly/pure-ts/core");
86
+ function atom(initialOrRead, writeOrOptions, options) {
87
+ if (typeof initialOrRead === "function") {
88
+ const read = initialOrRead;
89
+ if (typeof writeOrOptions === "function") {
90
+ return createDerivedAtom(read, writeOrOptions, options);
91
+ }
92
+ return createDerivedAtom(read, void 0, writeOrOptions);
93
+ }
94
+ return createPrimitiveAtom(initialOrRead, writeOrOptions);
95
+ }
96
+ function pull(n) {
97
+ let val = n.cache;
98
+ let err;
99
+ const unsub = n.subscribe((msgs) => {
100
+ for (const [t, v] of msgs) {
101
+ if (t === import_core.DATA) val = v;
102
+ if (t === import_core.ERROR) err = v;
103
+ }
104
+ });
105
+ unsub();
106
+ if (err) throw err;
107
+ return val;
108
+ }
109
+ function createPrimitiveAtom(initial, options) {
110
+ const n = (0, import_core.node)([], {
111
+ initial,
112
+ ...options,
113
+ resubscribable: true,
114
+ resetOnTeardown: true
115
+ });
116
+ return {
117
+ get: () => {
118
+ if (n.status === "sentinel") {
119
+ return pull(n);
120
+ }
121
+ return n.cache;
122
+ },
123
+ // Use `n.emit` (not raw `n.down`) so writes go through the framed
124
+ // emit pipeline: bundle() auto-prefixes DIRTY (diamond-safe wave
125
+ // coordination) and the equals check folds same-value writes to
126
+ // RESOLVED (no spurious subscriber fires).
127
+ set: (value) => n.emit(value),
128
+ update: (fn) => {
129
+ const current = n.status === "sentinel" ? pull(n) : n.cache;
130
+ n.emit(fn(current));
131
+ },
132
+ subscribe: (cb) => {
133
+ let initial2 = true;
134
+ return n.subscribe((msgs) => {
135
+ for (const [t, v] of msgs) {
136
+ if (t === import_core.DATA) {
137
+ if (initial2) {
138
+ initial2 = false;
139
+ continue;
140
+ }
141
+ cb(v);
142
+ }
143
+ }
144
+ });
145
+ },
146
+ meta: n.meta,
147
+ _node: n
148
+ };
149
+ }
150
+ function createDerivedAtom(read, write, options) {
151
+ const n = (0, import_core.autoTrackNode)(
152
+ (track) => read((a) => {
153
+ const dn = a._node;
154
+ if (dn.status === "sentinel") {
155
+ pull(dn);
156
+ }
157
+ return track(dn);
158
+ }),
159
+ {
160
+ ...options,
161
+ resubscribable: true,
162
+ resetOnTeardown: true,
163
+ // Jotai `atom(read)` consumers expect `read(get)` to return a
164
+ // well-typed `T`, not `undefined` from a freshly-discovered branch
165
+ // dep. Opt OUT of Lock 6.C′'s `partial:true` default — fn is
166
+ // gated until every tracked dep delivers DATA so `get(a)` always
167
+ // returns the atom's value.
168
+ partial: false
169
+ }
170
+ );
171
+ const result = {
172
+ get: () => {
173
+ if (n.status === "sentinel") {
174
+ return pull(n);
175
+ }
176
+ return n.cache;
177
+ },
178
+ subscribe: (cb) => {
179
+ let initial = true;
180
+ return n.subscribe((msgs) => {
181
+ for (const [t, v] of msgs) {
182
+ if (t === import_core.DATA) {
183
+ if (initial) {
184
+ initial = false;
185
+ continue;
186
+ }
187
+ cb(v);
188
+ }
189
+ }
190
+ });
191
+ },
192
+ meta: n.meta,
193
+ _node: n
194
+ };
195
+ if (write) {
196
+ const getFn = (a) => a.get();
197
+ const setFn = (a, value) => a.set(value);
198
+ const writable = result;
199
+ writable.set = (value) => write(getFn, setFn, value);
200
+ writable.update = (fn) => {
201
+ const current = n.status === "sentinel" ? pull(n) : n.cache;
202
+ return write(getFn, setFn, fn(current));
203
+ };
204
+ return writable;
205
+ }
206
+ return result;
207
+ }
208
+
209
+ // src/compat/nanostores/index.ts
210
+ var nanostores_exports = {};
211
+ __export(nanostores_exports, {
212
+ action: () => action,
213
+ atom: () => atom2,
214
+ computed: () => computed,
215
+ getValue: () => getValue,
216
+ map: () => map,
217
+ onMount: () => onMount,
218
+ onStart: () => onStart,
219
+ onStop: () => onStop
220
+ });
221
+ var import_core2 = require("@graphrefly/pure-ts/core");
222
+ var START_LISTENERS = /* @__PURE__ */ new WeakMap();
223
+ var STOP_LISTENERS = /* @__PURE__ */ new WeakMap();
224
+ function trigger(node7, map2) {
225
+ const callbacks = map2.get(node7);
226
+ if (callbacks) {
227
+ for (const cb of callbacks) cb();
228
+ }
229
+ }
230
+ function createStore(node7, extra = {}) {
231
+ let listeners = 0;
232
+ const store = {
233
+ ...extra,
234
+ get: () => getVal(node7),
235
+ subscribe: (cb) => {
236
+ if (listeners === 0) trigger(node7, START_LISTENERS);
237
+ listeners++;
238
+ const sub = node7.subscribe((msgs) => {
239
+ for (const [t, v] of msgs) {
240
+ if (t === import_core2.DATA) cb(v);
241
+ }
242
+ });
243
+ return () => {
244
+ sub();
245
+ listeners--;
246
+ if (listeners === 0) trigger(node7, STOP_LISTENERS);
247
+ };
248
+ },
249
+ listen: (cb) => {
250
+ if (listeners === 0) trigger(node7, START_LISTENERS);
251
+ listeners++;
252
+ let initial = true;
253
+ const sub = node7.subscribe((msgs) => {
254
+ for (const [t, v] of msgs) {
255
+ if (t === import_core2.DATA) {
256
+ if (initial) {
257
+ initial = false;
258
+ continue;
259
+ }
260
+ cb(v);
261
+ }
262
+ }
263
+ });
264
+ return () => {
265
+ sub();
266
+ listeners--;
267
+ if (listeners === 0) trigger(node7, STOP_LISTENERS);
268
+ };
269
+ },
270
+ _node: node7
271
+ };
272
+ return store;
273
+ }
274
+ function pull2(n) {
275
+ let val = n.cache;
276
+ let err;
277
+ const unsub = n.subscribe((msgs) => {
278
+ for (const [t, v] of msgs) {
279
+ if (t === import_core2.DATA) val = v;
280
+ if (t === import_core2.ERROR) err = v;
281
+ }
282
+ });
283
+ unsub();
284
+ if (err) throw err;
285
+ return val;
286
+ }
287
+ function getVal(n) {
288
+ if (n.status === "sentinel") {
289
+ return pull2(n);
290
+ }
291
+ return n.cache;
292
+ }
293
+ function atom2(initial) {
294
+ const n = (0, import_core2.node)([], {
295
+ initial,
296
+ resubscribable: true,
297
+ resetOnTeardown: true
298
+ });
299
+ return createStore(n, {
300
+ // `n.emit` routes through the framed pipeline: `bundle()` auto-
301
+ // prefixes `[DIRTY]` (diamond-safe wave coordination) and the
302
+ // node's `equals` (default `Object.is`) folds same-value writes
303
+ // into `RESOLVED`. Matches nanostores' documented Object.is
304
+ // dedup semantics without any custom check.
305
+ set: (value) => n.emit(value)
306
+ });
307
+ }
308
+ function computed(stores, fn) {
309
+ const storeArray = Array.isArray(stores) ? stores : [stores];
310
+ const depNodes = storeArray.map((s) => s._node);
311
+ const n = (0, import_core2.dynamicNode)(
312
+ depNodes,
313
+ (track) => {
314
+ const vals = storeArray.map((s) => {
315
+ const node7 = s._node;
316
+ if (node7.status === "sentinel") {
317
+ pull2(node7);
318
+ }
319
+ return track(node7);
320
+ });
321
+ return fn(...vals);
322
+ },
323
+ {
324
+ resubscribable: true,
325
+ resetOnTeardown: true,
326
+ equals: Object.is,
327
+ // nanostores `computed` calls `fn(a, b, ...)` with the resolved dep
328
+ // values; producing `undefined` for not-yet-delivered deps would
329
+ // hand `fn` arguments it never expected (e.g. `NaN` from `undefined
330
+ // + 3`). Opt OUT of Lock 6.C′'s `partial:true` default — fn is
331
+ // gated until every dep delivers DATA, matching nanostores'
332
+ // store-shaped consumer contract.
333
+ partial: false
334
+ }
335
+ );
336
+ return createStore(n);
337
+ }
338
+ function map(initial) {
339
+ const n = (0, import_core2.node)([], {
340
+ initial,
341
+ resubscribable: true,
342
+ resetOnTeardown: true,
343
+ equals: () => false
344
+ });
345
+ return createStore(n, {
346
+ // `map`'s state node is configured with `equals: () => false`
347
+ // above, so every `emit` produces DATA (even for same-key same-
348
+ // value sets). The `emit` path is still required for diamond
349
+ // coordination (`[DIRTY]` auto-prefix via `bundle()`).
350
+ set: (value) => n.emit(value),
351
+ setKey: (key, value) => {
352
+ const current = getVal(n);
353
+ n.emit({ ...current, [key]: value });
354
+ }
355
+ });
356
+ }
357
+ function getValue(store) {
358
+ return store.get();
359
+ }
360
+ function onStart(store, cb) {
361
+ const node7 = store._node;
362
+ let callbacks = START_LISTENERS.get(node7);
363
+ if (!callbacks) {
364
+ callbacks = /* @__PURE__ */ new Set();
365
+ START_LISTENERS.set(node7, callbacks);
366
+ }
367
+ callbacks.add(cb);
368
+ }
369
+ function onStop(store, cb) {
370
+ const node7 = store._node;
371
+ let callbacks = STOP_LISTENERS.get(node7);
372
+ if (!callbacks) {
373
+ callbacks = /* @__PURE__ */ new Set();
374
+ STOP_LISTENERS.set(node7, callbacks);
375
+ }
376
+ callbacks.add(cb);
377
+ }
378
+ function onMount(store, cb) {
379
+ onStart(store, () => {
380
+ const stop = cb();
381
+ if (typeof stop === "function") onStop(store, stop);
382
+ });
383
+ }
384
+ function action(_store, _name, fn) {
385
+ return (...args) => {
386
+ let result;
387
+ (0, import_core2.batch)(() => {
388
+ result = fn(...args);
389
+ });
390
+ return result;
391
+ };
392
+ }
393
+
394
+ // src/compat/nestjs/index.ts
395
+ var nestjs_exports = {};
396
+ __export(nestjs_exports, {
397
+ ACTOR_KEY: () => ACTOR_KEY,
398
+ COMMAND_HANDLERS: () => COMMAND_HANDLERS,
399
+ CQRS_EVENT_HANDLERS: () => CQRS_EVENT_HANDLERS,
400
+ CRON_HANDLERS: () => CRON_HANDLERS,
401
+ CommandHandler: () => CommandHandler,
402
+ EVENT_HANDLERS: () => EVENT_HANDLERS,
403
+ EventHandler: () => EventHandler,
404
+ GRAPHREFLY_REQUEST_GRAPH: () => GRAPHREFLY_REQUEST_GRAPH,
405
+ GRAPHREFLY_ROOT_GRAPH: () => GRAPHREFLY_ROOT_GRAPH,
406
+ GraphCron: () => GraphCron,
407
+ GraphInterval: () => GraphInterval,
408
+ GraphReflyEventExplorer: () => GraphReflyEventExplorer,
409
+ GraphReflyGuard: () => GraphReflyGuard,
410
+ GraphReflyGuardImpl: () => GraphReflyGuardImpl,
411
+ GraphReflyModule: () => GraphReflyModule,
412
+ INTERVAL_HANDLERS: () => INTERVAL_HANDLERS,
413
+ InjectCqrsGraph: () => InjectCqrsGraph,
414
+ InjectGraph: () => InjectGraph,
415
+ InjectNode: () => InjectNode,
416
+ ObserveGateway: () => ObserveGateway,
417
+ OnGraphEvent: () => OnGraphEvent,
418
+ QUERY_HANDLERS: () => QUERY_HANDLERS,
419
+ QueryHandler: () => QueryHandler,
420
+ SAGA_HANDLERS: () => SAGA_HANDLERS,
421
+ SagaHandler: () => SagaHandler,
422
+ fromHeader: () => fromHeader,
423
+ fromJwtPayload: () => fromJwtPayload,
424
+ getActor: () => getActor,
425
+ getGraphToken: () => getGraphToken,
426
+ getNodeToken: () => getNodeToken,
427
+ observeSSE: () => observeSSE,
428
+ observeSubscription: () => observeSubscription,
429
+ toObservable: () => toObservable
430
+ });
431
+
432
+ // src/base/composition/observable.ts
433
+ var import_core3 = require("@graphrefly/pure-ts/core");
434
+ var import_rxjs = require("rxjs");
435
+ function toObservable(node7, options) {
436
+ if (options?.raw) {
437
+ return new import_rxjs.Observable((subscriber) => {
438
+ const unsub = node7.subscribe((msgs) => {
439
+ if (subscriber.closed) return;
440
+ subscriber.next(msgs);
441
+ for (const m of msgs) {
442
+ if (m[0] === import_core3.ERROR) {
443
+ subscriber.error(m[1]);
444
+ return;
445
+ }
446
+ if (m[0] === import_core3.COMPLETE) {
447
+ subscriber.complete();
448
+ return;
449
+ }
450
+ }
451
+ });
452
+ return unsub;
453
+ });
454
+ }
455
+ return new import_rxjs.Observable((subscriber) => {
456
+ const unsub = node7.subscribe((msgs) => {
457
+ for (const m of msgs) {
458
+ if (subscriber.closed) return;
459
+ if (m[0] === import_core3.DATA) {
460
+ subscriber.next(m[1]);
461
+ } else if (m[0] === import_core3.ERROR) {
462
+ subscriber.error(m[1]);
463
+ return;
464
+ } else if (m[0] === import_core3.COMPLETE) {
465
+ subscriber.complete();
466
+ return;
467
+ }
468
+ }
469
+ });
470
+ return unsub;
471
+ });
472
+ }
473
+
474
+ // src/compat/nestjs/decorators.ts
475
+ var import_common = require("@nestjs/common");
476
+
477
+ // src/compat/nestjs/tokens.ts
478
+ var GRAPHREFLY_ROOT_GRAPH = /* @__PURE__ */ Symbol.for("graphrefly:root-graph");
479
+ var GRAPHREFLY_REQUEST_GRAPH = /* @__PURE__ */ Symbol.for("graphrefly:request-graph");
480
+ function getGraphToken(name) {
481
+ return /* @__PURE__ */ Symbol.for(`graphrefly:graph:${name}`);
482
+ }
483
+ function getNodeToken(path) {
484
+ return /* @__PURE__ */ Symbol.for(`graphrefly:node:${path}`);
485
+ }
486
+
487
+ // src/compat/nestjs/decorators.ts
488
+ var EVENT_HANDLERS = /* @__PURE__ */ new Map();
489
+ var INTERVAL_HANDLERS = /* @__PURE__ */ new Map();
490
+ var CRON_HANDLERS = /* @__PURE__ */ new Map();
491
+ var COMMAND_HANDLERS = /* @__PURE__ */ new Map();
492
+ var CQRS_EVENT_HANDLERS = /* @__PURE__ */ new Map();
493
+ var QUERY_HANDLERS = /* @__PURE__ */ new Map();
494
+ var SAGA_HANDLERS = /* @__PURE__ */ new Map();
495
+ function InjectGraph(name) {
496
+ if (name === "request") return (0, import_common.Inject)(GRAPHREFLY_REQUEST_GRAPH);
497
+ return (0, import_common.Inject)(name ? getGraphToken(name) : GRAPHREFLY_ROOT_GRAPH);
498
+ }
499
+ function InjectCqrsGraph(name) {
500
+ return (0, import_common.Inject)(getGraphToken(name));
501
+ }
502
+ function InjectNode(path) {
503
+ return (0, import_common.Inject)(getNodeToken(path));
504
+ }
505
+ function OnGraphEvent(nodeName) {
506
+ return (_value, context) => {
507
+ const methodKey = context.name;
508
+ context.addInitializer(function() {
509
+ const ctor = this.constructor;
510
+ const existing = EVENT_HANDLERS.get(ctor) ?? [];
511
+ existing.push({ nodeName, methodKey });
512
+ EVENT_HANDLERS.set(ctor, existing);
513
+ });
514
+ };
515
+ }
516
+ function GraphInterval(ms) {
517
+ return (_value, context) => {
518
+ const methodKey = context.name;
519
+ context.addInitializer(function() {
520
+ const ctor = this.constructor;
521
+ const existing = INTERVAL_HANDLERS.get(ctor) ?? [];
522
+ existing.push({ ms, methodKey });
523
+ INTERVAL_HANDLERS.set(ctor, existing);
524
+ });
525
+ };
526
+ }
527
+ function GraphCron(expr) {
528
+ return (_value, context) => {
529
+ const methodKey = context.name;
530
+ context.addInitializer(function() {
531
+ const ctor = this.constructor;
532
+ const existing = CRON_HANDLERS.get(ctor) ?? [];
533
+ existing.push({ expr, methodKey });
534
+ CRON_HANDLERS.set(ctor, existing);
535
+ });
536
+ };
537
+ }
538
+ function CommandHandler(cqrsName, commandName) {
539
+ return (_value, context) => {
540
+ const methodKey = context.name;
541
+ context.addInitializer(function() {
542
+ const ctor = this.constructor;
543
+ const existing = COMMAND_HANDLERS.get(ctor) ?? [];
544
+ existing.push({ cqrsName, commandName, methodKey });
545
+ COMMAND_HANDLERS.set(ctor, existing);
546
+ });
547
+ };
548
+ }
549
+ function EventHandler(cqrsName, eventName) {
550
+ return (_value, context) => {
551
+ const methodKey = context.name;
552
+ context.addInitializer(function() {
553
+ const ctor = this.constructor;
554
+ const existing = CQRS_EVENT_HANDLERS.get(ctor) ?? [];
555
+ existing.push({ cqrsName, eventName, methodKey });
556
+ CQRS_EVENT_HANDLERS.set(ctor, existing);
557
+ });
558
+ };
559
+ }
560
+ function QueryHandler(cqrsName, projectionName) {
561
+ return (_value, context) => {
562
+ const methodKey = context.name;
563
+ context.addInitializer(function() {
564
+ const ctor = this.constructor;
565
+ const existing = QUERY_HANDLERS.get(ctor) ?? [];
566
+ existing.push({ cqrsName, projectionName, methodKey });
567
+ QUERY_HANDLERS.set(ctor, existing);
568
+ });
569
+ };
570
+ }
571
+ function SagaHandler(cqrsName, sagaName, eventNames) {
572
+ return (_value, context) => {
573
+ const methodKey = context.name;
574
+ context.addInitializer(function() {
575
+ const ctor = this.constructor;
576
+ const existing = SAGA_HANDLERS.get(ctor) ?? [];
577
+ existing.push({ cqrsName, eventNames, sagaName, methodKey });
578
+ SAGA_HANDLERS.set(ctor, existing);
579
+ });
580
+ };
581
+ }
582
+
583
+ // src/compat/nestjs/explorer.ts
584
+ var import_core5 = require("@graphrefly/pure-ts/core");
585
+ var import_extra = require("@graphrefly/pure-ts/extra");
586
+
587
+ // src/base/sources/event/cron.ts
588
+ var import_core4 = require("@graphrefly/pure-ts/core");
589
+ function sourceOpts(opts) {
590
+ return { describeKind: "producer", ...opts };
591
+ }
592
+ function parseField(field, min, max) {
593
+ const result = /* @__PURE__ */ new Set();
594
+ for (const part of field.split(",")) {
595
+ const [range, stepStr] = part.split("/");
596
+ const step = stepStr ? Number.parseInt(stepStr, 10) : 1;
597
+ if (Number.isNaN(step) || step < 1) throw new Error(`Invalid cron step: ${part}`);
598
+ let start;
599
+ let end;
600
+ if (range === "*") {
601
+ start = min;
602
+ end = max;
603
+ } else if (range.includes("-")) {
604
+ const [a, b] = range.split("-");
605
+ start = Number.parseInt(a, 10);
606
+ end = Number.parseInt(b, 10);
607
+ } else {
608
+ start = Number.parseInt(range, 10);
609
+ end = start;
610
+ }
611
+ if (Number.isNaN(start) || Number.isNaN(end)) throw new Error(`Invalid cron field: ${field}`);
612
+ if (start < min || end > max)
613
+ throw new Error(`Cron field out of range: ${field} (${min}-${max})`);
614
+ if (start > end) throw new Error(`Invalid cron range: ${start}-${end} in ${field}`);
615
+ for (let i = start; i <= end; i += step) result.add(i);
616
+ }
617
+ return result;
618
+ }
619
+ function parseCron(expr) {
620
+ const parts = expr.trim().split(/\s+/);
621
+ if (parts.length !== 5) throw new Error(`Invalid cron: expected 5 fields, got ${parts.length}`);
622
+ return {
623
+ minutes: parseField(parts[0], 0, 59),
624
+ hours: parseField(parts[1], 0, 23),
625
+ daysOfMonth: parseField(parts[2], 1, 31),
626
+ months: parseField(parts[3], 1, 12),
627
+ daysOfWeek: parseField(parts[4], 0, 6)
628
+ };
629
+ }
630
+ function matchesCron(schedule, date) {
631
+ return schedule.minutes.has(date.getMinutes()) && schedule.hours.has(date.getHours()) && schedule.daysOfMonth.has(date.getDate()) && schedule.months.has(date.getMonth() + 1) && schedule.daysOfWeek.has(date.getDay());
632
+ }
633
+ function fromCron(expr, opts) {
634
+ const schedule = parseCron(expr);
635
+ const { tickMs: tickOpt, output, ...rest } = opts ?? {};
636
+ const tickMs = tickOpt ?? 6e4;
637
+ const emitDate = output === "date";
638
+ return (0, import_core4.node)(
639
+ (_data, a) => {
640
+ let lastFiredKey = -1;
641
+ const check = () => {
642
+ const now = /* @__PURE__ */ new Date();
643
+ const key = now.getFullYear() * 1e8 + (now.getMonth() + 1) * 1e6 + now.getDate() * 1e4 + now.getHours() * 100 + now.getMinutes();
644
+ if (key !== lastFiredKey && matchesCron(schedule, now)) {
645
+ lastFiredKey = key;
646
+ a.emit(emitDate ? now : (0, import_core4.wallClockNs)());
647
+ }
648
+ };
649
+ check();
650
+ const id = setInterval(check, tickMs);
651
+ return () => clearInterval(id);
652
+ },
653
+ { ...sourceOpts(rest), name: rest.name ?? `cron:${expr}` }
654
+ );
655
+ }
656
+
657
+ // src/compat/nestjs/explorer.ts
658
+ var scheduleSeq = 0;
659
+ var GraphReflyEventExplorer = class {
660
+ constructor(graph, moduleRef) {
661
+ this.graph = graph;
662
+ this.moduleRef = moduleRef;
663
+ }
664
+ disposers = [];
665
+ scheduleNodeNames = [];
666
+ onModuleInit() {
667
+ this.wireEvents();
668
+ this.wireIntervals();
669
+ this.wireCrons();
670
+ this.wireCqrsCommands();
671
+ this.wireCqrsEvents();
672
+ this.wireCqrsQueries();
673
+ this.wireCqrsSagas();
674
+ }
675
+ onModuleDestroy() {
676
+ for (const dispose of this.disposers) dispose();
677
+ this.disposers.length = 0;
678
+ for (const name of this.scheduleNodeNames) {
679
+ try {
680
+ this.graph.remove(name);
681
+ } catch {
682
+ }
683
+ }
684
+ this.scheduleNodeNames.length = 0;
685
+ }
686
+ // -----------------------------------------------------------------------
687
+ // @OnGraphEvent — reactive subscription via graph.observe()
688
+ // -----------------------------------------------------------------------
689
+ wireEvents() {
690
+ for (const [ctor, metas] of EVENT_HANDLERS) {
691
+ const instance = this.resolveInstance(ctor);
692
+ if (!instance) continue;
693
+ for (const meta of metas) {
694
+ this.wireEventHandler(instance, meta);
695
+ }
696
+ }
697
+ }
698
+ wireEventHandler(instance, meta) {
699
+ const method = instance[meta.methodKey];
700
+ if (typeof method !== "function") return;
701
+ const bound = method.bind(instance);
702
+ const handle = this.observeNode(meta.nodeName);
703
+ const unsub = handle.subscribe((msgs) => {
704
+ for (const m of msgs) {
705
+ if (m[0] === import_core5.DATA) {
706
+ bound(m[1]);
707
+ }
708
+ }
709
+ });
710
+ this.disposers.push(unsub);
711
+ }
712
+ // -----------------------------------------------------------------------
713
+ // @GraphInterval — reactive via fromTimer central timer primitive
714
+ // -----------------------------------------------------------------------
715
+ wireIntervals() {
716
+ for (const [ctor, metas] of INTERVAL_HANDLERS) {
717
+ const instance = this.resolveInstance(ctor);
718
+ if (!instance) continue;
719
+ for (const meta of metas) {
720
+ this.wireIntervalHandler(instance, ctor, meta);
721
+ }
722
+ }
723
+ }
724
+ wireIntervalHandler(instance, ctor, meta) {
725
+ const method = instance[meta.methodKey];
726
+ if (typeof method !== "function") return;
727
+ const bound = method.bind(instance);
728
+ const className = ctor.name ?? "anonymous";
729
+ const nodeName = `__schedule__.${className}.${String(meta.methodKey)}.${scheduleSeq++}`;
730
+ const timerNode = (0, import_extra.fromTimer)(meta.ms, { period: meta.ms, name: nodeName });
731
+ this.graph.add(timerNode);
732
+ this.scheduleNodeNames.push(nodeName);
733
+ const handle = this.observeNode(nodeName);
734
+ const unsub = handle.subscribe((msgs) => {
735
+ for (const m of msgs) {
736
+ if (m[0] === import_core5.DATA) bound(m[1]);
737
+ }
738
+ });
739
+ this.disposers.push(unsub);
740
+ }
741
+ // -----------------------------------------------------------------------
742
+ // @GraphCron — reactive via fromCron central timer primitive
743
+ // -----------------------------------------------------------------------
744
+ wireCrons() {
745
+ for (const [ctor, metas] of CRON_HANDLERS) {
746
+ const instance = this.resolveInstance(ctor);
747
+ if (!instance) continue;
748
+ for (const meta of metas) {
749
+ this.wireCronHandler(instance, ctor, meta);
750
+ }
751
+ }
752
+ }
753
+ wireCronHandler(instance, ctor, meta) {
754
+ const method = instance[meta.methodKey];
755
+ if (typeof method !== "function") return;
756
+ const bound = method.bind(instance);
757
+ const className = ctor.name ?? "anonymous";
758
+ const nodeName = `__schedule__.${className}.${String(meta.methodKey)}.${scheduleSeq++}`;
759
+ const cronNode = fromCron(meta.expr, { name: nodeName });
760
+ this.graph.add(cronNode);
761
+ this.scheduleNodeNames.push(nodeName);
762
+ const handle = this.observeNode(nodeName);
763
+ const unsub = handle.subscribe((msgs) => {
764
+ for (const m of msgs) {
765
+ if (m[0] === import_core5.DATA) bound(m[1]);
766
+ }
767
+ });
768
+ this.disposers.push(unsub);
769
+ }
770
+ // -----------------------------------------------------------------------
771
+ // @CommandHandler — register method as CqrsGraph command handler
772
+ // -----------------------------------------------------------------------
773
+ wireCqrsCommands() {
774
+ for (const [ctor, metas] of COMMAND_HANDLERS) {
775
+ const instance = this.resolveInstance(ctor);
776
+ if (!instance) continue;
777
+ for (const meta of metas) {
778
+ this.wireCqrsCommand(instance, meta);
779
+ }
780
+ }
781
+ }
782
+ wireCqrsCommand(instance, meta) {
783
+ const method = instance[meta.methodKey];
784
+ if (typeof method !== "function") return;
785
+ const bound = method.bind(instance);
786
+ const cqrsGraph = this.resolveCqrsGraph(meta.cqrsName);
787
+ if (!cqrsGraph) return;
788
+ cqrsGraph.command(meta.commandName, bound);
789
+ }
790
+ // -----------------------------------------------------------------------
791
+ // @EventHandler — subscribe method to CQRS event stream
792
+ // -----------------------------------------------------------------------
793
+ wireCqrsEvents() {
794
+ for (const [ctor, metas] of CQRS_EVENT_HANDLERS) {
795
+ const instance = this.resolveInstance(ctor);
796
+ if (!instance) continue;
797
+ for (const meta of metas) {
798
+ this.wireCqrsEventHandler(instance, meta);
799
+ }
800
+ }
801
+ }
802
+ wireCqrsEventHandler(instance, meta) {
803
+ const method = instance[meta.methodKey];
804
+ if (typeof method !== "function") return;
805
+ const bound = method.bind(instance);
806
+ const cqrsGraph = this.resolveCqrsGraph(meta.cqrsName);
807
+ if (!cqrsGraph) return;
808
+ cqrsGraph.event(meta.eventName);
809
+ const eventNode = cqrsGraph.resolve(meta.eventName);
810
+ const existingEntries = eventNode.cache;
811
+ let lastSeq = existingEntries && existingEntries.length > 0 ? existingEntries[existingEntries.length - 1].seq : 0;
812
+ const handle = this.observeNodeOn(cqrsGraph, meta.eventName);
813
+ const unsub = handle.subscribe((msgs) => {
814
+ for (const m of msgs) {
815
+ if (m[0] === import_core5.DATA) {
816
+ const entries = m[1];
817
+ for (const entry of entries) {
818
+ if (entry.seq > lastSeq) {
819
+ bound(entry);
820
+ lastSeq = entry.seq;
821
+ }
822
+ }
823
+ }
824
+ }
825
+ });
826
+ this.disposers.push(unsub);
827
+ }
828
+ // -----------------------------------------------------------------------
829
+ // @QueryHandler — subscribe method to CQRS projection changes
830
+ // -----------------------------------------------------------------------
831
+ wireCqrsQueries() {
832
+ for (const [ctor, metas] of QUERY_HANDLERS) {
833
+ const instance = this.resolveInstance(ctor);
834
+ if (!instance) continue;
835
+ for (const meta of metas) {
836
+ this.wireCqrsQuery(instance, meta);
837
+ }
838
+ }
839
+ }
840
+ wireCqrsQuery(instance, meta) {
841
+ const method = instance[meta.methodKey];
842
+ if (typeof method !== "function") return;
843
+ const bound = method.bind(instance);
844
+ const cqrsGraph = this.resolveCqrsGraph(meta.cqrsName);
845
+ if (!cqrsGraph) return;
846
+ const handle = this.observeNodeOn(cqrsGraph, meta.projectionName);
847
+ const unsub = handle.subscribe((msgs) => {
848
+ for (const m of msgs) {
849
+ if (m[0] === import_core5.DATA) {
850
+ bound(m[1]);
851
+ }
852
+ }
853
+ });
854
+ this.disposers.push(unsub);
855
+ }
856
+ // -----------------------------------------------------------------------
857
+ // @SagaHandler — register method as CqrsGraph saga (subgraph side effect)
858
+ // -----------------------------------------------------------------------
859
+ wireCqrsSagas() {
860
+ for (const [ctor, metas] of SAGA_HANDLERS) {
861
+ const instance = this.resolveInstance(ctor);
862
+ if (!instance) continue;
863
+ for (const meta of metas) {
864
+ this.wireCqrsSaga(instance, meta);
865
+ }
866
+ }
867
+ }
868
+ wireCqrsSaga(instance, meta) {
869
+ const method = instance[meta.methodKey];
870
+ if (typeof method !== "function") return;
871
+ const bound = method.bind(instance);
872
+ const cqrsGraph = this.resolveCqrsGraph(meta.cqrsName);
873
+ if (!cqrsGraph) return;
874
+ cqrsGraph.saga(meta.sagaName, meta.eventNames, bound);
875
+ }
876
+ // -----------------------------------------------------------------------
877
+ // Helpers
878
+ // -----------------------------------------------------------------------
879
+ observeNode(name) {
880
+ return this.graph.observe(name);
881
+ }
882
+ observeNodeOn(graph, name) {
883
+ return graph.observe(name);
884
+ }
885
+ resolveCqrsGraph(name) {
886
+ try {
887
+ return this.moduleRef.get(getGraphToken(name), { strict: false });
888
+ } catch {
889
+ console.warn(
890
+ `[GraphReFly] CqrsGraph "${name}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${name}" })?`
891
+ );
892
+ return null;
893
+ }
894
+ }
895
+ resolveInstance(ctor) {
896
+ try {
897
+ return this.moduleRef.get(ctor, { strict: false });
898
+ } catch {
899
+ return null;
900
+ }
901
+ }
902
+ };
903
+
904
+ // src/compat/nestjs/gateway.ts
905
+ var import_core7 = require("@graphrefly/pure-ts/core");
906
+
907
+ // src/base/composition/backpressure.ts
908
+ var import_core6 = require("@graphrefly/pure-ts/core");
909
+ var nextLockId = 0;
910
+ function createWatermarkController(sendUp, opts) {
911
+ if (opts.highWaterMark < 1) throw new RangeError("highWaterMark must be >= 1");
912
+ if (opts.lowWaterMark < 0) throw new RangeError("lowWaterMark must be >= 0");
913
+ if (opts.lowWaterMark >= opts.highWaterMark)
914
+ throw new RangeError("lowWaterMark must be < highWaterMark");
915
+ const lockId = /* @__PURE__ */ Symbol(`bp-${++nextLockId}`);
916
+ let pending = 0;
917
+ let paused = false;
918
+ return {
919
+ onEnqueue() {
920
+ pending += 1;
921
+ if (!paused && pending >= opts.highWaterMark) {
922
+ paused = true;
923
+ sendUp([[import_core6.PAUSE, lockId]]);
924
+ return true;
925
+ }
926
+ return false;
927
+ },
928
+ onDequeue() {
929
+ if (pending > 0) pending -= 1;
930
+ if (paused && pending <= opts.lowWaterMark) {
931
+ paused = false;
932
+ sendUp([[import_core6.RESUME, lockId]]);
933
+ return true;
934
+ }
935
+ return false;
936
+ },
937
+ get pending() {
938
+ return pending;
939
+ },
940
+ get paused() {
941
+ return paused;
942
+ },
943
+ dispose() {
944
+ if (paused) {
945
+ paused = false;
946
+ sendUp([[import_core6.RESUME, lockId]]);
947
+ }
948
+ }
949
+ };
950
+ }
951
+
952
+ // src/compat/nestjs/gateway.ts
953
+ function observeSSE(graph, path, opts) {
954
+ const { actor, serialize = defaultSerialize, keepAliveMs, signal } = opts ?? {};
955
+ const encoder = new TextEncoder();
956
+ let stop;
957
+ const useBackpressure = opts?.highWaterMark != null;
958
+ let wm;
959
+ let pullResolve;
960
+ const taggedBuf = [];
961
+ let closed = false;
962
+ return new ReadableStream({
963
+ start(controller) {
964
+ let keepAlive;
965
+ let unsub = () => {
966
+ };
967
+ const close = () => {
968
+ if (closed) return;
969
+ closed = true;
970
+ if (keepAlive !== void 0) clearInterval(keepAlive);
971
+ signal?.removeEventListener("abort", onAbort);
972
+ unsub();
973
+ wm?.dispose();
974
+ pullResolve?.();
975
+ pullResolve = void 0;
976
+ for (const entry of taggedBuf) controller.enqueue(entry.frame);
977
+ taggedBuf.length = 0;
978
+ controller.close();
979
+ };
980
+ stop = close;
981
+ const onAbort = () => close();
982
+ const handle = graph.observe(path, { actor });
983
+ if (useBackpressure) {
984
+ wm = createWatermarkController((msgs) => handle.up(msgs), {
985
+ highWaterMark: opts.highWaterMark,
986
+ lowWaterMark: opts.lowWaterMark ?? Math.floor(opts.highWaterMark / 2)
987
+ });
988
+ }
989
+ unsub = handle.subscribe((msgs) => {
990
+ for (const msg of msgs) {
991
+ if (closed) return;
992
+ const t = msg[0];
993
+ if (t === import_core7.DATA) {
994
+ const frame = encoder.encode(sseFrame("data", serialize(msg[1])));
995
+ if (useBackpressure) {
996
+ taggedBuf.push({ frame, counted: true });
997
+ wm.onEnqueue();
998
+ pullResolve?.();
999
+ pullResolve = void 0;
1000
+ } else {
1001
+ controller.enqueue(frame);
1002
+ }
1003
+ } else if (t === import_core7.ERROR) {
1004
+ const frame = encoder.encode(sseFrame("error", serialize(msg[1])));
1005
+ if (useBackpressure) {
1006
+ taggedBuf.push({ frame, counted: false });
1007
+ pullResolve?.();
1008
+ pullResolve = void 0;
1009
+ } else {
1010
+ controller.enqueue(frame);
1011
+ }
1012
+ close();
1013
+ return;
1014
+ } else if (t === import_core7.COMPLETE || t === import_core7.TEARDOWN) {
1015
+ if (t === import_core7.COMPLETE) {
1016
+ const frame = encoder.encode(sseFrame("complete"));
1017
+ if (useBackpressure) {
1018
+ taggedBuf.push({ frame, counted: false });
1019
+ pullResolve?.();
1020
+ pullResolve = void 0;
1021
+ } else {
1022
+ controller.enqueue(frame);
1023
+ }
1024
+ }
1025
+ close();
1026
+ return;
1027
+ }
1028
+ }
1029
+ });
1030
+ if (keepAliveMs !== void 0 && keepAliveMs > 0) {
1031
+ keepAlive = setInterval(() => {
1032
+ if (closed) return;
1033
+ if (useBackpressure) {
1034
+ taggedBuf.push({ frame: encoder.encode(": keepalive\n\n"), counted: false });
1035
+ pullResolve?.();
1036
+ pullResolve = void 0;
1037
+ } else {
1038
+ controller.enqueue(encoder.encode(": keepalive\n\n"));
1039
+ }
1040
+ }, keepAliveMs);
1041
+ }
1042
+ if (signal?.aborted) onAbort();
1043
+ else signal?.addEventListener("abort", onAbort, { once: true });
1044
+ },
1045
+ pull(controller) {
1046
+ if (!useBackpressure) return;
1047
+ if (closed) return;
1048
+ if (taggedBuf.length > 0) {
1049
+ const entry = taggedBuf.shift();
1050
+ controller.enqueue(entry.frame);
1051
+ if (entry.counted) wm.onDequeue();
1052
+ return;
1053
+ }
1054
+ return new Promise((resolve) => {
1055
+ pullResolve = resolve;
1056
+ });
1057
+ },
1058
+ cancel() {
1059
+ try {
1060
+ stop?.();
1061
+ } catch {
1062
+ }
1063
+ }
1064
+ });
1065
+ }
1066
+ function observeSubscription(graph, path, opts) {
1067
+ const { actor, filter } = opts ?? {};
1068
+ const queue = [];
1069
+ const waiters = [];
1070
+ let disposed = false;
1071
+ const handle = graph.observe(path, { actor });
1072
+ const wm = opts?.highWaterMark != null ? createWatermarkController((msgs) => handle.up(msgs), {
1073
+ highWaterMark: opts.highWaterMark,
1074
+ lowWaterMark: opts.lowWaterMark ?? Math.floor(opts.highWaterMark / 2)
1075
+ }) : void 0;
1076
+ const dispose = () => {
1077
+ if (disposed) return;
1078
+ disposed = true;
1079
+ wm?.dispose();
1080
+ unsub();
1081
+ };
1082
+ const push = (item) => {
1083
+ if (disposed) return;
1084
+ if (waiters.length > 0) {
1085
+ const w = waiters.shift();
1086
+ if (item.done && item.error) w.reject(item.error);
1087
+ else if (item.done) w.resolve({ done: true, value: void 0 });
1088
+ else w.resolve({ done: false, value: item.value });
1089
+ } else {
1090
+ queue.push(item);
1091
+ if (!item.done) wm?.onEnqueue();
1092
+ }
1093
+ };
1094
+ const unsub = handle.subscribe((msgs) => {
1095
+ for (const msg of msgs) {
1096
+ const t = msg[0];
1097
+ if (t === import_core7.DATA) {
1098
+ const value = msg[1];
1099
+ if (filter && !filter(value)) continue;
1100
+ push({ done: false, value });
1101
+ } else if (t === import_core7.ERROR) {
1102
+ const err = msg[1] instanceof Error ? msg[1] : new Error(String(msg[1]));
1103
+ push({ done: true, error: err });
1104
+ dispose();
1105
+ return;
1106
+ } else if (t === import_core7.COMPLETE || t === import_core7.TEARDOWN) {
1107
+ push({ done: true });
1108
+ dispose();
1109
+ return;
1110
+ }
1111
+ }
1112
+ });
1113
+ const iterator = {
1114
+ next() {
1115
+ if (queue.length > 0) {
1116
+ const item = queue.shift();
1117
+ if (!item.done) wm?.onDequeue();
1118
+ if (item.done && item.error) return Promise.reject(item.error);
1119
+ return Promise.resolve(
1120
+ item.done ? { done: true, value: void 0 } : { done: false, value: item.value }
1121
+ );
1122
+ }
1123
+ if (disposed) return Promise.resolve({ done: true, value: void 0 });
1124
+ return new Promise((resolve, reject) => {
1125
+ waiters.push({ resolve, reject });
1126
+ });
1127
+ },
1128
+ return() {
1129
+ dispose();
1130
+ for (const w of waiters) w.resolve({ done: true, value: void 0 });
1131
+ waiters.length = 0;
1132
+ return Promise.resolve({ done: true, value: void 0 });
1133
+ },
1134
+ throw(err) {
1135
+ dispose();
1136
+ return Promise.reject(err);
1137
+ },
1138
+ [Symbol.asyncIterator]() {
1139
+ return this;
1140
+ }
1141
+ };
1142
+ return iterator;
1143
+ }
1144
+ var ObserveGateway = class {
1145
+ constructor(graph, opts) {
1146
+ this.graph = graph;
1147
+ this.extractActor = opts?.extractActor ?? (() => void 0);
1148
+ this.parse = opts?.parse ?? defaultParseCommand;
1149
+ this.highWaterMark = opts?.highWaterMark;
1150
+ this.lowWaterMark = opts?.lowWaterMark;
1151
+ }
1152
+ clients = /* @__PURE__ */ new Map();
1153
+ extractActor;
1154
+ parse;
1155
+ highWaterMark;
1156
+ lowWaterMark;
1157
+ /**
1158
+ * Register a new client. Call from `handleConnection`.
1159
+ */
1160
+ handleConnection(client) {
1161
+ if (!this.clients.has(client)) {
1162
+ this.clients.set(client, /* @__PURE__ */ new Map());
1163
+ }
1164
+ }
1165
+ /**
1166
+ * Unregister a client and dispose all its subscriptions. Call from `handleDisconnect`.
1167
+ */
1168
+ handleDisconnect(client) {
1169
+ const subs = this.clients.get(client);
1170
+ if (!subs) return;
1171
+ for (const entry of subs.values()) {
1172
+ entry.wm?.dispose();
1173
+ entry.unsub();
1174
+ }
1175
+ this.clients.delete(client);
1176
+ }
1177
+ /**
1178
+ * Handle an incoming client message (subscribe/unsubscribe/ack command).
1179
+ *
1180
+ * @param client - The WebSocket client reference.
1181
+ * @param raw - Raw message data (string or parsed object).
1182
+ * @param send - Function to send a message back to the client.
1183
+ * Defaults to `client.send(JSON.stringify(msg))`.
1184
+ */
1185
+ handleMessage(client, raw, send) {
1186
+ const sender = send ?? defaultSend.bind(null, client);
1187
+ let cmd;
1188
+ try {
1189
+ cmd = typeof raw === "string" ? this.parse(raw) : raw;
1190
+ } catch {
1191
+ sender({ type: "err", message: "invalid command" });
1192
+ return;
1193
+ }
1194
+ if (cmd.type === "subscribe") {
1195
+ this.subscribe(client, cmd.path, sender);
1196
+ } else if (cmd.type === "unsubscribe") {
1197
+ this.unsubscribe(client, cmd.path, sender);
1198
+ } else if (cmd.type === "ack") {
1199
+ this.ack(client, cmd.path, cmd.count ?? 1);
1200
+ } else {
1201
+ sender({ type: "err", message: `unknown command type: ${cmd.type}` });
1202
+ }
1203
+ }
1204
+ /**
1205
+ * Number of active subscriptions for a client. Useful for tests.
1206
+ */
1207
+ subscriptionCount(client) {
1208
+ return this.clients.get(client)?.size ?? 0;
1209
+ }
1210
+ /**
1211
+ * Dispose all clients and subscriptions.
1212
+ */
1213
+ destroy() {
1214
+ for (const [client] of this.clients) {
1215
+ this.handleDisconnect(client);
1216
+ }
1217
+ }
1218
+ // -----------------------------------------------------------------------
1219
+ // Internal
1220
+ // -----------------------------------------------------------------------
1221
+ subscribe(client, path, send) {
1222
+ let subs = this.clients.get(client);
1223
+ if (!subs) {
1224
+ subs = /* @__PURE__ */ new Map();
1225
+ this.clients.set(client, subs);
1226
+ }
1227
+ if (subs.has(path)) {
1228
+ send({ type: "subscribed", path });
1229
+ return;
1230
+ }
1231
+ const actor = this.extractActor(client);
1232
+ let handle;
1233
+ try {
1234
+ handle = this.graph.observe(path, { actor });
1235
+ } catch (err) {
1236
+ const message = err instanceof Error ? err.message : String(err);
1237
+ send({ type: "err", message });
1238
+ return;
1239
+ }
1240
+ const wm = this.highWaterMark != null ? createWatermarkController((msgs) => handle.up(msgs), {
1241
+ highWaterMark: this.highWaterMark,
1242
+ lowWaterMark: this.lowWaterMark ?? Math.floor(this.highWaterMark / 2)
1243
+ }) : void 0;
1244
+ const cleanup = () => {
1245
+ wm?.dispose();
1246
+ unsub();
1247
+ subs.delete(path);
1248
+ };
1249
+ const unsub = handle.subscribe((msgs) => {
1250
+ for (const msg of msgs) {
1251
+ const t = msg[0];
1252
+ if (t === import_core7.DATA) {
1253
+ wm?.onEnqueue();
1254
+ trySend(send, { type: "data", path, value: msg[1] });
1255
+ } else if (t === import_core7.ERROR) {
1256
+ const errMsg = msg[1] instanceof Error ? msg[1].message : String(msg[1]);
1257
+ trySend(send, { type: "error", path, error: errMsg });
1258
+ cleanup();
1259
+ return;
1260
+ } else if (t === import_core7.COMPLETE || t === import_core7.TEARDOWN) {
1261
+ trySend(send, { type: "complete", path });
1262
+ cleanup();
1263
+ return;
1264
+ }
1265
+ }
1266
+ });
1267
+ subs.set(path, { unsub, wm });
1268
+ send({ type: "subscribed", path });
1269
+ }
1270
+ unsubscribe(client, path, send) {
1271
+ const subs = this.clients.get(client);
1272
+ const entry = subs?.get(path);
1273
+ if (entry) {
1274
+ entry.wm?.dispose();
1275
+ entry.unsub();
1276
+ subs.delete(path);
1277
+ }
1278
+ send({ type: "unsubscribed", path });
1279
+ }
1280
+ ack(client, path, count) {
1281
+ const entry = this.clients.get(client)?.get(path);
1282
+ if (!entry?.wm) return;
1283
+ const n = Math.min(Math.max(0, Math.floor(count)), 1024);
1284
+ for (let i = 0; i < n; i++) entry.wm.onDequeue();
1285
+ }
1286
+ };
1287
+ function defaultSerialize(value) {
1288
+ if (value instanceof Error) return value.message;
1289
+ try {
1290
+ return JSON.stringify(value);
1291
+ } catch {
1292
+ return String(value);
1293
+ }
1294
+ }
1295
+ function sseFrame(event, data) {
1296
+ let frame = `event: ${event}
1297
+ `;
1298
+ if (data !== void 0) {
1299
+ for (const line of data.split("\n")) {
1300
+ frame += `data: ${line}
1301
+ `;
1302
+ }
1303
+ }
1304
+ frame += "\n";
1305
+ return frame;
1306
+ }
1307
+ function defaultParseCommand(data) {
1308
+ return JSON.parse(data);
1309
+ }
1310
+ function defaultSend(client, msg) {
1311
+ try {
1312
+ client.send(JSON.stringify(msg));
1313
+ } catch {
1314
+ }
1315
+ }
1316
+ function trySend(send, msg) {
1317
+ try {
1318
+ send(msg);
1319
+ } catch {
1320
+ }
1321
+ }
1322
+
1323
+ // src/compat/nestjs/guard.ts
1324
+ var import_core8 = require("@graphrefly/pure-ts/core");
1325
+ var ACTOR_KEY = "graphReflyActor";
1326
+ function fromJwtPayload(mapping) {
1327
+ return (context) => {
1328
+ const req = context.switchToHttp().getRequest();
1329
+ const user = req?.user;
1330
+ if (user == null) return void 0;
1331
+ if (mapping) return mapping(user);
1332
+ return user;
1333
+ };
1334
+ }
1335
+ function fromHeader(headerName = "x-graphrefly-actor") {
1336
+ return (context) => {
1337
+ const req = context.switchToHttp().getRequest();
1338
+ const raw = req?.headers?.[headerName.toLowerCase()];
1339
+ if (typeof raw !== "string" || raw.length === 0) return void 0;
1340
+ try {
1341
+ return JSON.parse(raw);
1342
+ } catch {
1343
+ return void 0;
1344
+ }
1345
+ };
1346
+ }
1347
+ function getActor(req) {
1348
+ const actor = req?.[ACTOR_KEY];
1349
+ return actor != null ? (0, import_core8.normalizeActor)(actor) : import_core8.DEFAULT_ACTOR;
1350
+ }
1351
+ var GraphReflyGuardImpl = class {
1352
+ constructor(extractor) {
1353
+ this.extractor = extractor;
1354
+ }
1355
+ canActivate(context) {
1356
+ const actor = (0, import_core8.normalizeActor)(this.extractor(context));
1357
+ const req = context.switchToHttp().getRequest();
1358
+ if (req != null) {
1359
+ req[ACTOR_KEY] = actor;
1360
+ }
1361
+ return true;
1362
+ }
1363
+ };
1364
+ function GraphReflyGuard(extractor) {
1365
+ return new GraphReflyGuardImpl(extractor ?? fromJwtPayload());
1366
+ }
1367
+
1368
+ // src/compat/nestjs/module.ts
1369
+ var import_graph3 = require("@graphrefly/pure-ts/graph");
1370
+ var import_common2 = require("@nestjs/common");
1371
+ var import_core11 = require("@nestjs/core");
1372
+
1373
+ // src/utils/cqrs/index.ts
1374
+ var import_core10 = require("@graphrefly/pure-ts/core");
1375
+ var import_extra3 = require("@graphrefly/pure-ts/extra");
1376
+ var import_graph2 = require("@graphrefly/pure-ts/graph");
1377
+
1378
+ // src/base/mutation/index.ts
1379
+ var import_core9 = require("@graphrefly/pure-ts/core");
1380
+ var import_extra2 = require("@graphrefly/pure-ts/extra");
1381
+ var import_graph = require("@graphrefly/pure-ts/graph");
1382
+ var DEFAULT_AUDIT_GUARD = (0, import_core9.policy)((allow, deny) => {
1383
+ allow("observe");
1384
+ allow("signal");
1385
+ deny("write");
1386
+ });
1387
+ function createAuditLog(opts) {
1388
+ const log = (0, import_extra2.reactiveLog)([], {
1389
+ name: opts.name,
1390
+ maxSize: opts.retainedLimit ?? 1024,
1391
+ guard: opts.guard ?? DEFAULT_AUDIT_GUARD,
1392
+ ...opts.versioning != null ? { versioning: opts.versioning } : {}
1393
+ });
1394
+ log.withLatest();
1395
+ if (opts.graph) {
1396
+ opts.graph.add(log.entries, { name: opts.name });
1397
+ }
1398
+ return log;
1399
+ }
1400
+ function deepFreeze(value) {
1401
+ if (value === null || typeof value !== "object" || Object.isFrozen(value)) return value;
1402
+ for (const k of Object.keys(value)) {
1403
+ deepFreeze(value[k]);
1404
+ }
1405
+ return Object.freeze(value);
1406
+ }
1407
+ function mutate(act, opts) {
1408
+ const { up, down } = typeof act === "function" ? { up: act, down: void 0 } : act;
1409
+ const freeze = opts.freeze ?? true;
1410
+ if (opts.frame === "inline") {
1411
+ return function wrapped(...args) {
1412
+ const sealed = freeze ? args.map(deepFreeze) : args;
1413
+ const t_ns = (0, import_core9.wallClockNs)();
1414
+ const seq = opts.seq ? bumpCursor(opts.seq) : void 0;
1415
+ try {
1416
+ const result = up(...sealed);
1417
+ if (opts.log && opts.onSuccessRecord) {
1418
+ appendAudit(
1419
+ opts.log,
1420
+ opts.onSuccessRecord,
1421
+ sealed,
1422
+ result,
1423
+ { t_ns, seq },
1424
+ opts.handlerVersion
1425
+ );
1426
+ }
1427
+ return result;
1428
+ } catch (err) {
1429
+ if (opts.log && opts.onFailureRecord) {
1430
+ const errorType = err instanceof Error ? err.name : typeof err;
1431
+ appendAudit(
1432
+ opts.log,
1433
+ opts.onFailureRecord,
1434
+ sealed,
1435
+ err,
1436
+ { t_ns, seq, errorType },
1437
+ opts.handlerVersion
1438
+ );
1439
+ }
1440
+ throw err;
1441
+ }
1442
+ };
1443
+ }
1444
+ return function wrapped(...args) {
1445
+ const sealed = freeze ? args.map(deepFreeze) : args;
1446
+ const t_ns = (0, import_core9.wallClockNs)();
1447
+ let result;
1448
+ let captured;
1449
+ let captureSet = false;
1450
+ let seq;
1451
+ try {
1452
+ (0, import_core9.batch)(() => {
1453
+ if (opts.seq) seq = bumpCursor(opts.seq);
1454
+ try {
1455
+ result = up(...sealed);
1456
+ if (opts.log && opts.onSuccessRecord) {
1457
+ appendAudit(
1458
+ opts.log,
1459
+ opts.onSuccessRecord,
1460
+ sealed,
1461
+ result,
1462
+ { t_ns, seq },
1463
+ opts.handlerVersion
1464
+ );
1465
+ }
1466
+ } catch (err) {
1467
+ captured = err;
1468
+ captureSet = true;
1469
+ throw err;
1470
+ }
1471
+ });
1472
+ } catch (outerErr) {
1473
+ if (captureSet && down) {
1474
+ try {
1475
+ down(...sealed);
1476
+ } catch (downErr) {
1477
+ console.error(
1478
+ `mutate: down hook threw \u2014 original action error preserved (${captured instanceof Error ? captured.name : typeof captured}). Down error:`,
1479
+ downErr
1480
+ );
1481
+ }
1482
+ }
1483
+ if (captureSet && opts.log && opts.onFailureRecord) {
1484
+ const errorType = captured instanceof Error ? captured.name : typeof captured;
1485
+ appendAudit(
1486
+ opts.log,
1487
+ opts.onFailureRecord,
1488
+ sealed,
1489
+ captured,
1490
+ { t_ns, seq, errorType },
1491
+ opts.handlerVersion
1492
+ );
1493
+ }
1494
+ throw captureSet ? captured : outerErr;
1495
+ }
1496
+ return result;
1497
+ };
1498
+ }
1499
+ var _bumpCursorWarned = /* @__PURE__ */ new WeakSet();
1500
+ function bumpCursor(seq) {
1501
+ const raw = seq.cache;
1502
+ const valid = typeof raw === "number" && Number.isFinite(raw);
1503
+ if (!valid && raw !== void 0 && !_bumpCursorWarned.has(seq)) {
1504
+ _bumpCursorWarned.add(seq);
1505
+ console.warn(
1506
+ `bumpCursor: cursor cache held a non-numeric value (${String(raw)}); resetting to 0. Causes include: a snapshot codec round-tripping the cursor as a string / null / NaN, OR a malformed initial seed (e.g. state<number>(NaN)). Audit consumers may see colliding seq values after this point.`
1507
+ );
1508
+ }
1509
+ const cur = valid ? raw : 0;
1510
+ const next = cur + 1;
1511
+ seq.down([[import_core9.DIRTY], [import_core9.DATA, next]]);
1512
+ return next;
1513
+ }
1514
+ function appendAudit(audit, builder, args, value, meta, handlerVersion) {
1515
+ const record = builder(args, value, meta);
1516
+ if (record === void 0) return;
1517
+ const stamped = handlerVersion != null ? { ...record, handlerVersion } : record;
1518
+ audit.append(stamped);
1519
+ }
1520
+ function registerCursor(graph, name, initial = 0) {
1521
+ const cursor = (0, import_core9.node)([], { initial, name, describeKind: "state" });
1522
+ graph.add(cursor, { name });
1523
+ return cursor;
1524
+ }
1525
+ function registerCursorMap(graph, name, keys, initial = 0) {
1526
+ const out = {};
1527
+ const sub = new import_graph.Graph(name);
1528
+ for (const k of keys) {
1529
+ const cursor = (0, import_core9.node)([], {
1530
+ initial,
1531
+ name: k,
1532
+ describeKind: "state"
1533
+ });
1534
+ sub.add(cursor, { name: k });
1535
+ out[k] = cursor;
1536
+ }
1537
+ graph.mount(name, sub);
1538
+ return out;
1539
+ }
1540
+
1541
+ // src/utils/_errors/index.ts
1542
+ var GraphReFlyError = class extends Error {
1543
+ constructor(message, options) {
1544
+ super(message, options);
1545
+ this.name = this.constructor.name;
1546
+ }
1547
+ };
1548
+ var DuplicateRegistrationError = class extends GraphReFlyError {
1549
+ constructor(kind, registrationName) {
1550
+ super(`Duplicate ${kind} registration: "${registrationName}"`);
1551
+ this.kind = kind;
1552
+ this.registrationName = registrationName;
1553
+ }
1554
+ };
1555
+ var UndeclaredEmitError = class extends GraphReFlyError {
1556
+ constructor(commandName, eventName, declaredEmits) {
1557
+ super(
1558
+ `Command "${commandName}" emitted undeclared event "${eventName}". Declared emits: [${declaredEmits.join(", ")}]`
1559
+ );
1560
+ this.commandName = commandName;
1561
+ this.eventName = eventName;
1562
+ this.declaredEmits = declaredEmits;
1563
+ }
1564
+ };
1565
+ var OptimisticConcurrencyError = class extends GraphReFlyError {
1566
+ constructor(aggregateId, expected, actual) {
1567
+ super(
1568
+ `Optimistic concurrency conflict on aggregate "${aggregateId}": expected version ${expected}, got ${actual}`
1569
+ );
1570
+ this.aggregateId = aggregateId;
1571
+ this.expected = expected;
1572
+ this.actual = actual;
1573
+ }
1574
+ };
1575
+ var UnknownCommandError = class extends GraphReFlyError {
1576
+ constructor(commandName) {
1577
+ super(`Unknown command: "${commandName}". Register with command() first.`);
1578
+ this.commandName = commandName;
1579
+ }
1580
+ };
1581
+ var CommandHandlerError = class extends GraphReFlyError {
1582
+ constructor(commandName, cause) {
1583
+ super(
1584
+ `Command handler "${commandName}" threw: ${cause instanceof Error ? cause.message : String(cause)}`,
1585
+ { cause }
1586
+ );
1587
+ this.commandName = commandName;
1588
+ }
1589
+ };
1590
+ var RebuildError = class extends GraphReFlyError {
1591
+ constructor(projectionName, cause) {
1592
+ super(
1593
+ `Projection "${projectionName}" rebuild failed: ${cause instanceof Error ? cause.message : String(cause)}`,
1594
+ { cause }
1595
+ );
1596
+ this.projectionName = projectionName;
1597
+ }
1598
+ };
1599
+
1600
+ // src/utils/cqrs/index.ts
1601
+ var import_extra4 = require("@graphrefly/pure-ts/extra");
1602
+
1603
+ // src/base/meta/domain-meta.ts
1604
+ function domainMeta(domain, kind, extra) {
1605
+ return {
1606
+ [domain]: true,
1607
+ [`${domain}_type`]: kind,
1608
+ ...extra ?? {}
1609
+ };
1610
+ }
1611
+
1612
+ // src/utils/cqrs/index.ts
1613
+ var COMMAND_GUARD = (0, import_core10.policy)((allow, deny) => {
1614
+ allow("write");
1615
+ allow("signal");
1616
+ deny("observe");
1617
+ });
1618
+ var PROJECTION_GUARD = (0, import_core10.policy)((allow, deny) => {
1619
+ allow("observe");
1620
+ allow("signal");
1621
+ deny("write");
1622
+ });
1623
+ var EVENT_GUARD = (0, import_core10.policy)((allow, deny) => {
1624
+ allow("observe");
1625
+ allow("signal");
1626
+ deny("write");
1627
+ });
1628
+ function cqrsMeta(kind, extra) {
1629
+ return domainMeta("cqrs", kind, extra);
1630
+ }
1631
+ function deepFreeze2(value) {
1632
+ if (value === null || typeof value !== "object" || Object.isFrozen(value)) return value;
1633
+ for (const k of Object.keys(value)) {
1634
+ deepFreeze2(value[k]);
1635
+ }
1636
+ return Object.freeze(value);
1637
+ }
1638
+ var CqrsGraph = class extends import_graph2.Graph {
1639
+ /** Fan-in event streams (one per type, all aggregates merged). */
1640
+ _eventLogs = /* @__PURE__ */ new Map();
1641
+ /**
1642
+ * Per-aggregate event streams: type → aggregateId → entry. Used for
1643
+ * `event(type, aggregateId)` dual-form access and per-aggregate version
1644
+ * tracking. Only populated when an event with `aggregateId` is emitted.
1645
+ */
1646
+ _eventLogsByAggregate = /* @__PURE__ */ new Map();
1647
+ /** Per-aggregate version counters: `${type}::${aggregateId}` → current version. */
1648
+ _aggregateVersions = /* @__PURE__ */ new Map();
1649
+ /**
1650
+ * LRU access order for `${type}::${aggregateId}`. Map insertion order
1651
+ * tracks recency — `delete` + `set` on access moves to the end.
1652
+ */
1653
+ _aggregateLru = /* @__PURE__ */ new Map();
1654
+ _commandRegs = /* @__PURE__ */ new Map();
1655
+ _projections = /* @__PURE__ */ new Set();
1656
+ _sagas = /* @__PURE__ */ new Set();
1657
+ _seq = 0;
1658
+ _retainedLimit;
1659
+ _freezeCommandPayload;
1660
+ _freezeEventPayload;
1661
+ _maxAggregates;
1662
+ _dispatchSeqCursor;
1663
+ /** Audit log of every command dispatch (Audit 2). */
1664
+ dispatches;
1665
+ /** Alias for {@link CqrsGraph.dispatches} (Audit 2 `.audit` duplication). */
1666
+ audit;
1667
+ /** Per-aggregate LRU eviction observability; secondary log to `dispatches`. */
1668
+ aggregateEvictions;
1669
+ constructor(name, opts = {}) {
1670
+ super(name, opts.graph);
1671
+ this._retainedLimit = opts.retainedLimit ?? 1024;
1672
+ this._freezeCommandPayload = opts.freezeCommandPayload ?? true;
1673
+ this._freezeEventPayload = opts.freezeEventPayload ?? true;
1674
+ this._maxAggregates = opts.maxAggregates ?? 1e4;
1675
+ this.dispatches = createAuditLog({
1676
+ name: "dispatches",
1677
+ retainedLimit: this._retainedLimit,
1678
+ graph: this
1679
+ });
1680
+ this.audit = this.dispatches;
1681
+ this.aggregateEvictions = createAuditLog({
1682
+ name: "aggregateEvictions",
1683
+ retainedLimit: this._retainedLimit,
1684
+ graph: this
1685
+ });
1686
+ this._dispatchSeqCursor = registerCursor(this, "dispatch_seq", 0);
1687
+ }
1688
+ /**
1689
+ * Read the current per-aggregate version (last emitted `aggregateVersion`
1690
+ * for that `(type, aggregateId)` pair). Returns `0` if no events have been
1691
+ * emitted yet for this aggregate. Useful for callers preparing
1692
+ * {@link DispatchOptions.expectedAggregateVersion}.
1693
+ */
1694
+ aggregateVersion(type, aggregateId) {
1695
+ return this._aggregateVersions.get(`${type}::${aggregateId}`) ?? 0;
1696
+ }
1697
+ /** LRU touch — moves the key to the end of the access order. */
1698
+ _touchAggregate(key) {
1699
+ this._aggregateLru.delete(key);
1700
+ this._aggregateLru.set(key, true);
1701
+ }
1702
+ /**
1703
+ * Evict the oldest aggregate streams (least-recently-touched) until the
1704
+ * aggregate count is back within `_maxAggregates`. Emits one
1705
+ * `AggregateEvictionRecord` per eviction. The fan-in stream is NOT touched
1706
+ * — events stay in the type-level log; only the per-aggregate stream and
1707
+ * version counter are removed.
1708
+ */
1709
+ _enforceAggregateLru() {
1710
+ while (this._aggregateLru.size > this._maxAggregates) {
1711
+ const oldest = this._aggregateLru.keys().next();
1712
+ if (oldest.done) break;
1713
+ const key = oldest.value;
1714
+ this._aggregateLru.delete(key);
1715
+ const sep = key.indexOf("::");
1716
+ if (sep < 0) continue;
1717
+ const type = key.slice(0, sep);
1718
+ const aggregateId = key.slice(sep + 2);
1719
+ const lastVersion = this._aggregateVersions.get(key) ?? 0;
1720
+ this._aggregateVersions.delete(key);
1721
+ const byType = this._eventLogsByAggregate.get(type);
1722
+ if (byType) {
1723
+ byType.delete(aggregateId);
1724
+ if (byType.size === 0) this._eventLogsByAggregate.delete(type);
1725
+ }
1726
+ this.aggregateEvictions.append({
1727
+ aggregateId,
1728
+ type,
1729
+ lastVersion,
1730
+ t_ns: (0, import_core10.wallClockNs)()
1731
+ });
1732
+ }
1733
+ }
1734
+ /** Tiers attached via {@link attachEventStorage}; auto-wired into future event streams. */
1735
+ _attachedEventTiers = [];
1736
+ _attachedTierDisposers = /* @__PURE__ */ new Map();
1737
+ /**
1738
+ * Wire append-log storage tiers for ALL CQRS event streams — both currently
1739
+ * registered AND any future streams created via `event(name)` /
1740
+ * `event(name, aggregateId)` / handler emit. (M4 fix.)
1741
+ *
1742
+ * Returns a disposer that releases all storage subscriptions wired by this
1743
+ * call (including those for streams that were created after the call).
1744
+ */
1745
+ attachEventStorage(tiers) {
1746
+ this._attachedEventTiers.push(tiers);
1747
+ for (const [name, entry] of this._eventLogs) {
1748
+ const dispose = entry.log.attachStorage(tiers);
1749
+ let arr = this._attachedTierDisposers.get(name);
1750
+ if (!arr) {
1751
+ arr = [];
1752
+ this._attachedTierDisposers.set(name, arr);
1753
+ }
1754
+ arr.push(dispose);
1755
+ }
1756
+ for (const [type, byAgg] of this._eventLogsByAggregate) {
1757
+ for (const [aggId, entry] of byAgg) {
1758
+ const key = `${type}::${aggId}`;
1759
+ const dispose = entry.log.attachStorage(tiers);
1760
+ let arr = this._attachedTierDisposers.get(key);
1761
+ if (!arr) {
1762
+ arr = [];
1763
+ this._attachedTierDisposers.set(key, arr);
1764
+ }
1765
+ arr.push(dispose);
1766
+ }
1767
+ }
1768
+ return () => {
1769
+ const idx = this._attachedEventTiers.indexOf(tiers);
1770
+ if (idx >= 0) this._attachedEventTiers.splice(idx, 1);
1771
+ };
1772
+ }
1773
+ /** Wire newly-created event stream into all currently-attached tier sets. */
1774
+ _autoWireStreamStorage(key, log) {
1775
+ if (this._attachedEventTiers.length === 0) return;
1776
+ let arr = this._attachedTierDisposers.get(key);
1777
+ if (!arr) {
1778
+ arr = [];
1779
+ this._attachedTierDisposers.set(key, arr);
1780
+ }
1781
+ for (const tiers of this._attachedEventTiers) {
1782
+ arr.push(log.attachStorage(tiers));
1783
+ }
1784
+ }
1785
+ event(name, aggregateId) {
1786
+ if (aggregateId !== void 0) {
1787
+ return this._ensureAggregateStream(name, aggregateId).node;
1788
+ }
1789
+ const existing = this._eventLogs.get(name);
1790
+ if (existing) return existing.node;
1791
+ const log = (0, import_extra3.reactiveLog)([], {
1792
+ name,
1793
+ versioning: 0,
1794
+ maxSize: this._retainedLimit
1795
+ });
1796
+ log.withLatest();
1797
+ const entries = log.entries;
1798
+ const guarded = this.derived(
1799
+ name,
1800
+ [entries],
1801
+ (batchData, ctx) => {
1802
+ const latest = batchData[0] != null && batchData[0].length > 0 ? batchData[0].at(-1) : ctx.prevData[0];
1803
+ return [latest];
1804
+ },
1805
+ {
1806
+ meta: cqrsMeta("event", { event_name: name }),
1807
+ guard: EVENT_GUARD,
1808
+ initial: entries.cache
1809
+ }
1810
+ );
1811
+ this.addDisposer((0, import_extra4.keepalive)(guarded));
1812
+ this._eventLogs.set(name, { log, node: guarded });
1813
+ this._autoWireStreamStorage(name, log);
1814
+ return guarded;
1815
+ }
1816
+ /**
1817
+ * Get-or-create the per-aggregate event stream for `(type, aggregateId)`.
1818
+ * Mounts the stream as a sibling node named `<type>_<aggregateId>` so it
1819
+ * appears in `describe()`. LRU access is touched on every call.
1820
+ */
1821
+ _ensureAggregateStream(type, aggregateId) {
1822
+ if (!this._eventLogs.has(type)) this.event(type);
1823
+ let byType = this._eventLogsByAggregate.get(type);
1824
+ if (!byType) {
1825
+ byType = /* @__PURE__ */ new Map();
1826
+ this._eventLogsByAggregate.set(type, byType);
1827
+ }
1828
+ const lruKey = `${type}::${aggregateId}`;
1829
+ this._touchAggregate(lruKey);
1830
+ const existing = byType.get(aggregateId);
1831
+ if (existing) return existing;
1832
+ const nodeName = `${type}_${aggregateId.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
1833
+ const log = (0, import_extra3.reactiveLog)([], {
1834
+ name: nodeName,
1835
+ versioning: 0,
1836
+ maxSize: this._retainedLimit
1837
+ });
1838
+ log.withLatest();
1839
+ const entries = log.entries;
1840
+ let mountName = nodeName;
1841
+ let collisionIdx = 0;
1842
+ while (this.resolveOptional(mountName) !== void 0) {
1843
+ collisionIdx += 1;
1844
+ mountName = `${nodeName}_${collisionIdx}`;
1845
+ }
1846
+ let guarded;
1847
+ try {
1848
+ guarded = this.derived(
1849
+ mountName,
1850
+ [entries],
1851
+ (batchData, ctx) => {
1852
+ const latest = batchData[0] != null && batchData[0].length > 0 ? batchData[0].at(-1) : ctx.prevData[0];
1853
+ return [latest];
1854
+ },
1855
+ {
1856
+ meta: cqrsMeta("event_aggregate", {
1857
+ event_name: type,
1858
+ aggregate_id: aggregateId
1859
+ }),
1860
+ guard: EVENT_GUARD,
1861
+ initial: entries.cache
1862
+ }
1863
+ );
1864
+ } catch {
1865
+ guarded = (0, import_core10.node)(
1866
+ [entries],
1867
+ (batchData, actions, ctx) => {
1868
+ const latest = batchData[0] != null && batchData[0].length > 0 ? batchData[0].at(-1) : ctx.prevData[0];
1869
+ actions.emit(latest);
1870
+ },
1871
+ {
1872
+ name: nodeName,
1873
+ describeKind: "derived",
1874
+ meta: cqrsMeta("event_aggregate", {
1875
+ event_name: type,
1876
+ aggregate_id: aggregateId
1877
+ }),
1878
+ guard: EVENT_GUARD,
1879
+ initial: entries.cache
1880
+ }
1881
+ );
1882
+ }
1883
+ this.addDisposer((0, import_extra4.keepalive)(guarded));
1884
+ const entry = { log, node: guarded };
1885
+ byType.set(aggregateId, entry);
1886
+ this._autoWireStreamStorage(`${type}::${aggregateId}`, log);
1887
+ this._enforceAggregateLru();
1888
+ return entry;
1889
+ }
1890
+ /** Try `resolve(path)`; return `undefined` instead of throwing on missing. */
1891
+ resolveOptional(path) {
1892
+ try {
1893
+ return this.resolve(path);
1894
+ } catch {
1895
+ return void 0;
1896
+ }
1897
+ }
1898
+ /** Internal: append to an event log, auto-registering if needed. */
1899
+ _appendEvent(eventName, payload, extra) {
1900
+ let entry = this._eventLogs.get(eventName);
1901
+ if (!entry) {
1902
+ this.event(eventName);
1903
+ entry = this._eventLogs.get(eventName);
1904
+ }
1905
+ if (entry.node.status === "completed" || entry.node.status === "errored") {
1906
+ throw new Error(
1907
+ `Cannot dispatch to terminated event stream "${eventName}" (status: ${entry.node.status}).`
1908
+ );
1909
+ }
1910
+ let aggregateVersion;
1911
+ let aggregateEntry;
1912
+ if (extra?.aggregateId !== void 0) {
1913
+ const lruKey = `${eventName}::${extra.aggregateId}`;
1914
+ aggregateVersion = (this._aggregateVersions.get(lruKey) ?? 0) + 1;
1915
+ this._aggregateVersions.set(lruKey, aggregateVersion);
1916
+ aggregateEntry = this._ensureAggregateStream(eventName, extra.aggregateId);
1917
+ }
1918
+ const nv = entry.log.entries.v;
1919
+ const frozenPayload = this._freezeEventPayload ? deepFreeze2(payload) : payload;
1920
+ const evt = {
1921
+ type: eventName,
1922
+ payload: frozenPayload,
1923
+ timestampNs: (0, import_core10.wallClockNs)(),
1924
+ seq: ++this._seq,
1925
+ ...extra?.aggregateId !== void 0 ? { aggregateId: extra.aggregateId } : {},
1926
+ ...aggregateVersion !== void 0 ? { aggregateVersion } : {},
1927
+ ...extra?.correlationId !== void 0 ? { correlationId: extra.correlationId } : {},
1928
+ ...extra?.causationId !== void 0 ? { causationId: extra.causationId } : {},
1929
+ ...extra?.metadata !== void 0 ? { metadata: Object.freeze({ ...extra.metadata }) } : {},
1930
+ ...extra?.handlerVersion !== void 0 ? { handlerVersion: extra.handlerVersion } : {},
1931
+ ...nv != null ? { v0: { id: nv.id, version: nv.version } } : {}
1932
+ };
1933
+ entry.log.append(evt);
1934
+ if (aggregateEntry) {
1935
+ aggregateEntry.log.append(evt);
1936
+ }
1937
+ return evt;
1938
+ }
1939
+ // -- Commands -------------------------------------------------------------
1940
+ /**
1941
+ * Register a command with its handler. Guard denies `observe` (write-only).
1942
+ * Use `dispatch(name, payload)` to execute.
1943
+ *
1944
+ * The command node carries dynamic `meta.error` — a reactive companion
1945
+ * that holds the last handler error (or `null` on success).
1946
+ */
1947
+ command(name, handlerOrReg) {
1948
+ if (this._commandRegs.has(name)) {
1949
+ throw new DuplicateRegistrationError("command", name);
1950
+ }
1951
+ const reg = typeof handlerOrReg === "function" ? { handler: handlerOrReg } : handlerOrReg;
1952
+ const cmdNode = this.state(name, void 0, {
1953
+ meta: {
1954
+ ...cqrsMeta("command", { command_name: name }),
1955
+ error: null
1956
+ },
1957
+ guard: COMMAND_GUARD
1958
+ });
1959
+ this._commandRegs.set(name, {
1960
+ handler: reg.handler,
1961
+ ...reg.emits !== void 0 ? { emits: reg.emits } : {},
1962
+ ...reg.handlerVersion !== void 0 ? { handlerVersion: reg.handlerVersion } : {}
1963
+ });
1964
+ if (reg.emits) {
1965
+ for (const e of reg.emits) {
1966
+ if (!this._eventLogs.has(e)) this.event(e);
1967
+ }
1968
+ }
1969
+ return cmdNode;
1970
+ }
1971
+ /**
1972
+ * Execute a registered command. Wraps the entire dispatch in `batch()` so
1973
+ * the command node DATA and all emitted events settle atomically.
1974
+ *
1975
+ * If the handler throws, `meta.error` on the command node is set to the
1976
+ * error and the exception is re-thrown.
1977
+ *
1978
+ * **Tier 8 / COMPOSITION-GUIDE §35:** dispatch routes through the shared
1979
+ * {@link mutate} framework so freeze / rollback-on-throw / seq-cursor
1980
+ * advance / audit-record stamping flow through one centralized helper.
1981
+ * Failure records emit OUTSIDE the rolled-back batch (M5 / C4 invariants
1982
+ * preserved by the framework).
1983
+ */
1984
+ dispatch(commandName, payload, opts) {
1985
+ const reg = this._commandRegs.get(commandName);
1986
+ if (!reg) throw new UnknownCommandError(commandName);
1987
+ if (opts?.aggregateId !== void 0 && opts.expectedAggregateVersion !== void 0 && reg.emits !== void 0) {
1988
+ let observedVersion = 0;
1989
+ for (const t of reg.emits) {
1990
+ const v = this._aggregateVersions.get(`${t}::${opts.aggregateId}`);
1991
+ if (v !== void 0 && v > observedVersion) observedVersion = v;
1992
+ }
1993
+ if (observedVersion !== opts.expectedAggregateVersion) {
1994
+ throw new OptimisticConcurrencyError(
1995
+ opts.aggregateId,
1996
+ opts.expectedAggregateVersion,
1997
+ observedVersion
1998
+ );
1999
+ }
2000
+ }
2001
+ const cmdNode = this.resolve(commandName);
2002
+ const emittedEvents = [];
2003
+ let actionThrew = false;
2004
+ const action2 = (sealed) => {
2005
+ cmdNode.emit(sealed, { internal: true });
2006
+ try {
2007
+ reg.handler(sealed, {
2008
+ emit: (eName, data) => {
2009
+ if (reg.emits !== void 0 && !reg.emits.includes(eName)) {
2010
+ throw new UndeclaredEmitError(commandName, eName, reg.emits);
2011
+ }
2012
+ emittedEvents.push(eName);
2013
+ this._appendEvent(eName, data, {
2014
+ // D1: thread the dispatch's aggregateId through so events
2015
+ // participate in per-aggregate versioning. Handlers can
2016
+ // override per-emit by passing their own through a richer
2017
+ // emit signature (future extension).
2018
+ ...opts?.aggregateId !== void 0 ? { aggregateId: opts.aggregateId } : {},
2019
+ ...opts?.correlationId !== void 0 ? { correlationId: opts.correlationId } : {},
2020
+ ...opts?.causationId !== void 0 ? { causationId: opts.causationId } : {},
2021
+ ...opts?.metadata !== void 0 ? { metadata: Object.freeze({ ...opts.metadata }) } : {},
2022
+ ...reg.handlerVersion !== void 0 ? { handlerVersion: reg.handlerVersion } : {}
2023
+ });
2024
+ }
2025
+ });
2026
+ cmdNode.meta.error.emit(null, { internal: true });
2027
+ } catch (err) {
2028
+ actionThrew = true;
2029
+ throw err;
2030
+ }
2031
+ };
2032
+ try {
2033
+ mutate(action2, {
2034
+ frame: "transactional",
2035
+ log: this.dispatches,
2036
+ seq: this._dispatchSeqCursor,
2037
+ freeze: this._freezeCommandPayload,
2038
+ onSuccessRecord: ([sealed], _result, { t_ns, seq }) => ({
2039
+ commandName,
2040
+ payload: sealed,
2041
+ outcome: "success",
2042
+ emittedEvents: [...emittedEvents],
2043
+ t_ns,
2044
+ seq: seq ?? 0,
2045
+ ...reg.handlerVersion !== void 0 ? { handlerVersion: reg.handlerVersion } : {}
2046
+ }),
2047
+ onFailureRecord: ([sealed], err, { t_ns, seq, errorType }) => {
2048
+ const wrapped = err instanceof CommandHandlerError ? err : new CommandHandlerError(commandName, err);
2049
+ return {
2050
+ commandName,
2051
+ payload: sealed,
2052
+ outcome: "failure",
2053
+ error: wrapped,
2054
+ errorType,
2055
+ emittedEvents: [...emittedEvents],
2056
+ t_ns,
2057
+ seq: seq ?? 0,
2058
+ ...reg.handlerVersion !== void 0 ? { handlerVersion: reg.handlerVersion } : {}
2059
+ };
2060
+ }
2061
+ })(payload);
2062
+ } catch (outerErr) {
2063
+ if (actionThrew) {
2064
+ cmdNode.meta.error.emit(outerErr, { internal: true });
2065
+ }
2066
+ throw outerErr;
2067
+ }
2068
+ }
2069
+ // -- Projections ----------------------------------------------------------
2070
+ /**
2071
+ * Register a read-only projection derived from event streams.
2072
+ * Guard denies `write` — value is computed from events only.
2073
+ *
2074
+ * **Wave C.3 Unit 21 (locked 2026-04-24):**
2075
+ * - Object-bag signature replaces the positional `(name, events, reducer, initial)` form.
2076
+ * - `mode: "scan"` (default) — incremental fold; `"replay"` — full replay each wave.
2077
+ * - `snapshot` integration for cold-start load + auto-checkpoint save.
2078
+ * - `freezeInputs` (default `true`) — freeze the event array before passing to reducer.
2079
+ * - Returns `ProjectionController<TState>` with `.node`, `.rebuild()`, `.reset()`.
2080
+ *
2081
+ * Fan-in across `events` is implemented by depending on all event-type fan-in
2082
+ * nodes directly, which preserves `describe()` edges (e.g. `orderPlaced →
2083
+ * orderCount`). Events are sorted by `(timestampNs, seq, aggregateId)` before
2084
+ * passing to the reducer (Option-3 cross-aggregate ordering, C.3).
2085
+ */
2086
+ projection(opts) {
2087
+ const { name, events: eventNames, reducer, initial } = opts;
2088
+ const mode = opts.mode ?? "scan";
2089
+ const freezeInputs = opts.freezeInputs ?? true;
2090
+ const snapshotOpts = opts.snapshot;
2091
+ const eventNodes = eventNames.map((eName) => {
2092
+ if (!this._eventLogs.has(eName)) this.event(eName);
2093
+ return this._eventLogs.get(eName).node;
2094
+ });
2095
+ function sortEvents(evts) {
2096
+ evts.sort(
2097
+ (a, b) => a.timestampNs - b.timestampNs || a.seq - b.seq || (a.aggregateId ?? "").localeCompare(b.aggregateId ?? "")
2098
+ );
2099
+ }
2100
+ function collectAllEvents(snapshots) {
2101
+ const evts = [];
2102
+ for (const snap of snapshots) evts.push(...snap);
2103
+ sortEvents(evts);
2104
+ return evts;
2105
+ }
2106
+ const seedSnapshots = eventNodes.map(
2107
+ (n) => n.cache ?? []
2108
+ );
2109
+ const sortedSeed = collectAllEvents(seedSnapshots);
2110
+ const frozenSeed = freezeInputs ? Object.freeze(sortedSeed) : sortedSeed;
2111
+ let lastProcessedCount = 0;
2112
+ let scanState = initial;
2113
+ if (mode === "scan" && sortedSeed.length > 0) {
2114
+ scanState = reducer(initial, frozenSeed);
2115
+ lastProcessedCount = sortedSeed.length;
2116
+ }
2117
+ const seedState = mode === "replay" ? reducer(initial, frozenSeed) : scanState;
2118
+ const saveDebounceMs = snapshotOpts?.saveDebounceMs ?? 1e3;
2119
+ const saveEvery = snapshotOpts?.saveEvery ?? 1e3;
2120
+ let saveTimer;
2121
+ let savesSinceLastFlush = 0;
2122
+ function scheduleSave(currentState) {
2123
+ if (!snapshotOpts?.save) return;
2124
+ savesSinceLastFlush += 1;
2125
+ if (savesSinceLastFlush >= saveEvery) {
2126
+ savesSinceLastFlush = 0;
2127
+ if (saveTimer !== void 0) {
2128
+ clearTimeout(saveTimer);
2129
+ saveTimer = void 0;
2130
+ }
2131
+ const result = snapshotOpts.save(currentState);
2132
+ if (result instanceof Promise) result.catch(() => void 0);
2133
+ return;
2134
+ }
2135
+ if (saveTimer !== void 0) clearTimeout(saveTimer);
2136
+ saveTimer = setTimeout(() => {
2137
+ saveTimer = void 0;
2138
+ savesSinceLastFlush = 0;
2139
+ const result = snapshotOpts.save(currentState);
2140
+ if (result instanceof Promise) result.catch(() => void 0);
2141
+ }, saveDebounceMs);
2142
+ }
2143
+ const projNode = this.derived(
2144
+ name,
2145
+ eventNames,
2146
+ (batchData, ctx) => {
2147
+ const snapshots = batchData.map(
2148
+ (batch4, i) => batch4 != null && batch4.length > 0 ? batch4.at(-1) : ctx.prevData[i]
2149
+ );
2150
+ const allEvents = collectAllEvents(snapshots);
2151
+ let newState;
2152
+ if (mode === "replay") {
2153
+ const frozen = freezeInputs ? Object.freeze(allEvents) : allEvents;
2154
+ newState = reducer(initial, frozen);
2155
+ } else {
2156
+ const newOnly = allEvents.slice(lastProcessedCount);
2157
+ lastProcessedCount = allEvents.length;
2158
+ const frozenNew = freezeInputs ? Object.freeze(newOnly) : newOnly;
2159
+ newState = reducer(scanState, frozenNew);
2160
+ scanState = newState;
2161
+ }
2162
+ scheduleSave(newState);
2163
+ return [newState];
2164
+ },
2165
+ {
2166
+ meta: cqrsMeta("projection", { projection_name: name, source_events: eventNames }),
2167
+ guard: PROJECTION_GUARD,
2168
+ initial: seedState
2169
+ }
2170
+ );
2171
+ this.addDisposer((0, import_extra4.keepalive)(projNode));
2172
+ this.addDisposer(() => {
2173
+ if (saveTimer !== void 0) {
2174
+ clearTimeout(saveTimer);
2175
+ saveTimer = void 0;
2176
+ }
2177
+ });
2178
+ this._projections.add(name);
2179
+ const rebuild = async (rebuildOpts) => {
2180
+ try {
2181
+ const pageSize = rebuildOpts?.pageSize ?? 1e3;
2182
+ const tier = rebuildOpts?.fromTier ?? this._attachedEventTiers[0]?.[0];
2183
+ const preBuildCount = collectAllEvents(
2184
+ eventNodes.map((n) => n.cache ?? [])
2185
+ ).length;
2186
+ let rebuildState = initial;
2187
+ if (snapshotOpts?.load) {
2188
+ const loaded = await snapshotOpts.load();
2189
+ if (loaded !== void 0) rebuildState = loaded;
2190
+ }
2191
+ if (!tier || !tier.loadEntries) {
2192
+ const inMemory = collectAllEvents(
2193
+ eventNodes.map((n) => n.cache ?? [])
2194
+ );
2195
+ const frozen = freezeInputs ? Object.freeze(inMemory) : inMemory;
2196
+ rebuildState = reducer(rebuildState, frozen);
2197
+ } else {
2198
+ const watchedEvents = new Set(eventNames);
2199
+ let cursor;
2200
+ let done = false;
2201
+ while (!done) {
2202
+ const result = await tier.loadEntries({ cursor, pageSize });
2203
+ const page = [...result.entries].filter((e) => watchedEvents.has(e.type));
2204
+ sortEvents(page);
2205
+ const frozenPage = freezeInputs ? Object.freeze(page) : page;
2206
+ rebuildState = reducer(rebuildState, frozenPage);
2207
+ cursor = result.cursor;
2208
+ done = !cursor || result.entries.length === 0;
2209
+ }
2210
+ }
2211
+ if (mode === "scan") {
2212
+ const allInMemory = collectAllEvents(
2213
+ eventNodes.map((n) => n.cache ?? [])
2214
+ );
2215
+ const pendingEvents = allInMemory.slice(preBuildCount);
2216
+ if (pendingEvents.length > 0) {
2217
+ const frozenPending = freezeInputs ? Object.freeze(pendingEvents) : pendingEvents;
2218
+ rebuildState = reducer(rebuildState, frozenPending);
2219
+ }
2220
+ scanState = rebuildState;
2221
+ lastProcessedCount = allInMemory.length;
2222
+ }
2223
+ projNode.emit(rebuildState, { internal: true });
2224
+ return rebuildState;
2225
+ } catch (err) {
2226
+ throw new RebuildError(name, err);
2227
+ }
2228
+ };
2229
+ const reset = async () => {
2230
+ try {
2231
+ let baseState = initial;
2232
+ if (snapshotOpts?.load) {
2233
+ const loaded = await snapshotOpts.load();
2234
+ if (loaded !== void 0) baseState = loaded;
2235
+ }
2236
+ const inMemory = collectAllEvents(
2237
+ eventNodes.map((n) => n.cache ?? [])
2238
+ );
2239
+ const frozen = freezeInputs ? Object.freeze(inMemory) : inMemory;
2240
+ const newState = reducer(baseState, frozen);
2241
+ if (mode === "scan") {
2242
+ scanState = newState;
2243
+ lastProcessedCount = inMemory.length;
2244
+ }
2245
+ projNode.emit(newState, { internal: true });
2246
+ return newState;
2247
+ } catch (err) {
2248
+ throw new RebuildError(name, err);
2249
+ }
2250
+ };
2251
+ return { node: projNode, rebuild, reset };
2252
+ }
2253
+ // -- Sagas ----------------------------------------------------------------
2254
+ /**
2255
+ * Register an event-driven side effect. Runs handler for each **new** event
2256
+ * from the specified streams (tracks last-processed entry count per stream).
2257
+ *
2258
+ * The saga node carries dynamic `meta.error` — a reactive companion that
2259
+ * holds the last handler error (or `null` on success). Handler errors do
2260
+ * not propagate out of the saga run (the event cursor still advances so
2261
+ * the same entry is not delivered twice).
2262
+ */
2263
+ saga(name, eventNames, handler, opts = {}) {
2264
+ const _eventNodes = eventNames.map((eName) => {
2265
+ if (!this._eventLogs.has(eName)) this.event(eName);
2266
+ return this._eventLogs.get(eName).node;
2267
+ });
2268
+ const cursors = registerCursorMap(this, `${name}_cursor`, eventNames, 0);
2269
+ const invocations = createAuditLog({
2270
+ name: `${name}_invocations`,
2271
+ retainedLimit: this._retainedLimit,
2272
+ graph: this
2273
+ });
2274
+ const aggregateFilter = opts.aggregateId;
2275
+ const errorPolicy = opts.errorPolicy ?? "advance";
2276
+ const latestCursors = /* @__PURE__ */ new Map();
2277
+ for (const eName of eventNames) {
2278
+ const cursor = cursors[eName];
2279
+ latestCursors.set(eName, cursor.cache ?? 0);
2280
+ const sub = cursor.subscribe((msgs) => {
2281
+ for (const m of msgs) if (m[0] === import_core10.DATA) latestCursors.set(eName, m[1]);
2282
+ });
2283
+ this.addDisposer(sub);
2284
+ }
2285
+ const auditedHandler = mutate(
2286
+ (ev, _eName) => {
2287
+ handler(ev);
2288
+ },
2289
+ {
2290
+ frame: "inline",
2291
+ log: invocations,
2292
+ freeze: false,
2293
+ ...opts.handlerVersion !== void 0 ? { handlerVersion: opts.handlerVersion } : {},
2294
+ // D5 (qa lock): always include the `aggregateId` key (even when
2295
+ // undefined) for parity with the pre-Tier-8 saga record shape.
2296
+ // Consumers using `Object.hasOwn(record, "aggregateId")` or JSON
2297
+ // serialization shape would observe a pre-1.0 break otherwise.
2298
+ onSuccessRecord: ([ev, eName], _r, { t_ns }) => ({
2299
+ eventType: eName,
2300
+ outcome: "success",
2301
+ aggregateId: ev.aggregateId,
2302
+ event: ev,
2303
+ t_ns
2304
+ }),
2305
+ onFailureRecord: ([ev, eName], err, { t_ns, errorType }) => ({
2306
+ eventType: eName,
2307
+ outcome: "failure",
2308
+ error: err,
2309
+ errorType,
2310
+ aggregateId: ev.aggregateId,
2311
+ event: ev,
2312
+ t_ns
2313
+ })
2314
+ }
2315
+ );
2316
+ const sagaRef = {};
2317
+ const sagaNode = this.effect(
2318
+ name,
2319
+ eventNames,
2320
+ (snapshots, _up) => {
2321
+ const errNode = sagaRef.n.meta.error;
2322
+ for (let i = 0; i < snapshots.length; i++) {
2323
+ const batch4 = snapshots[i];
2324
+ if (batch4 == null || batch4.length === 0) continue;
2325
+ const entries = batch4.at(-1);
2326
+ if (!entries) continue;
2327
+ const eName = eventNames[i];
2328
+ const cursor = cursors[eName];
2329
+ const lastCount = latestCursors.get(eName) ?? 0;
2330
+ if (entries.length > lastCount) {
2331
+ const newEntries = entries.slice(lastCount);
2332
+ let advancedTo = lastCount;
2333
+ for (const entry of newEntries) {
2334
+ const ev = entry;
2335
+ if (aggregateFilter !== void 0 && ev.aggregateId !== aggregateFilter) {
2336
+ advancedTo += 1;
2337
+ continue;
2338
+ }
2339
+ try {
2340
+ auditedHandler(ev, eName);
2341
+ errNode.emit(null, { internal: true });
2342
+ advancedTo += 1;
2343
+ } catch (err) {
2344
+ errNode.emit(err, { internal: true });
2345
+ if (errorPolicy === "hold") break;
2346
+ advancedTo += 1;
2347
+ }
2348
+ }
2349
+ cursor.emit(advancedTo);
2350
+ }
2351
+ }
2352
+ },
2353
+ {
2354
+ meta: {
2355
+ ...cqrsMeta("saga", { saga_name: name, source_events: eventNames }),
2356
+ error: null
2357
+ }
2358
+ }
2359
+ );
2360
+ sagaRef.n = sagaNode;
2361
+ this.addDisposer((0, import_extra4.keepalive)(sagaNode));
2362
+ this._sagas.add(name);
2363
+ return {
2364
+ node: sagaNode,
2365
+ invocations,
2366
+ audit: invocations,
2367
+ cursors
2368
+ };
2369
+ }
2370
+ };
2371
+ function cqrs(name, opts) {
2372
+ const g = new CqrsGraph(name, opts);
2373
+ const { factory: _f, factoryArgs: _fa, ...tagArgs } = opts ?? {};
2374
+ g.tagFactory("cqrs", (0, import_core10.placeholderArgs)(tagArgs));
2375
+ return g;
2376
+ }
2377
+
2378
+ // src/compat/nestjs/module.ts
2379
+ var GraphReflyRootLifecycle = class {
2380
+ constructor(graph) {
2381
+ this.graph = graph;
2382
+ }
2383
+ onModuleDestroy() {
2384
+ this.graph.destroy();
2385
+ }
2386
+ };
2387
+ var GraphReflyRequestLifecycle = class {
2388
+ graph = new import_graph3.Graph("request");
2389
+ onModuleDestroy() {
2390
+ this.graph.destroy();
2391
+ }
2392
+ };
2393
+ var _GraphReflyModule_decorators, _init;
2394
+ _GraphReflyModule_decorators = [(0, import_common2.Module)({})];
2395
+ var _GraphReflyModule = class _GraphReflyModule {
2396
+ /**
2397
+ * Register the root `Graph` singleton in the NestJS DI container.
2398
+ *
2399
+ * The root graph is `@Global()` — injectable everywhere without importing
2400
+ * the module again. Use `@InjectGraph()` to inject it.
2401
+ *
2402
+ * Lifecycle:
2403
+ * - **init:** Graph created in factory. If `build` is provided, it runs
2404
+ * first (registers nodes/mounts). If `snapshot` is provided, values
2405
+ * are restored via `graph.restore()`.
2406
+ * - **destroy:** Calls `graph.destroy()` — sends `[[TEARDOWN]]` to all
2407
+ * nodes, including mounted feature subgraphs (cascading teardown).
2408
+ */
2409
+ static forRoot(opts) {
2410
+ const options = opts ?? {};
2411
+ const graphName = options.name ?? "root";
2412
+ const providers = [
2413
+ {
2414
+ provide: GRAPHREFLY_ROOT_GRAPH,
2415
+ useFactory: () => {
2416
+ const g = new import_graph3.Graph(graphName);
2417
+ if (options.build) options.build(g);
2418
+ if (options.snapshot) g.restore(options.snapshot);
2419
+ return g;
2420
+ }
2421
+ },
2422
+ {
2423
+ provide: /* @__PURE__ */ Symbol.for("graphrefly:root-lifecycle"),
2424
+ useFactory: (graph) => new GraphReflyRootLifecycle(graph),
2425
+ inject: [GRAPHREFLY_ROOT_GRAPH]
2426
+ },
2427
+ {
2428
+ provide: GraphReflyEventExplorer,
2429
+ useFactory: (graph, moduleRef) => new GraphReflyEventExplorer(graph, moduleRef),
2430
+ inject: [GRAPHREFLY_ROOT_GRAPH, import_core11.ModuleRef]
2431
+ }
2432
+ ];
2433
+ if (options.nodes) {
2434
+ for (const path of options.nodes) {
2435
+ providers.push({
2436
+ provide: getNodeToken(path),
2437
+ useFactory: (graph) => graph.resolve(path),
2438
+ inject: [GRAPHREFLY_ROOT_GRAPH]
2439
+ });
2440
+ }
2441
+ }
2442
+ if (options.requestScope) {
2443
+ providers.push(
2444
+ {
2445
+ provide: /* @__PURE__ */ Symbol.for("graphrefly:request-lifecycle"),
2446
+ useFactory: () => new GraphReflyRequestLifecycle(),
2447
+ scope: import_common2.Scope.REQUEST
2448
+ },
2449
+ {
2450
+ provide: GRAPHREFLY_REQUEST_GRAPH,
2451
+ useFactory: (lifecycle) => lifecycle.graph,
2452
+ inject: [/* @__PURE__ */ Symbol.for("graphrefly:request-lifecycle")],
2453
+ scope: import_common2.Scope.REQUEST
2454
+ }
2455
+ );
2456
+ }
2457
+ return {
2458
+ module: _GraphReflyModule,
2459
+ global: true,
2460
+ providers,
2461
+ exports: [
2462
+ GRAPHREFLY_ROOT_GRAPH,
2463
+ ...(options.nodes ?? []).map(getNodeToken),
2464
+ ...options.requestScope ? [GRAPHREFLY_REQUEST_GRAPH] : []
2465
+ ]
2466
+ };
2467
+ }
2468
+ /**
2469
+ * Register a feature subgraph that auto-mounts into the root graph.
2470
+ *
2471
+ * The feature graph is created in the factory, built/restored, then
2472
+ * mounted into root via `root.mount(name, featureGraph)`. On app
2473
+ * shutdown, root's `graph.destroy()` cascades TEARDOWN through all
2474
+ * mounted subgraphs (no explicit remove needed).
2475
+ *
2476
+ * Node tokens are auto-qualified as `featureName::path` to prevent
2477
+ * collisions between features declaring nodes with the same local name.
2478
+ *
2479
+ * Injectable via `@InjectGraph(name)`.
2480
+ */
2481
+ static forFeature(opts) {
2482
+ const providers = [
2483
+ {
2484
+ provide: getGraphToken(opts.name),
2485
+ useFactory: (rootGraph) => {
2486
+ const g = new import_graph3.Graph(opts.name);
2487
+ if (opts.build) opts.build(g);
2488
+ if (opts.snapshot) g.restore(opts.snapshot);
2489
+ rootGraph.mount(opts.name, g);
2490
+ return g;
2491
+ },
2492
+ inject: [GRAPHREFLY_ROOT_GRAPH]
2493
+ }
2494
+ ];
2495
+ if (opts.nodes) {
2496
+ for (const path of opts.nodes) {
2497
+ providers.push({
2498
+ provide: getNodeToken(`${opts.name}::${path}`),
2499
+ useFactory: (graph) => graph.resolve(path),
2500
+ inject: [getGraphToken(opts.name)]
2501
+ });
2502
+ }
2503
+ }
2504
+ return {
2505
+ module: _GraphReflyModule,
2506
+ providers,
2507
+ exports: [
2508
+ getGraphToken(opts.name),
2509
+ ...(opts.nodes ?? []).map((p) => getNodeToken(`${opts.name}::${p}`))
2510
+ ]
2511
+ };
2512
+ }
2513
+ /**
2514
+ * Register a CQRS subgraph that auto-mounts into the root graph.
2515
+ *
2516
+ * Creates a `CqrsGraph` via the `cqrs()` factory (roadmap §4.5), mounts it
2517
+ * into the root graph, and exposes it for DI via `@InjectGraph(name)`.
2518
+ *
2519
+ * CQRS decorators (`@CommandHandler`, `@EventHandler`, `@QueryHandler`,
2520
+ * `@SagaHandler`) are discovered by the explorer and wired to this graph
2521
+ * on module init.
2522
+ *
2523
+ * @example
2524
+ * ```ts
2525
+ * GraphReflyModule.forCqrs({
2526
+ * name: "orders",
2527
+ * build: (g) => {
2528
+ * g.event("orderPlaced");
2529
+ * g.projection({ name: "orderCount", events: ["orderPlaced"], reducer: (_s, evts) => evts.length, initial: 0 });
2530
+ * },
2531
+ * })
2532
+ * ```
2533
+ */
2534
+ static forCqrs(opts) {
2535
+ const providers = [
2536
+ {
2537
+ provide: getGraphToken(opts.name),
2538
+ useFactory: (rootGraph) => {
2539
+ const g = cqrs(opts.name, opts.cqrs);
2540
+ if (opts.eventStorage) g.attachEventStorage(opts.eventStorage);
2541
+ if (opts.build) opts.build(g);
2542
+ rootGraph.mount(opts.name, g);
2543
+ return g;
2544
+ },
2545
+ inject: [GRAPHREFLY_ROOT_GRAPH]
2546
+ }
2547
+ ];
2548
+ if (opts.nodes) {
2549
+ for (const path of opts.nodes) {
2550
+ providers.push({
2551
+ provide: getNodeToken(`${opts.name}::${path}`),
2552
+ useFactory: (graph) => graph.resolve(path),
2553
+ inject: [getGraphToken(opts.name)]
2554
+ });
2555
+ }
2556
+ }
2557
+ return {
2558
+ module: _GraphReflyModule,
2559
+ providers,
2560
+ exports: [
2561
+ getGraphToken(opts.name),
2562
+ ...(opts.nodes ?? []).map((p) => getNodeToken(`${opts.name}::${p}`))
2563
+ ]
2564
+ };
2565
+ }
2566
+ };
2567
+ _init = __decoratorStart(null);
2568
+ _GraphReflyModule = __decorateElement(_init, 0, "GraphReflyModule", _GraphReflyModule_decorators, _GraphReflyModule);
2569
+ __runInitializers(_init, 1, _GraphReflyModule);
2570
+ var GraphReflyModule = _GraphReflyModule;
2571
+
2572
+ // src/compat/react/index.ts
2573
+ var react_exports = {};
2574
+ __export(react_exports, {
2575
+ useStore: () => useStore,
2576
+ useSubscribe: () => useSubscribe,
2577
+ useSubscribeRecord: () => useSubscribeRecord
2578
+ });
2579
+ var import_core12 = require("@graphrefly/pure-ts/core");
2580
+ var import_react = require("react");
2581
+ function useSubscribe(node7) {
2582
+ return (0, import_react.useSyncExternalStore)(
2583
+ (onStoreChange) => {
2584
+ let disposed = false;
2585
+ const unsub = node7.subscribe(() => {
2586
+ if (!disposed) onStoreChange();
2587
+ });
2588
+ return () => {
2589
+ disposed = true;
2590
+ unsub();
2591
+ };
2592
+ },
2593
+ () => node7.cache,
2594
+ () => node7.cache
2595
+ // Server snapshot
2596
+ );
2597
+ }
2598
+ function useStore(node7) {
2599
+ const value = useSubscribe(node7);
2600
+ const setter = (0, import_react.useCallback)(
2601
+ (v) => {
2602
+ node7.down([[import_core12.DIRTY], [import_core12.DATA, v]]);
2603
+ },
2604
+ [node7]
2605
+ );
2606
+ return [value, setter];
2607
+ }
2608
+ function useSubscribeRecord(keysNode, factory) {
2609
+ const factoryRef = (0, import_react.useRef)(factory);
2610
+ factoryRef.current = factory;
2611
+ const store = (0, import_react.useMemo)(() => {
2612
+ const computeSnap = () => {
2613
+ const snap = {};
2614
+ const keys = keysNode.cache ?? [];
2615
+ for (const key of keys) {
2616
+ const nodes = factoryRef.current(key);
2617
+ const values = {};
2618
+ for (const field of Object.keys(nodes)) {
2619
+ values[field] = nodes[field].cache;
2620
+ }
2621
+ snap[key] = values;
2622
+ }
2623
+ return snap;
2624
+ };
2625
+ let currentSnapshot = computeSnap();
2626
+ return {
2627
+ subscribe: (onStoreChange) => {
2628
+ let disposed = false;
2629
+ let entrySubs = [];
2630
+ const cleanupEntries = () => {
2631
+ for (const unsub of entrySubs) unsub();
2632
+ entrySubs = [];
2633
+ };
2634
+ const sync = (nextKeys) => {
2635
+ cleanupEntries();
2636
+ for (const key of nextKeys) {
2637
+ const nodes = factoryRef.current(key);
2638
+ for (const field of Object.keys(nodes)) {
2639
+ const unsub = nodes[field].subscribe(() => {
2640
+ currentSnapshot = computeSnap();
2641
+ if (!disposed) onStoreChange();
2642
+ });
2643
+ entrySubs.push(unsub);
2644
+ }
2645
+ }
2646
+ currentSnapshot = computeSnap();
2647
+ if (!disposed) onStoreChange();
2648
+ };
2649
+ const keysUnsub = keysNode.subscribe((msgs) => {
2650
+ const hasSettled = msgs.some((m) => m[0] === import_core12.DATA || m[0] === import_core12.RESOLVED);
2651
+ if (!disposed && hasSettled) sync(keysNode.cache ?? []);
2652
+ });
2653
+ sync(keysNode.cache ?? []);
2654
+ return () => {
2655
+ disposed = true;
2656
+ keysUnsub();
2657
+ cleanupEntries();
2658
+ };
2659
+ },
2660
+ getSnapshot: () => currentSnapshot
2661
+ };
2662
+ }, [keysNode]);
2663
+ return (0, import_react.useSyncExternalStore)(store.subscribe, store.getSnapshot, store.getSnapshot);
2664
+ }
2665
+
2666
+ // src/compat/signals/index.ts
2667
+ var signals_exports = {};
2668
+ __export(signals_exports, {
2669
+ Signal: () => Signal
2670
+ });
2671
+ var import_core13 = require("@graphrefly/pure-ts/core");
2672
+ var trackingStack = [];
2673
+ function pull3(n) {
2674
+ let val = n.cache;
2675
+ const unsub = n.subscribe((msgs) => {
2676
+ for (const [t, v] of msgs) {
2677
+ if (t === import_core13.DATA) val = v;
2678
+ }
2679
+ });
2680
+ unsub();
2681
+ return val;
2682
+ }
2683
+ var SignalState = class {
2684
+ /** @internal */
2685
+ _node;
2686
+ _equals;
2687
+ constructor(initial, opts) {
2688
+ this._equals = opts?.equals ?? Object.is;
2689
+ this._node = (0, import_core13.node)([], {
2690
+ initial,
2691
+ ...opts,
2692
+ resubscribable: true,
2693
+ resetOnTeardown: true
2694
+ });
2695
+ }
2696
+ get() {
2697
+ const tracker = trackingStack[trackingStack.length - 1];
2698
+ if (tracker) {
2699
+ if (this._node.status === "sentinel") {
2700
+ pull3(this._node);
2701
+ }
2702
+ return tracker(this._node);
2703
+ }
2704
+ if (this._node.status === "sentinel") {
2705
+ return pull3(this._node);
2706
+ }
2707
+ return this._node.cache;
2708
+ }
2709
+ set(value) {
2710
+ if (this._equals(this.get(), value)) return;
2711
+ (0, import_core13.batch)(() => {
2712
+ this._node.down([[import_core13.DIRTY], [import_core13.DATA, value]]);
2713
+ });
2714
+ }
2715
+ };
2716
+ var SignalComputed = class {
2717
+ /** @internal */
2718
+ _node;
2719
+ constructor(computation, opts) {
2720
+ this._node = (0, import_core13.autoTrackNode)(
2721
+ (track) => {
2722
+ trackingStack.push(track);
2723
+ try {
2724
+ return computation();
2725
+ } finally {
2726
+ trackingStack.pop();
2727
+ }
2728
+ },
2729
+ {
2730
+ ...opts,
2731
+ describeKind: "derived",
2732
+ resubscribable: true,
2733
+ resetOnTeardown: true,
2734
+ // TC39 Signal semantics require `Signal.Computed` to return
2735
+ // the user-provided computation value, never `undefined` from
2736
+ // a not-yet-discovered branch dep. Opt OUT of Lock 6.C′'s
2737
+ // partial:true default — the gate suppresses fn until newly
2738
+ // discovered branch deps deliver their first DATA, so `track`
2739
+ // never returns `undefined` after a branch flip.
2740
+ partial: false
2741
+ }
2742
+ );
2743
+ }
2744
+ get() {
2745
+ const tracker = trackingStack[trackingStack.length - 1];
2746
+ if (tracker) {
2747
+ if (this._node.status === "sentinel") {
2748
+ pull3(this._node);
2749
+ }
2750
+ return tracker(this._node);
2751
+ }
2752
+ if (this._node.status === "sentinel") {
2753
+ return pull3(this._node);
2754
+ }
2755
+ return this._node.cache;
2756
+ }
2757
+ };
2758
+ var Signal = {
2759
+ State: SignalState,
2760
+ Computed: SignalComputed,
2761
+ /**
2762
+ * Subscribes to changes on a signal.
2763
+ * Returns an unsubscribe callback.
2764
+ *
2765
+ * @example
2766
+ * ```ts
2767
+ * const count = new Signal.State(0);
2768
+ * const unsub = Signal.sub(count, v => console.log(v));
2769
+ * ```
2770
+ */
2771
+ sub: (signal, callback) => {
2772
+ const handlers = typeof callback === "function" ? { data: callback, error: void 0, complete: void 0 } : callback;
2773
+ let initial = true;
2774
+ return signal._node.subscribe((msgs) => {
2775
+ for (const [t, v] of msgs) {
2776
+ if (t === import_core13.DATA) {
2777
+ if (initial) {
2778
+ initial = false;
2779
+ continue;
2780
+ }
2781
+ handlers.data?.(v);
2782
+ }
2783
+ if (t === import_core13.ERROR) handlers.error?.(v);
2784
+ if (t === import_core13.COMPLETE) handlers.complete?.();
2785
+ }
2786
+ });
2787
+ }
2788
+ };
2789
+
2790
+ // src/compat/solid/index.ts
2791
+ var solid_exports = {};
2792
+ __export(solid_exports, {
2793
+ useStore: () => useStore2,
2794
+ useSubscribe: () => useSubscribe2,
2795
+ useSubscribeRecord: () => useSubscribeRecord2
2796
+ });
2797
+ var import_core14 = require("@graphrefly/pure-ts/core");
2798
+ var import_solid_js = require("solid-js");
2799
+ function useSubscribe2(node7) {
2800
+ const [value, setValue] = (0, import_solid_js.createSignal)(node7.cache, { equals: false });
2801
+ const unsub = node7.subscribe(() => {
2802
+ setValue(() => node7.cache);
2803
+ });
2804
+ if ((0, import_solid_js.getOwner)()) {
2805
+ (0, import_solid_js.onCleanup)(() => unsub());
2806
+ } else if (typeof console !== "undefined") {
2807
+ console.warn(
2808
+ "[graphrefly-ts] useSubscribe called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."
2809
+ );
2810
+ }
2811
+ return value;
2812
+ }
2813
+ function useStore2(node7) {
2814
+ const value = useSubscribe2(node7);
2815
+ const setter = (v) => {
2816
+ node7.down([[import_core14.DIRTY], [import_core14.DATA, v]]);
2817
+ };
2818
+ return [value, setter];
2819
+ }
2820
+ function useSubscribeRecord2(keysNode, factory) {
2821
+ const [value, setValue] = (0, import_solid_js.createSignal)({}, { equals: false });
2822
+ let entrySubs = [];
2823
+ const cleanupEntries = () => {
2824
+ for (const unsub of entrySubs) unsub();
2825
+ entrySubs = [];
2826
+ };
2827
+ const buildSnapshot = () => {
2828
+ const snap = {};
2829
+ for (const key of keysNode.cache ?? []) {
2830
+ const nodes = factory(key);
2831
+ const values = {};
2832
+ for (const field of Object.keys(nodes)) {
2833
+ values[field] = nodes[field].cache;
2834
+ }
2835
+ snap[key] = values;
2836
+ }
2837
+ return snap;
2838
+ };
2839
+ const sync = (nextKeys) => {
2840
+ cleanupEntries();
2841
+ for (const key of nextKeys) {
2842
+ const nodes = factory(key);
2843
+ for (const field of Object.keys(nodes)) {
2844
+ const unsub = nodes[field].subscribe(() => {
2845
+ setValue(() => buildSnapshot());
2846
+ });
2847
+ entrySubs.push(unsub);
2848
+ }
2849
+ }
2850
+ setValue(() => buildSnapshot());
2851
+ };
2852
+ const keysUnsub = keysNode.subscribe((msgs) => {
2853
+ if (msgs.some((m) => m[0] === import_core14.DATA || m[0] === import_core14.RESOLVED)) {
2854
+ sync(keysNode.cache ?? []);
2855
+ }
2856
+ });
2857
+ sync(keysNode.cache ?? []);
2858
+ if ((0, import_solid_js.getOwner)()) {
2859
+ (0, import_solid_js.onCleanup)(() => {
2860
+ keysUnsub();
2861
+ cleanupEntries();
2862
+ });
2863
+ } else if (typeof console !== "undefined") {
2864
+ console.warn(
2865
+ "[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."
2866
+ );
2867
+ }
2868
+ return value;
2869
+ }
2870
+
2871
+ // src/compat/svelte/index.ts
2872
+ var svelte_exports = {};
2873
+ __export(svelte_exports, {
2874
+ useStore: () => useStore3,
2875
+ useSubscribe: () => useSubscribe3,
2876
+ useSubscribeRecord: () => useSubscribeRecord3
2877
+ });
2878
+ var import_core15 = require("@graphrefly/pure-ts/core");
2879
+ function useSubscribe3(node7) {
2880
+ return {
2881
+ subscribe(run) {
2882
+ const unsub = node7.subscribe(() => {
2883
+ run(node7.cache);
2884
+ });
2885
+ run(node7.cache);
2886
+ return unsub;
2887
+ }
2888
+ };
2889
+ }
2890
+ function useStore3(node7) {
2891
+ return {
2892
+ subscribe(run) {
2893
+ const unsub = node7.subscribe(() => {
2894
+ run(node7.cache);
2895
+ });
2896
+ run(node7.cache);
2897
+ return unsub;
2898
+ },
2899
+ set(value) {
2900
+ node7.down([[import_core15.DIRTY], [import_core15.DATA, value]]);
2901
+ },
2902
+ update(updater) {
2903
+ const next = updater(node7.cache);
2904
+ node7.down([[import_core15.DIRTY], [import_core15.DATA, next]]);
2905
+ }
2906
+ };
2907
+ }
2908
+ function useSubscribeRecord3(keysNode, factory) {
2909
+ return {
2910
+ subscribe(run) {
2911
+ let entrySubs = [];
2912
+ const cleanupEntries = () => {
2913
+ for (const unsub of entrySubs) unsub();
2914
+ entrySubs = [];
2915
+ };
2916
+ const buildSnapshot = () => {
2917
+ const snap = {};
2918
+ for (const key of keysNode.cache ?? []) {
2919
+ const nodes = factory(key);
2920
+ const values = {};
2921
+ for (const field of Object.keys(nodes)) {
2922
+ values[field] = nodes[field].cache;
2923
+ }
2924
+ snap[key] = values;
2925
+ }
2926
+ return snap;
2927
+ };
2928
+ const sync = (nextKeys) => {
2929
+ cleanupEntries();
2930
+ for (const key of nextKeys) {
2931
+ const nodes = factory(key);
2932
+ for (const field of Object.keys(nodes)) {
2933
+ const unsub = nodes[field].subscribe(() => {
2934
+ run(buildSnapshot());
2935
+ });
2936
+ entrySubs.push(unsub);
2937
+ }
2938
+ }
2939
+ run(buildSnapshot());
2940
+ };
2941
+ const keysUnsub = keysNode.subscribe((msgs) => {
2942
+ if (msgs.some((m) => m[0] === import_core15.DATA || m[0] === import_core15.RESOLVED)) {
2943
+ sync(keysNode.cache ?? []);
2944
+ }
2945
+ });
2946
+ sync(keysNode.cache ?? []);
2947
+ return () => {
2948
+ keysUnsub();
2949
+ cleanupEntries();
2950
+ };
2951
+ }
2952
+ };
2953
+ }
2954
+
2955
+ // src/compat/vue/index.ts
2956
+ var vue_exports = {};
2957
+ __export(vue_exports, {
2958
+ useStore: () => useStore4,
2959
+ useSubscribe: () => useSubscribe4,
2960
+ useSubscribeRecord: () => useSubscribeRecord4
2961
+ });
2962
+ var import_core16 = require("@graphrefly/pure-ts/core");
2963
+ var import_vue = require("vue");
2964
+ function useSubscribe4(node7) {
2965
+ const ref = (0, import_vue.shallowRef)(node7.cache);
2966
+ const unsub = node7.subscribe(() => {
2967
+ ref.value = node7.cache;
2968
+ });
2969
+ if ((0, import_vue.getCurrentScope)()) {
2970
+ (0, import_vue.onScopeDispose)(() => unsub());
2971
+ } else if (typeof console !== "undefined") {
2972
+ console.warn(
2973
+ "[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."
2974
+ );
2975
+ }
2976
+ return (0, import_vue.readonly)(ref);
2977
+ }
2978
+ function useStore4(node7) {
2979
+ const inner = (0, import_vue.shallowRef)(node7.cache);
2980
+ const unsub = node7.subscribe(() => {
2981
+ inner.value = node7.cache;
2982
+ });
2983
+ if ((0, import_vue.getCurrentScope)()) {
2984
+ (0, import_vue.onScopeDispose)(() => unsub());
2985
+ } else if (typeof console !== "undefined") {
2986
+ console.warn(
2987
+ "[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."
2988
+ );
2989
+ }
2990
+ return (0, import_vue.computed)({
2991
+ get: () => inner.value,
2992
+ set: (v) => {
2993
+ node7.down([[import_core16.DIRTY], [import_core16.DATA, v]]);
2994
+ }
2995
+ });
2996
+ }
2997
+ function useSubscribeRecord4(keys, factory) {
2998
+ const result = (0, import_vue.shallowRef)({});
2999
+ const activeSubs = /* @__PURE__ */ new Map();
3000
+ function flushResult() {
3001
+ const snap = {};
3002
+ for (const [key, entry] of activeSubs) {
3003
+ snap[key] = { ...entry.values };
3004
+ }
3005
+ result.value = snap;
3006
+ }
3007
+ function sync(newKeys) {
3008
+ for (const entry of activeSubs.values()) {
3009
+ for (const unsub of entry.subs) unsub();
3010
+ }
3011
+ activeSubs.clear();
3012
+ for (const key of newKeys) {
3013
+ const nodes = factory(key);
3014
+ const fields = Object.keys(nodes);
3015
+ const values = {};
3016
+ const subs = [];
3017
+ for (const field of fields) {
3018
+ const node7 = nodes[field];
3019
+ values[field] = node7.cache;
3020
+ const unsub = node7.subscribe(() => {
3021
+ values[field] = node7.cache;
3022
+ flushResult();
3023
+ });
3024
+ subs.push(unsub);
3025
+ }
3026
+ activeSubs.set(key, { subs, values });
3027
+ }
3028
+ const snap = {};
3029
+ for (const [key, entry] of activeSubs) {
3030
+ snap[key] = { ...entry.values };
3031
+ }
3032
+ result.value = snap;
3033
+ }
3034
+ const readKeys = () => {
3035
+ const current = typeof keys === "function" ? keys() : (0, import_vue.isRef)(keys) ? keys.value : keys;
3036
+ return [...current ?? []];
3037
+ };
3038
+ (0, import_vue.watch)(readKeys, (newKeys) => sync(newKeys ?? []), { immediate: true });
3039
+ if ((0, import_vue.getCurrentScope)()) {
3040
+ (0, import_vue.onScopeDispose)(() => {
3041
+ for (const entry of activeSubs.values()) {
3042
+ for (const unsub of entry.subs) unsub();
3043
+ }
3044
+ activeSubs.clear();
3045
+ });
3046
+ } else if (typeof console !== "undefined") {
3047
+ console.warn(
3048
+ "[graphrefly-ts] useSubscribeRecord called outside a Vue scope \u2014 subscription will not be auto-disposed."
3049
+ );
3050
+ }
3051
+ return (0, import_vue.readonly)(result);
3052
+ }
3053
+
3054
+ // src/compat/zustand/index.ts
3055
+ var zustand_exports = {};
3056
+ __export(zustand_exports, {
3057
+ create: () => create
3058
+ });
3059
+ var import_core17 = require("@graphrefly/pure-ts/core");
3060
+ var import_graph4 = require("@graphrefly/pure-ts/graph");
3061
+ var alwaysDiffer = () => false;
3062
+ function create(initializer) {
3063
+ const g = new import_graph4.Graph("zustand");
3064
+ const s = (0, import_core17.node)([], {
3065
+ initial: void 0,
3066
+ name: "state",
3067
+ equals: alwaysDiffer
3068
+ });
3069
+ g.add(s, { name: "state" });
3070
+ const getState = () => s.cache;
3071
+ const setState = (partial, replace) => {
3072
+ const prev = s.cache;
3073
+ const next = typeof partial === "function" ? partial(prev) : partial;
3074
+ s.emit(replace ? next : { ...prev, ...next });
3075
+ };
3076
+ const api = {
3077
+ getState,
3078
+ setState,
3079
+ getInitialState: () => initialValue,
3080
+ subscribe: (listener) => {
3081
+ let initial = true;
3082
+ let prev = s.cache;
3083
+ return s.subscribe((msgs) => {
3084
+ for (const [t, v] of msgs) {
3085
+ if (t === import_core17.DATA) {
3086
+ if (initial) {
3087
+ initial = false;
3088
+ continue;
3089
+ }
3090
+ listener(v, prev);
3091
+ prev = v;
3092
+ }
3093
+ }
3094
+ });
3095
+ },
3096
+ destroy: g.destroy.bind(g)
3097
+ };
3098
+ const initialValue = initializer(setState, getState, api);
3099
+ s.emit(initialValue);
3100
+ return Object.assign(g, api);
3101
+ }
3102
+ //# sourceMappingURL=index.cjs.map