@graphrefly/graphrefly 0.27.0 → 0.29.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 (428) hide show
  1. package/dist/backoff-HPZMEZNF.js +1 -0
  2. package/dist/cascading-Bp99ckMJ.d.ts +180 -0
  3. package/dist/cascading-CcAgRacD.d.cts +180 -0
  4. package/dist/chunk-22F4K3G7.js +1 -0
  5. package/dist/chunk-22SVXUPB.js +64 -0
  6. package/dist/chunk-2GQREQ6C.js +1 -0
  7. package/dist/chunk-3JXNEPCD.js +2 -0
  8. package/dist/chunk-4JJCCD5S.js +2 -0
  9. package/dist/chunk-4OFIQ66T.js +1 -0
  10. package/dist/chunk-4V4C7K56.js +1 -0
  11. package/dist/chunk-4VVTGLXJ.js +1 -0
  12. package/dist/chunk-567NWZ3T.js +1 -0
  13. package/dist/chunk-5JDE5JHE.js +1 -0
  14. package/dist/chunk-5QDBSZBV.js +1 -0
  15. package/dist/chunk-5Z4HDCO6.js +1 -0
  16. package/dist/chunk-63FFOHLA.js +1 -0
  17. package/dist/chunk-6QZNQS5B.js +1 -0
  18. package/dist/chunk-7JDLFI6N.js +1 -0
  19. package/dist/chunk-7TDOES3L.js +1 -0
  20. package/dist/chunk-A7IAQQ63.js +1 -0
  21. package/dist/chunk-AMG5VBHW.js +1 -0
  22. package/dist/chunk-AUY2YKCO.js +1 -0
  23. package/dist/chunk-AV3PIDFQ.js +1 -0
  24. package/dist/chunk-BA5URFYW.js +1 -0
  25. package/dist/chunk-BKPLTBL5.js +1 -0
  26. package/dist/chunk-BZP5T4X6.js +1 -0
  27. package/dist/chunk-CK2E7BTU.js +1 -0
  28. package/dist/chunk-CSJE2EKV.js +1 -0
  29. package/dist/chunk-E3AXATVZ.js +9 -0
  30. package/dist/chunk-ESMPEKEV.js +1 -0
  31. package/dist/chunk-GJR3P6JG.js +1 -0
  32. package/dist/chunk-GNCBXARM.js +1 -0
  33. package/dist/chunk-GPW2V3RE.js +1 -0
  34. package/dist/chunk-HSIEYSDY.js +1 -0
  35. package/dist/chunk-I6VIH3VA.js +1 -0
  36. package/dist/chunk-ISCENNXS.js +1 -0
  37. package/dist/chunk-JYOUF6UQ.js +1 -0
  38. package/dist/chunk-KASHOCF5.js +1 -0
  39. package/dist/chunk-LGSNR4LU.js +5 -0
  40. package/dist/chunk-LVGBLZM2.js +1 -0
  41. package/dist/chunk-MGKAO4EK.js +7 -0
  42. package/dist/chunk-NSG4C6BF.js +23 -0
  43. package/dist/chunk-OL33ZI6R.js +1 -0
  44. package/dist/chunk-PCZ35NXD.js +78 -0
  45. package/dist/chunk-PGMUCUHG.js +43 -0
  46. package/dist/chunk-QYADASLV.js +1 -0
  47. package/dist/chunk-RD52SNH2.js +1 -0
  48. package/dist/chunk-SLMYTGTU.js +1 -0
  49. package/dist/chunk-TWMEGG45.js +1 -0
  50. package/dist/chunk-UVJQ35G2.js +1 -0
  51. package/dist/chunk-VGTCGNRX.js +18 -0
  52. package/dist/chunk-VIMF6LGM.js +1 -0
  53. package/dist/chunk-VJLMUKOI.js +1 -0
  54. package/dist/chunk-VWPRPPKR.js +1 -0
  55. package/dist/chunk-W4TSQ6RJ.js +1 -0
  56. package/dist/chunk-WM7H7WTY.js +3 -0
  57. package/dist/chunk-Y32RJO24.js +1 -0
  58. package/dist/chunk-Y53B6NS4.js +1 -0
  59. package/dist/compat/index.cjs +15 -7656
  60. package/dist/compat/index.d.cts +15 -14
  61. package/dist/compat/index.d.ts +15 -14
  62. package/dist/compat/index.js +1 -50
  63. package/dist/compat/jotai/index.cjs +1 -2048
  64. package/dist/compat/jotai/index.d.cts +2 -2
  65. package/dist/compat/jotai/index.d.ts +2 -2
  66. package/dist/compat/jotai/index.js +1 -9
  67. package/dist/compat/nanostores/index.cjs +1 -2175
  68. package/dist/compat/nanostores/index.d.cts +2 -2
  69. package/dist/compat/nanostores/index.d.ts +2 -2
  70. package/dist/compat/nanostores/index.js +1 -23
  71. package/dist/compat/nestjs/index.cjs +15 -6782
  72. package/dist/compat/nestjs/index.d.cts +7 -6
  73. package/dist/compat/nestjs/index.d.ts +7 -6
  74. package/dist/compat/nestjs/index.js +1 -83
  75. package/dist/compat/react/index.cjs +1 -141
  76. package/dist/compat/react/index.d.cts +2 -2
  77. package/dist/compat/react/index.d.ts +2 -2
  78. package/dist/compat/react/index.js +1 -12
  79. package/dist/compat/solid/index.cjs +1 -128
  80. package/dist/compat/solid/index.d.cts +2 -2
  81. package/dist/compat/solid/index.d.ts +2 -2
  82. package/dist/compat/solid/index.js +1 -12
  83. package/dist/compat/svelte/index.cjs +1 -131
  84. package/dist/compat/svelte/index.d.cts +2 -2
  85. package/dist/compat/svelte/index.d.ts +2 -2
  86. package/dist/compat/svelte/index.js +1 -12
  87. package/dist/compat/vue/index.cjs +1 -146
  88. package/dist/compat/vue/index.d.cts +2 -2
  89. package/dist/compat/vue/index.d.ts +2 -2
  90. package/dist/compat/vue/index.js +1 -12
  91. package/dist/compat/zustand/index.cjs +7 -4931
  92. package/dist/compat/zustand/index.d.cts +5 -5
  93. package/dist/compat/zustand/index.d.ts +5 -5
  94. package/dist/compat/zustand/index.js +1 -12
  95. package/dist/composite-BL-llbnE.d.ts +69 -0
  96. package/dist/composite-Dze--DaA.d.cts +69 -0
  97. package/dist/core/index.cjs +1 -2271
  98. package/dist/core/index.d.cts +4 -4
  99. package/dist/core/index.d.ts +4 -4
  100. package/dist/core/index.js +1 -110
  101. package/dist/extra/browser.cjs +1 -0
  102. package/dist/extra/browser.d.cts +3 -0
  103. package/dist/extra/browser.d.ts +3 -0
  104. package/dist/extra/browser.js +1 -0
  105. package/dist/extra/index.cjs +24 -9971
  106. package/dist/extra/index.d.cts +13 -6
  107. package/dist/extra/index.d.ts +13 -6
  108. package/dist/extra/index.js +1 -381
  109. package/dist/extra/node.cjs +3 -0
  110. package/dist/extra/node.d.cts +81 -0
  111. package/dist/extra/node.d.ts +81 -0
  112. package/dist/extra/node.js +2 -0
  113. package/dist/extra/operators.cjs +1 -0
  114. package/dist/extra/operators.d.cts +910 -0
  115. package/dist/extra/operators.d.ts +910 -0
  116. package/dist/extra/operators.js +1 -0
  117. package/dist/extra/reactive.cjs +1 -0
  118. package/dist/extra/reactive.d.cts +352 -0
  119. package/dist/extra/reactive.d.ts +352 -0
  120. package/dist/extra/reactive.js +1 -0
  121. package/dist/extra/sources.cjs +1 -2486
  122. package/dist/extra/sources.d.cts +6 -2
  123. package/dist/extra/sources.d.ts +6 -2
  124. package/dist/extra/sources.js +1 -57
  125. package/dist/extra/storage-browser.cjs +1 -0
  126. package/dist/extra/storage-browser.d.cts +71 -0
  127. package/dist/extra/storage-browser.d.ts +71 -0
  128. package/dist/extra/storage-browser.js +1 -0
  129. package/dist/extra/storage-core.cjs +1 -0
  130. package/dist/extra/storage-core.d.cts +98 -0
  131. package/dist/extra/storage-core.d.ts +98 -0
  132. package/dist/extra/storage-core.js +1 -0
  133. package/dist/extra/storage-node.cjs +2 -0
  134. package/dist/extra/storage-node.d.cts +60 -0
  135. package/dist/extra/storage-node.d.ts +60 -0
  136. package/dist/extra/storage-node.js +1 -0
  137. package/dist/fallback-BaTS7vVY.d.cts +258 -0
  138. package/dist/fallback-eOm3LNxP.d.ts +258 -0
  139. package/dist/graph/index.cjs +7 -5030
  140. package/dist/graph/index.d.cts +6 -5
  141. package/dist/graph/index.d.ts +6 -5
  142. package/dist/graph/index.js +1 -50
  143. package/dist/{graph-DNCrvZSn.d.cts → graph-DgohqXK-.d.cts} +151 -32
  144. package/dist/{graph-CCwGKLCm.d.ts → graph-Qjg9gWHI.d.ts} +151 -32
  145. package/dist/{index-BwfLUNw4.d.ts → index-2BVuRCI4.d.ts} +173 -2040
  146. package/dist/{index-BPVt8kqc.d.ts → index-2NvguqQA.d.ts} +10 -195
  147. package/dist/index-A65LZhoM.d.ts +186 -0
  148. package/dist/{index-DlLp-2Xn.d.cts → index-B-8FCEua.d.cts} +10 -195
  149. package/dist/index-B-gqvYel.d.ts +135 -0
  150. package/dist/index-B2PRuolf.d.cts +86 -0
  151. package/dist/index-BJqt9EwW.d.ts +231 -0
  152. package/dist/{index-BHlKbUwO.d.cts → index-BKjT5DiZ.d.cts} +173 -2040
  153. package/dist/{index-C0svESO4.d.ts → index-BM8BU4q6.d.ts} +1 -1
  154. package/dist/{index-VdHQMPy1.d.ts → index-BQaEnxBf.d.ts} +1 -1
  155. package/dist/index-BSfwiy5B.d.ts +192 -0
  156. package/dist/index-BTSkeCZs.d.cts +291 -0
  157. package/dist/index-BUVtw1Ay.d.cts +186 -0
  158. package/dist/index-BUi57v_p.d.ts +163 -0
  159. package/dist/{messaging-Gt4LPbyA.d.cts → index-BanNUILp.d.cts} +31 -93
  160. package/dist/{audit-DRlSzBu9.d.ts → index-BayHDRx6.d.cts} +27 -21
  161. package/dist/{index-B6D3QNSA.d.ts → index-BiyjsZ0m.d.ts} +148 -20
  162. package/dist/index-BqZ6vB2A.d.ts +2057 -0
  163. package/dist/{memory-li6FL5RM.d.ts → index-BuVidq3D.d.cts} +26 -26
  164. package/dist/index-Byh-xTyp.d.ts +105 -0
  165. package/dist/index-C08QPDcV.d.cts +321 -0
  166. package/dist/{demo-shell-BDkOptd6.d.ts → index-C66RJiX8.d.ts} +14 -14
  167. package/dist/index-C8RfjffH.d.ts +291 -0
  168. package/dist/index-CA1Cu7Ud.d.ts +873 -0
  169. package/dist/{index-ByQxazQJ.d.cts → index-CABbltIu.d.cts} +1 -1
  170. package/dist/{index-VHqptjhu.d.cts → index-CHEBsnYv.d.cts} +1 -1
  171. package/dist/{index-BuEoe-Qu.d.ts → index-CI0yDnLp.d.ts} +9 -9
  172. package/dist/{index-B9B7_HEY.d.ts → index-CJ45TW-h.d.ts} +1 -1
  173. package/dist/{index-CO8uBlUh.d.cts → index-CJZKZoo4.d.cts} +148 -20
  174. package/dist/{index-wEn0eFe8.d.ts → index-CX2tFJL1.d.ts} +1 -1
  175. package/dist/{index-BaSM3aYt.d.ts → index-CcWOJ6F0.d.ts} +3 -3
  176. package/dist/{audit-ClmqGOCx.d.cts → index-CiaVoZGo.d.ts} +27 -21
  177. package/dist/{index-Dzk2hrlR.d.ts → index-Ct5CWc4E.d.ts} +1 -1
  178. package/dist/index-D38duMCv.d.cts +357 -0
  179. package/dist/{index-C8oil6M6.d.ts → index-D5XJ2tSx.d.ts} +30 -6
  180. package/dist/{index-DO_6JN9Z.d.cts → index-D80do5jX.d.cts} +1 -1
  181. package/dist/index-D9HKAH_-.d.cts +231 -0
  182. package/dist/index-DBe_8XW5.d.cts +143 -0
  183. package/dist/{memory-C6Z2tGpC.d.cts → index-DCeTyFlB.d.ts} +26 -26
  184. package/dist/index-DDy8eeXS.d.ts +321 -0
  185. package/dist/index-DJ5oNBc8.d.ts +143 -0
  186. package/dist/{index-CI3DprxP.d.cts → index-DP0_O3ls.d.cts} +30 -6
  187. package/dist/{demo-shell-Crid1WdR.d.cts → index-DX8xS-yB.d.cts} +14 -14
  188. package/dist/index-DiZejfCI.d.cts +2057 -0
  189. package/dist/index-DknyJ2Fu.d.cts +163 -0
  190. package/dist/index-DoWMs-Kk.d.cts +135 -0
  191. package/dist/{messaging-XDoYablx.d.ts → index-DuB5aO4-.d.ts} +31 -93
  192. package/dist/index-DwjJGKxV.d.ts +357 -0
  193. package/dist/{index-B6EhDnjH.d.cts → index-H_oxVec5.d.cts} +1 -1
  194. package/dist/{index-3lsddbbS.d.ts → index-IMAHq-ia.d.ts} +1 -1
  195. package/dist/{index-B1tloyhO.d.cts → index-U1nir7MX.d.cts} +1 -1
  196. package/dist/index-Vg7tORgk.d.ts +86 -0
  197. package/dist/index-dig-r2tQ.d.cts +873 -0
  198. package/dist/{index-CxFrXH4m.d.ts → index-gsT79Xu9.d.ts} +1 -1
  199. package/dist/{index-D8wS_PeY.d.cts → index-i99Ka8s7.d.cts} +9 -9
  200. package/dist/index-iKkyJosF.d.cts +105 -0
  201. package/dist/{index-Xi3u0HCQ.d.cts → index-jleeotBT.d.cts} +1 -1
  202. package/dist/{index-DVGiGFGT.d.cts → index-kykKWwV-.d.cts} +3 -3
  203. package/dist/index-vgcLF5TH.d.cts +192 -0
  204. package/dist/{index-DYme44FM.d.cts → index-y1RllPn4.d.cts} +1 -1
  205. package/dist/index.cjs +151 -24142
  206. package/dist/index.d.cts +69 -2099
  207. package/dist/index.d.ts +69 -2099
  208. package/dist/index.js +1 -3868
  209. package/dist/{meta-CbznRPYJ.d.ts → meta-CX7YsOzp.d.cts} +5 -5
  210. package/dist/{meta-BxCA7rcr.d.cts → meta-CckhhFRd.d.ts} +5 -5
  211. package/dist/{node-BmerH3kS.d.cts → node-Dd6wHSib.d.cts} +71 -11
  212. package/dist/{node-BmerH3kS.d.ts → node-Dd6wHSib.d.ts} +71 -11
  213. package/dist/{observable-BgGUwcqp.d.ts → observable-BZJgo616.d.ts} +1 -1
  214. package/dist/{observable-DJt_AxzQ.d.cts → observable-kwzpLvbi.d.cts} +1 -1
  215. package/dist/patterns/ai/browser.cjs +25 -0
  216. package/dist/patterns/ai/browser.d.cts +127 -0
  217. package/dist/patterns/ai/browser.d.ts +127 -0
  218. package/dist/patterns/ai/browser.js +3 -0
  219. package/dist/patterns/ai/index.cjs +92 -0
  220. package/dist/patterns/ai/index.d.cts +17 -0
  221. package/dist/patterns/ai/index.d.ts +17 -0
  222. package/dist/patterns/ai/index.js +1 -0
  223. package/dist/patterns/ai/node.cjs +2 -0
  224. package/dist/patterns/ai/node.d.cts +58 -0
  225. package/dist/patterns/ai/node.d.ts +58 -0
  226. package/dist/patterns/ai/node.js +1 -0
  227. package/dist/patterns/audit/index.cjs +7 -0
  228. package/dist/patterns/audit/index.d.cts +6 -0
  229. package/dist/patterns/audit/index.d.ts +6 -0
  230. package/dist/patterns/audit/index.js +1 -0
  231. package/dist/patterns/cqrs/index.cjs +7 -0
  232. package/dist/patterns/cqrs/index.d.cts +5 -0
  233. package/dist/patterns/cqrs/index.d.ts +5 -0
  234. package/dist/patterns/cqrs/index.js +1 -0
  235. package/dist/patterns/demo-shell/index.cjs +8 -0
  236. package/dist/patterns/demo-shell/index.d.cts +6 -0
  237. package/dist/patterns/demo-shell/index.d.ts +6 -0
  238. package/dist/patterns/demo-shell/index.js +1 -0
  239. package/dist/patterns/domain-templates/index.cjs +7 -0
  240. package/dist/patterns/domain-templates/index.d.cts +5 -0
  241. package/dist/patterns/domain-templates/index.d.ts +5 -0
  242. package/dist/patterns/domain-templates/index.js +1 -0
  243. package/dist/patterns/graphspec/index.cjs +84 -0
  244. package/dist/patterns/graphspec/index.d.cts +7 -0
  245. package/dist/patterns/graphspec/index.d.ts +7 -0
  246. package/dist/patterns/graphspec/index.js +1 -0
  247. package/dist/patterns/guarded-execution/index.cjs +7 -0
  248. package/dist/patterns/guarded-execution/index.d.cts +7 -0
  249. package/dist/patterns/guarded-execution/index.d.ts +7 -0
  250. package/dist/patterns/guarded-execution/index.js +1 -0
  251. package/dist/patterns/harness/index.cjs +49 -0
  252. package/dist/patterns/harness/index.d.cts +11 -0
  253. package/dist/patterns/harness/index.d.ts +11 -0
  254. package/dist/patterns/harness/index.js +1 -0
  255. package/dist/patterns/job-queue/index.cjs +7 -0
  256. package/dist/patterns/job-queue/index.d.cts +5 -0
  257. package/dist/patterns/job-queue/index.d.ts +5 -0
  258. package/dist/patterns/job-queue/index.js +1 -0
  259. package/dist/patterns/lens/index.cjs +7 -0
  260. package/dist/patterns/lens/index.d.cts +7 -0
  261. package/dist/patterns/lens/index.d.ts +7 -0
  262. package/dist/patterns/lens/index.js +1 -0
  263. package/dist/patterns/memory/index.cjs +7 -0
  264. package/dist/patterns/memory/index.d.cts +5 -0
  265. package/dist/patterns/memory/index.d.ts +5 -0
  266. package/dist/patterns/memory/index.js +1 -0
  267. package/dist/patterns/messaging/index.cjs +7 -0
  268. package/dist/patterns/messaging/index.d.cts +5 -0
  269. package/dist/patterns/messaging/index.d.ts +5 -0
  270. package/dist/patterns/messaging/index.js +1 -0
  271. package/dist/patterns/orchestration/index.cjs +7 -0
  272. package/dist/patterns/orchestration/index.d.cts +6 -0
  273. package/dist/patterns/orchestration/index.d.ts +6 -0
  274. package/dist/patterns/orchestration/index.js +1 -0
  275. package/dist/patterns/reactive-layout/index.cjs +8 -6444
  276. package/dist/patterns/reactive-layout/index.d.cts +6 -6
  277. package/dist/patterns/reactive-layout/index.d.ts +6 -6
  278. package/dist/patterns/reactive-layout/index.js +1 -56
  279. package/dist/patterns/reduction/index.cjs +7 -0
  280. package/dist/patterns/reduction/index.d.cts +5 -0
  281. package/dist/patterns/reduction/index.d.ts +5 -0
  282. package/dist/patterns/reduction/index.js +1 -0
  283. package/dist/patterns/refine-loop/index.cjs +9 -0
  284. package/dist/patterns/refine-loop/index.d.cts +7 -0
  285. package/dist/patterns/refine-loop/index.d.ts +7 -0
  286. package/dist/patterns/refine-loop/index.js +1 -0
  287. package/dist/patterns/resilient-pipeline/index.cjs +1 -0
  288. package/dist/patterns/resilient-pipeline/index.d.cts +7 -0
  289. package/dist/patterns/resilient-pipeline/index.d.ts +7 -0
  290. package/dist/patterns/resilient-pipeline/index.js +1 -0
  291. package/dist/patterns/surface/index.cjs +15 -0
  292. package/dist/patterns/surface/index.d.cts +8 -0
  293. package/dist/patterns/surface/index.d.ts +8 -0
  294. package/dist/patterns/surface/index.js +1 -0
  295. package/dist/{reactive-layout-u5Ulnqag.d.ts → reactive-layout-BkBwVvwm.d.ts} +2 -2
  296. package/dist/{reactive-layout-MQP--J3F.d.cts → reactive-layout-PiFwVaWS.d.cts} +2 -2
  297. package/dist/reactive-log-1QTyx10a.d.ts +190 -0
  298. package/dist/reactive-log-BiVoSxke.d.cts +190 -0
  299. package/dist/{composite-aUCvjZVR.d.ts → reactive-map-CwO_COHy.d.cts} +2 -67
  300. package/dist/{composite-C7PcQvcs.d.cts → reactive-map-FeuTVAJb.d.ts} +2 -67
  301. package/dist/resilience-CBfYJW5C.d.ts +493 -0
  302. package/dist/resilience-XRUF267O.js +1 -0
  303. package/dist/resilience-uBz4yvYB.d.cts +493 -0
  304. package/dist/{sugar-CCOxXK1e.d.ts → sugar-CY-MCfZ9.d.ts} +17 -15
  305. package/dist/{sugar-D02n5JjF.d.cts → sugar-DHttV0LX.d.cts} +17 -15
  306. package/dist/topology-tree-CVjt2gp7.d.cts +25 -0
  307. package/dist/topology-tree-one6oSKY.d.ts +25 -0
  308. package/dist/types-O3GzJY2U.d.cts +401 -0
  309. package/dist/types-u64Ose53.d.ts +401 -0
  310. package/package.json +252 -22
  311. package/dist/ai-CaR_912Q.d.cts +0 -1033
  312. package/dist/ai-WlRltJV7.d.ts +0 -1033
  313. package/dist/chunk-3ZWCKRHX.js +0 -117
  314. package/dist/chunk-3ZWCKRHX.js.map +0 -1
  315. package/dist/chunk-7TAQJHQV.js +0 -103
  316. package/dist/chunk-7TAQJHQV.js.map +0 -1
  317. package/dist/chunk-APFNLIRG.js +0 -62
  318. package/dist/chunk-APFNLIRG.js.map +0 -1
  319. package/dist/chunk-AT5LKYNL.js +0 -395
  320. package/dist/chunk-AT5LKYNL.js.map +0 -1
  321. package/dist/chunk-BQ6RQQFF.js +0 -5087
  322. package/dist/chunk-BQ6RQQFF.js.map +0 -1
  323. package/dist/chunk-BVZYTZ5H.js +0 -599
  324. package/dist/chunk-BVZYTZ5H.js.map +0 -1
  325. package/dist/chunk-DST5DKZS.js +0 -1371
  326. package/dist/chunk-DST5DKZS.js.map +0 -1
  327. package/dist/chunk-GTE6PWRZ.js +0 -866
  328. package/dist/chunk-GTE6PWRZ.js.map +0 -1
  329. package/dist/chunk-HXZEYDUR.js +0 -94
  330. package/dist/chunk-HXZEYDUR.js.map +0 -1
  331. package/dist/chunk-J22W6HV3.js +0 -107
  332. package/dist/chunk-J22W6HV3.js.map +0 -1
  333. package/dist/chunk-J2VBW3DZ.js +0 -302
  334. package/dist/chunk-J2VBW3DZ.js.map +0 -1
  335. package/dist/chunk-JSCT3CR4.js +0 -38
  336. package/dist/chunk-JSCT3CR4.js.map +0 -1
  337. package/dist/chunk-JWBCY4NC.js +0 -330
  338. package/dist/chunk-JWBCY4NC.js.map +0 -1
  339. package/dist/chunk-K2AUJHVP.js +0 -2251
  340. package/dist/chunk-K2AUJHVP.js.map +0 -1
  341. package/dist/chunk-MJ2NKQQL.js +0 -119
  342. package/dist/chunk-MJ2NKQQL.js.map +0 -1
  343. package/dist/chunk-N6UR7YVY.js +0 -198
  344. package/dist/chunk-N6UR7YVY.js.map +0 -1
  345. package/dist/chunk-NC6S43JJ.js +0 -456
  346. package/dist/chunk-NC6S43JJ.js.map +0 -1
  347. package/dist/chunk-OFVJBJXR.js +0 -98
  348. package/dist/chunk-OFVJBJXR.js.map +0 -1
  349. package/dist/chunk-OHISZPOJ.js +0 -97
  350. package/dist/chunk-OHISZPOJ.js.map +0 -1
  351. package/dist/chunk-OU5CQKNW.js +0 -102
  352. package/dist/chunk-OU5CQKNW.js.map +0 -1
  353. package/dist/chunk-PF7GRZMW.js +0 -2712
  354. package/dist/chunk-PF7GRZMW.js.map +0 -1
  355. package/dist/chunk-PHOUUNK7.js +0 -2291
  356. package/dist/chunk-PHOUUNK7.js.map +0 -1
  357. package/dist/chunk-RNHBMHKA.js +0 -1665
  358. package/dist/chunk-RNHBMHKA.js.map +0 -1
  359. package/dist/chunk-SX52TAR4.js +0 -110
  360. package/dist/chunk-SX52TAR4.js.map +0 -1
  361. package/dist/chunk-VYPWMZ6H.js +0 -98
  362. package/dist/chunk-VYPWMZ6H.js.map +0 -1
  363. package/dist/chunk-WBZOVTYK.js +0 -171
  364. package/dist/chunk-WBZOVTYK.js.map +0 -1
  365. package/dist/chunk-WKNUIZOY.js +0 -354
  366. package/dist/chunk-WKNUIZOY.js.map +0 -1
  367. package/dist/chunk-X3VMZYBT.js +0 -713
  368. package/dist/chunk-X3VMZYBT.js.map +0 -1
  369. package/dist/chunk-X5R3GL6H.js +0 -525
  370. package/dist/chunk-X5R3GL6H.js.map +0 -1
  371. package/dist/chunk-XGPU467M.js +0 -136
  372. package/dist/chunk-XGPU467M.js.map +0 -1
  373. package/dist/compat/index.cjs.map +0 -1
  374. package/dist/compat/index.js.map +0 -1
  375. package/dist/compat/jotai/index.cjs.map +0 -1
  376. package/dist/compat/jotai/index.js.map +0 -1
  377. package/dist/compat/nanostores/index.cjs.map +0 -1
  378. package/dist/compat/nanostores/index.js.map +0 -1
  379. package/dist/compat/nestjs/index.cjs.map +0 -1
  380. package/dist/compat/nestjs/index.js.map +0 -1
  381. package/dist/compat/react/index.cjs.map +0 -1
  382. package/dist/compat/react/index.js.map +0 -1
  383. package/dist/compat/solid/index.cjs.map +0 -1
  384. package/dist/compat/solid/index.js.map +0 -1
  385. package/dist/compat/svelte/index.cjs.map +0 -1
  386. package/dist/compat/svelte/index.js.map +0 -1
  387. package/dist/compat/vue/index.cjs.map +0 -1
  388. package/dist/compat/vue/index.js.map +0 -1
  389. package/dist/compat/zustand/index.cjs.map +0 -1
  390. package/dist/compat/zustand/index.js.map +0 -1
  391. package/dist/core/index.cjs.map +0 -1
  392. package/dist/core/index.js.map +0 -1
  393. package/dist/extra/index.cjs.map +0 -1
  394. package/dist/extra/index.js.map +0 -1
  395. package/dist/extra/sources.cjs.map +0 -1
  396. package/dist/extra/sources.js.map +0 -1
  397. package/dist/graph/index.cjs.map +0 -1
  398. package/dist/graph/index.js.map +0 -1
  399. package/dist/index.cjs.map +0 -1
  400. package/dist/index.js.map +0 -1
  401. package/dist/patterns/ai.cjs +0 -7930
  402. package/dist/patterns/ai.cjs.map +0 -1
  403. package/dist/patterns/ai.d.cts +0 -10
  404. package/dist/patterns/ai.d.ts +0 -10
  405. package/dist/patterns/ai.js +0 -71
  406. package/dist/patterns/ai.js.map +0 -1
  407. package/dist/patterns/audit.cjs +0 -5805
  408. package/dist/patterns/audit.cjs.map +0 -1
  409. package/dist/patterns/audit.d.cts +0 -6
  410. package/dist/patterns/audit.d.ts +0 -6
  411. package/dist/patterns/audit.js +0 -29
  412. package/dist/patterns/audit.js.map +0 -1
  413. package/dist/patterns/demo-shell.cjs +0 -5604
  414. package/dist/patterns/demo-shell.cjs.map +0 -1
  415. package/dist/patterns/demo-shell.d.cts +0 -6
  416. package/dist/patterns/demo-shell.d.ts +0 -6
  417. package/dist/patterns/demo-shell.js +0 -15
  418. package/dist/patterns/demo-shell.js.map +0 -1
  419. package/dist/patterns/memory.cjs +0 -5283
  420. package/dist/patterns/memory.cjs.map +0 -1
  421. package/dist/patterns/memory.d.cts +0 -5
  422. package/dist/patterns/memory.d.ts +0 -5
  423. package/dist/patterns/memory.js +0 -20
  424. package/dist/patterns/memory.js.map +0 -1
  425. package/dist/patterns/reactive-layout/index.cjs.map +0 -1
  426. package/dist/patterns/reactive-layout/index.js.map +0 -1
  427. package/dist/storage-CMjUUuxn.d.ts +0 -190
  428. package/dist/storage-DdWlZo6U.d.cts +0 -190
@@ -1,2175 +1 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/compat/nanostores/index.ts
21
- var nanostores_exports = {};
22
- __export(nanostores_exports, {
23
- action: () => action,
24
- atom: () => atom,
25
- computed: () => computed,
26
- getValue: () => getValue,
27
- map: () => map,
28
- onMount: () => onMount,
29
- onStart: () => onStart,
30
- onStop: () => onStop
31
- });
32
- module.exports = __toCommonJS(nanostores_exports);
33
-
34
- // src/core/batch.ts
35
- var MAX_DRAIN_ITERATIONS = 1e3;
36
- var batchDepth = 0;
37
- var flushInProgress = false;
38
- var drainPhase2 = [];
39
- var drainPhase3 = [];
40
- var drainPhase4 = [];
41
- var flushHooks = [];
42
- function isBatching() {
43
- return batchDepth > 0 || flushInProgress;
44
- }
45
- function isExplicitlyBatching() {
46
- return batchDepth > 0;
47
- }
48
- function registerBatchFlushHook(hook) {
49
- if (batchDepth > 0) {
50
- flushHooks.push(hook);
51
- } else {
52
- hook();
53
- }
54
- }
55
- function batch(fn) {
56
- batchDepth += 1;
57
- let threw = false;
58
- try {
59
- fn();
60
- } catch (e) {
61
- threw = true;
62
- throw e;
63
- } finally {
64
- batchDepth -= 1;
65
- if (batchDepth === 0) {
66
- if (threw) {
67
- if (!flushInProgress) {
68
- const hooks = flushHooks.splice(0);
69
- for (const h of hooks) {
70
- try {
71
- h();
72
- } catch {
73
- }
74
- }
75
- drainPhase2.length = 0;
76
- drainPhase3.length = 0;
77
- drainPhase4.length = 0;
78
- }
79
- } else {
80
- drainPending();
81
- }
82
- }
83
- }
84
- }
85
- function drainPending() {
86
- const ownsFlush = !flushInProgress;
87
- if (ownsFlush) flushInProgress = true;
88
- const errors = [];
89
- let iterations = 0;
90
- try {
91
- while (drainPhase2.length > 0 || drainPhase3.length > 0 || drainPhase4.length > 0 || ownsFlush && flushHooks.length > 0) {
92
- if (ownsFlush && flushHooks.length > 0) {
93
- const hooks = flushHooks.splice(0);
94
- for (const h of hooks) {
95
- try {
96
- h();
97
- } catch (e) {
98
- errors.push(e);
99
- }
100
- }
101
- continue;
102
- }
103
- iterations += 1;
104
- if (iterations > MAX_DRAIN_ITERATIONS) {
105
- drainPhase2.length = 0;
106
- drainPhase3.length = 0;
107
- drainPhase4.length = 0;
108
- throw new Error(
109
- `batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations \u2014 likely a reactive cycle`
110
- );
111
- }
112
- const queue = drainPhase2.length > 0 ? drainPhase2 : drainPhase3.length > 0 ? drainPhase3 : drainPhase4;
113
- const ops = queue.splice(0);
114
- for (const run of ops) {
115
- try {
116
- run();
117
- } catch (e) {
118
- errors.push(e);
119
- }
120
- }
121
- }
122
- } finally {
123
- if (ownsFlush) flushInProgress = false;
124
- }
125
- if (errors.length === 1) throw errors[0];
126
- if (errors.length > 1) {
127
- throw new AggregateError(errors, "batch drain: multiple callbacks threw");
128
- }
129
- }
130
- function downWithBatch(sink, messages, tierOf) {
131
- if (messages.length === 0) return;
132
- if (messages.length === 1) {
133
- const tier = tierOf(messages[0][0]);
134
- if (tier < 3 || !isBatching()) {
135
- sink(messages);
136
- return;
137
- }
138
- const queue = tier >= 5 ? drainPhase4 : tier === 4 ? drainPhase3 : drainPhase2;
139
- queue.push(() => sink(messages));
140
- return;
141
- }
142
- const n = messages.length;
143
- let phase2Start = n;
144
- let phase3Start = n;
145
- let phase4Start = n;
146
- let i = 0;
147
- while (i < n && tierOf(messages[i][0]) < 3) i++;
148
- phase2Start = i;
149
- while (i < n && tierOf(messages[i][0]) === 3) i++;
150
- phase3Start = i;
151
- while (i < n && tierOf(messages[i][0]) === 4) i++;
152
- phase4Start = i;
153
- const batching = isBatching();
154
- if (phase2Start > 0) {
155
- const immediate = messages.slice(0, phase2Start);
156
- sink(immediate);
157
- }
158
- if (phase3Start > phase2Start) {
159
- const phase2 = messages.slice(phase2Start, phase3Start);
160
- if (batching) drainPhase2.push(() => sink(phase2));
161
- else sink(phase2);
162
- }
163
- if (phase4Start > phase3Start) {
164
- const phase3 = messages.slice(phase3Start, phase4Start);
165
- if (batching) drainPhase3.push(() => sink(phase3));
166
- else sink(phase3);
167
- }
168
- if (n > phase4Start) {
169
- const phase4 = messages.slice(phase4Start, n);
170
- if (batching) drainPhase4.push(() => sink(phase4));
171
- else sink(phase4);
172
- }
173
- }
174
-
175
- // src/core/messages.ts
176
- var START = /* @__PURE__ */ Symbol.for("graphrefly/START");
177
- var DATA = /* @__PURE__ */ Symbol.for("graphrefly/DATA");
178
- var DIRTY = /* @__PURE__ */ Symbol.for("graphrefly/DIRTY");
179
- var RESOLVED = /* @__PURE__ */ Symbol.for("graphrefly/RESOLVED");
180
- var INVALIDATE = /* @__PURE__ */ Symbol.for("graphrefly/INVALIDATE");
181
- var PAUSE = /* @__PURE__ */ Symbol.for("graphrefly/PAUSE");
182
- var RESUME = /* @__PURE__ */ Symbol.for("graphrefly/RESUME");
183
- var TEARDOWN = /* @__PURE__ */ Symbol.for("graphrefly/TEARDOWN");
184
- var COMPLETE = /* @__PURE__ */ Symbol.for("graphrefly/COMPLETE");
185
- var ERROR = /* @__PURE__ */ Symbol.for("graphrefly/ERROR");
186
- var DIRTY_MSG = Object.freeze([DIRTY]);
187
- var RESOLVED_MSG = Object.freeze([RESOLVED]);
188
- var INVALIDATE_MSG = Object.freeze([INVALIDATE]);
189
- var START_MSG = Object.freeze([START]);
190
- var COMPLETE_MSG = Object.freeze([COMPLETE]);
191
- var TEARDOWN_MSG = Object.freeze([TEARDOWN]);
192
- var DIRTY_ONLY_BATCH = Object.freeze([DIRTY_MSG]);
193
- var RESOLVED_ONLY_BATCH = Object.freeze([RESOLVED_MSG]);
194
- var INVALIDATE_ONLY_BATCH = Object.freeze([INVALIDATE_MSG]);
195
- var COMPLETE_ONLY_BATCH = Object.freeze([COMPLETE_MSG]);
196
- var TEARDOWN_ONLY_BATCH = Object.freeze([TEARDOWN_MSG]);
197
-
198
- // src/graph/codec.ts
199
- var JsonCodec = {
200
- name: "json",
201
- version: 1,
202
- contentType: "application/json",
203
- encode(snapshot) {
204
- const json = JSON.stringify(snapshot);
205
- return new TextEncoder().encode(json);
206
- },
207
- decode(buffer, _codecVersion) {
208
- const json = new TextDecoder().decode(buffer);
209
- return JSON.parse(json);
210
- }
211
- };
212
- function registerBuiltinCodecs(config) {
213
- config.registerCodec(JsonCodec);
214
- }
215
-
216
- // src/core/actor.ts
217
- var DEFAULT_ACTOR = { type: "system", id: "" };
218
- function normalizeActor(actor) {
219
- if (actor == null) return DEFAULT_ACTOR;
220
- const { type, id, ...rest } = actor;
221
- return {
222
- type: type ?? "system",
223
- id: id ?? "",
224
- ...rest
225
- };
226
- }
227
-
228
- // src/core/clock.ts
229
- function wallClockNs() {
230
- return Date.now() * 1e6;
231
- }
232
-
233
- // src/core/config.ts
234
- var GraphReFlyConfig = class {
235
- _messageTypes = /* @__PURE__ */ new Map();
236
- _codecs = /* @__PURE__ */ new Map();
237
- _onMessage;
238
- _onSubscribe;
239
- _defaultVersioning;
240
- _defaultHashFn;
241
- _inspectorEnabled = !(typeof process !== "undefined" && process.env?.NODE_ENV === "production");
242
- _globalInspector;
243
- _frozen = false;
244
- /**
245
- * Pre-bound tier lookup — shared by every node bound to this config. Since
246
- * the registry is frozen on first hook access, this closure can be built
247
- * once in the constructor and handed directly to `downWithBatch` /
248
- * `_frameBatch` paths without per-node or per-emission `.bind(config)`
249
- * allocation.
250
- */
251
- tierOf;
252
- constructor(init) {
253
- this._onMessage = init.onMessage;
254
- this._onSubscribe = init.onSubscribe;
255
- this._defaultVersioning = init.defaultVersioning;
256
- this._defaultHashFn = init.defaultHashFn;
257
- this.tierOf = (t) => {
258
- const reg = this._messageTypes.get(t);
259
- return reg != null ? reg.tier : 1;
260
- };
261
- }
262
- // --- Hook getters (freeze on read) ---
263
- get onMessage() {
264
- this._frozen = true;
265
- return this._onMessage;
266
- }
267
- get onSubscribe() {
268
- this._frozen = true;
269
- return this._onSubscribe;
270
- }
271
- // --- Hook setters (throw when frozen) ---
272
- set onMessage(v) {
273
- this._assertUnfrozen();
274
- this._onMessage = v;
275
- }
276
- set onSubscribe(v) {
277
- this._assertUnfrozen();
278
- this._onSubscribe = v;
279
- }
280
- /**
281
- * Default versioning level applied to every node bound to this config,
282
- * unless the node's own `opts.versioning` provides an explicit override.
283
- * Setting this is only allowed before the config freezes (i.e., before
284
- * the first node is created) so every node in the graph sees a
285
- * consistent starting level. Individual nodes can still opt into a
286
- * higher level via `opts.versioning`, or post-hoc via
287
- * `NodeImpl._applyVersioning(level)` when the node is quiescent.
288
- *
289
- * v0 is the minimum opt-in — unversioned nodes (`undefined`) skip
290
- * the version counter entirely. v1 adds content-addressed cid.
291
- * Future levels (v2, v3) are reserved for linked-history and
292
- * cryptographic attestation extensions.
293
- */
294
- get defaultVersioning() {
295
- return this._defaultVersioning;
296
- }
297
- set defaultVersioning(v) {
298
- this._assertUnfrozen();
299
- this._defaultVersioning = v;
300
- }
301
- /**
302
- * Default content-hash function applied to every versioned node bound
303
- * to this config, unless the node's own `opts.versioningHash` provides
304
- * an explicit override. Use this when a graph needs a non-default hash
305
- * — e.g., swap the vendored sync SHA-256 for a faster non-crypto hash
306
- * (xxHash, FNV-1a) in hot-path workloads, or a stronger hash when
307
- * versioning v1 cids are used as audit anchors.
308
- *
309
- * Only settable before the config freezes. Individual nodes can still
310
- * override via `opts.versioningHash`.
311
- */
312
- get defaultHashFn() {
313
- return this._defaultHashFn;
314
- }
315
- set defaultHashFn(v) {
316
- this._assertUnfrozen();
317
- this._defaultHashFn = v;
318
- }
319
- /**
320
- * When `false`, structured observation options (`causal`, `timeline`)
321
- * and `Graph.trace()` writes are no-ops. Raw `Graph.observe()` always
322
- * works. Default: `true` outside production (`NODE_ENV !== "production"`).
323
- *
324
- * Settable at any time — inspector gating is an operational concern, not
325
- * a protocol invariant, so it does NOT require freeze before node creation.
326
- */
327
- get inspectorEnabled() {
328
- return this._inspectorEnabled;
329
- }
330
- set inspectorEnabled(v) {
331
- this._inspectorEnabled = v;
332
- }
333
- /**
334
- * Process-global observability hook (Redux-DevTools-style full-graph
335
- * tracer). Fires once per outgoing batch from every node bound to this
336
- * config, gated by {@link inspectorEnabled}. See {@link GlobalInspectorHook}.
337
- *
338
- * Settable at any time — like {@link inspectorEnabled} this is operational,
339
- * not protocol-shaping, so it does NOT trigger config freeze.
340
- */
341
- get globalInspector() {
342
- return this._globalInspector;
343
- }
344
- set globalInspector(v) {
345
- this._globalInspector = v;
346
- }
347
- // --- Registry (writes require unfrozen; reads are free lookups) ---
348
- /**
349
- * Register a custom message type. Must be called before any node that
350
- * uses this config has been created — otherwise throws. Default
351
- * `wireCrossing` is `tier >= 3`.
352
- */
353
- registerMessageType(t, input) {
354
- this._assertUnfrozen();
355
- this._messageTypes.set(t, {
356
- tier: input.tier,
357
- wireCrossing: input.wireCrossing ?? input.tier >= 3,
358
- metaPassthrough: input.metaPassthrough ?? true
359
- });
360
- return this;
361
- }
362
- /** Tier for `t`. Unknown types default to tier 1 (immediate, after START). */
363
- messageTier(t) {
364
- const reg = this._messageTypes.get(t);
365
- return reg != null ? reg.tier : 1;
366
- }
367
- /**
368
- * Whether `t` is registered as wire-crossing. Unknown types default to
369
- * `true` (spec §1.3.6 forward-compat — unknowns cross the wire).
370
- */
371
- isWireCrossing(t) {
372
- const reg = this._messageTypes.get(t);
373
- return reg != null ? reg.wireCrossing : true;
374
- }
375
- /** Convenience inverse of {@link isWireCrossing}. */
376
- isLocalOnly(t) {
377
- return !this.isWireCrossing(t);
378
- }
379
- /**
380
- * Whether `t` is forwarded to meta companions by `Graph.signal`. Defaults
381
- * to `true` for unknowns (forward-compat — new types pass through meta by
382
- * default; opt-in filter via `registerMessageType({metaPassthrough: false})`).
383
- */
384
- isMetaPassthrough(t) {
385
- const reg = this._messageTypes.get(t);
386
- return reg != null ? reg.metaPassthrough : true;
387
- }
388
- /** Whether `t` is a registered (built-in or custom) type. */
389
- isKnownMessageType(t) {
390
- return this._messageTypes.has(t);
391
- }
392
- // --- Codec registry (writes require unfrozen; reads are free lookups) ---
393
- /**
394
- * Register a graph codec by `codec.name`. Used by the envelope-based
395
- * `graph.snapshot({format: "bytes", codec: name})` path and
396
- * `Graph.decode(bytes)` auto-dispatch. Must be called before any node
397
- * bound to this config is created — otherwise throws.
398
- *
399
- * Re-registering the same name overwrites, so user codecs can shadow
400
- * built-in ones before freeze (e.g., to swap a zstd-wrapped dag-cbor in
401
- * for `"dag-cbor"`).
402
- */
403
- registerCodec(codec) {
404
- this._assertUnfrozen();
405
- this._codecs.set(codec.name, codec);
406
- return this;
407
- }
408
- /**
409
- * Resolve a registered codec by name. Returns `undefined` for unknown
410
- * names. Typed callers cast to their concrete codec interface (e.g.,
411
- * `config.lookupCodec<GraphCodec>("json")`) — this method stays
412
- * layer-pure (no import of graph-layer types into `core/`).
413
- */
414
- lookupCodec(name) {
415
- return this._codecs.get(name);
416
- }
417
- /** @internal Used by tests and dev tooling — check freeze state without triggering it. */
418
- _isFrozen() {
419
- return this._frozen;
420
- }
421
- _assertUnfrozen() {
422
- if (this._frozen) {
423
- throw new Error(
424
- "GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node."
425
- );
426
- }
427
- }
428
- };
429
- function registerBuiltins(cfg) {
430
- cfg.registerMessageType(START, { tier: 0, wireCrossing: false });
431
- cfg.registerMessageType(DIRTY, { tier: 1, wireCrossing: false });
432
- cfg.registerMessageType(INVALIDATE, {
433
- tier: 1,
434
- wireCrossing: false,
435
- metaPassthrough: false
436
- });
437
- cfg.registerMessageType(PAUSE, { tier: 2, wireCrossing: false });
438
- cfg.registerMessageType(RESUME, { tier: 2, wireCrossing: false });
439
- cfg.registerMessageType(DATA, { tier: 3, wireCrossing: true });
440
- cfg.registerMessageType(RESOLVED, { tier: 3, wireCrossing: true });
441
- cfg.registerMessageType(COMPLETE, {
442
- tier: 4,
443
- wireCrossing: true,
444
- metaPassthrough: false
445
- });
446
- cfg.registerMessageType(ERROR, {
447
- tier: 4,
448
- wireCrossing: true,
449
- metaPassthrough: false
450
- });
451
- cfg.registerMessageType(TEARDOWN, {
452
- tier: 5,
453
- wireCrossing: true,
454
- metaPassthrough: false
455
- });
456
- }
457
-
458
- // src/core/guard.ts
459
- var GuardDenied = class extends Error {
460
- actor;
461
- action;
462
- nodeName;
463
- /**
464
- * @param details - Actor, action, and optional node name for the denial.
465
- * @param message - Optional override for the default error message.
466
- */
467
- constructor(details, message) {
468
- super(
469
- message ?? `GuardDenied: action "${String(details.action)}" denied for actor type "${String(details.actor.type)}"`
470
- );
471
- this.name = "GuardDenied";
472
- this.actor = details.actor;
473
- this.action = details.action;
474
- this.nodeName = details.nodeName;
475
- }
476
- /** Qualified registry path when known (roadmap diagnostics: same as {@link nodeName}). */
477
- get node() {
478
- return this.nodeName;
479
- }
480
- };
481
-
482
- // src/core/versioning.ts
483
- function canonicalizeForHash(value) {
484
- if (value === void 0) return null;
485
- if (typeof value === "number") {
486
- if (!Number.isFinite(value)) {
487
- throw new TypeError(`Cannot hash non-finite number: ${value}`);
488
- }
489
- if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
490
- throw new TypeError(
491
- `Cannot hash integer outside safe range (|n| > 2^53-1): ${value}. Cross-language cid parity is not guaranteed for unsafe integers.`
492
- );
493
- }
494
- return value;
495
- }
496
- if (typeof value === "string" || typeof value === "boolean" || value === null) {
497
- return value;
498
- }
499
- if (Array.isArray(value)) {
500
- return value.map(canonicalizeForHash);
501
- }
502
- if (typeof value === "object" && value !== null) {
503
- const sorted = {};
504
- for (const k of Object.keys(value).sort()) {
505
- sorted[k] = canonicalizeForHash(value[k]);
506
- }
507
- return sorted;
508
- }
509
- return null;
510
- }
511
- var SHA256_K = /* @__PURE__ */ new Uint32Array([
512
- 1116352408,
513
- 1899447441,
514
- 3049323471,
515
- 3921009573,
516
- 961987163,
517
- 1508970993,
518
- 2453635748,
519
- 2870763221,
520
- 3624381080,
521
- 310598401,
522
- 607225278,
523
- 1426881987,
524
- 1925078388,
525
- 2162078206,
526
- 2614888103,
527
- 3248222580,
528
- 3835390401,
529
- 4022224774,
530
- 264347078,
531
- 604807628,
532
- 770255983,
533
- 1249150122,
534
- 1555081692,
535
- 1996064986,
536
- 2554220882,
537
- 2821834349,
538
- 2952996808,
539
- 3210313671,
540
- 3336571891,
541
- 3584528711,
542
- 113926993,
543
- 338241895,
544
- 666307205,
545
- 773529912,
546
- 1294757372,
547
- 1396182291,
548
- 1695183700,
549
- 1986661051,
550
- 2177026350,
551
- 2456956037,
552
- 2730485921,
553
- 2820302411,
554
- 3259730800,
555
- 3345764771,
556
- 3516065817,
557
- 3600352804,
558
- 4094571909,
559
- 275423344,
560
- 430227734,
561
- 506948616,
562
- 659060556,
563
- 883997877,
564
- 958139571,
565
- 1322822218,
566
- 1537002063,
567
- 1747873779,
568
- 1955562222,
569
- 2024104815,
570
- 2227730452,
571
- 2361852424,
572
- 2428436474,
573
- 2756734187,
574
- 3204031479,
575
- 3329325298
576
- ]);
577
- var UTF8_ENCODER = /* @__PURE__ */ new TextEncoder();
578
- function sha256Hex(msg) {
579
- const bytes = UTF8_ENCODER.encode(msg);
580
- const msgLen = bytes.length;
581
- const bitLen = msgLen * 8;
582
- const totalLen = msgLen + 9 + 63 & ~63;
583
- const padded = new Uint8Array(totalLen);
584
- padded.set(bytes);
585
- padded[msgLen] = 128;
586
- const dv = new DataView(padded.buffer);
587
- dv.setUint32(totalLen - 4, bitLen >>> 0, false);
588
- dv.setUint32(totalLen - 8, Math.floor(bitLen / 4294967296) >>> 0, false);
589
- let h0 = 1779033703;
590
- let h1 = 3144134277;
591
- let h2 = 1013904242;
592
- let h3 = 2773480762;
593
- let h4 = 1359893119;
594
- let h5 = 2600822924;
595
- let h6 = 528734635;
596
- let h7 = 1541459225;
597
- const W = new Uint32Array(64);
598
- const rotr = (x, n) => x >>> n | x << 32 - n;
599
- for (let off = 0; off < totalLen; off += 64) {
600
- for (let i = 0; i < 16; i++) W[i] = dv.getUint32(off + i * 4, false);
601
- for (let i = 16; i < 64; i++) {
602
- const w15 = W[i - 15];
603
- const w2 = W[i - 2];
604
- const s0 = rotr(w15, 7) ^ rotr(w15, 18) ^ w15 >>> 3;
605
- const s1 = rotr(w2, 17) ^ rotr(w2, 19) ^ w2 >>> 10;
606
- W[i] = W[i - 16] + s0 + W[i - 7] + s1 >>> 0;
607
- }
608
- let a = h0;
609
- let b = h1;
610
- let c = h2;
611
- let d = h3;
612
- let e = h4;
613
- let f = h5;
614
- let g = h6;
615
- let h = h7;
616
- for (let i = 0; i < 64; i++) {
617
- const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
618
- const ch = e & f ^ ~e & g;
619
- const t1 = h + S1 + ch + SHA256_K[i] + W[i] >>> 0;
620
- const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
621
- const mj = a & b ^ a & c ^ b & c;
622
- const t2 = S0 + mj >>> 0;
623
- h = g;
624
- g = f;
625
- f = e;
626
- e = d + t1 >>> 0;
627
- d = c;
628
- c = b;
629
- b = a;
630
- a = t1 + t2 >>> 0;
631
- }
632
- h0 = h0 + a >>> 0;
633
- h1 = h1 + b >>> 0;
634
- h2 = h2 + c >>> 0;
635
- h3 = h3 + d >>> 0;
636
- h4 = h4 + e >>> 0;
637
- h5 = h5 + f >>> 0;
638
- h6 = h6 + g >>> 0;
639
- h7 = h7 + h >>> 0;
640
- }
641
- const toHex = (x) => x.toString(16).padStart(8, "0");
642
- return toHex(h0) + toHex(h1) + toHex(h2) + toHex(h3) + toHex(h4) + toHex(h5) + toHex(h6) + toHex(h7);
643
- }
644
- function defaultHash(value) {
645
- const canonical = canonicalizeForHash(value ?? null);
646
- const json = JSON.stringify(canonical);
647
- return sha256Hex(json).slice(0, 16);
648
- }
649
- function randomUuid() {
650
- const c = globalThis.crypto;
651
- if (c?.randomUUID) return c.randomUUID();
652
- const r = () => Math.floor(Math.random() * 4294967296).toString(16).padStart(8, "0");
653
- const hex = r() + r() + r() + r();
654
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${(parseInt(hex.slice(16, 17), 16) & 3 | 8).toString(16)}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
655
- }
656
- function createVersioning(level, initialValue, opts) {
657
- const id = opts?.id ?? randomUuid();
658
- if (level === 0) {
659
- return { id, version: 0 };
660
- }
661
- const hash = opts?.hash ?? defaultHash;
662
- const cid = hash(initialValue);
663
- return { id, version: 0, cid, prev: null };
664
- }
665
- function advanceVersion(info, newValue, hashFn) {
666
- info.version += 1;
667
- if ("cid" in info) {
668
- info.prev = info.cid;
669
- info.cid = hashFn(newValue);
670
- }
671
- }
672
-
673
- // src/core/node.ts
674
- var noopUnsub = () => {
675
- };
676
- var MAX_RERUN_DEPTH = 100;
677
- function createDepRecord(n) {
678
- return {
679
- node: n,
680
- unsub: null,
681
- prevData: void 0,
682
- dirty: false,
683
- involvedThisWave: false,
684
- dataBatch: [],
685
- terminal: void 0
686
- };
687
- }
688
- function resetDepRecord(d) {
689
- d.prevData = void 0;
690
- d.dirty = false;
691
- d.involvedThisWave = false;
692
- d.dataBatch.length = 0;
693
- d.terminal = void 0;
694
- }
695
- function normalizeMessages(input) {
696
- if (input.length === 0) return input;
697
- return typeof input[0] === "symbol" ? [input] : input;
698
- }
699
- var defaultOnMessage = (node2, msg, ctx, _actions) => {
700
- if (ctx.direction === "down-in") {
701
- node2._onDepMessage(ctx.depIndex, msg);
702
- }
703
- return void 0;
704
- };
705
- var defaultOnSubscribe = (node2, sink, _ctx, _actions) => {
706
- const impl = node2;
707
- if (impl._status === "completed" || impl._status === "errored") return;
708
- const cached = impl._cached;
709
- const initial = cached === void 0 ? [START_MSG] : [START_MSG, [DATA, cached]];
710
- if (impl._status === "dirty") initial.push(DIRTY_MSG);
711
- downWithBatch(sink, initial, impl._config.tierOf);
712
- };
713
- var defaultConfig = new GraphReFlyConfig({
714
- onMessage: defaultOnMessage,
715
- onSubscribe: defaultOnSubscribe
716
- });
717
- registerBuiltins(defaultConfig);
718
- registerBuiltinCodecs(defaultConfig);
719
- var NodeImpl = class _NodeImpl {
720
- // --- Identity ---
721
- _optsName;
722
- _describeKind;
723
- meta;
724
- /**
725
- * Cached `Object.keys(meta).length > 0` check. `meta` is frozen at
726
- * construction so this boolean never flips. Used by `_emit` to skip
727
- * the meta TEARDOWN fan-out block allocation on the common "no meta"
728
- * hot path.
729
- */
730
- _hasMeta;
731
- // --- Config ---
732
- _config;
733
- // --- Topology ---
734
- /** Mutable for autoTrackNode / Graph.connect() post-construction dep addition. */
735
- _deps;
736
- _sinks = null;
737
- _sinkCount = 0;
738
- // --- State ---
739
- _cached;
740
- _status;
741
- _cleanup;
742
- _store = {};
743
- _waveHasNewData = false;
744
- _hasNewTerminal = false;
745
- _hasCalledFnOnce = false;
746
- _paused = false;
747
- _pendingWave = false;
748
- _isExecutingFn = false;
749
- _pendingRerun = false;
750
- _rerunDepth = 0;
751
- // --- Settlement counter (A3) ---
752
- /**
753
- * Count of deps currently in `dirty === true`. `_maybeRunFnOnSettlement`
754
- * treats `0` as "wave settled" — O(1) check for full dep settlement.
755
- */
756
- _dirtyDepCount = 0;
757
- // --- Per-batch emit accumulator (Bug 2: K+1 fan-in fix) ---
758
- /**
759
- * Inside an explicit `batch(() => ...)` scope, every `_emit` accumulates
760
- * its already-framed messages here instead of dispatching synchronously.
761
- * At batch end, `_flushBatchPending` runs (registered via
762
- * `registerBatchFlushHook`) and delivers the whole accumulated batch as
763
- * one `downWithBatch` call — collapsing what would otherwise be K
764
- * separate sink invocations into one. This is the fix for the diamond
765
- * fan-in K+1 over-fire.
766
- *
767
- * `null` outside batch (or after flush). Only ever appended to within
768
- * a single explicit batch lifetime; reset to `null` on flush. State
769
- * updates (cache, version, status) still happen per-emit via
770
- * `_updateState` — only the downstream delivery is coalesced.
771
- */
772
- _batchPendingMessages = null;
773
- // --- PAUSE/RESUME lock tracking (C0) ---
774
- /**
775
- * Set of active pause locks held against this node. Every `[PAUSE, lockId]`
776
- * adds its `lockId` to the set; every `[RESUME, lockId]` removes it.
777
- * `_paused` is a derived quantity: `_pauseLocks.size > 0`. Multi-pauser
778
- * correctness — one controller releasing its lock does NOT resume the
779
- * node while another controller still holds its lock.
780
- */
781
- _pauseLocks = null;
782
- /**
783
- * Buffered DATA messages held while paused. Only populated when
784
- * `_pausable === "resumeAll"` (bufferAll mode). On final lock release
785
- * the buffer is replayed through the node's outgoing pipeline in the
786
- * order received. Non-bufferAll pause mode drops DATA on the floor
787
- * (upstream is expected to honor PAUSE by suppressing production).
788
- */
789
- _pauseBuffer = null;
790
- // --- Options (frozen at construction) ---
791
- _fn;
792
- _equals;
793
- _resubscribable;
794
- _resetOnTeardown;
795
- _autoComplete;
796
- _autoError;
797
- _pausable;
798
- _guard;
799
- /**
800
- * @internal Additional guards stacked at runtime via {@link NodeImpl._pushGuard}
801
- * (e.g. by `policyEnforcer({ mode: "enforce" })`, roadmap §9.2). Effective
802
- * write/signal/observe checks AND the original `_guard` with every entry here.
803
- */
804
- _extraGuards;
805
- _hashFn;
806
- _versioning;
807
- /**
808
- * Explicit versioning level, tracked separately from `_versioning` so
809
- * monotonicity checks and future v2/v3 extensions don't rely on the
810
- * fragile `"cid" in _versioning` shape discriminator. `undefined` means
811
- * the node has no versioning attached; `0` / `1` / future levels name
812
- * the tier. Mutated in lockstep with `_versioning` by the constructor
813
- * and by `_applyVersioning`.
814
- */
815
- _versioningLevel;
816
- // --- ABAC ---
817
- _lastMutation;
818
- /**
819
- * @internal Per-node inspector hooks for `Graph.observe(path,
820
- * { causal, derived })`. Fires in `_onDepMessage` and `_execFn`.
821
- * Attached via `_setInspectorHook` (returns a disposer). Multiple
822
- * observers can attach simultaneously — all registered hooks fire for
823
- * every event.
824
- */
825
- _inspectorHooks;
826
- // --- Actions (built once in the constructor) ---
827
- _actions;
828
- constructor(deps, fn, opts) {
829
- this._config = opts.config ?? defaultConfig;
830
- void this._config.onMessage;
831
- this._optsName = opts.name;
832
- this._describeKind = opts.describeKind;
833
- this._equals = opts.equals ?? Object.is;
834
- this._resubscribable = opts.resubscribable ?? false;
835
- this._resetOnTeardown = opts.resetOnTeardown ?? false;
836
- this._autoComplete = opts.completeWhenDepsComplete ?? true;
837
- this._autoError = opts.errorWhenDepsError ?? true;
838
- this._pausable = opts.pausable ?? true;
839
- this._guard = opts.guard;
840
- this._fn = fn;
841
- this._cached = opts.initial !== void 0 ? opts.initial : void 0;
842
- this._status = deps.length === 0 && fn == null && this._cached !== void 0 ? "settled" : "sentinel";
843
- this._hashFn = opts.versioningHash ?? this._config.defaultHashFn ?? defaultHash;
844
- const versioningLevel = opts.versioning ?? this._config.defaultVersioning;
845
- this._versioningLevel = versioningLevel;
846
- this._versioning = versioningLevel != null ? createVersioning(versioningLevel, this._cached === void 0 ? void 0 : this._cached, {
847
- id: opts.versioningId,
848
- hash: this._hashFn
849
- }) : void 0;
850
- this._deps = deps.map(createDepRecord);
851
- const meta = {};
852
- for (const [k, v] of Object.entries(opts.meta ?? {})) {
853
- const metaOpts = {
854
- initial: v,
855
- name: `${opts.name ?? "node"}:meta:${k}`,
856
- describeKind: "state",
857
- config: this._config
858
- };
859
- if (opts.guard != null) metaOpts.guard = opts.guard;
860
- meta[k] = new _NodeImpl([], void 0, metaOpts);
861
- }
862
- Object.freeze(meta);
863
- this.meta = meta;
864
- this._hasMeta = Object.keys(meta).length > 0;
865
- const self = this;
866
- this._actions = {
867
- emit(value) {
868
- self._emit([[DATA, value]]);
869
- },
870
- down(messageOrMessages) {
871
- self._emit(normalizeMessages(messageOrMessages));
872
- },
873
- up(messageOrMessages) {
874
- self._emitUp(normalizeMessages(messageOrMessages));
875
- }
876
- };
877
- this.down = this.down.bind(this);
878
- this.up = this.up.bind(this);
879
- }
880
- // --- Derived state ---
881
- get _isTerminal() {
882
- return this._status === "completed" || this._status === "errored";
883
- }
884
- // --- Public getters ---
885
- get name() {
886
- return this._optsName;
887
- }
888
- get status() {
889
- return this._status;
890
- }
891
- get cache() {
892
- return this._cached === void 0 ? void 0 : this._cached;
893
- }
894
- get lastMutation() {
895
- return this._lastMutation;
896
- }
897
- get v() {
898
- return this._versioning;
899
- }
900
- hasGuard() {
901
- return this._guard != null;
902
- }
903
- /**
904
- * @internal Retroactively attach (or upgrade) versioning state on this
905
- * node. Intended for `Graph.setVersioning(level)` bulk application and
906
- * for rare cases where a specific node needs to be bumped to a higher
907
- * level (e.g., `v0 → v1`) after construction.
908
- *
909
- * **Safety:** the mutation is rejected mid-wave. Specifically,
910
- * throws if the node is currently executing its fn (`_isExecutingFn`).
911
- * Callers at quiescent points — before the first sink subscribes, or
912
- * after all sinks unsubscribe, or between external `down()` / `emit()`
913
- * invocations — are safe. The re-entrance window that motivated §10.6.4
914
- * removal was the "transition `_versioning` from `undefined` to a fresh
915
- * object mid-`_updateState`" case; that path is now guarded.
916
- *
917
- * **Monotonicity:** levels can only go up. Downgrade (e.g., `v1 → v0`)
918
- * is a no-op — once a node carries higher-level metadata, dropping it
919
- * mid-graph would tear the linked-history invariant for v1 and above.
920
- *
921
- * **Linked-history boundary (D1, 2026-04-13):** upgrading v0 → v1
922
- * produces a **fresh history root**. The new v1 state has `cid =
923
- * hash(currentCachedValue)` and `prev = null`, not a synthetic `prev`
924
- * anchored to any previous v0 value. The v0 monotonic `version` counter
925
- * is preserved across the upgrade, but the linked-cid chain (spec §7)
926
- * starts fresh at the upgrade point. Downstream audit tools that walk
927
- * `v.cid.prev` backwards through time will see a `null` boundary at
928
- * the upgrade — **this is intentional**: v0 had no cid to link to, and
929
- * fabricating one would lie about the hash. Callers that require an
930
- * unbroken cid chain from birth must attach versioning at construction
931
- * via `opts.versioning` or `config.defaultVersioning`, not retroactively.
932
- *
933
- * @param level - New minimum versioning level.
934
- * @param opts - Optional id / hash overrides; applied only if the
935
- * node currently has no versioning state.
936
- */
937
- _applyVersioning(level, opts) {
938
- if (this._isExecutingFn) {
939
- throw new Error(
940
- `Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`
941
- );
942
- }
943
- const currentLevel = this._versioningLevel;
944
- if (currentLevel != null && level <= currentLevel) {
945
- return;
946
- }
947
- const hash = opts?.hash ?? this._hashFn;
948
- if (hash !== this._hashFn) this._hashFn = hash;
949
- const initialValue = this._cached === void 0 ? void 0 : this._cached;
950
- const current = this._versioning;
951
- const preservedId = current?.id ?? opts?.id;
952
- const preservedVersion = current?.version ?? 0;
953
- const fresh = createVersioning(level, initialValue, {
954
- id: preservedId,
955
- hash
956
- });
957
- fresh.version = preservedVersion;
958
- this._versioning = fresh;
959
- this._versioningLevel = level;
960
- }
961
- /**
962
- * @internal Attach an inspector hook. Returns a disposer that removes
963
- * the hook. Used by `Graph.observe(path, { causal, derived })` to build
964
- * causal traces. Multiple hooks may be attached concurrently — all fire
965
- * for every event in registration order. Passing `undefined` is a no-op
966
- * and returns a no-op disposer.
967
- */
968
- _setInspectorHook(hook) {
969
- if (hook == null) return () => {
970
- };
971
- if (this._inspectorHooks == null) this._inspectorHooks = /* @__PURE__ */ new Set();
972
- this._inspectorHooks.add(hook);
973
- return () => {
974
- this._inspectorHooks?.delete(hook);
975
- if (this._inspectorHooks?.size === 0) this._inspectorHooks = void 0;
976
- };
977
- }
978
- /**
979
- * @internal Push an additional guard onto this node. Effective enforcement
980
- * is the AND of `_guard` and every guard pushed via this hook — any one
981
- * rejecting throws {@link GuardDenied}. Returns a disposer that removes
982
- * the pushed guard. Multiple guards may be stacked simultaneously.
983
- *
984
- * Used by `policyEnforcer({ mode: "enforce" })` (roadmap §9.2) to overlay
985
- * runtime constraint enforcement onto an existing graph without rebuilding
986
- * its nodes. Pre-1.0 internal API; not part of the public surface.
987
- *
988
- * **Identity semantics:** guards are tracked in a `Set`, so pushing the
989
- * same `NodeGuard` reference twice is a single registration. Wrap each
990
- * push in a unique closure if independent stacking is needed.
991
- *
992
- * **Iteration order:** insertion-ordered (`Set` semantics). Determinism
993
- * follows from single-threaded JS execution; nested re-entry from inside
994
- * a guard body (push/pop while iterating) is undefined-but-survivable.
995
- */
996
- _pushGuard(guard) {
997
- if (this._extraGuards == null) this._extraGuards = /* @__PURE__ */ new Set();
998
- this._extraGuards.add(guard);
999
- return () => {
1000
- this._extraGuards?.delete(guard);
1001
- if (this._extraGuards?.size === 0) this._extraGuards = void 0;
1002
- };
1003
- }
1004
- allowsObserve(actor) {
1005
- if (this._guard == null && this._extraGuards == null) return true;
1006
- const a = normalizeActor(actor);
1007
- if (this._guard != null && !this._guard(a, "observe")) return false;
1008
- if (this._extraGuards != null) {
1009
- for (const eg of this._extraGuards) {
1010
- if (!eg(a, "observe")) return false;
1011
- }
1012
- }
1013
- return true;
1014
- }
1015
- // --- Guard helper ---
1016
- _checkGuard(options) {
1017
- if (options?.internal) return;
1018
- const hasGuard = this._guard != null || this._extraGuards != null;
1019
- const hasActor = options?.actor != null;
1020
- if (!hasGuard && !hasActor) return;
1021
- const actor = normalizeActor(options?.actor);
1022
- const action2 = options?.delivery === "signal" ? "signal" : "write";
1023
- if (this._guard != null && !this._guard(actor, action2)) {
1024
- throw new GuardDenied({ actor, action: action2, nodeName: this.name });
1025
- }
1026
- if (this._extraGuards != null) {
1027
- for (const eg of this._extraGuards) {
1028
- if (!eg(actor, action2)) {
1029
- throw new GuardDenied({ actor, action: action2, nodeName: this.name });
1030
- }
1031
- }
1032
- }
1033
- this._lastMutation = { actor, timestamp_ns: wallClockNs() };
1034
- }
1035
- // --- Public transport ---
1036
- down(messageOrMessages, options) {
1037
- const messages = normalizeMessages(messageOrMessages);
1038
- if (messages.length === 0) return;
1039
- this._checkGuard(options);
1040
- this._emit(messages);
1041
- }
1042
- emit(value, options) {
1043
- this._checkGuard(options);
1044
- this._emit([[DATA, value]]);
1045
- }
1046
- up(messageOrMessages, options) {
1047
- if (this._deps.length === 0) return;
1048
- const messages = normalizeMessages(messageOrMessages);
1049
- if (messages.length === 0) return;
1050
- this._checkGuard(options);
1051
- const forwardOpts = options ?? { internal: true };
1052
- this._validateUpTiers(messages);
1053
- for (const d of this._deps) {
1054
- d.node.up?.(messages, forwardOpts);
1055
- }
1056
- }
1057
- /**
1058
- * @internal Internal up-path used by `actions.up(...)` from inside fn.
1059
- * Same tier validation as public `up`, but bypasses the guard check
1060
- * since the fn context is already inside an authorized operation.
1061
- */
1062
- _emitUp(messages) {
1063
- if (this._deps.length === 0) return;
1064
- if (messages.length === 0) return;
1065
- this._validateUpTiers(messages);
1066
- for (const d of this._deps) {
1067
- d.node.up?.(messages, { internal: true });
1068
- }
1069
- }
1070
- /**
1071
- * @internal Enforce spec §1.2 — up-direction messages are restricted to
1072
- * tier 0–2 and tier 5 (START, DIRTY, INVALIDATE, PAUSE, RESUME,
1073
- * TEARDOWN). Tier 3 (DATA/RESOLVED) and tier 4 (COMPLETE/ERROR) are
1074
- * downstream-only. Emitting tier-3/4 via `up` would bypass equals
1075
- * substitution and cache advance entirely and is a protocol bug.
1076
- */
1077
- _validateUpTiers(messages) {
1078
- const tierOf = this._config.tierOf;
1079
- for (const m of messages) {
1080
- const tier = tierOf(m[0]);
1081
- if (tier === 3 || tier === 4) {
1082
- throw new Error(
1083
- `Node "${this.name}": tier-${tier} 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).`
1084
- );
1085
- }
1086
- }
1087
- }
1088
- subscribe(sink, actor) {
1089
- if (actor != null && this._guard != null) {
1090
- const a = normalizeActor(actor);
1091
- if (!this._guard(a, "observe")) {
1092
- throw new GuardDenied({ actor: a, action: "observe", nodeName: this.name });
1093
- }
1094
- }
1095
- const wasTerminal = this._isTerminal;
1096
- const afterTerminalReset = wasTerminal && this._resubscribable;
1097
- if (afterTerminalReset) {
1098
- this._cached = void 0;
1099
- this._status = "sentinel";
1100
- this._store = {};
1101
- this._hasCalledFnOnce = false;
1102
- this._waveHasNewData = false;
1103
- this._hasNewTerminal = false;
1104
- this._paused = false;
1105
- this._pendingWave = false;
1106
- this._pendingRerun = false;
1107
- this._isExecutingFn = false;
1108
- this._rerunDepth = 0;
1109
- this._dirtyDepCount = 0;
1110
- this._pauseLocks = null;
1111
- this._pauseBuffer = null;
1112
- for (const d of this._deps) resetDepRecord(d);
1113
- }
1114
- this._sinkCount += 1;
1115
- let subCleanup;
1116
- try {
1117
- subCleanup = this._config.onSubscribe(
1118
- this,
1119
- sink,
1120
- { sinkCount: this._sinkCount, afterTerminalReset },
1121
- this._actions
1122
- );
1123
- } catch (err) {
1124
- this._sinkCount -= 1;
1125
- throw err;
1126
- }
1127
- if (this._sinks == null) {
1128
- this._sinks = sink;
1129
- } else if (typeof this._sinks === "function") {
1130
- this._sinks = /* @__PURE__ */ new Set([this._sinks, sink]);
1131
- } else {
1132
- this._sinks.add(sink);
1133
- }
1134
- const isTerminalNow = this._isTerminal;
1135
- if (this._sinkCount === 1 && !isTerminalNow) {
1136
- try {
1137
- this._activate();
1138
- } catch (err) {
1139
- this._sinkCount -= 1;
1140
- this._removeSink(sink);
1141
- if (this._sinkCount === 0) this._status = "sentinel";
1142
- if (typeof subCleanup === "function") {
1143
- try {
1144
- subCleanup();
1145
- } catch {
1146
- }
1147
- }
1148
- throw err;
1149
- }
1150
- }
1151
- if (this._status === "sentinel" && this._cached === void 0) {
1152
- this._status = "pending";
1153
- }
1154
- let removed = false;
1155
- return () => {
1156
- if (removed) return;
1157
- removed = true;
1158
- this._sinkCount -= 1;
1159
- this._removeSink(sink);
1160
- if (typeof subCleanup === "function") subCleanup();
1161
- if (this._sinks == null) this._deactivate();
1162
- };
1163
- }
1164
- _removeSink(sink) {
1165
- if (this._sinks === sink) {
1166
- this._sinks = null;
1167
- } else if (this._sinks != null && typeof this._sinks !== "function") {
1168
- this._sinks.delete(sink);
1169
- if (this._sinks.size === 1) {
1170
- const [only] = this._sinks;
1171
- this._sinks = only;
1172
- } else if (this._sinks.size === 0) {
1173
- this._sinks = null;
1174
- }
1175
- }
1176
- }
1177
- // --- Lifecycle ---
1178
- /**
1179
- * @internal First-sink activation. For a producer (no deps + fn),
1180
- * invokes fn once. For a compute node (has deps), subscribes to every
1181
- * dep with the pre-set-dirty trick so the first-run gate waits for
1182
- * every dep to settle at least once.
1183
- */
1184
- _activate() {
1185
- if (this._deps.length === 0) {
1186
- if (this._fn) this._execFn();
1187
- return;
1188
- }
1189
- this._dirtyDepCount = 0;
1190
- const initialLen = this._deps.length;
1191
- let subscribedCount = 0;
1192
- try {
1193
- for (let i = 0; i < initialLen; i++) {
1194
- const depIdx = i;
1195
- const dep = this._deps[i];
1196
- dep.unsub = noopUnsub;
1197
- dep.unsub = dep.node.subscribe((msgs) => {
1198
- if (dep.unsub === null) return;
1199
- const tierOf = this._config.tierOf;
1200
- let sawSettlement = false;
1201
- for (const m of msgs) {
1202
- if (tierOf(m[0]) >= 3) sawSettlement = true;
1203
- this._config.onMessage(
1204
- this,
1205
- m,
1206
- { direction: "down-in", depIndex: depIdx },
1207
- this._actions
1208
- );
1209
- }
1210
- if (sawSettlement) this._maybeRunFnOnSettlement();
1211
- });
1212
- subscribedCount++;
1213
- }
1214
- } catch (err) {
1215
- this._deps[subscribedCount].unsub = null;
1216
- for (let j = 0; j < subscribedCount; j++) {
1217
- const d = this._deps[j];
1218
- if (d.unsub != null) {
1219
- const u = d.unsub;
1220
- d.unsub = null;
1221
- try {
1222
- u();
1223
- } catch {
1224
- }
1225
- resetDepRecord(d);
1226
- }
1227
- }
1228
- this._dirtyDepCount = 0;
1229
- throw err;
1230
- }
1231
- }
1232
- /**
1233
- * @internal Append a dep post-construction. Used by `autoTrackNode`
1234
- * (runtime dep discovery) and `Graph.connect()` (post-construction
1235
- * wiring). Subscribes immediately — if DATA arrives synchronously
1236
- * during subscribe and fn is currently executing, the re-run is
1237
- * deferred via `_pendingRerun` flag (see `_execFn` guard).
1238
- *
1239
- * **Dedup:** idempotent on duplicate `depNode` — if `depNode` is
1240
- * already in `_deps`, returns the existing index without mutating
1241
- * state. Callers can safely invoke `_addDep` without their own
1242
- * "already added" check. `autoTrackNode` still keeps a `depIndexMap`
1243
- * as a fast-path lookup for known deps (returning cached `data[idx]`
1244
- * without calling `_addDep` at all); this internal dedup is the
1245
- * backstop for any caller that doesn't track its own dep set.
1246
- *
1247
- * @returns The index of the new dep in `_deps`, or the existing index
1248
- * if the dep was already present.
1249
- */
1250
- _addDep(depNode) {
1251
- for (let i = 0; i < this._deps.length; i++) {
1252
- if (this._deps[i].node === depNode) return i;
1253
- }
1254
- const depIdx = this._deps.length;
1255
- const record = createDepRecord(depNode);
1256
- this._deps.push(record);
1257
- if (this._sinks == null) return depIdx;
1258
- record.dirty = true;
1259
- this._dirtyDepCount++;
1260
- if (this._status !== "dirty") this._emit(DIRTY_ONLY_BATCH);
1261
- record.unsub = noopUnsub;
1262
- try {
1263
- record.unsub = depNode.subscribe((msgs) => {
1264
- if (record.unsub === null) return;
1265
- const tierOf = this._config.tierOf;
1266
- let sawSettlement = false;
1267
- for (const m of msgs) {
1268
- if (tierOf(m[0]) >= 3) sawSettlement = true;
1269
- this._config.onMessage(
1270
- this,
1271
- m,
1272
- { direction: "down-in", depIndex: depIdx },
1273
- this._actions
1274
- );
1275
- }
1276
- if (sawSettlement) this._maybeRunFnOnSettlement();
1277
- });
1278
- } catch (err) {
1279
- record.unsub = null;
1280
- this._deps.pop();
1281
- this._dirtyDepCount--;
1282
- throw err;
1283
- }
1284
- return depIdx;
1285
- }
1286
- /**
1287
- * @internal Unsubscribes from deps, fires fn cleanup (both shapes),
1288
- * clears wave/store state, and (for compute nodes) drops `_cached` per
1289
- * the ROM/RAM rule. Idempotent: second call is a no-op.
1290
- *
1291
- * @param skipStatusUpdate — When `true`, the caller takes responsibility
1292
- * for setting `_status` after deactivation (e.g. TEARDOWN always sets
1293
- * `"sentinel"` unconditionally). When `false` (default), deactivation
1294
- * applies the ROM rule: compute nodes → `"sentinel"`, state nodes
1295
- * preserve their current status.
1296
- */
1297
- _deactivate(skipStatusUpdate = false) {
1298
- const cleanup = this._cleanup;
1299
- this._cleanup = void 0;
1300
- if (typeof cleanup === "function") {
1301
- try {
1302
- cleanup();
1303
- } catch (err) {
1304
- this._emit([[ERROR, this._wrapFnError("cleanup threw", err)]]);
1305
- }
1306
- } else if (cleanup != null && typeof cleanup.deactivation === "function") {
1307
- try {
1308
- cleanup.deactivation();
1309
- } catch (err) {
1310
- this._emit([[ERROR, this._wrapFnError("cleanup.deactivation threw", err)]]);
1311
- }
1312
- }
1313
- for (const d of this._deps) {
1314
- if (d.unsub != null) {
1315
- const u = d.unsub;
1316
- d.unsub = null;
1317
- try {
1318
- u();
1319
- } catch {
1320
- }
1321
- }
1322
- resetDepRecord(d);
1323
- }
1324
- this._waveHasNewData = false;
1325
- this._hasNewTerminal = false;
1326
- this._hasCalledFnOnce = false;
1327
- this._paused = false;
1328
- this._pendingWave = false;
1329
- this._pendingRerun = false;
1330
- this._rerunDepth = 0;
1331
- this._store = {};
1332
- this._dirtyDepCount = 0;
1333
- this._pauseLocks = null;
1334
- this._pauseBuffer = null;
1335
- if (this._fn != null) {
1336
- this._cached = void 0;
1337
- }
1338
- if (!skipStatusUpdate) {
1339
- if (this._fn != null || this._deps.length > 0) {
1340
- if (!this._isTerminal || this._resubscribable) {
1341
- this._status = "sentinel";
1342
- }
1343
- }
1344
- }
1345
- }
1346
- // --- Dep message dispatch (§3.5 singleton default) ---
1347
- /**
1348
- * @internal Default per-tier dispatch for incoming dep messages. Called
1349
- * by `defaultOnMessage`. Updates the DepRecord, triggers wave
1350
- * completion, and forwards passthrough traffic.
1351
- */
1352
- _onDepMessage(depIndex, msg) {
1353
- const dep = this._deps[depIndex];
1354
- const t = msg[0];
1355
- if (this._inspectorHooks != null) {
1356
- const ev = { kind: "dep_message", depIndex, message: msg };
1357
- for (const hook of this._inspectorHooks) hook(ev);
1358
- }
1359
- if (t === START) return;
1360
- if (t === DIRTY) {
1361
- this._depDirtied(dep);
1362
- return;
1363
- }
1364
- if (t === INVALIDATE) {
1365
- this._depInvalidated(dep);
1366
- this._emit(INVALIDATE_ONLY_BATCH);
1367
- return;
1368
- }
1369
- if (t === PAUSE || t === RESUME) {
1370
- this._emit([msg]);
1371
- return;
1372
- }
1373
- if (t === TEARDOWN) {
1374
- this._emit(TEARDOWN_ONLY_BATCH);
1375
- return;
1376
- }
1377
- if (t === DATA) {
1378
- this._depSettledAsData(dep, msg[1]);
1379
- } else if (t === RESOLVED) {
1380
- this._depSettledAsResolved(dep);
1381
- } else if (t === COMPLETE) {
1382
- this._depSettledAsTerminal(dep, true);
1383
- } else if (t === ERROR) {
1384
- this._depSettledAsTerminal(dep, msg[1]);
1385
- } else {
1386
- this._emit([msg]);
1387
- return;
1388
- }
1389
- if (!this._fn) {
1390
- if (t === DATA || t === RESOLVED) {
1391
- this._emit([msg]);
1392
- }
1393
- if (t === COMPLETE || t === ERROR) {
1394
- this._maybeAutoTerminalAfterWave();
1395
- }
1396
- return;
1397
- }
1398
- }
1399
- // --- Centralized dep-state transitions (A3 settlement counters) ---
1400
- //
1401
- // Every mutation to `DepRecord.dirty` / `DepRecord.prevData` /
1402
- // `DepRecord.terminal` must go through one of these helpers so the
1403
- // `_dirtyDepCount` and `_sentinelDepCount` counters stay in sync with
1404
- // the per-record flags. `_maybeRunFnOnSettlement` reads the counters
1405
- // and never re-scans the `_deps` array.
1406
- /**
1407
- * Called when a dep transitions `dirty: false → true` (either from an
1408
- * incoming DIRTY, or pre-set during `_activate` / `_addDep` /
1409
- * `_depInvalidated`). No-op if the dep is already dirty. Fires the
1410
- * downstream DIRTY emit if we're the first to dirty this wave.
1411
- */
1412
- _depDirtied(dep) {
1413
- if (dep.dirty) return;
1414
- dep.dirty = true;
1415
- dep.involvedThisWave = true;
1416
- this._dirtyDepCount++;
1417
- if (this._status !== "dirty") {
1418
- this._emit(DIRTY_ONLY_BATCH);
1419
- }
1420
- }
1421
- /**
1422
- * Called when a dep delivers new DATA: clears dirty, stores the payload,
1423
- * marks wave-has-data, and — if this is the dep's first DATA — clears
1424
- * its sentinel slot so the first-run gate can open.
1425
- */
1426
- _depSettledAsData(dep, value) {
1427
- if (dep.dirty) {
1428
- dep.dirty = false;
1429
- this._dirtyDepCount--;
1430
- }
1431
- dep.involvedThisWave = true;
1432
- dep.dataBatch.push(value);
1433
- this._waveHasNewData = true;
1434
- }
1435
- /**
1436
- * Called when a dep emits RESOLVED (wave settled, value unchanged).
1437
- * Clears dirty; does NOT touch `prevData` / `terminal` / sentinel
1438
- * count — sentinel only exits on first DATA or terminal, not RESOLVED.
1439
- */
1440
- _depSettledAsResolved(dep) {
1441
- if (dep.dirty) {
1442
- dep.dirty = false;
1443
- this._dirtyDepCount--;
1444
- }
1445
- }
1446
- /**
1447
- * Called when a dep delivers COMPLETE (`terminal = true`) or ERROR
1448
- * (`terminal = errorPayload`). Clears dirty, stores the terminal, and
1449
- * — if the dep had never contributed a DATA yet — leaves sentinel
1450
- * since the gate treats "terminated without data" as gate-open too.
1451
- */
1452
- _depSettledAsTerminal(dep, terminal) {
1453
- if (dep.dirty) {
1454
- dep.dirty = false;
1455
- this._dirtyDepCount--;
1456
- }
1457
- dep.terminal = terminal;
1458
- dep.involvedThisWave = true;
1459
- this._hasNewTerminal = true;
1460
- }
1461
- /**
1462
- * Called when a dep emits INVALIDATE: clears prevData, terminal, and
1463
- * dataBatch. The dep is now back in the "never delivered a real value"
1464
- * state — `prevData === undefined` so the sentinel check in fn will fire.
1465
- */
1466
- _depInvalidated(dep) {
1467
- dep.prevData = void 0;
1468
- dep.terminal = void 0;
1469
- dep.dataBatch.length = 0;
1470
- if (!dep.dirty) {
1471
- dep.dirty = true;
1472
- dep.involvedThisWave = true;
1473
- this._dirtyDepCount++;
1474
- } else {
1475
- dep.involvedThisWave = false;
1476
- }
1477
- }
1478
- _maybeRunFnOnSettlement() {
1479
- if (this._isTerminal && !this._resubscribable) return;
1480
- if (this._dirtyDepCount > 0) return;
1481
- if (this._paused) {
1482
- this._pendingWave = true;
1483
- return;
1484
- }
1485
- if (!this._waveHasNewData && !this._hasNewTerminal && this._hasCalledFnOnce) {
1486
- this._clearWaveFlags();
1487
- this._emit(RESOLVED_ONLY_BATCH);
1488
- this._maybeAutoTerminalAfterWave();
1489
- return;
1490
- }
1491
- if (this._fn) this._execFn();
1492
- this._maybeAutoTerminalAfterWave();
1493
- }
1494
- _maybeAutoTerminalAfterWave() {
1495
- if (this._deps.length === 0) return;
1496
- if (this._isTerminal) return;
1497
- const erroredDep = this._deps.find((d) => d.terminal !== void 0 && d.terminal !== true);
1498
- if (erroredDep != null) {
1499
- if (this._autoError) {
1500
- this._emit([[ERROR, erroredDep.terminal]]);
1501
- }
1502
- return;
1503
- }
1504
- if (this._autoComplete && this._deps.every((d) => d.terminal !== void 0)) {
1505
- this._emit(COMPLETE_ONLY_BATCH);
1506
- }
1507
- }
1508
- // --- Fn execution ---
1509
- /**
1510
- * @internal Runs the node fn once. Default cleanup (function form) fires
1511
- * before the new run; `{ deactivation }` cleanup survives.
1512
- */
1513
- _execFn() {
1514
- if (!this._fn) return;
1515
- if (this._isTerminal && !this._resubscribable) return;
1516
- if (this._isExecutingFn) {
1517
- this._pendingRerun = true;
1518
- return;
1519
- }
1520
- const prevCleanup = this._cleanup;
1521
- if (typeof prevCleanup === "function") {
1522
- this._cleanup = void 0;
1523
- try {
1524
- prevCleanup();
1525
- } catch (err) {
1526
- this._emit([[ERROR, this._wrapFnError("cleanup threw", err)]]);
1527
- return;
1528
- }
1529
- }
1530
- const batchData = this._deps.map(
1531
- (d) => !d.involvedThisWave ? void 0 : d.dataBatch.length > 0 ? [...d.dataBatch] : []
1532
- );
1533
- const prevData = this._deps.map((d) => d.prevData);
1534
- for (let i = 0; i < this._deps.length; i++) {
1535
- const batch2 = batchData[i];
1536
- if (batch2 != null && batch2.length > 0) {
1537
- this._deps[i].prevData = batch2[batch2.length - 1];
1538
- }
1539
- }
1540
- const terminalDeps = this._deps.map((d) => d.terminal);
1541
- const ctx = { prevData, terminalDeps, store: this._store };
1542
- this._hasCalledFnOnce = true;
1543
- this._clearWaveFlags();
1544
- if (this._inspectorHooks != null) {
1545
- const ev = { kind: "run", batchData, prevData };
1546
- for (const hook of this._inspectorHooks) hook(ev);
1547
- }
1548
- this._isExecutingFn = true;
1549
- try {
1550
- const result = this._fn(batchData, this._actions, ctx);
1551
- if (typeof result === "function") {
1552
- this._cleanup = result;
1553
- } else if (result != null && typeof result === "object" && typeof result.deactivation === "function") {
1554
- this._cleanup = result;
1555
- }
1556
- } catch (err) {
1557
- this._emit([[ERROR, this._wrapFnError("fn threw", err)]]);
1558
- } finally {
1559
- this._isExecutingFn = false;
1560
- if (this._pendingRerun) {
1561
- this._pendingRerun = false;
1562
- this._rerunDepth += 1;
1563
- if (this._rerunDepth > MAX_RERUN_DEPTH) {
1564
- this._rerunDepth = 0;
1565
- this._emit([
1566
- [
1567
- ERROR,
1568
- new Error(
1569
- `Node "${this.name}": _pendingRerun depth exceeded ${MAX_RERUN_DEPTH} \u2014 likely a reactive cycle`
1570
- )
1571
- ]
1572
- ]);
1573
- } else {
1574
- this._maybeRunFnOnSettlement();
1575
- }
1576
- } else {
1577
- this._rerunDepth = 0;
1578
- }
1579
- this._clearWaveFlags();
1580
- }
1581
- }
1582
- _clearWaveFlags() {
1583
- this._waveHasNewData = false;
1584
- this._hasNewTerminal = false;
1585
- for (const d of this._deps) {
1586
- d.involvedThisWave = false;
1587
- d.dataBatch.length = 0;
1588
- }
1589
- }
1590
- _wrapFnError(label, err) {
1591
- const msg = err instanceof Error ? err.message : String(err);
1592
- return new Error(`Node "${this.name}": ${label}: ${msg}`, { cause: err });
1593
- }
1594
- // --- Framing (tier sort + synthetic DIRTY prefix) ---
1595
- /**
1596
- * @internal Stable tier sort + synthetic DIRTY prefix for an outgoing
1597
- * batch. Fast path: already-monotone single-tier batches (the common
1598
- * case from interned singletons like `DIRTY_ONLY_BATCH`) return the
1599
- * input unchanged. General path: decorate-sort-undecorate into a new
1600
- * array, then prepend `[DIRTY]` after any tier-0 START entries when
1601
- * a tier-3 payload is present and the node isn't already dirty.
1602
- *
1603
- * Single source of truth for the spec §1.3.1 framing invariant. Every
1604
- * outgoing path hits `_frameBatch` exactly once via `_emit`.
1605
- */
1606
- _frameBatch(messages) {
1607
- const tierOf = this._config.tierOf;
1608
- if (messages.length === 1) {
1609
- const t = tierOf(messages[0][0]);
1610
- if (t === 3 && this._status !== "dirty") {
1611
- return [DIRTY_MSG, messages[0]];
1612
- }
1613
- return messages;
1614
- }
1615
- let monotone = true;
1616
- let hasTier3 = false;
1617
- let hasDirty = false;
1618
- let prevTier = -1;
1619
- for (const m of messages) {
1620
- const tier = tierOf(m[0]);
1621
- if (tier < prevTier) monotone = false;
1622
- if (tier === 3) hasTier3 = true;
1623
- if (m[0] === DIRTY) hasDirty = true;
1624
- prevTier = tier;
1625
- }
1626
- let sorted = messages;
1627
- if (!monotone) {
1628
- const indexed = messages.map((m, i) => ({ m, i, tier: tierOf(m[0]) }));
1629
- indexed.sort((a, b) => a.tier - b.tier || a.i - b.i);
1630
- sorted = indexed.map((x) => x.m);
1631
- }
1632
- if (hasTier3 && !hasDirty && this._status !== "dirty") {
1633
- let insertAt = 0;
1634
- while (insertAt < sorted.length && tierOf(sorted[insertAt][0]) === 0) insertAt++;
1635
- if (insertAt === 0) return [DIRTY_MSG, ...sorted];
1636
- return [...sorted.slice(0, insertAt), DIRTY_MSG, ...sorted.slice(insertAt)];
1637
- }
1638
- return sorted;
1639
- }
1640
- // --- Emit pipeline ---
1641
- /**
1642
- * @internal The unified dispatch waist — one call = one wave.
1643
- * See `GRAPHREFLY-SPEC.md` §1.3.1 for protocol context — the stages
1644
- * below are the implementation order.
1645
- *
1646
- * Pipeline stages, in order:
1647
- *
1648
- * 1. Terminal filter — post-COMPLETE/ERROR only TEARDOWN/INVALIDATE
1649
- * still propagate so graph teardown and cache-clear still work.
1650
- * 2. Tier sort (stable) — the batch can be in any order when it
1651
- * arrives; the walker downstream (`downWithBatch`) assumes
1652
- * ascending tier monotone, and so does `_updateState`'s tier-3
1653
- * slice walk. This is the single source of truth for ordering.
1654
- * 3. Synthetic DIRTY prefix — if a tier-3 payload is present, no
1655
- * DIRTY is already in the batch, and the node isn't already in
1656
- * `"dirty"` status, prepend `[DIRTY]` after any tier-0 START
1657
- * entries. Guarantees spec §1.3.1 (DIRTY precedes DATA within
1658
- * the same batch) uniformly across every entry point.
1659
- * 4. PAUSE/RESUME lock bookkeeping (C0) — update `_pauseLocks`,
1660
- * derive `_paused`, filter unknown-lockId RESUME, replay
1661
- * bufferAll buffer on final lock release.
1662
- * 5. Meta TEARDOWN fan-out — notify meta children before
1663
- * `_updateState`'s TEARDOWN branch calls `_deactivate`. Hoisted
1664
- * out of the walk to keep `_updateState` re-entrance-free.
1665
- * 6. `_updateState` — walk the batch in tier order, advancing
1666
- * `_cached` / `_status` / `_versioning` and running equals
1667
- * substitution on tier-3 DATA (§3.5.1). Returns
1668
- * `{finalMessages, equalsError?}`.
1669
- * 7. `downWithBatch` dispatch (or bufferAll capture if paused with
1670
- * `pausable: "resumeAll"`).
1671
- * 8. Recursive ERROR emission if equals threw mid-walk.
1672
- */
1673
- _emit(messages) {
1674
- if (messages.length === 0) return;
1675
- let deliverable = messages;
1676
- const terminal = this._isTerminal;
1677
- if (terminal && !this._resubscribable) {
1678
- const pass = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);
1679
- if (pass.length === 0) return;
1680
- deliverable = pass;
1681
- }
1682
- deliverable = this._frameBatch(deliverable);
1683
- let filtered = null;
1684
- for (let i = 0; i < deliverable.length; i++) {
1685
- const m = deliverable[i];
1686
- const t = m[0];
1687
- if (t !== PAUSE && t !== RESUME) {
1688
- if (filtered != null) filtered.push(m);
1689
- continue;
1690
- }
1691
- if (m.length < 2) {
1692
- throw new Error(
1693
- `Node "${this.name}": [[${t === PAUSE ? "PAUSE" : "RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`
1694
- );
1695
- }
1696
- let forward = true;
1697
- if (this._pausable !== false) {
1698
- const lockId = m[1];
1699
- if (t === PAUSE) {
1700
- if (this._pauseLocks == null) this._pauseLocks = /* @__PURE__ */ new Set();
1701
- this._pauseLocks.add(lockId);
1702
- this._paused = true;
1703
- if (this._pausable === "resumeAll" && this._pauseBuffer == null) {
1704
- this._pauseBuffer = [];
1705
- }
1706
- } else {
1707
- if (this._pauseLocks == null || !this._pauseLocks.has(lockId)) {
1708
- forward = false;
1709
- } else {
1710
- this._pauseLocks.delete(lockId);
1711
- if (this._pauseLocks.size === 0) {
1712
- this._paused = false;
1713
- if (this._pauseBuffer != null && this._pauseBuffer.length > 0) {
1714
- const drain = this._pauseBuffer;
1715
- this._pauseBuffer = [];
1716
- this._emit(drain);
1717
- }
1718
- if (this._pendingWave) {
1719
- this._pendingWave = false;
1720
- this._maybeRunFnOnSettlement();
1721
- }
1722
- }
1723
- }
1724
- }
1725
- }
1726
- if (!forward) {
1727
- if (filtered == null) filtered = deliverable.slice(0, i);
1728
- } else if (filtered != null) {
1729
- filtered.push(m);
1730
- }
1731
- }
1732
- if (filtered != null) {
1733
- if (filtered.length === 0) return;
1734
- deliverable = filtered;
1735
- }
1736
- if (this._hasMeta && deliverable.some((m) => m[0] === TEARDOWN)) {
1737
- for (const k of Object.keys(this.meta)) {
1738
- try {
1739
- this.meta[k]._emit(TEARDOWN_ONLY_BATCH);
1740
- } catch {
1741
- }
1742
- }
1743
- }
1744
- const { finalMessages, equalsError } = this._updateState(deliverable);
1745
- if (finalMessages.length > 0 && this._config.inspectorEnabled) {
1746
- const inspector = this._config.globalInspector;
1747
- if (inspector != null) {
1748
- try {
1749
- inspector({ kind: "emit", node: this, messages: finalMessages });
1750
- } catch {
1751
- }
1752
- }
1753
- }
1754
- if (finalMessages.length > 0) {
1755
- if (this._paused && this._pausable === "resumeAll" && this._pauseBuffer != null) {
1756
- const tierOf = this._config.tierOf;
1757
- const immediate = [];
1758
- for (const m of finalMessages) {
1759
- const tier = tierOf(m[0]);
1760
- if (tier < 3 || tier === 5) {
1761
- immediate.push(m);
1762
- } else {
1763
- this._pauseBuffer.push(m);
1764
- }
1765
- }
1766
- if (immediate.length > 0) {
1767
- this._dispatchOrAccumulate(immediate);
1768
- }
1769
- } else {
1770
- this._dispatchOrAccumulate(finalMessages);
1771
- }
1772
- }
1773
- if (equalsError != null) {
1774
- this._emit([[ERROR, equalsError]]);
1775
- }
1776
- }
1777
- /**
1778
- * @internal Walk an outgoing (already-framed) batch, updating own
1779
- * cache / status / versioning and running equals substitution on
1780
- * every tier-3 DATA (§3.5.1). Framing — tier sort and synthetic
1781
- * DIRTY prefix — has already happened upstream in `_frameBatch`.
1782
- * This walk trusts the input is in monotone tier order and that the
1783
- * spec §1.3.1 DIRTY/RESOLVED precedence invariant is already
1784
- * satisfied by the frame.
1785
- *
1786
- * Equals substitution: every DATA payload is compared against the
1787
- * live `_cached`; when equal, the tuple is rewritten to `[RESOLVED]`
1788
- * in a per-call copy and cache is not re-advanced. `.cache` remains
1789
- * coherent with "the last DATA payload this node actually sent
1790
- * downstream".
1791
- *
1792
- * Returns `{ finalMessages, equalsError? }`:
1793
- * - `finalMessages` — the array to deliver to sinks (may be
1794
- * `messages` unchanged, a rewritten copy with DATA→RESOLVED
1795
- * substitutions, or a truncated prefix when equals throws mid-walk).
1796
- * - `equalsError` — present only when the configured `equals` function
1797
- * threw on some DATA message. `_emit` delivers the prefix first,
1798
- * then emits a fresh ERROR batch via a recursive `_emit` call so
1799
- * subscribers observe `[...walked_prefix, ERROR]` in order.
1800
- */
1801
- _updateState(messages) {
1802
- const tierOf = this._config.tierOf;
1803
- let rewritten;
1804
- let equalsError;
1805
- let abortedAt = -1;
1806
- let dataCount = 0;
1807
- for (const m of messages) {
1808
- if (tierOf(m[0]) === 3) dataCount++;
1809
- }
1810
- const checkEquals = dataCount <= 1;
1811
- let lastDataIdx = -1;
1812
- if (this._versioning != null && dataCount > 1) {
1813
- for (let i = messages.length - 1; i >= 0; i--) {
1814
- if (messages[i][0] === DATA) {
1815
- lastDataIdx = i;
1816
- break;
1817
- }
1818
- }
1819
- }
1820
- for (let i = 0; i < messages.length; i++) {
1821
- const m = messages[i];
1822
- const t = m[0];
1823
- if (t === DATA) {
1824
- if (m.length >= 2) {
1825
- let unchanged = false;
1826
- if (checkEquals && this._cached !== void 0) {
1827
- try {
1828
- unchanged = this._equals(this._cached, m[1]);
1829
- } catch (err) {
1830
- equalsError = this._wrapFnError("equals threw", err);
1831
- abortedAt = i;
1832
- break;
1833
- }
1834
- }
1835
- if (unchanged) {
1836
- if (rewritten == null) rewritten = messages.slice(0, i);
1837
- rewritten.push(RESOLVED_MSG);
1838
- this._status = "resolved";
1839
- continue;
1840
- }
1841
- this._cached = m[1];
1842
- if (this._versioning != null) {
1843
- if (lastDataIdx < 0 || i === lastDataIdx) {
1844
- advanceVersion(this._versioning, m[1], this._hashFn);
1845
- }
1846
- }
1847
- }
1848
- this._status = "settled";
1849
- if (rewritten != null) rewritten.push(m);
1850
- } else {
1851
- if (rewritten != null) rewritten.push(m);
1852
- if (t === DIRTY) {
1853
- this._status = "dirty";
1854
- } else if (t === RESOLVED) {
1855
- this._status = "resolved";
1856
- } else if (t === COMPLETE) {
1857
- this._status = "completed";
1858
- } else if (t === ERROR) {
1859
- this._status = "errored";
1860
- } else if (t === INVALIDATE) {
1861
- this._cached = void 0;
1862
- this._status = "dirty";
1863
- const c = this._cleanup;
1864
- if (typeof c === "function") {
1865
- this._cleanup = void 0;
1866
- try {
1867
- c();
1868
- } catch {
1869
- }
1870
- }
1871
- } else if (t === TEARDOWN) {
1872
- if (this._resetOnTeardown) this._cached = void 0;
1873
- this._deactivate(
1874
- /* skipStatusUpdate */
1875
- true
1876
- );
1877
- this._status = "sentinel";
1878
- }
1879
- }
1880
- }
1881
- const base = abortedAt >= 0 ? rewritten ?? messages.slice(0, abortedAt) : rewritten ?? messages;
1882
- return equalsError != null ? { finalMessages: base, equalsError } : { finalMessages: base };
1883
- }
1884
- _deliverToSinks = (messages) => {
1885
- if (this._sinks == null) return;
1886
- if (typeof this._sinks === "function") {
1887
- this._sinks(messages);
1888
- return;
1889
- }
1890
- const snapshot = [...this._sinks];
1891
- for (const sink of snapshot) sink(messages);
1892
- };
1893
- /**
1894
- * @internal Dispatch entry point that respects the per-batch emit
1895
- * accumulator (Bug 2). Inside an explicit `batch()` scope, append to
1896
- * `_batchPendingMessages` and register a flush hook on first append.
1897
- * Outside batch — or during a drain (where `flushInProgress` is true
1898
- * but `batchDepth` is 0) — dispatch synchronously through `downWithBatch`.
1899
- *
1900
- * Per-emit state updates (`_frameBatch`, `_updateState`) have already
1901
- * happened by the time we reach here; only the **downstream delivery**
1902
- * is coalesced. Cache, version, and status are visible mid-batch on
1903
- * the emitting node itself.
1904
- */
1905
- _dispatchOrAccumulate(messages) {
1906
- if (isExplicitlyBatching()) {
1907
- if (this._batchPendingMessages === null) {
1908
- this._batchPendingMessages = [];
1909
- registerBatchFlushHook(() => this._flushBatchPending());
1910
- }
1911
- for (const m of messages) this._batchPendingMessages.push(m);
1912
- return;
1913
- }
1914
- downWithBatch(this._deliverToSinks, messages, this._config.tierOf);
1915
- }
1916
- /**
1917
- * @internal Flushes the accumulated batch through `downWithBatch` and
1918
- * clears the pending state. Idempotent — safe to call when pending is
1919
- * already null or empty (e.g. on a `batch()` throw, where the hook
1920
- * fires for cleanup but the drainPhase queues are wiped after).
1921
- *
1922
- * Critical: the accumulated batch is interleaved per-emit framings like
1923
- * `[DIRTY, DATA(1), DIRTY, DATA(2)]` — non-monotone tier order. We must
1924
- * re-frame to sort by tier before handing to `downWithBatch`, which
1925
- * assumes pre-sorted input. `_frameBatch` also handles the synthetic
1926
- * DIRTY prepend rule (no-op here — `hasDirty` is true since each
1927
- * accumulated emit already carries its own DIRTY prefix).
1928
- */
1929
- _flushBatchPending() {
1930
- const pending = this._batchPendingMessages;
1931
- if (pending === null) return;
1932
- this._batchPendingMessages = null;
1933
- if (pending.length === 0) return;
1934
- const framed = this._frameBatch(pending);
1935
- downWithBatch(this._deliverToSinks, framed, this._config.tierOf);
1936
- }
1937
- };
1938
- var isNodeArray = (value) => Array.isArray(value);
1939
- var isNodeOptionsObject = (value) => typeof value === "object" && value != null && !Array.isArray(value);
1940
- function node(depsOrFn, fnOrOpts, optsArg) {
1941
- const deps = isNodeArray(depsOrFn) ? depsOrFn : [];
1942
- const fn = typeof depsOrFn === "function" ? depsOrFn : typeof fnOrOpts === "function" ? fnOrOpts : void 0;
1943
- let opts = {};
1944
- if (isNodeArray(depsOrFn)) {
1945
- opts = (isNodeOptionsObject(fnOrOpts) ? fnOrOpts : optsArg) ?? {};
1946
- } else if (isNodeOptionsObject(depsOrFn)) {
1947
- opts = depsOrFn;
1948
- } else {
1949
- opts = (isNodeOptionsObject(fnOrOpts) ? fnOrOpts : optsArg) ?? {};
1950
- }
1951
- return new NodeImpl(deps, fn, opts);
1952
- }
1953
-
1954
- // src/core/sugar.ts
1955
- function sentinelGuard(batchData, ctx, allowPartial) {
1956
- if (allowPartial) return false;
1957
- return batchData.some(
1958
- (batch2, i) => !(batch2 != null && batch2.length > 0) && ctx.prevData[i] === void 0
1959
- );
1960
- }
1961
- function state(initial, opts) {
1962
- return node([], { ...opts, initial });
1963
- }
1964
- function derived(deps, fn, opts) {
1965
- const allowPartial = opts?.partial ?? false;
1966
- const wrapped = (batchData, actions, ctx) => {
1967
- if (sentinelGuard(batchData, ctx, allowPartial)) {
1968
- actions.down([[RESOLVED]]);
1969
- return void 0;
1970
- }
1971
- const data = batchData.map(
1972
- (batch2, i) => batch2 != null && batch2.length > 0 ? batch2.at(-1) : ctx.prevData[i]
1973
- );
1974
- actions.emit(fn(data, ctx));
1975
- return void 0;
1976
- };
1977
- return node(deps, wrapped, { describeKind: "derived", ...opts });
1978
- }
1979
- function dynamicNode(allDeps, fn, opts) {
1980
- const depIndex = /* @__PURE__ */ new Map();
1981
- allDeps.forEach((d, i) => {
1982
- depIndex.set(d, i);
1983
- });
1984
- return derived(
1985
- allDeps,
1986
- // data[i] is already sugar-unwrapped to a scalar by derived()'s wrapper.
1987
- (data, ctx) => {
1988
- const track = (dep) => {
1989
- const i = depIndex.get(dep);
1990
- if (i == null) {
1991
- throw new Error(`dynamicNode: untracked dep "${dep.name ?? "<unnamed>"}"`);
1992
- }
1993
- return data[i];
1994
- };
1995
- return fn(track, ctx);
1996
- },
1997
- opts
1998
- );
1999
- }
2000
-
2001
- // src/compat/nanostores/index.ts
2002
- var START_LISTENERS = /* @__PURE__ */ new WeakMap();
2003
- var STOP_LISTENERS = /* @__PURE__ */ new WeakMap();
2004
- function trigger(node2, map2) {
2005
- const callbacks = map2.get(node2);
2006
- if (callbacks) {
2007
- for (const cb of callbacks) cb();
2008
- }
2009
- }
2010
- function createStore(node2, extra = {}) {
2011
- let listeners = 0;
2012
- const store = {
2013
- ...extra,
2014
- get: () => getVal(node2),
2015
- subscribe: (cb) => {
2016
- if (listeners === 0) trigger(node2, START_LISTENERS);
2017
- listeners++;
2018
- const sub = node2.subscribe((msgs) => {
2019
- for (const [t, v] of msgs) {
2020
- if (t === DATA) cb(v);
2021
- }
2022
- });
2023
- return () => {
2024
- sub();
2025
- listeners--;
2026
- if (listeners === 0) trigger(node2, STOP_LISTENERS);
2027
- };
2028
- },
2029
- listen: (cb) => {
2030
- if (listeners === 0) trigger(node2, START_LISTENERS);
2031
- listeners++;
2032
- let initial = true;
2033
- const sub = node2.subscribe((msgs) => {
2034
- for (const [t, v] of msgs) {
2035
- if (t === DATA) {
2036
- if (initial) {
2037
- initial = false;
2038
- continue;
2039
- }
2040
- cb(v);
2041
- }
2042
- }
2043
- });
2044
- return () => {
2045
- sub();
2046
- listeners--;
2047
- if (listeners === 0) trigger(node2, STOP_LISTENERS);
2048
- };
2049
- },
2050
- _node: node2
2051
- };
2052
- return store;
2053
- }
2054
- function pull(n) {
2055
- let val = n.cache;
2056
- let err;
2057
- const unsub = n.subscribe((msgs) => {
2058
- for (const [t, v] of msgs) {
2059
- if (t === DATA) val = v;
2060
- if (t === ERROR) err = v;
2061
- }
2062
- });
2063
- unsub();
2064
- if (err) throw err;
2065
- return val;
2066
- }
2067
- function getVal(n) {
2068
- if (n.status === "sentinel") {
2069
- return pull(n);
2070
- }
2071
- return n.cache;
2072
- }
2073
- function atom(initial) {
2074
- const n = state(initial, {
2075
- resubscribable: true,
2076
- resetOnTeardown: true
2077
- });
2078
- return createStore(n, {
2079
- // `n.emit` routes through the framed pipeline: `bundle()` auto-
2080
- // prefixes `[DIRTY]` (diamond-safe wave coordination) and the
2081
- // node's `equals` (default `Object.is`) folds same-value writes
2082
- // into `RESOLVED`. Matches nanostores' documented Object.is
2083
- // dedup semantics without any custom check.
2084
- set: (value) => n.emit(value)
2085
- });
2086
- }
2087
- function computed(stores, fn) {
2088
- const storeArray = Array.isArray(stores) ? stores : [stores];
2089
- const depNodes = storeArray.map((s) => s._node);
2090
- const n = dynamicNode(
2091
- depNodes,
2092
- (track) => {
2093
- const vals = storeArray.map((s) => {
2094
- const node2 = s._node;
2095
- if (node2.status === "sentinel") {
2096
- pull(node2);
2097
- }
2098
- return track(node2);
2099
- });
2100
- return fn(...vals);
2101
- },
2102
- {
2103
- resubscribable: true,
2104
- resetOnTeardown: true,
2105
- equals: Object.is
2106
- }
2107
- );
2108
- return createStore(n);
2109
- }
2110
- function map(initial) {
2111
- const n = state(initial, {
2112
- resubscribable: true,
2113
- resetOnTeardown: true,
2114
- equals: () => false
2115
- });
2116
- return createStore(n, {
2117
- // `map`'s state node is configured with `equals: () => false`
2118
- // above, so every `emit` produces DATA (even for same-key same-
2119
- // value sets). The `emit` path is still required for diamond
2120
- // coordination (`[DIRTY]` auto-prefix via `bundle()`).
2121
- set: (value) => n.emit(value),
2122
- setKey: (key, value) => {
2123
- const current = getVal(n);
2124
- n.emit({ ...current, [key]: value });
2125
- }
2126
- });
2127
- }
2128
- function getValue(store) {
2129
- return store.get();
2130
- }
2131
- function onStart(store, cb) {
2132
- const node2 = store._node;
2133
- let callbacks = START_LISTENERS.get(node2);
2134
- if (!callbacks) {
2135
- callbacks = /* @__PURE__ */ new Set();
2136
- START_LISTENERS.set(node2, callbacks);
2137
- }
2138
- callbacks.add(cb);
2139
- }
2140
- function onStop(store, cb) {
2141
- const node2 = store._node;
2142
- let callbacks = STOP_LISTENERS.get(node2);
2143
- if (!callbacks) {
2144
- callbacks = /* @__PURE__ */ new Set();
2145
- STOP_LISTENERS.set(node2, callbacks);
2146
- }
2147
- callbacks.add(cb);
2148
- }
2149
- function onMount(store, cb) {
2150
- onStart(store, () => {
2151
- const stop = cb();
2152
- if (typeof stop === "function") onStop(store, stop);
2153
- });
2154
- }
2155
- function action(_store, _name, fn) {
2156
- return (...args) => {
2157
- let result;
2158
- batch(() => {
2159
- result = fn(...args);
2160
- });
2161
- return result;
2162
- };
2163
- }
2164
- // Annotate the CommonJS export names for ESM import in node:
2165
- 0 && (module.exports = {
2166
- action,
2167
- atom,
2168
- computed,
2169
- getValue,
2170
- map,
2171
- onMount,
2172
- onStart,
2173
- onStop
2174
- });
2175
- //# sourceMappingURL=index.cjs.map
1
+ "use strict";var re=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Be=Object.prototype.hasOwnProperty;var We=(n,e)=>{for(var t in e)re(n,t,{get:e[t],enumerable:!0})},je=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ue(e))!Be.call(n,r)&&r!==t&&re(n,r,{get:()=>e[r],enumerable:!(s=Pe(e,r))||s.enumerable});return n};var ze=n=>je(re({},"__esModule",{value:!0}),n);var ut={};We(ut,{action:()=>lt,atom:()=>ot,computed:()=>it,getValue:()=>dt,map:()=>at,onMount:()=>ct,onStart:()=>Ge,onStop:()=>He});module.exports=ze(ut);var O=0,P=!1,A=[],k=[],D=[],U=[];function me(){return O>0||P}function be(){return O>0}function ve(n){O>0?U.push(n):n()}function Te(n){O+=1;let e=!1;try{n()}catch(t){throw e=!0,t}finally{if(O-=1,O===0)if(e){if(!P){let t=U.splice(0);for(let s of t)try{s()}catch{}A.length=0,k.length=0,D.length=0}}else $e()}}function $e(){let n=!P;n&&(P=!0);let e=[],t=0;try{for(;A.length>0||k.length>0||D.length>0||n&&U.length>0;){if(n&&U.length>0){let i=U.splice(0);for(let a of i)try{a()}catch(o){e.push(o)}continue}if(t+=1,t>1e3)throw A.length=0,k.length=0,D.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let r=(A.length>0?A:k.length>0?k:D).splice(0);for(let i of r)try{i()}catch(a){e.push(a)}}}finally{n&&(P=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function q(n,e,t){if(e.length===0)return;if(e.length===1){let c=t(e[0][0]);if(c<3||!me()){n(e);return}(c>=5?D:c===4?k:A).push(()=>n(e));return}let s=e.length,r=s,i=s,a=s,o=0;for(;o<s&&t(e[o][0])<3;)o++;for(r=o;o<s&&t(e[o][0])===3;)o++;for(i=o;o<s&&t(e[o][0])===4;)o++;a=o;let d=me();if(r>0){let c=e.slice(0,r);n(c)}if(i>r){let c=e.slice(r,i);d?A.push(()=>n(c)):n(c)}if(a>i){let c=e.slice(i,a);d?k.push(()=>n(c)):n(c)}if(s>a){let c=e.slice(a,s);d?D.push(()=>n(c)):n(c)}}var B=Symbol.for("graphrefly/START"),g=Symbol.for("graphrefly/DATA"),M=Symbol.for("graphrefly/DIRTY"),E=Symbol.for("graphrefly/RESOLVED"),S=Symbol.for("graphrefly/INVALIDATE"),C=Symbol.for("graphrefly/PAUSE"),W=Symbol.for("graphrefly/RESUME"),w=Symbol.for("graphrefly/TEARDOWN"),R=Symbol.for("graphrefly/COMPLETE"),f=Symbol.for("graphrefly/ERROR"),F=Object.freeze([M]),oe=Object.freeze([E]),qe=Object.freeze([S]),ie=Object.freeze([B]),Ke=Object.freeze([R]),Ye=Object.freeze([w]),ae=Object.freeze([F]),xe=Object.freeze([oe]),we=Object.freeze([qe]),Ne=Object.freeze([Ke]),de=Object.freeze([Ye]);var Je={name:"json",version:1,contentType:"application/json",encode(n){let e=JSON.stringify(n);return new TextEncoder().encode(e)},decode(n,e){let t=new TextDecoder().decode(n);return JSON.parse(t)}};function Ae(n){n.registerCodec(Je)}var Xe={type:"system",id:""};function K(n){if(n==null)return Xe;let{type:e,id:t,...s}=n;return{type:e??"system",id:t??"",...s}}function ke(){return Date.now()*1e6}var Y=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_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 s=this._messageTypes.get(t);return s!=null?s.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}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 Me(n){n.registerMessageType(B,{tier:0,wireCrossing:!1}),n.registerMessageType(M,{tier:1,wireCrossing:!1}),n.registerMessageType(S,{tier:1,wireCrossing:!1,metaPassthrough:!1}),n.registerMessageType(C,{tier:2,wireCrossing:!1}),n.registerMessageType(W,{tier:2,wireCrossing:!1}),n.registerMessageType(g,{tier:3,wireCrossing:!0}),n.registerMessageType(E,{tier:3,wireCrossing:!0}),n.registerMessageType(R,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(f,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(w,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var I=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}};function ce(n){if(n===void 0)return null;if(typeof n=="number"){if(!Number.isFinite(n))throw new TypeError(`Cannot hash non-finite number: ${n}`);if(Number.isInteger(n)&&!Number.isSafeInteger(n))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${n}. Cross-language cid parity is not guaranteed for unsafe integers.`);return n}if(typeof n=="string"||typeof n=="boolean"||n===null)return n;if(Array.isArray(n))return n.map(ce);if(typeof n=="object"&&n!==null){let e={};for(let t of Object.keys(n).sort())e[t]=ce(n[t]);return e}return null}var Ze=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]),Qe=new TextEncoder;function et(n){let e=Qe.encode(n),t=e.length,s=t*8,r=t+9+63&-64,i=new Uint8Array(r);i.set(e),i[t]=128;let a=new DataView(i.buffer);a.setUint32(r-4,s>>>0,!1),a.setUint32(r-8,Math.floor(s/4294967296)>>>0,!1);let o=1779033703,d=3144134277,c=1013904242,l=2773480762,h=1359893119,p=2600822924,_=528734635,b=1541459225,N=new Uint32Array(64),m=(T,y)=>T>>>y|T<<32-y;for(let T=0;T<r;T+=64){for(let u=0;u<16;u++)N[u]=a.getUint32(T+u*4,!1);for(let u=16;u<64;u++){let L=N[u-15],V=N[u-2],$=m(L,7)^m(L,18)^L>>>3,se=m(V,17)^m(V,19)^V>>>10;N[u]=N[u-16]+$+N[u-7]+se>>>0}let y=o,G=d,H=c,te=l,x=h,j=p,z=_,ne=b;for(let u=0;u<64;u++){let L=m(x,6)^m(x,11)^m(x,25),V=x&j^~x&z,$=ne+L+V+Ze[u]+N[u]>>>0,se=m(y,2)^m(y,13)^m(y,22),Le=y&G^y&H^G&H,Ve=se+Le>>>0;ne=z,z=j,j=x,x=te+$>>>0,te=H,H=G,G=y,y=$+Ve>>>0}o=o+y>>>0,d=d+G>>>0,c=c+H>>>0,l=l+te>>>0,h=h+x>>>0,p=p+j>>>0,_=_+z>>>0,b=b+ne>>>0}let v=T=>T.toString(16).padStart(8,"0");return v(o)+v(d)+v(c)+v(l)+v(h)+v(p)+v(_)+v(b)}function le(n){let e=ce(n??null),t=JSON.stringify(e);return et(t).slice(0,16)}function tt(){let n=globalThis.crypto;if(n?.randomUUID)return n.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 ue(n,e,t){let s=t?.id??tt();if(n===0)return{id:s,version:0};let i=(t?.hash??le)(e);return{id:s,version:0,cid:i,prev:null}}function Ee(n,e,t){n.version+=1,"cid"in n&&(n.prev=n.cid,n.cid=t(e))}var Se=()=>{},Ce=100;function Re(n){return{node:n,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function fe(n){n.prevData=void 0,n.dirty=!1,n.involvedThisWave=!1,n.dataBatch.length=0,n.terminal=void 0}function J(n){return n.length===0?n:typeof n[0]=="symbol"?[n]:n}var nt=(n,e,t,s)=>{t.direction==="down-in"&&n._onDepMessage(t.depIndex,e)},st=(n,e,t,s)=>{let r=n;if(r._status==="completed"||r._status==="errored")return;let i=r._cached,a=i===void 0?[ie]:[ie,[g,i]];r._status==="dirty"&&a.push(F),q(e,a,r._config.tierOf)},pe=new Y({onMessage:nt,onSubscribe:st});Me(pe);Ae(pe);var X=class n{_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,s){this._config=s.config??pe,this._config.onMessage,this._optsName=s.name,this._describeKind=s.describeKind,this._equals=s.equals??Object.is,this._resubscribable=s.resubscribable??!1,this._resetOnTeardown=s.resetOnTeardown??!1,this._autoComplete=s.completeWhenDepsComplete??!0,this._autoError=s.errorWhenDepsError??!0,this._pausable=s.pausable??!0,this._guard=s.guard,this._fn=t,this._partial=s.partial??!1,this._cached=s.initial!==void 0?s.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=s.versioningHash??this._config.defaultHashFn??le;let r=s.versioning??this._config.defaultVersioning;this._versioningLevel=r,this._versioning=r!=null?ue(r,this._cached===void 0?void 0:this._cached,{id:s.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Re);let i={};for(let[o,d]of Object.entries(s.meta??{})){let c={initial:d,name:`${s.name??"node"}:meta:${o}`,describeKind:"state",config:this._config};s.guard!=null&&(c.guard=s.guard),i[o]=new n([],void 0,c)}Object.freeze(i),this.meta=i,this._hasMeta=Object.keys(i).length>0;let a=this;this._actions={emit(o){a._emit([[g,o]])},down(o){a._emit(J(o))},up(o){a._emitUp(J(o))}},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 s=this._versioningLevel;if(s!=null&&e<=s)return;let r=t?.hash??this._hashFn;r!==this._hashFn&&(this._hashFn=r);let i=this._cached===void 0?void 0:this._cached,a=this._versioning,o=a?.id??t?.id,d=a?.version??0,c=ue(e,i,{id:o,hash:r});c.version=d,this._versioning=c,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=K(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let s of this._extraGuards)if(!s(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,s=e?.actor!=null;if(!t&&!s)return;let r=K(e?.actor),i=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(r,i))throw new I({actor:r,action:i,nodeName:this.name});if(this._extraGuards!=null){for(let a of this._extraGuards)if(!a(r,i))throw new I({actor:r,action:i,nodeName:this.name})}this._lastMutation={actor:r,timestamp_ns:ke()}}down(e,t){let s=J(e);s.length!==0&&(this._checkGuard(t),this._emit(s))}emit(e,t){this._checkGuard(t),this._emit([[g,e]])}up(e,t){if(this._deps.length===0)return;let s=J(e);if(s.length===0)return;this._checkGuard(t);let r=t??{internal:!0};this._validateUpTiers(s);for(let i of this._deps)i.node.up?.(s,r)}_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 s of e){let r=t(s[0]);if(r===3||r===4)throw new Error(`Node "${this.name}": tier-${r} 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=K(t);if(!this._guard(d,"observe"))throw new I({actor:d,action:"observe",nodeName:this.name})}let r=this._isTerminal&&this._resubscribable;if(r){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)fe(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 i;try{i=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:r},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 i=="function")try{i()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let o=!1;return()=>{o||(o=!0,this._sinkCount-=1,this._removeSink(e),typeof i=="function"&&i(),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 s=0;s<e;s++){let r=s,i=this._deps[s];i.unsub=Se,i.unsub=i.node.subscribe(a=>{if(i.unsub===null)return;let o=this._config.tierOf,d=!1;for(let c of a)o(c[0])>=3&&(d=!0),this._config.onMessage(this,c,{direction:"down-in",depIndex:r},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(s){this._deps[t].unsub=null;for(let r=0;r<t;r++){let i=this._deps[r];if(i.unsub!=null){let a=i.unsub;i.unsub=null;try{a()}catch{}fe(i)}}throw this._dirtyDepCount=0,s}}_addDep(e){for(let r=0;r<this._deps.length;r++)if(this._deps[r].node===e)return r;let t=this._deps.length,s=Re(e);if(this._deps.push(s),this._sinks==null)return t;s.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ae),s.unsub=Se;try{s.unsub=e.subscribe(r=>{if(s.unsub===null)return;let i=this._config.tierOf,a=!1;for(let o of r)i(o[0])>=3&&(a=!0),this._config.onMessage(this,o,{direction:"down-in",depIndex:t},this._actions);a&&this._maybeRunFnOnSettlement()})}catch(r){throw s.unsub=null,this._deps.pop(),this._dirtyDepCount--,r}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(s){this._emit([[f,this._wrapFnError("cleanup threw",s)]])}else if(t!=null&&typeof t=="object"){let s=t.deactivate;if(typeof s=="function")try{s()}catch(r){this._emit([[f,this._wrapFnError("cleanup.deactivate threw",r)]])}}for(let s of this._deps){if(s.unsub!=null){let r=s.unsub;s.unsub=null;try{r()}catch{}}fe(s)}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 s=this._deps[e],r=t[0];if(this._inspectorHooks!=null){let i={kind:"dep_message",depIndex:e,message:t};for(let a of this._inspectorHooks)a(i)}if(r!==B){if(r===M){this._depDirtied(s);return}if(r===S){this._depInvalidated(s),this._emit(we);return}if(r===C||r===W){this._emit([t]);return}if(r===w){this._emit(de);return}if(r===g)this._depSettledAsData(s,t[1]);else if(r===E)this._depSettledAsResolved(s);else if(r===R)this._depSettledAsTerminal(s,!0);else if(r===f)this._depSettledAsTerminal(s,t[1]);else{this._emit([t]);return}if(!this._fn){(r===g||r===E)&&this._emit([t]),(r===R||r===f)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ae))}_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(xe),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([[f,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(Ne)}_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([[f,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(o){this._emit([[f,this._wrapFnError("cleanup.beforeRun threw",o)]]);return}}}let t=this._deps.map(a=>a.involvedThisWave?a.dataBatch.length>0?[...a.dataBatch]:[]:void 0),s=this._deps.map(a=>a.prevData);for(let a=0;a<this._deps.length;a++){let o=t[a];o!=null&&o.length>0&&(this._deps[a].prevData=o[o.length-1])}let r=this._deps.map(a=>a.terminal),i={prevData:s,terminalDeps:r,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let a={kind:"run",batchData:t,prevData:s};for(let o of this._inspectorHooks)o(a)}this._isExecutingFn=!0;try{let a=this._fn(t,this._actions,i);if(typeof a=="function")this._cleanup=a;else if(a!=null&&typeof a=="object"){let o=a;(typeof o.beforeRun=="function"||typeof o.deactivate=="function"||typeof o.invalidate=="function")&&(this._cleanup=a)}}catch(a){this._emit([[f,this._wrapFnError("fn threw",a)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Ce?(this._rerunDepth=0,this._emit([[f,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Ce} \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 s=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${s}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[F,e[0]]:e;let s=!0,r=!1,i=!1,a=-1;for(let d of e){let c=t(d[0]);c<a&&(s=!1),c===3&&(r=!0),d[0]===M&&(i=!0),a=c}let o=e;if(!s){let d=e.map((c,l)=>({m:c,i:l,tier:t(c[0])}));d.sort((c,l)=>c.tier-l.tier||c.i-l.i),o=d.map(c=>c.m)}if(r&&!i&&this._status!=="dirty"){let d=0;for(;d<o.length&&t(o[d][0])===0;)d++;return d===0?[F,...o]:[...o.slice(0,d),F,...o.slice(d)]}return o}_emit(e){if(e.length===0)return;for(let o=0;o<e.length;o++){let d=e[o];if(d[0]===f&&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 o=e.filter(d=>d[0]===w||d[0]===S);if(o.length===0)return;t=o}t=this._frameBatch(t);let r=null;for(let o=0;o<t.length;o++){let d=t[o],c=d[0];if(c!==C&&c!==W){r?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${c===C?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let l=!0;if(this._pausable!==!1){let h=d[1];if(c===C)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(h),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(h))l=!1;else if(this._pauseLocks.delete(h),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())}}l?r?.push(d):r==null&&(r=t.slice(0,o))}if(r!=null){if(r.length===0)return;t=r}if(this._hasMeta&&t.some(o=>o[0]===w))for(let o of Object.keys(this.meta))try{this.meta[o]._emit(de)}catch{}let{finalMessages:i,equalsError:a}=this._updateState(t);if(i.length>0&&this._config.inspectorEnabled){let o=this._config.globalInspector;if(o!=null)try{o({kind:"emit",node:this,messages:i})}catch{}}if(i.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let o=this._config.tierOf,d=[];for(let c of i)o(c[0])===3?this._pauseBuffer.push(c):d.push(c);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(i);a!=null&&this._emit([[f,a]])}_updateState(e){let t=this._config.tierOf,s,r,i=-1,a=0;for(let l of e)t(l[0])===3&&a++;let o=a<=1,d=-1;if(this._versioning!=null&&a>1){for(let l=e.length-1;l>=0;l--)if(e[l][0]===g){d=l;break}}for(let l=0;l<e.length;l++){let h=e[l],p=h[0];if(p===g){if(h.length>=2){let _=!1;if(o&&this._cached!==void 0)try{_=this._equals(this._cached,h[1])}catch(b){r=this._wrapFnError("equals threw",b),i=l;break}if(_){s==null&&(s=e.slice(0,l)),s.push(oe),this._status="resolved";continue}this._cached=h[1],this._versioning!=null&&(d<0||l===d)&&Ee(this._versioning,h[1],this._hashFn)}this._status="settled",s?.push(h)}else if(s?.push(h),p===M)this._status="dirty";else if(p===E)this._status="resolved";else if(p===R)this._status="completed";else if(p===f)this._status="errored";else if(p===S){this._cached=void 0,this._status="dirty";let _=this._cleanup;if(typeof _=="function"){this._cleanup=void 0;try{_()}catch{}}else if(_!=null&&typeof _=="object"){let b=_.invalidate;if(typeof b=="function")try{b()}catch{}}}else p===w&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let c=i>=0?s??e.slice(0,i):s??e;return r!=null?{finalMessages:c,equalsError:r}:{finalMessages:c}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let s of t)s(e)};_dispatchOrAccumulate(e){if(be()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],ve(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}q(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);q(this._deliverToSinks,t,this._config.tierOf)}},Oe=n=>Array.isArray(n),he=n=>typeof n=="object"&&n!=null&&!Array.isArray(n);function ge(n,e,t){let s=Oe(n)?n:[],r=typeof n=="function"?n:typeof e=="function"?e:void 0,i={};return Oe(n)?i=(he(e)?e:t)??{}:he(n)?i=n:i=(he(e)?e:t)??{},new X(s,r,i)}function _e(n,e){return ge([],{...e,initial:n})}function rt(n,e,t){return ge(n,(r,i,a)=>{let o=r.map((d,c)=>d!=null&&d.length>0?d.at(-1):a.prevData[c]);i.emit(e(o,a))},{describeKind:"derived",...t})}function De(n,e,t){let s=new Map;return n.forEach((r,i)=>{s.set(r,i)}),rt(n,(r,i)=>e(o=>{let d=s.get(o);if(d==null)throw new Error(`dynamicNode: untracked dep "${o.name??"<unnamed>"}"`);return r[d]},i),t)}var Q=new WeakMap,ee=new WeakMap;function Z(n,e){let t=e.get(n);if(t)for(let s of t)s()}function ye(n,e={}){let t=0;return{...e,get:()=>Ie(n),subscribe:r=>{t===0&&Z(n,Q),t++;let i=n.subscribe(a=>{for(let[o,d]of a)o===g&&r(d)});return()=>{i(),t--,t===0&&Z(n,ee)}},listen:r=>{t===0&&Z(n,Q),t++;let i=!0,a=n.subscribe(o=>{for(let[d,c]of o)if(d===g){if(i){i=!1;continue}r(c)}});return()=>{a(),t--,t===0&&Z(n,ee)}},_node:n}}function Fe(n){let e=n.cache,t;if(n.subscribe(r=>{for(let[i,a]of r)i===g&&(e=a),i===f&&(t=a)})(),t)throw t;return e}function Ie(n){return n.status==="sentinel"?Fe(n):n.cache}function ot(n){let e=_e(n,{resubscribable:!0,resetOnTeardown:!0});return ye(e,{set:t=>e.emit(t)})}function it(n,e){let t=Array.isArray(n)?n:[n],s=t.map(i=>i._node),r=De(s,i=>{let a=t.map(o=>{let d=o._node;return d.status==="sentinel"&&Fe(d),i(d)});return e(...a)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return ye(r)}function at(n){let e=_e(n,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return ye(e,{set:t=>e.emit(t),setKey:(t,s)=>{let r=Ie(e);e.emit({...r,[t]:s})}})}function dt(n){return n.get()}function Ge(n,e){let t=n._node,s=Q.get(t);s||(s=new Set,Q.set(t,s)),s.add(e)}function He(n,e){let t=n._node,s=ee.get(t);s||(s=new Set,ee.set(t,s)),s.add(e)}function ct(n,e){Ge(n,()=>{let t=e();typeof t=="function"&&He(n,t)})}function lt(n,e,t){return(...s)=>{let r;return Te(()=>{r=t(...s)}),r}}0&&(module.exports={action,atom,computed,getValue,map,onMount,onStart,onStop});