@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,5087 +0,0 @@
1
- import {
2
- createWatermarkController,
3
- toObservable
4
- } from "./chunk-OFVJBJXR.js";
5
- import {
6
- NS_PER_MS,
7
- NS_PER_SEC,
8
- audit,
9
- buffer,
10
- bufferCount,
11
- bufferTime,
12
- catchError,
13
- combine,
14
- combineLatest,
15
- concat,
16
- concatMap,
17
- constant,
18
- debounce,
19
- debounceTime,
20
- decorrelatedJitter,
21
- delay,
22
- distill,
23
- distinctUntilChanged,
24
- elementAt,
25
- exhaustMap,
26
- exponential,
27
- fibonacci,
28
- filter,
29
- find,
30
- first,
31
- flatMap,
32
- interval,
33
- last,
34
- linear,
35
- map,
36
- merge,
37
- mergeMap,
38
- pairwise,
39
- pausable,
40
- race,
41
- reduce,
42
- repeat,
43
- rescue,
44
- resolveBackoffPreset,
45
- sample,
46
- scan,
47
- skip,
48
- switchMap,
49
- take,
50
- takeUntil,
51
- takeWhile,
52
- tap,
53
- throttle,
54
- throttleTime,
55
- valve,
56
- verifiable,
57
- window,
58
- windowCount,
59
- windowTime,
60
- withLatestFrom,
61
- withMaxAttempts,
62
- zip
63
- } from "./chunk-RNHBMHKA.js";
64
- import {
65
- NativeListBackend,
66
- NativeMapBackend,
67
- reactiveList,
68
- reactiveMap
69
- } from "./chunk-WKNUIZOY.js";
70
- import {
71
- NativeLogBackend,
72
- reactiveLog
73
- } from "./chunk-J2VBW3DZ.js";
74
- import {
75
- cached,
76
- empty,
77
- escapeRegexChar,
78
- firstValueFrom,
79
- firstWhere,
80
- forEach,
81
- fromAny,
82
- fromAsyncIter,
83
- fromCron,
84
- fromEvent,
85
- fromIter,
86
- fromPromise,
87
- fromRaf,
88
- fromTimer,
89
- globToRegExp,
90
- keepalive,
91
- matchesAnyPattern,
92
- matchesCron,
93
- never,
94
- of,
95
- parseCron,
96
- reactiveCounter,
97
- replay,
98
- share,
99
- shareReplay,
100
- throwError,
101
- toArray
102
- } from "./chunk-BVZYTZ5H.js";
103
- import {
104
- ResettableTimer,
105
- RingBuffer
106
- } from "./chunk-7TAQJHQV.js";
107
- import {
108
- batch,
109
- defaultConfig,
110
- derived,
111
- effect,
112
- monotonicNs,
113
- node,
114
- producer,
115
- state,
116
- wallClockNs
117
- } from "./chunk-PHOUUNK7.js";
118
- import {
119
- COMPLETE,
120
- DATA,
121
- DIRTY,
122
- ERROR,
123
- INVALIDATE,
124
- PAUSE,
125
- RESOLVED,
126
- RESUME,
127
- TEARDOWN,
128
- __export,
129
- __require
130
- } from "./chunk-SX52TAR4.js";
131
-
132
- // src/extra/index.ts
133
- var extra_exports = {};
134
- __export(extra_exports, {
135
- CircuitOpenError: () => CircuitOpenError,
136
- NS_PER_MS: () => NS_PER_MS,
137
- NS_PER_SEC: () => NS_PER_SEC,
138
- NativeIndexBackend: () => NativeIndexBackend,
139
- NativeListBackend: () => NativeListBackend,
140
- NativeLogBackend: () => NativeLogBackend,
141
- NativeMapBackend: () => NativeMapBackend,
142
- NativePubSubBackend: () => NativePubSubBackend,
143
- RateLimiterOverflowError: () => RateLimiterOverflowError,
144
- ResettableTimer: () => ResettableTimer,
145
- TimeoutError: () => TimeoutError,
146
- audit: () => audit,
147
- buffer: () => buffer,
148
- bufferCount: () => bufferCount,
149
- bufferTime: () => bufferTime,
150
- cached: () => cached,
151
- cascadingCache: () => cascadingCache,
152
- catchError: () => catchError,
153
- checkpointToRedis: () => checkpointToRedis,
154
- checkpointToS3: () => checkpointToS3,
155
- circuitBreaker: () => circuitBreaker,
156
- combine: () => combine,
157
- combineLatest: () => combineLatest,
158
- concat: () => concat,
159
- concatMap: () => concatMap,
160
- constant: () => constant,
161
- createTransport: () => createTransport,
162
- createWatermarkController: () => createWatermarkController,
163
- csvRows: () => csvRows,
164
- debounce: () => debounce,
165
- debounceTime: () => debounceTime,
166
- decorrelatedJitter: () => decorrelatedJitter,
167
- delay: () => delay,
168
- deserializeError: () => deserializeError,
169
- dictStorage: () => dictStorage,
170
- distill: () => distill,
171
- distinctUntilChanged: () => distinctUntilChanged,
172
- elementAt: () => elementAt,
173
- empty: () => empty,
174
- escapeRegexChar: () => escapeRegexChar,
175
- exhaustMap: () => exhaustMap,
176
- exponential: () => exponential,
177
- externalBundle: () => externalBundle,
178
- externalProducer: () => externalProducer,
179
- fallback: () => fallback,
180
- fibonacci: () => fibonacci,
181
- fileStorage: () => fileStorage,
182
- filter: () => filter,
183
- find: () => find,
184
- first: () => first,
185
- firstValueFrom: () => firstValueFrom,
186
- firstWhere: () => firstWhere,
187
- flatMap: () => flatMap,
188
- forEach: () => forEach,
189
- fromAny: () => fromAny,
190
- fromAsyncIter: () => fromAsyncIter,
191
- fromCSV: () => fromCSV,
192
- fromClickHouseWatch: () => fromClickHouseWatch,
193
- fromCron: () => fromCron,
194
- fromDrizzle: () => fromDrizzle,
195
- fromEvent: () => fromEvent,
196
- fromFSWatch: () => fromFSWatch,
197
- fromGitHook: () => fromGitHook,
198
- fromHTTP: () => fromHTTP,
199
- fromHTTPPoll: () => fromHTTPPoll,
200
- fromHTTPStream: () => fromHTTPStream,
201
- fromIDBRequest: () => fromIDBRequest,
202
- fromIDBTransaction: () => fromIDBTransaction,
203
- fromIter: () => fromIter,
204
- fromKafka: () => fromKafka,
205
- fromKysely: () => fromKysely,
206
- fromMCP: () => fromMCP,
207
- fromNATS: () => fromNATS,
208
- fromNDJSON: () => fromNDJSON,
209
- fromOTel: () => fromOTel,
210
- fromPrisma: () => fromPrisma,
211
- fromPrometheus: () => fromPrometheus,
212
- fromPromise: () => fromPromise,
213
- fromPulsar: () => fromPulsar,
214
- fromRabbitMQ: () => fromRabbitMQ,
215
- fromRaf: () => fromRaf,
216
- fromRedisStream: () => fromRedisStream,
217
- fromSSE: () => fromSSE,
218
- fromSqlite: () => fromSqlite,
219
- fromSqliteCursor: () => fromSqliteCursor,
220
- fromStatsD: () => fromStatsD,
221
- fromSyslog: () => fromSyslog,
222
- fromTimer: () => fromTimer,
223
- fromWebSocket: () => fromWebSocket,
224
- fromWebSocketReconnect: () => fromWebSocketReconnect,
225
- fromWebhook: () => fromWebhook,
226
- globToRegExp: () => globToRegExp,
227
- indexedDbStorage: () => indexedDbStorage,
228
- interval: () => interval,
229
- keepalive: () => keepalive,
230
- last: () => last,
231
- linear: () => linear,
232
- lru: () => lru,
233
- map: () => map,
234
- matchesAnyPattern: () => matchesAnyPattern,
235
- matchesCron: () => matchesCron,
236
- memoryStorage: () => memoryStorage,
237
- merge: () => merge,
238
- mergeMap: () => mergeMap,
239
- nameToSignal: () => nameToSignal,
240
- ndjsonRows: () => ndjsonRows,
241
- never: () => never,
242
- of: () => of,
243
- pairwise: () => pairwise,
244
- parseCron: () => parseCron,
245
- parsePrometheusText: () => parsePrometheusText,
246
- parseStatsD: () => parseStatsD,
247
- parseSyslog: () => parseSyslog,
248
- pausable: () => pausable,
249
- pubsub: () => pubsub,
250
- race: () => race,
251
- rateLimiter: () => rateLimiter,
252
- reactiveCounter: () => reactiveCounter,
253
- reactiveIndex: () => reactiveIndex,
254
- reactiveList: () => reactiveList,
255
- reactiveLog: () => reactiveLog,
256
- reactiveMap: () => reactiveMap,
257
- reactiveSink: () => reactiveSink,
258
- reduce: () => reduce,
259
- repeat: () => repeat,
260
- replay: () => replay,
261
- rescue: () => rescue,
262
- resolveBackoffPreset: () => resolveBackoffPreset,
263
- retry: () => retry,
264
- retrySource: () => retrySource,
265
- sample: () => sample,
266
- scan: () => scan,
267
- serializeError: () => serializeError,
268
- share: () => share,
269
- shareReplay: () => shareReplay,
270
- signalToName: () => signalToName,
271
- skip: () => skip,
272
- sqliteStorage: () => sqliteStorage,
273
- switchMap: () => switchMap,
274
- take: () => take,
275
- takeUntil: () => takeUntil,
276
- takeWhile: () => takeWhile,
277
- tap: () => tap,
278
- throttle: () => throttle,
279
- throttleTime: () => throttleTime,
280
- throwError: () => throwError,
281
- timeout: () => timeout,
282
- toArray: () => toArray,
283
- toCSV: () => toCSV,
284
- toClickHouse: () => toClickHouse,
285
- toFile: () => toFile,
286
- toHTTP: () => toHTTP,
287
- toKafka: () => toKafka,
288
- toLoki: () => toLoki,
289
- toMongo: () => toMongo,
290
- toNATS: () => toNATS,
291
- toObservable: () => toObservable,
292
- toPostgres: () => toPostgres,
293
- toPulsar: () => toPulsar,
294
- toRabbitMQ: () => toRabbitMQ,
295
- toReadableStream: () => toReadableStream,
296
- toRedisStream: () => toRedisStream,
297
- toS3: () => toS3,
298
- toSSE: () => toSSE,
299
- toSSEBytes: () => toSSEBytes,
300
- toSqlite: () => toSqlite,
301
- toTempo: () => toTempo,
302
- toWebSocket: () => toWebSocket,
303
- tokenBucket: () => tokenBucket,
304
- valve: () => valve,
305
- verifiable: () => verifiable,
306
- window: () => window,
307
- windowCount: () => windowCount,
308
- windowTime: () => windowTime,
309
- withBreaker: () => withBreaker,
310
- withLatestFrom: () => withLatestFrom,
311
- withMaxAttempts: () => withMaxAttempts,
312
- withStatus: () => withStatus,
313
- workerBridge: () => workerBridge,
314
- workerSelf: () => workerSelf,
315
- zip: () => zip
316
- });
317
-
318
- // src/extra/external-register.ts
319
- function sourceOpts(opts) {
320
- return { describeKind: "producer", ...opts };
321
- }
322
- function externalProducer(register, opts) {
323
- return producer((a) => {
324
- let active = true;
325
- const triad = {
326
- emit(value) {
327
- if (!active) return;
328
- a.emit(value);
329
- },
330
- error(err) {
331
- if (!active) return;
332
- active = false;
333
- a.down([[ERROR, err]]);
334
- },
335
- complete() {
336
- if (!active) return;
337
- active = false;
338
- a.down([[COMPLETE]]);
339
- }
340
- };
341
- let cleanup;
342
- try {
343
- const ret = register(triad);
344
- cleanup = typeof ret === "function" ? ret : void 0;
345
- } catch (err) {
346
- triad.error(err);
347
- return () => {
348
- active = false;
349
- };
350
- }
351
- return () => {
352
- active = false;
353
- try {
354
- cleanup?.();
355
- } catch {
356
- }
357
- };
358
- }, sourceOpts(opts));
359
- }
360
- function externalBundle(register, channels, opts) {
361
- let active = true;
362
- let cleanup;
363
- let activatedCount = 0;
364
- let teardownCount = 0;
365
- const nodes = {};
366
- const channelNodes = [];
367
- const finishCleanup = () => {
368
- const fn = cleanup;
369
- cleanup = void 0;
370
- try {
371
- fn?.();
372
- } catch {
373
- }
374
- };
375
- for (const ch of channels) {
376
- const name = opts?.name ? `${opts.name}::${ch}` : ch;
377
- const chOpts = opts?.channelOpts?.[ch];
378
- const n = producer(
379
- (_a) => {
380
- activatedCount++;
381
- return () => {
382
- teardownCount++;
383
- if (activatedCount > 0 && teardownCount >= activatedCount && teardownCount >= channels.length) {
384
- finishCleanup();
385
- }
386
- };
387
- },
388
- sourceOpts({ ...chOpts, name })
389
- );
390
- nodes[ch] = n;
391
- channelNodes.push(n);
392
- }
393
- const bundle = {};
394
- for (const ch of channels) {
395
- bundle[ch] = (value) => {
396
- if (!active) return;
397
- nodes[ch].down([[DATA, value]]);
398
- };
399
- }
400
- bundle.error = (err) => {
401
- if (!active) return;
402
- active = false;
403
- batch(() => {
404
- for (const n of channelNodes) n.down([[ERROR, err]]);
405
- });
406
- finishCleanup();
407
- };
408
- bundle.complete = () => {
409
- if (!active) return;
410
- active = false;
411
- batch(() => {
412
- for (const n of channelNodes) n.down([[COMPLETE]]);
413
- });
414
- finishCleanup();
415
- };
416
- const ret = register(bundle);
417
- cleanup = typeof ret === "function" ? ret : void 0;
418
- const dispose = () => {
419
- if (!active) return;
420
- active = false;
421
- batch(() => {
422
- for (const n of channelNodes) {
423
- try {
424
- n.down([[COMPLETE]]);
425
- } catch {
426
- }
427
- }
428
- });
429
- finishCleanup();
430
- };
431
- return Object.assign(nodes, { dispose });
432
- }
433
-
434
- // src/extra/reactive-sink.ts
435
- var BackpressureBuffer = class {
436
- ring;
437
- arr;
438
- constructor(cap) {
439
- if (cap === Number.POSITIVE_INFINITY || cap <= 0) {
440
- this.arr = [];
441
- this.ring = null;
442
- } else {
443
- this.ring = new RingBuffer(cap);
444
- this.arr = null;
445
- }
446
- }
447
- get length() {
448
- return this.ring != null ? this.ring.size : this.arr.length;
449
- }
450
- push(item) {
451
- if (this.ring != null) this.ring.push(item);
452
- else this.arr.push(item);
453
- }
454
- /** Drop-oldest — O(1) in bounded mode. Returns undefined when empty. */
455
- shift() {
456
- if (this.ring != null) return this.ring.shift();
457
- return this.arr.shift();
458
- }
459
- /** Full drain — returns contents, resets to empty. */
460
- drain() {
461
- if (this.ring != null) {
462
- const out2 = this.ring.toArray();
463
- this.ring.clear();
464
- return out2;
465
- }
466
- const out = this.arr;
467
- this.arr = [];
468
- return out;
469
- }
470
- };
471
- function coerceError(err) {
472
- return err instanceof Error ? err : new Error(String(err));
473
- }
474
- function resolveBackoff(backoff) {
475
- if (backoff === void 0) return null;
476
- if (typeof backoff === "string") return resolveBackoffPreset(backoff);
477
- return backoff;
478
- }
479
- function reactiveSink(source, config) {
480
- const {
481
- name,
482
- onTransportError,
483
- retry: retry2,
484
- backpressure,
485
- batchSize = Number.POSITIVE_INFINITY,
486
- flushIntervalMs = 0,
487
- serialize,
488
- stopOn,
489
- onUpstreamMessage,
490
- onDispose,
491
- send,
492
- sendBatch,
493
- ctx: ctxValue
494
- } = config;
495
- if (!send && !sendBatch) {
496
- throw new Error("reactiveSink: `send` or `sendBatch` must be provided");
497
- }
498
- const ctx = ctxValue;
499
- const maxAttempts = Math.max(1, retry2?.maxAttempts ?? 1);
500
- const backoffStrategy = resolveBackoff(
501
- retry2?.backoff ?? (maxAttempts > 1 ? "exponential" : void 0)
502
- );
503
- const shouldRetry = retry2?.shouldRetry ?? (() => true);
504
- const useBuffering = sendBatch !== void 0 || batchSize < Number.POSITIVE_INFINITY || flushIntervalMs > 0;
505
- const nameFor = (suffix) => name ? `${name}::${suffix}` : void 0;
506
- const sent = state(void 0, {
507
- equals: () => false,
508
- name: nameFor("sent")
509
- });
510
- const failed = state(null, { name: nameFor("failed") });
511
- const inFlightCountNode = state(0, { name: nameFor("inFlight") });
512
- const errorsNode = state(null, { name: nameFor("errors") });
513
- const bufferedNode = useBuffering ? state(0, { name: nameFor("buffered") }) : void 0;
514
- const pausedNode = backpressure ? state(false, { name: nameFor("paused") }) : void 0;
515
- let inFlightCount = 0;
516
- const bumpInFlight = (delta) => {
517
- inFlightCount += delta;
518
- inFlightCountNode.down([[DATA, inFlightCount]]);
519
- };
520
- const reportError = (err) => {
521
- try {
522
- onTransportError?.(err);
523
- } catch {
524
- }
525
- try {
526
- errorsNode.down([[DATA, err]]);
527
- } catch {
528
- }
529
- };
530
- const inFlightPromises = /* @__PURE__ */ new Set();
531
- const trackPromise = (p) => {
532
- inFlightPromises.add(p);
533
- const done = () => inFlightPromises.delete(p);
534
- p.then(done, done);
535
- };
536
- const scheduleRetry = (runAgain, attempt, error) => {
537
- const raw = backoffStrategy ? backoffStrategy(attempt - 1, error, null) : 0;
538
- const delayNs = raw === null || raw === void 0 ? 0 : typeof raw === "number" && raw > 0 ? raw : 0;
539
- const delayMs = Math.max(1, Math.ceil(delayNs / NS_PER_MS));
540
- return new Promise((resolve) => {
541
- setTimeout(() => resolve(runAgain()), delayMs);
542
- });
543
- };
544
- const isThenable2 = (v) => v != null && typeof v === "object" && typeof v.then === "function";
545
- const performSend = (value) => {
546
- let payload;
547
- try {
548
- payload = serialize ? serialize(value) : value;
549
- } catch (rawErr) {
550
- const error = coerceError(rawErr);
551
- reportError({ stage: "serialize", error, value });
552
- failed.down([[DATA, { value, error, attempts: 0 }]]);
553
- return Promise.resolve();
554
- }
555
- let attempt = 0;
556
- const onError = (rawErr) => {
557
- bumpInFlight(-1);
558
- const error = coerceError(rawErr);
559
- reportError({ stage: "send", error, value, attempt });
560
- const more = attempt < maxAttempts && shouldRetry(error, attempt);
561
- if (!more) {
562
- failed.down([[DATA, { value, error, attempts: attempt }]]);
563
- return void 0;
564
- }
565
- return scheduleRetry(run, attempt, error);
566
- };
567
- const onSuccess = () => {
568
- bumpInFlight(-1);
569
- sent.down([[DATA, value]]);
570
- };
571
- function run() {
572
- attempt += 1;
573
- bumpInFlight(1);
574
- let result;
575
- try {
576
- result = send(payload, ctx);
577
- } catch (rawErr) {
578
- return onError(rawErr) ?? Promise.resolve();
579
- }
580
- if (isThenable2(result)) {
581
- return result.then(onSuccess, (rawErr) => onError(rawErr));
582
- }
583
- onSuccess();
584
- return Promise.resolve();
585
- }
586
- return run();
587
- };
588
- const maxBuf = backpressure?.maxBuffer ?? Number.POSITIVE_INFINITY;
589
- const buffer2 = new BackpressureBuffer(maxBuf);
590
- let flushTimer;
591
- let disposed = false;
592
- const updateBuffered = () => {
593
- bufferedNode?.down([[DATA, buffer2.length]]);
594
- };
595
- const markPaused = (paused) => {
596
- if (!pausedNode) return;
597
- pausedNode.down([[DATA, paused]]);
598
- };
599
- const bpStrategy = backpressure?.strategy ?? "drop-oldest";
600
- const pushWithBackpressure = (value, payload) => {
601
- const entry = { value, payload };
602
- if (buffer2.length < maxBuf) {
603
- buffer2.push(entry);
604
- updateBuffered();
605
- return true;
606
- }
607
- if (bpStrategy === "drop-oldest") {
608
- const dropped = buffer2.shift();
609
- buffer2.push(entry);
610
- updateBuffered();
611
- markPaused(true);
612
- failed.down([
613
- [
614
- DATA,
615
- {
616
- value: dropped.value,
617
- error: new Error("backpressure: buffer overflow \u2014 dropped oldest"),
618
- attempts: 0
619
- }
620
- ]
621
- ]);
622
- return true;
623
- }
624
- if (bpStrategy === "drop-newest") {
625
- markPaused(true);
626
- failed.down([
627
- [
628
- DATA,
629
- {
630
- value,
631
- error: new Error("backpressure: buffer overflow \u2014 dropped newest"),
632
- attempts: 0
633
- }
634
- ]
635
- ]);
636
- return false;
637
- }
638
- const err = new Error("backpressure: buffer overflow");
639
- reportError({ stage: "send", error: err, value });
640
- failed.down([[DATA, { value, error: err, attempts: 0 }]]);
641
- markPaused(true);
642
- return false;
643
- };
644
- const performBufferedBatchFlush = (chunk) => {
645
- let attempt = 0;
646
- const payloads = chunk.map((e) => e.payload);
647
- const onError = (rawErr) => {
648
- bumpInFlight(-1);
649
- const error = coerceError(rawErr);
650
- reportError({ stage: "send", error, value: chunk.map((e) => e.value), attempt });
651
- const more = attempt < maxAttempts && shouldRetry(error, attempt);
652
- if (!more) {
653
- for (const { value: v } of chunk) {
654
- failed.down([[DATA, { value: v, error, attempts: attempt }]]);
655
- }
656
- return void 0;
657
- }
658
- return scheduleRetry(run, attempt, error);
659
- };
660
- const onSuccess = () => {
661
- bumpInFlight(-1);
662
- for (const { value: v } of chunk) sent.down([[DATA, v]]);
663
- };
664
- function run() {
665
- attempt += 1;
666
- bumpInFlight(1);
667
- let result;
668
- try {
669
- result = sendBatch(payloads, ctx);
670
- } catch (rawErr) {
671
- return onError(rawErr) ?? Promise.resolve();
672
- }
673
- if (isThenable2(result)) {
674
- return result.then(onSuccess, (rawErr) => onError(rawErr));
675
- }
676
- onSuccess();
677
- return Promise.resolve();
678
- }
679
- return run();
680
- };
681
- const performBufferedPerRecordFlush = async (chunk) => {
682
- for (const entry of chunk) {
683
- await performPreSerializedSend(entry.value, entry.payload);
684
- }
685
- };
686
- const performPreSerializedSend = (value, payload) => {
687
- let attempt = 0;
688
- const onError = (rawErr) => {
689
- bumpInFlight(-1);
690
- const error = coerceError(rawErr);
691
- reportError({ stage: "send", error, value, attempt });
692
- const more = attempt < maxAttempts && shouldRetry(error, attempt);
693
- if (!more) {
694
- failed.down([[DATA, { value, error, attempts: attempt }]]);
695
- return void 0;
696
- }
697
- return scheduleRetry(run, attempt, error);
698
- };
699
- const onSuccess = () => {
700
- bumpInFlight(-1);
701
- sent.down([[DATA, value]]);
702
- };
703
- function run() {
704
- attempt += 1;
705
- bumpInFlight(1);
706
- let result;
707
- try {
708
- result = send(payload, ctx);
709
- } catch (rawErr) {
710
- return onError(rawErr) ?? Promise.resolve();
711
- }
712
- if (isThenable2(result)) {
713
- return result.then(onSuccess, (rawErr) => onError(rawErr));
714
- }
715
- onSuccess();
716
- return Promise.resolve();
717
- }
718
- return run();
719
- };
720
- const doFlush = () => {
721
- if (disposed || buffer2.length === 0) return Promise.resolve();
722
- const chunk = buffer2.drain();
723
- updateBuffered();
724
- markPaused(false);
725
- if (sendBatch !== void 0) {
726
- const p2 = performBufferedBatchFlush(chunk);
727
- trackPromise(p2);
728
- return p2;
729
- }
730
- const p = performBufferedPerRecordFlush(chunk);
731
- trackPromise(p);
732
- return p;
733
- };
734
- const scheduleFlush = () => {
735
- if (flushTimer !== void 0 || disposed) return;
736
- if (flushIntervalMs <= 0) return;
737
- flushTimer = setTimeout(() => {
738
- flushTimer = void 0;
739
- void doFlush();
740
- }, flushIntervalMs);
741
- };
742
- const unsub = source.subscribe((msgs) => {
743
- for (const msg of msgs) {
744
- const type = msg[0];
745
- if (type !== DATA) {
746
- try {
747
- onUpstreamMessage?.(msg);
748
- } catch {
749
- }
750
- }
751
- if (type === DATA) {
752
- const value = msg[1];
753
- if (useBuffering) {
754
- let payload;
755
- if (serialize) {
756
- try {
757
- payload = serialize(value);
758
- } catch (rawErr) {
759
- const error = coerceError(rawErr);
760
- reportError({ stage: "serialize", error, value });
761
- failed.down([[DATA, { value, error, attempts: 0 }]]);
762
- continue;
763
- }
764
- } else {
765
- payload = value;
766
- }
767
- const admitted = pushWithBackpressure(value, payload);
768
- if (!admitted) continue;
769
- if (buffer2.length >= batchSize) void doFlush();
770
- else scheduleFlush();
771
- } else {
772
- const p = performSend(value);
773
- trackPromise(p);
774
- }
775
- } else if (defaultConfig.messageTier(type) >= 3) {
776
- if (useBuffering) {
777
- if (flushTimer !== void 0) {
778
- clearTimeout(flushTimer);
779
- flushTimer = void 0;
780
- }
781
- void doFlush();
782
- }
783
- }
784
- }
785
- });
786
- let stopUnsub;
787
- if (stopOn) {
788
- let firstBatchSeen = false;
789
- stopUnsub = stopOn.subscribe((msgs) => {
790
- if (!firstBatchSeen) {
791
- firstBatchSeen = true;
792
- return;
793
- }
794
- if (msgs.length > 0 && !teardownRequested) dispose();
795
- });
796
- }
797
- let teardownRequested = false;
798
- const dispose = () => {
799
- if (teardownRequested) return;
800
- teardownRequested = true;
801
- if (flushTimer !== void 0) {
802
- clearTimeout(flushTimer);
803
- flushTimer = void 0;
804
- }
805
- if (useBuffering) void doFlush();
806
- disposed = true;
807
- stopUnsub?.();
808
- unsub();
809
- const tearDown = (n) => {
810
- try {
811
- n.down([[TEARDOWN]]);
812
- } catch {
813
- }
814
- };
815
- tearDown(errorsNode);
816
- tearDown(failed);
817
- tearDown(sent);
818
- tearDown(inFlightCountNode);
819
- if (bufferedNode) tearDown(bufferedNode);
820
- if (pausedNode) tearDown(pausedNode);
821
- try {
822
- onDispose?.();
823
- } catch {
824
- }
825
- };
826
- const handle = {
827
- dispose,
828
- sent,
829
- failed,
830
- inFlight: inFlightCountNode,
831
- errors: errorsNode
832
- };
833
- if (useBuffering) {
834
- handle.buffered = bufferedNode;
835
- handle.flush = async () => {
836
- if (disposed) return;
837
- await doFlush();
838
- await Promise.all(inFlightPromises);
839
- };
840
- }
841
- if (pausedNode) handle.paused = pausedNode;
842
- void COMPLETE;
843
- void ERROR;
844
- return handle;
845
- }
846
-
847
- // src/extra/resilience.ts
848
- function operatorOpts(opts) {
849
- return { describeKind: "derived", ...opts };
850
- }
851
- function clampNonNegative(value) {
852
- return value < 0 ? 0 : value;
853
- }
854
- function msgVal(m) {
855
- return m[1];
856
- }
857
- function coerceDelayNs(raw) {
858
- if (typeof raw !== "number" || !Number.isFinite(raw)) {
859
- throw new TypeError("backoff strategy must return a finite number");
860
- }
861
- return raw < 0 ? 0 : raw;
862
- }
863
- function retry(source, opts) {
864
- const count = opts?.count;
865
- const backoffOpt = opts?.backoff;
866
- const maxRetries = count !== void 0 ? count : backoffOpt === void 0 ? 0 : 2147483647;
867
- if (maxRetries < 0) throw new RangeError("retry count must be >= 0");
868
- const strategy = backoffOpt === void 0 ? null : typeof backoffOpt === "string" ? resolveBackoffPreset(backoffOpt) : backoffOpt;
869
- return producer(
870
- (a) => {
871
- let attempt = 0;
872
- let stopped = false;
873
- let prevDelay = null;
874
- let unsub;
875
- const timer = new ResettableTimer();
876
- function disconnectUpstream() {
877
- unsub?.();
878
- unsub = void 0;
879
- }
880
- function scheduleRetryOrFinish(err) {
881
- if (stopped) return;
882
- if (attempt >= maxRetries) {
883
- disconnectUpstream();
884
- a.down([[ERROR, err]]);
885
- return;
886
- }
887
- const raw = strategy === null ? 0 : strategy(attempt, err, prevDelay);
888
- if (raw === null || raw === void 0) {
889
- disconnectUpstream();
890
- a.down([[ERROR, err]]);
891
- return;
892
- }
893
- let delayNs;
894
- try {
895
- delayNs = coerceDelayNs(raw);
896
- } catch {
897
- disconnectUpstream();
898
- a.down([[ERROR, err]]);
899
- return;
900
- }
901
- prevDelay = delayNs;
902
- attempt += 1;
903
- disconnectUpstream();
904
- const delayMs = delayNs > 0 ? delayNs / NS_PER_MS : 1;
905
- timer.start(delayMs, () => {
906
- if (stopped) return;
907
- connect();
908
- });
909
- }
910
- function connect() {
911
- timer.cancel();
912
- disconnectUpstream();
913
- unsub = source.subscribe((msgs) => {
914
- if (stopped) return;
915
- for (const m of msgs) {
916
- const t = m[0];
917
- if (t === DIRTY) a.down([[DIRTY]]);
918
- else if (t === DATA) {
919
- attempt = 0;
920
- prevDelay = null;
921
- a.emit(m[1]);
922
- } else if (t === RESOLVED) a.down([[RESOLVED]]);
923
- else if (t === COMPLETE) {
924
- disconnectUpstream();
925
- a.down([[COMPLETE]]);
926
- } else if (t === ERROR) {
927
- scheduleRetryOrFinish(msgVal(m));
928
- return;
929
- } else a.down([m]);
930
- }
931
- });
932
- }
933
- connect();
934
- return () => {
935
- stopped = true;
936
- timer.cancel();
937
- disconnectUpstream();
938
- };
939
- },
940
- {
941
- ...operatorOpts(),
942
- initial: source.cache
943
- }
944
- );
945
- }
946
- function retrySource(factory, opts) {
947
- const count = opts?.count;
948
- const backoffOpt = opts?.backoff;
949
- const maxRetries = count !== void 0 ? count : backoffOpt === void 0 ? 0 : 2147483647;
950
- if (maxRetries < 0) throw new RangeError("retry count must be >= 0");
951
- const strategy = backoffOpt === void 0 ? null : typeof backoffOpt === "string" ? resolveBackoffPreset(backoffOpt) : backoffOpt;
952
- return producer(
953
- (a) => {
954
- let attempt = 0;
955
- let stopped = false;
956
- let prevDelay = null;
957
- let unsub;
958
- const timer = new ResettableTimer();
959
- function disconnectUpstream() {
960
- unsub?.();
961
- unsub = void 0;
962
- }
963
- function scheduleRetryOrFinish(err) {
964
- if (stopped) return;
965
- if (attempt >= maxRetries) {
966
- disconnectUpstream();
967
- a.down([[ERROR, err]]);
968
- return;
969
- }
970
- const raw = strategy === null ? 0 : strategy(attempt, err, prevDelay);
971
- if (raw === null || raw === void 0) {
972
- disconnectUpstream();
973
- a.down([[ERROR, err]]);
974
- return;
975
- }
976
- let delayNs;
977
- try {
978
- delayNs = coerceDelayNs(raw);
979
- } catch {
980
- disconnectUpstream();
981
- a.down([[ERROR, err]]);
982
- return;
983
- }
984
- prevDelay = delayNs;
985
- attempt += 1;
986
- disconnectUpstream();
987
- const delayMs = delayNs > 0 ? delayNs / NS_PER_MS : 1;
988
- timer.start(delayMs, () => {
989
- if (stopped) return;
990
- connect();
991
- });
992
- }
993
- function connect() {
994
- timer.cancel();
995
- disconnectUpstream();
996
- let src;
997
- try {
998
- src = factory();
999
- } catch (err) {
1000
- scheduleRetryOrFinish(err);
1001
- return;
1002
- }
1003
- unsub = src.subscribe((msgs) => {
1004
- if (stopped) return;
1005
- for (const m of msgs) {
1006
- const t = m[0];
1007
- if (t === DIRTY) a.down([[DIRTY]]);
1008
- else if (t === DATA) {
1009
- attempt = 0;
1010
- prevDelay = null;
1011
- a.emit(m[1]);
1012
- } else if (t === RESOLVED) a.down([[RESOLVED]]);
1013
- else if (t === COMPLETE) {
1014
- disconnectUpstream();
1015
- a.down([[COMPLETE]]);
1016
- } else if (t === ERROR) {
1017
- scheduleRetryOrFinish(msgVal(m));
1018
- return;
1019
- } else a.down([m]);
1020
- }
1021
- });
1022
- }
1023
- connect();
1024
- return () => {
1025
- stopped = true;
1026
- timer.cancel();
1027
- disconnectUpstream();
1028
- };
1029
- },
1030
- {
1031
- ...operatorOpts(),
1032
- initial: opts?.initial
1033
- }
1034
- );
1035
- }
1036
- var CircuitOpenError = class extends Error {
1037
- name = "CircuitOpenError";
1038
- constructor() {
1039
- super("Circuit breaker is open");
1040
- }
1041
- };
1042
- function circuitBreaker(options) {
1043
- const threshold = Math.max(1, options?.failureThreshold ?? 5);
1044
- const baseCooldownNs = clampNonNegative(options?.cooldownNs ?? 30 * NS_PER_SEC);
1045
- const cooldownStrategy = options?.cooldown ?? null;
1046
- const halfOpenMax = Math.max(1, options?.halfOpenMax ?? 1);
1047
- const now = options?.now ?? monotonicNs;
1048
- let _state = "closed";
1049
- let _failureCount = 0;
1050
- let _openCycle = 0;
1051
- let _lastOpenedAt = 0;
1052
- let _lastCooldownNs = baseCooldownNs;
1053
- let _halfOpenAttempts = 0;
1054
- function getCooldownNs() {
1055
- if (!cooldownStrategy) return baseCooldownNs;
1056
- const delayNs = cooldownStrategy(_openCycle);
1057
- return delayNs !== null ? delayNs : baseCooldownNs;
1058
- }
1059
- function transitionToOpen() {
1060
- _state = "open";
1061
- _lastCooldownNs = getCooldownNs();
1062
- _lastOpenedAt = now();
1063
- _halfOpenAttempts = 0;
1064
- }
1065
- const breaker = {
1066
- canExecute() {
1067
- if (_state === "closed") return true;
1068
- if (_state === "open") {
1069
- const elapsed = now() - _lastOpenedAt;
1070
- if (elapsed >= _lastCooldownNs) {
1071
- _state = "half-open";
1072
- _halfOpenAttempts = 1;
1073
- return true;
1074
- }
1075
- return false;
1076
- }
1077
- if (_halfOpenAttempts < halfOpenMax) {
1078
- _halfOpenAttempts++;
1079
- return true;
1080
- }
1081
- return false;
1082
- },
1083
- recordSuccess() {
1084
- if (_state === "half-open") {
1085
- _state = "closed";
1086
- _failureCount = 0;
1087
- _openCycle = 0;
1088
- } else if (_state === "closed") {
1089
- _failureCount = 0;
1090
- }
1091
- },
1092
- recordFailure(_error) {
1093
- if (_state === "half-open") {
1094
- _openCycle++;
1095
- transitionToOpen();
1096
- return;
1097
- }
1098
- if (_state === "closed") {
1099
- _failureCount++;
1100
- if (_failureCount >= threshold) {
1101
- transitionToOpen();
1102
- }
1103
- }
1104
- },
1105
- get state() {
1106
- return _state;
1107
- },
1108
- get failureCount() {
1109
- return _failureCount;
1110
- },
1111
- reset() {
1112
- _state = "closed";
1113
- _failureCount = 0;
1114
- _openCycle = 0;
1115
- _halfOpenAttempts = 0;
1116
- }
1117
- };
1118
- return breaker;
1119
- }
1120
- function withBreaker(breaker, options) {
1121
- const onOpen = options?.onOpen ?? "skip";
1122
- return (source) => {
1123
- const wrapped = node(
1124
- [],
1125
- (_deps, a) => {
1126
- function syncState() {
1127
- wrapped.meta.breakerState.down([[DATA, breaker.state]]);
1128
- }
1129
- const unsub = source.subscribe((msgs) => {
1130
- for (const m of msgs) {
1131
- const t = m[0];
1132
- if (t === DIRTY) a.down([[DIRTY]]);
1133
- else if (t === DATA) {
1134
- if (breaker.canExecute()) {
1135
- syncState();
1136
- a.emit(m[1]);
1137
- } else {
1138
- syncState();
1139
- if (onOpen === "error") a.down([[ERROR, new CircuitOpenError()]]);
1140
- else a.down([[RESOLVED]]);
1141
- }
1142
- } else if (t === RESOLVED) a.down([[RESOLVED]]);
1143
- else if (t === COMPLETE) {
1144
- breaker.recordSuccess();
1145
- syncState();
1146
- a.down([[COMPLETE]]);
1147
- } else if (t === ERROR) {
1148
- breaker.recordFailure(msgVal(m));
1149
- syncState();
1150
- a.down([m]);
1151
- } else a.down([m]);
1152
- }
1153
- });
1154
- syncState();
1155
- return unsub;
1156
- },
1157
- {
1158
- ...operatorOpts(),
1159
- meta: { breakerState: breaker.state },
1160
- completeWhenDepsComplete: false,
1161
- initial: source.cache
1162
- }
1163
- );
1164
- return { node: wrapped, breakerState: wrapped.meta.breakerState };
1165
- };
1166
- }
1167
- function tokenBucket(capacity, refillPerSecond) {
1168
- if (capacity <= 0) throw new RangeError("capacity must be > 0");
1169
- if (refillPerSecond < 0) throw new RangeError("refillPerSecond must be >= 0");
1170
- let tokens = capacity;
1171
- let updatedAt = monotonicNs();
1172
- function refill(now) {
1173
- if (refillPerSecond > 0) {
1174
- const elapsedNs = now - updatedAt;
1175
- tokens = Math.min(capacity, tokens + elapsedNs / NS_PER_SEC * refillPerSecond);
1176
- }
1177
- updatedAt = now;
1178
- }
1179
- return {
1180
- available() {
1181
- refill(monotonicNs());
1182
- return tokens;
1183
- },
1184
- tryConsume(cost = 1) {
1185
- if (cost <= 0) return true;
1186
- const now = monotonicNs();
1187
- refill(now);
1188
- if (tokens >= cost) {
1189
- tokens -= cost;
1190
- return true;
1191
- }
1192
- return false;
1193
- }
1194
- };
1195
- }
1196
- var RateLimiterOverflowError = class extends Error {
1197
- name = "RateLimiterOverflowError";
1198
- constructor(maxBuffer) {
1199
- super(`rateLimiter buffer overflow (maxBuffer=${maxBuffer})`);
1200
- }
1201
- };
1202
- function rateLimiter(source, opts) {
1203
- const { maxEvents, windowNs } = opts;
1204
- if (maxEvents <= 0) throw new RangeError("maxEvents must be > 0");
1205
- if (windowNs <= 0) throw new RangeError("windowNs must be > 0");
1206
- const maxBuffer = opts.maxBuffer;
1207
- if (maxBuffer !== void 0 && maxBuffer < 1) throw new RangeError("maxBuffer must be >= 1");
1208
- const onOverflow = opts.onOverflow ?? "drop-newest";
1209
- const refillPerSec = maxEvents * NS_PER_SEC / windowNs;
1210
- return producer(
1211
- (a) => {
1212
- const bucket = tokenBucket(maxEvents, refillPerSec);
1213
- const pending = [];
1214
- const timer = new ResettableTimer();
1215
- let terminated = false;
1216
- const tokenTimeNs = NS_PER_SEC / refillPerSec;
1217
- function tryEmit() {
1218
- while (pending.length > 0) {
1219
- if (bucket.tryConsume(1)) {
1220
- a.emit(pending.shift());
1221
- } else {
1222
- timer.start(Math.max(1, tokenTimeNs / NS_PER_MS), tryEmit);
1223
- return;
1224
- }
1225
- }
1226
- }
1227
- const unsub = source.subscribe((msgs) => {
1228
- for (const m of msgs) {
1229
- if (terminated) return;
1230
- const t = m[0];
1231
- if (t === DIRTY) a.down([[DIRTY]]);
1232
- else if (t === DATA) {
1233
- if (maxBuffer !== void 0 && pending.length >= maxBuffer) {
1234
- if (onOverflow === "drop-newest") {
1235
- } else if (onOverflow === "drop-oldest") {
1236
- pending.shift();
1237
- pending.push(m[1]);
1238
- } else {
1239
- terminated = true;
1240
- timer.cancel();
1241
- pending.length = 0;
1242
- a.down([[ERROR, new RateLimiterOverflowError(maxBuffer)]]);
1243
- return;
1244
- }
1245
- } else {
1246
- pending.push(m[1]);
1247
- }
1248
- tryEmit();
1249
- } else if (t === RESOLVED) a.down([[RESOLVED]]);
1250
- else if (t === COMPLETE) {
1251
- terminated = true;
1252
- timer.cancel();
1253
- pending.length = 0;
1254
- a.down([[COMPLETE]]);
1255
- } else if (t === ERROR) {
1256
- terminated = true;
1257
- timer.cancel();
1258
- pending.length = 0;
1259
- a.down([m]);
1260
- } else if (t === TEARDOWN) {
1261
- terminated = true;
1262
- timer.cancel();
1263
- pending.length = 0;
1264
- a.down([m]);
1265
- return;
1266
- } else a.down([m]);
1267
- }
1268
- });
1269
- return () => {
1270
- terminated = true;
1271
- timer.cancel();
1272
- unsub();
1273
- };
1274
- },
1275
- {
1276
- ...operatorOpts(),
1277
- initial: source.cache
1278
- }
1279
- );
1280
- }
1281
- function withStatus(src, options) {
1282
- const initialStatus = options?.initialStatus ?? "pending";
1283
- const out = node(
1284
- [],
1285
- (_deps, a) => {
1286
- let currentStatus = initialStatus;
1287
- out.meta.status.down([[DATA, initialStatus]]);
1288
- out.meta.error.down([[DATA, null]]);
1289
- const unsub = src.subscribe((msgs) => {
1290
- for (const m of msgs) {
1291
- const t = m[0];
1292
- if (t === DIRTY) a.down([[DIRTY]]);
1293
- else if (t === DATA) {
1294
- if (currentStatus === "errored") {
1295
- batch(() => {
1296
- out.meta.error.down([[DATA, null]]);
1297
- out.meta.status.down([[DATA, "active"]]);
1298
- });
1299
- } else {
1300
- out.meta.status.down([[DATA, "active"]]);
1301
- }
1302
- currentStatus = "active";
1303
- a.emit(m[1]);
1304
- } else if (t === RESOLVED) a.down([[RESOLVED]]);
1305
- else if (t === COMPLETE) {
1306
- out.meta.status.down([[DATA, "completed"]]);
1307
- currentStatus = "completed";
1308
- a.down([[COMPLETE]]);
1309
- } else if (t === ERROR) {
1310
- const err = msgVal(m);
1311
- batch(() => {
1312
- out.meta.error.down([[DATA, err]]);
1313
- out.meta.status.down([[DATA, "errored"]]);
1314
- });
1315
- currentStatus = "errored";
1316
- a.down([m]);
1317
- } else a.down([m]);
1318
- }
1319
- });
1320
- return unsub;
1321
- },
1322
- {
1323
- ...operatorOpts(),
1324
- meta: { status: initialStatus, error: null },
1325
- completeWhenDepsComplete: false,
1326
- resubscribable: true,
1327
- initial: src.cache
1328
- }
1329
- );
1330
- return {
1331
- node: out,
1332
- status: out.meta.status,
1333
- error: out.meta.error
1334
- };
1335
- }
1336
- var TimeoutError = class extends Error {
1337
- name = "TimeoutError";
1338
- constructor(ns) {
1339
- super(`Timed out after ${ns / NS_PER_MS}ms`);
1340
- }
1341
- };
1342
- function isNode(x) {
1343
- return x != null && typeof x === "object" && "cache" in x && typeof x.subscribe === "function";
1344
- }
1345
- function isThenable(x) {
1346
- return x != null && typeof x.then === "function";
1347
- }
1348
- function isAsyncIterable(x) {
1349
- return x != null && typeof x === "object" && typeof x[Symbol.asyncIterator] === "function";
1350
- }
1351
- function fallback(source, fb) {
1352
- return producer(
1353
- (a) => {
1354
- let fallbackUnsub;
1355
- let sourceUnsub;
1356
- function switchToFallback() {
1357
- sourceUnsub?.();
1358
- sourceUnsub = void 0;
1359
- if (isNode(fb) || isThenable(fb) || isAsyncIterable(fb)) {
1360
- const fbNode = fromAny(fb);
1361
- fallbackUnsub = fbNode.subscribe((fMsgs) => {
1362
- a.down(fMsgs);
1363
- });
1364
- } else {
1365
- a.emit(fb);
1366
- a.down([[COMPLETE]]);
1367
- }
1368
- }
1369
- sourceUnsub = source.subscribe((msgs) => {
1370
- for (const m of msgs) {
1371
- const t = m[0];
1372
- if (t === DIRTY) a.down([[DIRTY]]);
1373
- else if (t === DATA) a.emit(m[1]);
1374
- else if (t === RESOLVED) a.down([[RESOLVED]]);
1375
- else if (t === COMPLETE) a.down([[COMPLETE]]);
1376
- else if (t === ERROR) {
1377
- switchToFallback();
1378
- return;
1379
- } else if (t === TEARDOWN) {
1380
- fallbackUnsub?.();
1381
- a.down([m]);
1382
- return;
1383
- } else a.down([m]);
1384
- }
1385
- });
1386
- return () => {
1387
- sourceUnsub?.();
1388
- fallbackUnsub?.();
1389
- };
1390
- },
1391
- {
1392
- ...operatorOpts(),
1393
- initial: source.cache
1394
- }
1395
- );
1396
- }
1397
- function timeout(source, timeoutNs) {
1398
- if (timeoutNs <= 0) throw new RangeError("timeoutNs must be > 0");
1399
- return producer(
1400
- (a) => {
1401
- let stopped = false;
1402
- const timer = new ResettableTimer();
1403
- function startTimer() {
1404
- const delayMs = timeoutNs / NS_PER_MS;
1405
- timer.start(delayMs, () => {
1406
- if (stopped) return;
1407
- stopped = true;
1408
- unsub();
1409
- a.down([[ERROR, new TimeoutError(timeoutNs)]]);
1410
- });
1411
- }
1412
- const unsub = source.subscribe((msgs) => {
1413
- for (const m of msgs) {
1414
- if (stopped) return;
1415
- const t = m[0];
1416
- if (t === DIRTY) a.down([[DIRTY]]);
1417
- else if (t === DATA) {
1418
- startTimer();
1419
- a.emit(m[1]);
1420
- } else if (t === RESOLVED) a.down([[RESOLVED]]);
1421
- else if (t === COMPLETE) {
1422
- timer.cancel();
1423
- stopped = true;
1424
- a.down([[COMPLETE]]);
1425
- return;
1426
- } else if (t === ERROR) {
1427
- timer.cancel();
1428
- stopped = true;
1429
- a.down([m]);
1430
- return;
1431
- } else if (t === TEARDOWN) {
1432
- timer.cancel();
1433
- stopped = true;
1434
- a.down([m]);
1435
- return;
1436
- } else a.down([m]);
1437
- }
1438
- });
1439
- startTimer();
1440
- return () => {
1441
- stopped = true;
1442
- timer.cancel();
1443
- unsub();
1444
- };
1445
- },
1446
- {
1447
- ...operatorOpts(),
1448
- initial: source.cache
1449
- }
1450
- );
1451
- }
1452
-
1453
- // src/extra/adapters.ts
1454
- function sourceOpts2(opts) {
1455
- return { describeKind: "producer", ...opts };
1456
- }
1457
- function fromWebSocket(socketOrRegister, opts) {
1458
- const { parse, closeOnTeardown = false, ...rest } = opts ?? {};
1459
- return producer((a) => {
1460
- let active = true;
1461
- let cleanup;
1462
- const runCleanup = () => {
1463
- const fn = cleanup;
1464
- cleanup = void 0;
1465
- fn?.();
1466
- };
1467
- const terminate = (message) => {
1468
- if (!active) return;
1469
- active = false;
1470
- a.down([message]);
1471
- runCleanup();
1472
- };
1473
- const emit = (raw, event = raw) => {
1474
- if (!active) return;
1475
- try {
1476
- const payload = raw !== null && typeof raw === "object" && "data" in raw ? raw.data : raw;
1477
- const parsed = parse ? parse(payload, event) : payload;
1478
- a.emit(parsed);
1479
- } catch (err) {
1480
- terminate([ERROR, err]);
1481
- }
1482
- };
1483
- const error = (err) => {
1484
- terminate([ERROR, err]);
1485
- };
1486
- const complete = () => {
1487
- terminate([COMPLETE]);
1488
- };
1489
- if (typeof socketOrRegister === "function") {
1490
- try {
1491
- cleanup = socketOrRegister(emit, error, complete);
1492
- if (typeof cleanup !== "function") {
1493
- throw new Error(
1494
- "fromWebSocket register contract violation: register must return cleanup callable"
1495
- );
1496
- }
1497
- } catch (err) {
1498
- terminate([ERROR, err]);
1499
- }
1500
- return () => {
1501
- active = false;
1502
- runCleanup();
1503
- };
1504
- }
1505
- const ws = socketOrRegister;
1506
- const onMessage = (event) => emit(event, event);
1507
- const onError = (event) => error(event);
1508
- const onClose = () => complete();
1509
- ws.addEventListener("message", onMessage);
1510
- ws.addEventListener("error", onError);
1511
- ws.addEventListener("close", onClose);
1512
- cleanup = () => {
1513
- ws.removeEventListener("message", onMessage);
1514
- ws.removeEventListener("error", onError);
1515
- ws.removeEventListener("close", onClose);
1516
- if (closeOnTeardown) ws.close();
1517
- };
1518
- return () => {
1519
- active = false;
1520
- runCleanup();
1521
- };
1522
- }, sourceOpts2(rest));
1523
- }
1524
- function fromWebhook(register, opts) {
1525
- return externalProducer(register, opts);
1526
- }
1527
- function fromHTTP(url, opts) {
1528
- const {
1529
- method = "GET",
1530
- headers,
1531
- body: bodyOpt,
1532
- transform = (r) => r.json(),
1533
- timeoutNs = 30 * NS_PER_SEC,
1534
- signal: externalSignal,
1535
- completeAfterFetch = false,
1536
- refetchOnSubscribe = false,
1537
- ...rest
1538
- } = opts ?? {};
1539
- const fetchCount = state(0, { name: `${rest.name ?? "http"}/fetchCount` });
1540
- const lastUpdated = state(0, { name: `${rest.name ?? "http"}/lastUpdated` });
1541
- const fetched = state(false, { name: `${rest.name ?? "http"}/fetched` });
1542
- let fetchCountLocal = 0;
1543
- const body = bodyOpt !== void 0 ? typeof bodyOpt === "string" ? bodyOpt : JSON.stringify(bodyOpt) : void 0;
1544
- const runFetch = (a) => {
1545
- const abort = new AbortController();
1546
- let active = true;
1547
- if (externalSignal?.aborted) {
1548
- active = false;
1549
- a.down([[ERROR, externalSignal.reason ?? new Error("Aborted")]]);
1550
- return () => {
1551
- };
1552
- }
1553
- externalSignal?.addEventListener("abort", () => abort.abort(externalSignal.reason), {
1554
- once: true
1555
- });
1556
- const timeoutId = setTimeout(
1557
- () => abort.abort(new Error("Request timeout")),
1558
- Math.ceil(timeoutNs / NS_PER_MS)
1559
- );
1560
- fetch(url, { method, headers, body, signal: abort.signal }).then(async (res) => {
1561
- clearTimeout(timeoutId);
1562
- if (!active) return;
1563
- if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`);
1564
- const data = await transform(res);
1565
- if (!active) return;
1566
- batch(() => {
1567
- fetchCountLocal += 1;
1568
- fetchCount.down([[DATA, fetchCountLocal]]);
1569
- lastUpdated.down([[DATA, wallClockNs()]]);
1570
- fetched.down([[DATA, true]]);
1571
- a.emit(data);
1572
- });
1573
- if (completeAfterFetch) a.down([[COMPLETE]]);
1574
- }).catch((err) => {
1575
- clearTimeout(timeoutId);
1576
- if (!active) return;
1577
- if (err && err.name === "AbortError") return;
1578
- a.down([[ERROR, err]]);
1579
- });
1580
- return () => {
1581
- active = false;
1582
- abort.abort();
1583
- };
1584
- };
1585
- const sourceNode = producer(
1586
- (a) => runFetch({
1587
- emit: (v) => a.emit(v),
1588
- down: (msgs) => a.down(msgs)
1589
- }),
1590
- {
1591
- ...sourceOpts2(rest),
1592
- // `resubscribable: true` when refetchOnSubscribe — each new activation
1593
- // (subscribe after full deactivation) re-runs the producer fn → fresh
1594
- // fetch. Default (cache-once) stays non-resubscribable: producer runs
1595
- // once on first activation, cached DATA replays to late subscribers.
1596
- resubscribable: refetchOnSubscribe
1597
- }
1598
- );
1599
- const tracked = withStatus(sourceNode);
1600
- return {
1601
- ...tracked,
1602
- fetchCount,
1603
- lastUpdated,
1604
- fetched
1605
- };
1606
- }
1607
- function toHTTP(source, url, opts) {
1608
- const {
1609
- method = "POST",
1610
- headers = { "Content-Type": "application/json" },
1611
- serialize = (v) => JSON.stringify(v),
1612
- timeoutNs,
1613
- batchFormat = "json-array",
1614
- batchSize,
1615
- flushIntervalMs,
1616
- retry: retry2,
1617
- onTransportError
1618
- } = opts ?? {};
1619
- const sendOne = async (body) => {
1620
- const controller = timeoutNs !== void 0 ? new AbortController() : void 0;
1621
- let timeoutId;
1622
- if (controller && timeoutNs !== void 0) {
1623
- timeoutId = setTimeout(
1624
- () => controller.abort(new Error("Request timeout")),
1625
- Math.ceil(timeoutNs / NS_PER_MS)
1626
- );
1627
- }
1628
- try {
1629
- const res = await fetch(url, {
1630
- method,
1631
- headers,
1632
- body,
1633
- signal: controller?.signal
1634
- });
1635
- const drain = async () => {
1636
- try {
1637
- await res.arrayBuffer?.();
1638
- } catch {
1639
- }
1640
- };
1641
- if (!res.ok) {
1642
- await drain();
1643
- throw new Error(`HTTP ${res.status}: ${res.statusText}`);
1644
- }
1645
- await drain();
1646
- } finally {
1647
- if (timeoutId !== void 0) clearTimeout(timeoutId);
1648
- }
1649
- };
1650
- const buffered = batchSize !== void 0 || flushIntervalMs !== void 0;
1651
- if (buffered) {
1652
- return reactiveSink(source, {
1653
- onTransportError,
1654
- retry: retry2,
1655
- batchSize,
1656
- flushIntervalMs,
1657
- sendBatch: async (chunk) => {
1658
- let body;
1659
- if (batchFormat === "ndjson") {
1660
- body = chunk.map((v) => {
1661
- const s = serialize(v);
1662
- return typeof s === "string" ? s : new TextDecoder().decode(s);
1663
- }).join("\n");
1664
- } else {
1665
- body = JSON.stringify(chunk);
1666
- }
1667
- await sendOne(body);
1668
- }
1669
- });
1670
- }
1671
- return reactiveSink(source, {
1672
- onTransportError,
1673
- retry: retry2,
1674
- serialize,
1675
- send: async (payload) => {
1676
- await sendOne(payload);
1677
- }
1678
- });
1679
- }
1680
- function messageTypeLabel(t) {
1681
- return Symbol.keyFor(t) ?? t.description ?? "message";
1682
- }
1683
- function serializeSseData(value, serialize) {
1684
- if (typeof value === "string") return value;
1685
- return serialize(value);
1686
- }
1687
- function sseFrame(event, data) {
1688
- let out = `event: ${event}
1689
- `;
1690
- if (data !== void 0) {
1691
- const lines = data.split(/\r?\n/);
1692
- for (const line of lines) {
1693
- out += `data: ${line}
1694
- `;
1695
- }
1696
- }
1697
- return `${out}
1698
- `;
1699
- }
1700
- function toSSE(source, opts) {
1701
- const {
1702
- serialize = (value) => {
1703
- if (value instanceof Error) return value.message;
1704
- try {
1705
- return JSON.stringify(value);
1706
- } catch {
1707
- return String(value);
1708
- }
1709
- },
1710
- dataEvent = "data",
1711
- errorEvent = "error",
1712
- completeEvent = "complete",
1713
- includeResolved = false,
1714
- includeDirty = false,
1715
- keepAliveMs,
1716
- signal,
1717
- eventNameResolver = messageTypeLabel
1718
- } = opts ?? {};
1719
- const encoder = new TextEncoder();
1720
- let stop;
1721
- return new ReadableStream({
1722
- start(controller) {
1723
- let closed = false;
1724
- let keepAlive;
1725
- let unsub = () => {
1726
- };
1727
- const close = () => {
1728
- if (closed) return;
1729
- closed = true;
1730
- if (keepAlive !== void 0) clearInterval(keepAlive);
1731
- signal?.removeEventListener("abort", onAbort);
1732
- unsub();
1733
- controller.close();
1734
- };
1735
- stop = close;
1736
- const write = (event, data) => {
1737
- if (closed) return;
1738
- controller.enqueue(encoder.encode(sseFrame(event, data)));
1739
- };
1740
- const onAbort = () => {
1741
- if (closed) return;
1742
- close();
1743
- };
1744
- unsub = source.subscribe((msgs) => {
1745
- for (const msg of msgs) {
1746
- const t = msg[0];
1747
- if (defaultConfig.isLocalOnly(t)) {
1748
- if (t === DIRTY && includeDirty) {
1749
- } else continue;
1750
- }
1751
- if (t === DATA) {
1752
- write(dataEvent, serializeSseData(msg[1], serialize));
1753
- continue;
1754
- }
1755
- if (t === ERROR) {
1756
- write(errorEvent, serializeSseData(msg[1], serialize));
1757
- close();
1758
- return;
1759
- }
1760
- if (t === COMPLETE) {
1761
- write(completeEvent);
1762
- close();
1763
- return;
1764
- }
1765
- if (!includeResolved && t === RESOLVED) continue;
1766
- write(
1767
- eventNameResolver(t),
1768
- msg.length > 1 ? serializeSseData(msg[1], serialize) : void 0
1769
- );
1770
- }
1771
- });
1772
- if (keepAliveMs !== void 0 && keepAliveMs > 0) {
1773
- keepAlive = setInterval(() => {
1774
- if (closed) return;
1775
- controller.enqueue(encoder.encode(": keepalive\n\n"));
1776
- }, keepAliveMs);
1777
- }
1778
- if (signal?.aborted) onAbort();
1779
- else signal?.addEventListener("abort", onAbort, { once: true });
1780
- },
1781
- cancel() {
1782
- stop?.();
1783
- }
1784
- });
1785
- }
1786
- function toSSEBytes(source, opts) {
1787
- const {
1788
- serialize = (value) => {
1789
- if (value instanceof Error) return value.message;
1790
- try {
1791
- return JSON.stringify(value);
1792
- } catch {
1793
- return String(value);
1794
- }
1795
- },
1796
- dataEvent = "data",
1797
- errorEvent = "error",
1798
- completeEvent = "complete",
1799
- includeResolved = false,
1800
- includeDirty = false,
1801
- keepAliveMs,
1802
- signal,
1803
- eventNameResolver = messageTypeLabel
1804
- } = opts ?? {};
1805
- const encoder = new TextEncoder();
1806
- return producer((a) => {
1807
- let active = true;
1808
- let keepAlive;
1809
- const emitFrame = (event, data) => {
1810
- if (!active) return;
1811
- a.emit(encoder.encode(sseFrame(event, data)));
1812
- };
1813
- const onAbort = () => {
1814
- if (!active) return;
1815
- active = false;
1816
- a.down([[COMPLETE]]);
1817
- };
1818
- const unsub = source.subscribe((msgs) => {
1819
- if (!active) return;
1820
- for (const msg of msgs) {
1821
- const t = msg[0];
1822
- if (defaultConfig.isLocalOnly(t)) {
1823
- if (t === DIRTY && includeDirty) {
1824
- } else continue;
1825
- }
1826
- if (t === DATA) {
1827
- emitFrame(dataEvent, serializeSseData(msg[1], serialize));
1828
- continue;
1829
- }
1830
- if (t === ERROR) {
1831
- emitFrame(errorEvent, serializeSseData(msg[1], serialize));
1832
- active = false;
1833
- a.down([[COMPLETE]]);
1834
- return;
1835
- }
1836
- if (t === COMPLETE) {
1837
- emitFrame(completeEvent);
1838
- active = false;
1839
- a.down([[COMPLETE]]);
1840
- return;
1841
- }
1842
- if (!includeResolved && t === RESOLVED) continue;
1843
- emitFrame(
1844
- eventNameResolver(t),
1845
- msg.length > 1 ? serializeSseData(msg[1], serialize) : void 0
1846
- );
1847
- }
1848
- });
1849
- if (keepAliveMs !== void 0 && keepAliveMs > 0) {
1850
- keepAlive = setInterval(() => {
1851
- if (!active) return;
1852
- a.emit(encoder.encode(": keepalive\n\n"));
1853
- }, keepAliveMs);
1854
- }
1855
- if (signal?.aborted) onAbort();
1856
- else signal?.addEventListener("abort", onAbort, { once: true });
1857
- return () => {
1858
- active = false;
1859
- if (keepAlive !== void 0) clearInterval(keepAlive);
1860
- signal?.removeEventListener("abort", onAbort);
1861
- unsub();
1862
- };
1863
- });
1864
- }
1865
- function toReadableStream(bytes) {
1866
- let unsub;
1867
- let closed = false;
1868
- return new ReadableStream({
1869
- start(controller) {
1870
- unsub = bytes.subscribe((msgs) => {
1871
- for (const m of msgs) {
1872
- const t = m[0];
1873
- if (closed) return;
1874
- if (t === DATA) {
1875
- try {
1876
- controller.enqueue(m[1]);
1877
- } catch {
1878
- closed = true;
1879
- unsub?.();
1880
- }
1881
- } else if (t === ERROR) {
1882
- closed = true;
1883
- try {
1884
- controller.error(m[1]);
1885
- } catch {
1886
- }
1887
- return;
1888
- } else if (t === COMPLETE) {
1889
- closed = true;
1890
- try {
1891
- controller.close();
1892
- } catch {
1893
- }
1894
- return;
1895
- }
1896
- }
1897
- });
1898
- },
1899
- cancel() {
1900
- closed = true;
1901
- unsub?.();
1902
- }
1903
- });
1904
- }
1905
- function fromSSE(source, opts) {
1906
- const { parse = (raw) => raw, ...rest } = opts ?? {};
1907
- return producer((a) => {
1908
- let active = true;
1909
- const decoder = new TextDecoder();
1910
- let buffer2 = "";
1911
- let currentEvent = "message";
1912
- let currentData = [];
1913
- let currentId;
1914
- let currentRetry;
1915
- const flushEvent = () => {
1916
- if (currentData.length === 0 && currentEvent === "message" && currentId === void 0) {
1917
- currentData = [];
1918
- return;
1919
- }
1920
- const raw = currentData.join("\n");
1921
- a.emit({
1922
- event: currentEvent,
1923
- data: parse(raw),
1924
- id: currentId,
1925
- retry: currentRetry
1926
- });
1927
- currentEvent = "message";
1928
- currentData = [];
1929
- currentId = void 0;
1930
- currentRetry = void 0;
1931
- };
1932
- const processLine = (line) => {
1933
- if (line === "") {
1934
- flushEvent();
1935
- return;
1936
- }
1937
- if (line.startsWith(":")) return;
1938
- const colon = line.indexOf(":");
1939
- const field = colon < 0 ? line : line.slice(0, colon);
1940
- let value = colon < 0 ? "" : line.slice(colon + 1);
1941
- if (value.startsWith(" ")) value = value.slice(1);
1942
- switch (field) {
1943
- case "event":
1944
- currentEvent = value;
1945
- break;
1946
- case "data":
1947
- currentData.push(value);
1948
- break;
1949
- case "id":
1950
- if (!value.includes("\0")) currentId = value;
1951
- break;
1952
- case "retry": {
1953
- const n = Number(value);
1954
- if (Number.isFinite(n)) currentRetry = n;
1955
- break;
1956
- }
1957
- }
1958
- };
1959
- const processChunk = (chunk, done) => {
1960
- if (!active) return;
1961
- buffer2 += decoder.decode(chunk, { stream: !done });
1962
- const parts = buffer2.split(/\r?\n/);
1963
- buffer2 = parts.pop() ?? "";
1964
- for (const line of parts) processLine(line);
1965
- };
1966
- let reader;
1967
- let iter;
1968
- const run = async () => {
1969
- try {
1970
- const resp = source;
1971
- const stream = source instanceof ReadableStream ? source : resp && typeof resp === "object" && resp.body instanceof ReadableStream ? resp.body : null;
1972
- if (stream) {
1973
- reader = stream.getReader();
1974
- while (active) {
1975
- const { value, done } = await reader.read();
1976
- if (done) break;
1977
- processChunk(value, false);
1978
- }
1979
- processChunk(new Uint8Array(), true);
1980
- } else {
1981
- const asyncIter = source;
1982
- iter = asyncIter[Symbol.asyncIterator]();
1983
- while (active) {
1984
- const step = await iter.next();
1985
- if (step.done) break;
1986
- processChunk(step.value, false);
1987
- }
1988
- processChunk(new Uint8Array(), true);
1989
- }
1990
- if (buffer2.trim()) {
1991
- for (const line of buffer2.split(/\r?\n/)) processLine(line);
1992
- flushEvent();
1993
- }
1994
- if (active) a.down([[COMPLETE]]);
1995
- } catch (err) {
1996
- if (active) a.down([[ERROR, err]]);
1997
- }
1998
- };
1999
- void run();
2000
- return () => {
2001
- active = false;
2002
- if (reader) {
2003
- void reader.cancel().catch(() => {
2004
- });
2005
- }
2006
- if (iter && typeof iter.return === "function") {
2007
- void Promise.resolve(iter.return()).catch(() => void 0);
2008
- }
2009
- };
2010
- }, sourceOpts2(rest));
2011
- }
2012
- function fromHTTPStream(url, opts) {
2013
- const { method = "GET", headers, body: bodyOpt, signal: externalSignal, ...rest } = opts ?? {};
2014
- return producer((a) => {
2015
- let active = true;
2016
- const abort = new AbortController();
2017
- if (externalSignal?.aborted) {
2018
- a.down([[ERROR, externalSignal.reason ?? new Error("Aborted")]]);
2019
- return () => {
2020
- };
2021
- }
2022
- externalSignal?.addEventListener("abort", () => abort.abort(externalSignal.reason), {
2023
- once: true
2024
- });
2025
- const body = bodyOpt !== void 0 ? typeof bodyOpt === "string" ? bodyOpt : JSON.stringify(bodyOpt) : void 0;
2026
- const run = async () => {
2027
- try {
2028
- const res = await fetch(url, { method, headers, body, signal: abort.signal });
2029
- if (!active) return;
2030
- if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`);
2031
- if (!res.body) throw new Error("HTTP response has no body");
2032
- const reader = res.body.getReader();
2033
- while (active) {
2034
- const { value, done } = await reader.read();
2035
- if (done) break;
2036
- if (value) a.emit(value);
2037
- }
2038
- if (active) a.down([[COMPLETE]]);
2039
- } catch (err) {
2040
- if (!active) return;
2041
- if (err && err.name === "AbortError") return;
2042
- a.down([[ERROR, err]]);
2043
- }
2044
- };
2045
- void run();
2046
- return () => {
2047
- active = false;
2048
- abort.abort();
2049
- };
2050
- }, sourceOpts2(rest));
2051
- }
2052
- function fromHTTPPoll(url, opts) {
2053
- const { intervalMs = 5e3, ...httpOpts } = opts ?? {};
2054
- return switchMap(
2055
- fromTimer(intervalMs, { period: intervalMs }),
2056
- () => fromHTTP(url, { ...httpOpts, completeAfterFetch: true }).node
2057
- );
2058
- }
2059
- function toWebSocket(source, socket, opts) {
2060
- const {
2061
- serialize = (value) => {
2062
- if (typeof value === "string" || value instanceof Blob || value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
2063
- return value;
2064
- }
2065
- try {
2066
- return JSON.stringify(value);
2067
- } catch {
2068
- return String(value);
2069
- }
2070
- },
2071
- closeOnComplete = true,
2072
- closeOnError = true,
2073
- closeCode,
2074
- closeReason,
2075
- onTransportError,
2076
- retry: retry2,
2077
- backpressure,
2078
- stopOn
2079
- } = opts ?? {};
2080
- let socketClosed = false;
2081
- const closeSocket = (trigger) => {
2082
- if (socketClosed) return;
2083
- socketClosed = true;
2084
- try {
2085
- socket.close(closeCode, closeReason);
2086
- } catch (err) {
2087
- const error = err instanceof Error ? err : new Error(String(err));
2088
- try {
2089
- onTransportError?.({ stage: "close", error, value: void 0, message: trigger });
2090
- } catch {
2091
- }
2092
- }
2093
- };
2094
- let externalCloseHandler = null;
2095
- const removeExternalCloseHandler = () => {
2096
- if (externalCloseHandler) {
2097
- try {
2098
- socket.removeEventListener("close", externalCloseHandler);
2099
- } catch {
2100
- }
2101
- externalCloseHandler = null;
2102
- }
2103
- };
2104
- const handle = reactiveSink(source, {
2105
- onTransportError,
2106
- serialize: (value) => {
2107
- const s = serialize(value);
2108
- if (s === void 0) {
2109
- throw new Error("serialize returned undefined");
2110
- }
2111
- return s;
2112
- },
2113
- retry: retry2,
2114
- backpressure,
2115
- stopOn,
2116
- onDispose: removeExternalCloseHandler,
2117
- send: (payload) => {
2118
- socket.send(payload);
2119
- },
2120
- onUpstreamMessage: (msg) => {
2121
- if (msg[0] === COMPLETE && closeOnComplete) closeSocket(msg);
2122
- else if (msg[0] === ERROR && closeOnError) closeSocket(msg);
2123
- }
2124
- });
2125
- externalCloseHandler = () => {
2126
- socketClosed = true;
2127
- handle.dispose();
2128
- };
2129
- socket.addEventListener("close", externalCloseHandler);
2130
- return handle;
2131
- }
2132
- function fromWebSocketReconnect(factory, opts) {
2133
- const {
2134
- parse,
2135
- maxRetries,
2136
- backoff = "exponential",
2137
- closeOnTeardown = true,
2138
- ...rest
2139
- } = opts ?? {};
2140
- return retrySource(
2141
- () => fromWebSocket(factory(), {
2142
- parse,
2143
- closeOnTeardown,
2144
- ...rest
2145
- }),
2146
- { count: maxRetries, backoff }
2147
- );
2148
- }
2149
- function fromMCP(client, opts) {
2150
- const { method = "notifications/message", onDisconnect, ...rest } = opts ?? {};
2151
- return externalProducer(({ emit, error }) => {
2152
- client.setNotificationHandler(method, (notification) => emit(notification));
2153
- onDisconnect?.((err) => error(err ?? new Error("MCP client disconnected")));
2154
- return () => client.setNotificationHandler(method, () => {
2155
- });
2156
- }, rest);
2157
- }
2158
- function fromGitHook(repoPath, opts) {
2159
- const { pollMs = 5e3, include, exclude, maxConsecutiveErrors = 1 } = opts ?? {};
2160
- const includePatterns = include?.map(globToRegExp) ?? [];
2161
- const excludePatterns = exclude?.map(globToRegExp) ?? [];
2162
- const { execFileSync } = __require("child_process");
2163
- const gitQuery = (args) => execFileSync("git", args, { cwd: repoPath, encoding: "utf-8" }).trim();
2164
- let lastSeen;
2165
- let consecutiveErrors = 0;
2166
- return switchMap(
2167
- fromTimer(0, { period: pollMs }),
2168
- () => producer((a) => {
2169
- try {
2170
- const head = gitQuery(["rev-parse", "HEAD"]);
2171
- if (!head) {
2172
- consecutiveErrors = 0;
2173
- return () => {
2174
- };
2175
- }
2176
- if (lastSeen === void 0) {
2177
- lastSeen = head;
2178
- consecutiveErrors = 0;
2179
- return () => {
2180
- };
2181
- }
2182
- if (head === lastSeen) {
2183
- consecutiveErrors = 0;
2184
- return () => {
2185
- };
2186
- }
2187
- let files = gitQuery(["diff", "--name-only", `${lastSeen}..${head}`]).split("\n").filter(Boolean);
2188
- if (includePatterns.length > 0) {
2189
- files = files.filter((f) => matchesAnyPattern(f, includePatterns));
2190
- }
2191
- if (excludePatterns.length > 0) {
2192
- files = files.filter((f) => !matchesAnyPattern(f, excludePatterns));
2193
- }
2194
- const message = gitQuery(["log", "-1", "--format=%s", head]);
2195
- const author = gitQuery(["log", "-1", "--format=%an", head]);
2196
- a.emit({
2197
- hook: "post-commit",
2198
- commit: head,
2199
- files,
2200
- message,
2201
- author,
2202
- timestamp_ns: wallClockNs()
2203
- });
2204
- lastSeen = head;
2205
- consecutiveErrors = 0;
2206
- } catch (err) {
2207
- consecutiveErrors += 1;
2208
- if (consecutiveErrors >= maxConsecutiveErrors) {
2209
- a.down([[ERROR, err]]);
2210
- }
2211
- }
2212
- return () => {
2213
- };
2214
- })
2215
- );
2216
- }
2217
- function fromOTel(register, opts) {
2218
- const nodes = externalBundle(
2219
- ({ traces, metrics, logs, error }) => {
2220
- return register({
2221
- onTraces: (spans) => {
2222
- batch(() => {
2223
- for (const s of spans) traces(s);
2224
- });
2225
- },
2226
- onMetrics: (ms) => {
2227
- batch(() => {
2228
- for (const m of ms) metrics(m);
2229
- });
2230
- },
2231
- onLogs: (ls) => {
2232
- batch(() => {
2233
- for (const l of ls) logs(l);
2234
- });
2235
- },
2236
- onError: error
2237
- }) ?? void 0;
2238
- },
2239
- ["traces", "metrics", "logs"],
2240
- opts?.name ? { name: opts.name } : void 0
2241
- );
2242
- return nodes;
2243
- }
2244
- function fromSyslog(register, opts) {
2245
- return externalProducer(register, opts);
2246
- }
2247
- function parseSyslog(raw) {
2248
- const match = raw.match(/^<(\d{1,3})>\d?\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*(.*)/s);
2249
- if (!match) {
2250
- const nowNs = wallClockNs();
2251
- return {
2252
- facility: 1,
2253
- severity: 6,
2254
- timestamp: new Date(Math.floor(nowNs / 1e6)).toISOString(),
2255
- hostname: "-",
2256
- appName: "-",
2257
- procId: "-",
2258
- msgId: "-",
2259
- message: raw.trim(),
2260
- timestampNs: nowNs
2261
- };
2262
- }
2263
- const pri = Number(match[1]);
2264
- return {
2265
- facility: pri >> 3,
2266
- severity: pri & 7,
2267
- timestamp: match[2],
2268
- hostname: match[3],
2269
- appName: match[4],
2270
- procId: match[5],
2271
- msgId: match[6],
2272
- message: (match[7] ?? "").trim(),
2273
- timestampNs: wallClockNs()
2274
- };
2275
- }
2276
- function fromStatsD(register, opts) {
2277
- return externalProducer(register, opts);
2278
- }
2279
- var STATSD_TYPES = {
2280
- c: "counter",
2281
- g: "gauge",
2282
- ms: "timer",
2283
- h: "histogram",
2284
- s: "set",
2285
- d: "distribution"
2286
- };
2287
- function parseStatsD(line) {
2288
- const parts = line.split("|");
2289
- const [name, valueStr] = (parts[0] ?? "").split(":");
2290
- if (!name || valueStr === void 0) {
2291
- throw new Error(`Invalid StatsD line: ${line}`);
2292
- }
2293
- const typeCode = parts[1]?.trim() ?? "c";
2294
- const type = STATSD_TYPES[typeCode] ?? "counter";
2295
- const value = type === "set" ? 0 : Number(valueStr);
2296
- let sampleRate;
2297
- const tags = {};
2298
- for (let i = 2; i < parts.length; i++) {
2299
- const part = parts[i].trim();
2300
- if (part.startsWith("@")) {
2301
- sampleRate = Number(part.slice(1));
2302
- } else if (part.startsWith("#")) {
2303
- for (const tag of part.slice(1).split(",")) {
2304
- const [k, v] = tag.split(":");
2305
- if (k) tags[k] = v ?? "";
2306
- }
2307
- }
2308
- }
2309
- return { name: name.trim(), value, type, sampleRate, tags, timestampNs: wallClockNs() };
2310
- }
2311
- function fromPrometheus(endpoint, opts) {
2312
- const {
2313
- intervalNs = 15 * NS_PER_SEC,
2314
- headers,
2315
- timeoutNs = 10 * NS_PER_SEC,
2316
- signal: externalSignal,
2317
- maxConsecutiveErrors = 1
2318
- } = opts ?? {};
2319
- const intervalMs = Math.ceil(intervalNs / NS_PER_MS);
2320
- let consecutiveErrors = 0;
2321
- return switchMap(
2322
- fromTimer(0, { period: intervalMs, signal: externalSignal }),
2323
- () => producer((a) => {
2324
- let active = true;
2325
- const abort = new AbortController();
2326
- const timeoutId = setTimeout(
2327
- () => abort.abort(new Error("Scrape timeout")),
2328
- Math.ceil(timeoutNs / NS_PER_MS)
2329
- );
2330
- const run = async () => {
2331
- try {
2332
- const res = await fetch(endpoint, {
2333
- headers: { Accept: "text/plain", ...headers },
2334
- signal: abort.signal
2335
- });
2336
- clearTimeout(timeoutId);
2337
- if (!active) return;
2338
- if (!res.ok) throw new Error(`Prometheus scrape ${res.status}: ${res.statusText}`);
2339
- const text = await res.text();
2340
- if (!active) return;
2341
- const metrics = parsePrometheusText(text);
2342
- for (const m of metrics) a.emit(m);
2343
- consecutiveErrors = 0;
2344
- a.down([[COMPLETE]]);
2345
- } catch (err) {
2346
- clearTimeout(timeoutId);
2347
- if (!active) return;
2348
- if (err instanceof Error && err.name === "AbortError") return;
2349
- consecutiveErrors += 1;
2350
- if (consecutiveErrors >= maxConsecutiveErrors) {
2351
- a.down([[ERROR, err]]);
2352
- }
2353
- }
2354
- };
2355
- void run();
2356
- return () => {
2357
- active = false;
2358
- clearTimeout(timeoutId);
2359
- abort.abort();
2360
- };
2361
- })
2362
- );
2363
- }
2364
- function parsePrometheusText(text) {
2365
- const results = [];
2366
- const types = /* @__PURE__ */ new Map();
2367
- const helps = /* @__PURE__ */ new Map();
2368
- for (const rawLine of text.split("\n")) {
2369
- const line = rawLine.trim();
2370
- if (!line) continue;
2371
- if (line.startsWith("# TYPE ")) {
2372
- const rest = line.slice(7);
2373
- const spaceIdx = rest.indexOf(" ");
2374
- if (spaceIdx > 0) {
2375
- types.set(rest.slice(0, spaceIdx), rest.slice(spaceIdx + 1).trim());
2376
- }
2377
- continue;
2378
- }
2379
- if (line.startsWith("# HELP ")) {
2380
- const rest = line.slice(7);
2381
- const spaceIdx = rest.indexOf(" ");
2382
- if (spaceIdx > 0) {
2383
- helps.set(rest.slice(0, spaceIdx), rest.slice(spaceIdx + 1).trim());
2384
- }
2385
- continue;
2386
- }
2387
- if (line.startsWith("#")) continue;
2388
- let name;
2389
- let labels = {};
2390
- let valueStr;
2391
- let tsStr;
2392
- const braceIdx = line.indexOf("{");
2393
- if (braceIdx >= 0) {
2394
- name = line.slice(0, braceIdx);
2395
- const closeBrace = line.indexOf("}", braceIdx);
2396
- if (closeBrace < 0) continue;
2397
- const labelStr = line.slice(braceIdx + 1, closeBrace);
2398
- labels = parsePrometheusLabels(labelStr);
2399
- const after = line.slice(closeBrace + 1).trim().split(/\s+/);
2400
- valueStr = after[0] ?? "";
2401
- tsStr = after[1];
2402
- } else {
2403
- const parts = line.split(/\s+/);
2404
- name = parts[0] ?? "";
2405
- valueStr = parts[1] ?? "";
2406
- tsStr = parts[2];
2407
- }
2408
- if (!name || !valueStr) continue;
2409
- const baseName = name.replace(/(_total|_count|_sum|_bucket|_created|_info)$/, "");
2410
- results.push({
2411
- name,
2412
- labels,
2413
- value: Number(valueStr),
2414
- timestampMs: tsStr ? Number(tsStr) : void 0,
2415
- type: types.get(baseName) ?? types.get(name),
2416
- help: helps.get(baseName) ?? helps.get(name),
2417
- timestampNs: wallClockNs()
2418
- });
2419
- }
2420
- return results;
2421
- }
2422
- function parsePrometheusLabels(str) {
2423
- const labels = {};
2424
- const re = /(\w+)="((?:[^"\\]|\\.)*)"/g;
2425
- let m = re.exec(str);
2426
- while (m !== null) {
2427
- labels[m[1]] = m[2].replace(/\\(.)/g, "$1");
2428
- m = re.exec(str);
2429
- }
2430
- return labels;
2431
- }
2432
- function fromKafka(consumer, topic, opts) {
2433
- const {
2434
- fromBeginning = false,
2435
- deserialize = (buf) => {
2436
- if (buf === null) return null;
2437
- try {
2438
- return JSON.parse(buf.toString());
2439
- } catch {
2440
- return buf.toString();
2441
- }
2442
- },
2443
- ...rest
2444
- } = opts ?? {};
2445
- return producer((a) => {
2446
- let active = true;
2447
- const start = async () => {
2448
- try {
2449
- await consumer.subscribe({ topic, fromBeginning });
2450
- await consumer.run({
2451
- eachMessage: async ({ topic: t, partition, message: msg }) => {
2452
- if (!active) return;
2453
- const headers = {};
2454
- if (msg.headers) {
2455
- for (const [k, v] of Object.entries(msg.headers)) {
2456
- if (v !== void 0) headers[k] = typeof v === "string" ? v : v.toString();
2457
- }
2458
- }
2459
- a.emit({
2460
- topic: t,
2461
- partition,
2462
- key: msg.key?.toString() ?? null,
2463
- value: deserialize(msg.value),
2464
- headers,
2465
- offset: msg.offset,
2466
- timestamp: msg.timestamp,
2467
- timestampNs: wallClockNs()
2468
- });
2469
- }
2470
- });
2471
- } catch (err) {
2472
- if (active) a.down([[ERROR, err]]);
2473
- }
2474
- };
2475
- void start();
2476
- return () => {
2477
- active = false;
2478
- };
2479
- }, sourceOpts2(rest));
2480
- }
2481
- function toKafka(source, kafkaProducer, topic, opts) {
2482
- const { serialize = (v) => JSON.stringify(v), keyExtractor, onTransportError } = opts ?? {};
2483
- return reactiveSink(source, {
2484
- onTransportError,
2485
- send: async (value) => {
2486
- const key = keyExtractor?.(value) ?? null;
2487
- const serialized = serialize(value);
2488
- await kafkaProducer.send({
2489
- topic,
2490
- messages: [{ key, value: Buffer.from(serialized) }]
2491
- });
2492
- }
2493
- });
2494
- }
2495
- function fromRedisStream(client, key, opts) {
2496
- const {
2497
- blockMs = 5e3,
2498
- startId = "$",
2499
- parse = (fields) => {
2500
- for (let i = 0; i < fields.length; i += 2) {
2501
- if (fields[i] === "data") {
2502
- try {
2503
- return JSON.parse(fields[i + 1]);
2504
- } catch {
2505
- return fields[i + 1];
2506
- }
2507
- }
2508
- }
2509
- const obj = {};
2510
- for (let i = 0; i < fields.length; i += 2) {
2511
- obj[fields[i]] = fields[i + 1];
2512
- }
2513
- return obj;
2514
- },
2515
- ...rest
2516
- } = opts ?? {};
2517
- return producer((a) => {
2518
- let active = true;
2519
- let lastId = startId;
2520
- const poll = async () => {
2521
- while (active) {
2522
- try {
2523
- const result = await client.xread("BLOCK", blockMs, "STREAMS", key, lastId);
2524
- if (!active) return;
2525
- if (result) {
2526
- for (const [_streamKey, entries] of result) {
2527
- for (const [id, fields] of entries) {
2528
- lastId = id;
2529
- a.emit({
2530
- id,
2531
- key,
2532
- data: parse(fields),
2533
- timestampNs: wallClockNs()
2534
- });
2535
- }
2536
- }
2537
- }
2538
- } catch (err) {
2539
- if (!active) return;
2540
- a.down([[ERROR, err]]);
2541
- return;
2542
- }
2543
- }
2544
- };
2545
- void poll();
2546
- return () => {
2547
- active = false;
2548
- };
2549
- }, sourceOpts2(rest));
2550
- }
2551
- function toRedisStream(source, client, key, opts) {
2552
- const {
2553
- serialize = (v) => ["data", JSON.stringify(v)],
2554
- maxLen,
2555
- onTransportError
2556
- } = opts ?? {};
2557
- return reactiveSink(source, {
2558
- onTransportError,
2559
- send: async (value) => {
2560
- const fields = serialize(value);
2561
- await (maxLen !== void 0 ? client.xadd(key, "MAXLEN", "~", String(maxLen), "*", ...fields) : client.xadd(key, "*", ...fields));
2562
- }
2563
- });
2564
- }
2565
- function fromCSV(source, opts) {
2566
- const {
2567
- delimiter = ",",
2568
- hasHeader = true,
2569
- columns: explicitColumns,
2570
- parseLine,
2571
- ...rest
2572
- } = opts ?? {};
2573
- const parse = parseLine ?? ((line) => parseCSVLine(line, delimiter));
2574
- return producer((a) => {
2575
- let cancelled = false;
2576
- const run = async () => {
2577
- try {
2578
- let headers = explicitColumns;
2579
- let buffer2 = "";
2580
- for await (const chunk of source) {
2581
- if (cancelled) return;
2582
- buffer2 += chunk;
2583
- const lines = buffer2.split(/\r?\n/);
2584
- buffer2 = lines.pop() ?? "";
2585
- for (const line of lines) {
2586
- if (cancelled) return;
2587
- if (!line.trim()) continue;
2588
- const values = parse(line);
2589
- if (!headers && hasHeader) {
2590
- headers = values;
2591
- continue;
2592
- }
2593
- if (!headers) {
2594
- headers = values.map((_, i) => `col${i}`);
2595
- }
2596
- const row = {};
2597
- for (let i = 0; i < headers.length; i++) {
2598
- row[headers[i]] = values[i] ?? "";
2599
- }
2600
- a.emit(row);
2601
- }
2602
- }
2603
- if (!cancelled && buffer2.trim()) {
2604
- const values = parse(buffer2);
2605
- if (headers) {
2606
- const row = {};
2607
- for (let i = 0; i < headers.length; i++) {
2608
- row[headers[i]] = values[i] ?? "";
2609
- }
2610
- a.emit(row);
2611
- }
2612
- }
2613
- if (!cancelled) a.down([[COMPLETE]]);
2614
- } catch (err) {
2615
- if (!cancelled) a.down([[ERROR, err]]);
2616
- }
2617
- };
2618
- void run();
2619
- return () => {
2620
- cancelled = true;
2621
- };
2622
- }, sourceOpts2(rest));
2623
- }
2624
- function csvRows(source, opts) {
2625
- const {
2626
- delimiter = ",",
2627
- hasHeader = true,
2628
- columns: explicitColumns,
2629
- parseLine,
2630
- ...rest
2631
- } = opts ?? {};
2632
- const parse = parseLine ?? ((line) => parseCSVLine(line, delimiter));
2633
- return node(
2634
- [source],
2635
- (data, a, ctx) => {
2636
- const batch0 = data[0];
2637
- if (batch0 == null || batch0.length === 0) return;
2638
- const s = ctx.store;
2639
- if (typeof s.buffer !== "string") s.buffer = "";
2640
- if (s.headers === void 0 && explicitColumns) s.headers = explicitColumns.slice();
2641
- for (const chunkRaw of batch0) {
2642
- s.buffer = s.buffer + chunkRaw;
2643
- const lines = s.buffer.split(/\r?\n/);
2644
- s.buffer = lines.pop() ?? "";
2645
- for (const line of lines) {
2646
- if (!line.trim()) continue;
2647
- const values = parse(line);
2648
- if (!s.headers && hasHeader) {
2649
- s.headers = values;
2650
- continue;
2651
- }
2652
- if (!s.headers) s.headers = values.map((_, i) => `col${i}`);
2653
- const row = {};
2654
- for (let i = 0; i < s.headers.length; i++) row[s.headers[i]] = values[i] ?? "";
2655
- a.emit(row);
2656
- }
2657
- }
2658
- },
2659
- { describeKind: "derived", ...rest }
2660
- );
2661
- }
2662
- function ndjsonRows(source, opts) {
2663
- return node(
2664
- [source],
2665
- (data, a, ctx) => {
2666
- const batch0 = data[0];
2667
- if (batch0 == null || batch0.length === 0) return;
2668
- const s = ctx.store;
2669
- if (typeof s.buffer !== "string") s.buffer = "";
2670
- for (const chunkRaw of batch0) {
2671
- s.buffer = s.buffer + chunkRaw;
2672
- const lines = s.buffer.split(/\r?\n/);
2673
- s.buffer = lines.pop() ?? "";
2674
- for (const line of lines) {
2675
- if (!line.trim()) continue;
2676
- try {
2677
- a.emit(JSON.parse(line));
2678
- } catch (err) {
2679
- a.down([[ERROR, err]]);
2680
- return;
2681
- }
2682
- }
2683
- }
2684
- },
2685
- { describeKind: "derived", ...opts ?? {} }
2686
- );
2687
- }
2688
- function parseCSVLine(line, delimiter) {
2689
- const values = [];
2690
- let current = "";
2691
- let inQuotes = false;
2692
- for (let i = 0; i < line.length; i++) {
2693
- const ch = line[i];
2694
- if (inQuotes) {
2695
- if (ch === '"') {
2696
- if (line[i + 1] === '"') {
2697
- current += '"';
2698
- i++;
2699
- } else {
2700
- inQuotes = false;
2701
- }
2702
- } else {
2703
- current += ch;
2704
- }
2705
- } else if (ch === '"') {
2706
- inQuotes = true;
2707
- } else if (ch === delimiter) {
2708
- values.push(current);
2709
- current = "";
2710
- } else {
2711
- current += ch;
2712
- }
2713
- }
2714
- values.push(current);
2715
- return values;
2716
- }
2717
- function fromNDJSON(source, opts) {
2718
- return producer((a) => {
2719
- let cancelled = false;
2720
- const run = async () => {
2721
- try {
2722
- let buffer2 = "";
2723
- for await (const chunk of source) {
2724
- if (cancelled) return;
2725
- buffer2 += chunk;
2726
- const lines = buffer2.split(/\r?\n/);
2727
- buffer2 = lines.pop() ?? "";
2728
- for (const line of lines) {
2729
- if (cancelled) return;
2730
- const trimmed = line.trim();
2731
- if (!trimmed) continue;
2732
- a.emit(JSON.parse(trimmed));
2733
- }
2734
- }
2735
- if (!cancelled && buffer2.trim()) {
2736
- a.emit(JSON.parse(buffer2.trim()));
2737
- }
2738
- if (!cancelled) a.down([[COMPLETE]]);
2739
- } catch (err) {
2740
- if (!cancelled) a.down([[ERROR, err]]);
2741
- }
2742
- };
2743
- void run();
2744
- return () => {
2745
- cancelled = true;
2746
- };
2747
- }, sourceOpts2(opts));
2748
- }
2749
- function fromClickHouseWatch(client, query, opts) {
2750
- const {
2751
- intervalNs = 5 * NS_PER_SEC,
2752
- format = "JSONEachRow",
2753
- signal: externalSignal,
2754
- maxConsecutiveErrors = 1
2755
- } = opts ?? {};
2756
- const intervalMs = Math.ceil(intervalNs / NS_PER_MS);
2757
- let consecutiveErrors = 0;
2758
- return switchMap(
2759
- fromTimer(0, { period: intervalMs, signal: externalSignal }),
2760
- () => producer((a) => {
2761
- let active = true;
2762
- const run = async () => {
2763
- try {
2764
- const result = await client.query({ query, format });
2765
- if (!active) return;
2766
- const rows = await result.json();
2767
- if (!active) return;
2768
- for (const row of rows) a.emit(row);
2769
- consecutiveErrors = 0;
2770
- a.down([[COMPLETE]]);
2771
- } catch (err) {
2772
- if (!active) return;
2773
- consecutiveErrors += 1;
2774
- if (consecutiveErrors >= maxConsecutiveErrors) {
2775
- a.down([[ERROR, err]]);
2776
- }
2777
- }
2778
- };
2779
- void run();
2780
- return () => {
2781
- active = false;
2782
- };
2783
- })
2784
- );
2785
- }
2786
- function fromPulsar(consumer, opts) {
2787
- const {
2788
- autoAck = true,
2789
- deserialize = (buf) => {
2790
- try {
2791
- return JSON.parse(buf.toString());
2792
- } catch {
2793
- return buf.toString();
2794
- }
2795
- },
2796
- onAckError,
2797
- ...rest
2798
- } = opts ?? {};
2799
- const reportAckError = (err) => {
2800
- if (!onAckError) return;
2801
- try {
2802
- onAckError(err instanceof Error ? err : new Error(String(err)));
2803
- } catch {
2804
- }
2805
- };
2806
- return producer((a) => {
2807
- let active = true;
2808
- const loop = async () => {
2809
- while (active) {
2810
- try {
2811
- const rawMsg = await consumer.receive();
2812
- if (!active) return;
2813
- const structured = {
2814
- topic: rawMsg.getTopicName(),
2815
- messageId: rawMsg.getMessageId().toString(),
2816
- key: rawMsg.getPartitionKey(),
2817
- value: deserialize(rawMsg.getData()),
2818
- properties: rawMsg.getProperties(),
2819
- publishTime: rawMsg.getPublishTimestamp(),
2820
- eventTime: rawMsg.getEventTimestamp(),
2821
- timestampNs: wallClockNs()
2822
- };
2823
- if (autoAck) {
2824
- a.emit(structured);
2825
- void consumer.acknowledge(rawMsg).catch(reportAckError);
2826
- } else {
2827
- let settled = false;
2828
- const envelope = {
2829
- value: structured,
2830
- ack() {
2831
- if (settled) return;
2832
- settled = true;
2833
- void consumer.acknowledge(rawMsg).catch(reportAckError);
2834
- },
2835
- nack(_opts) {
2836
- if (settled) return;
2837
- settled = true;
2838
- const anyConsumer = consumer;
2839
- try {
2840
- const result = anyConsumer.negativeAcknowledge?.(rawMsg);
2841
- if (result && typeof result.then === "function") {
2842
- void result.catch(reportAckError);
2843
- }
2844
- } catch (err) {
2845
- reportAckError(err);
2846
- }
2847
- }
2848
- };
2849
- a.emit(envelope);
2850
- }
2851
- } catch (err) {
2852
- if (active) a.down([[ERROR, err]]);
2853
- return;
2854
- }
2855
- }
2856
- };
2857
- void loop();
2858
- return () => {
2859
- active = false;
2860
- };
2861
- }, sourceOpts2(rest));
2862
- }
2863
- function toPulsar(source, pulsarProducer, opts) {
2864
- const {
2865
- serialize = (v) => Buffer.from(JSON.stringify(v)),
2866
- keyExtractor,
2867
- propertiesExtractor,
2868
- onTransportError
2869
- } = opts ?? {};
2870
- return reactiveSink(source, {
2871
- onTransportError,
2872
- send: async (value) => {
2873
- await pulsarProducer.send({
2874
- data: serialize(value),
2875
- partitionKey: keyExtractor?.(value),
2876
- properties: propertiesExtractor?.(value)
2877
- });
2878
- }
2879
- });
2880
- }
2881
- function fromNATS(client, subject, opts) {
2882
- const decoder = new TextDecoder();
2883
- const {
2884
- queue,
2885
- deserialize = (data) => {
2886
- const text = decoder.decode(data);
2887
- try {
2888
- return JSON.parse(text);
2889
- } catch {
2890
- return text;
2891
- }
2892
- },
2893
- ...rest
2894
- } = opts ?? {};
2895
- return producer((a) => {
2896
- let active = true;
2897
- const sub = client.subscribe(subject, queue ? { queue } : void 0);
2898
- const loop = async () => {
2899
- try {
2900
- for await (const msg of sub) {
2901
- if (!active) return;
2902
- const headers = {};
2903
- if (msg.headers) {
2904
- for (const k of msg.headers.keys()) {
2905
- headers[k] = msg.headers.get(k);
2906
- }
2907
- }
2908
- a.emit({
2909
- subject: msg.subject,
2910
- data: deserialize(msg.data),
2911
- headers,
2912
- reply: msg.reply,
2913
- sid: msg.sid,
2914
- timestampNs: wallClockNs()
2915
- });
2916
- }
2917
- if (active) a.down([[COMPLETE]]);
2918
- } catch (err) {
2919
- if (active) a.down([[ERROR, err]]);
2920
- }
2921
- };
2922
- void loop();
2923
- return () => {
2924
- active = false;
2925
- };
2926
- }, sourceOpts2(rest));
2927
- }
2928
- function toNATS(source, client, subject, opts) {
2929
- const encoder = new TextEncoder();
2930
- const { serialize = (v) => encoder.encode(JSON.stringify(v)), onTransportError } = opts ?? {};
2931
- return reactiveSink(source, {
2932
- onTransportError,
2933
- send: (value) => {
2934
- client.publish(subject, serialize(value));
2935
- }
2936
- });
2937
- }
2938
- function fromRabbitMQ(channel, queue, opts) {
2939
- const {
2940
- autoAck = true,
2941
- deserialize = (buf) => {
2942
- try {
2943
- return JSON.parse(buf.toString());
2944
- } catch {
2945
- return buf.toString();
2946
- }
2947
- },
2948
- onAckError,
2949
- ...rest
2950
- } = opts ?? {};
2951
- const reportAckError = (err) => {
2952
- if (!onAckError) return;
2953
- try {
2954
- onAckError(err instanceof Error ? err : new Error(String(err)));
2955
- } catch {
2956
- }
2957
- };
2958
- return producer((a) => {
2959
- let active = true;
2960
- let consumerTag;
2961
- const start = async () => {
2962
- try {
2963
- const result = await channel.consume(
2964
- queue,
2965
- (rawMsg) => {
2966
- if (!active) return;
2967
- if (rawMsg === null) {
2968
- if (active) a.down([[ERROR, new Error("Consumer cancelled by broker")]]);
2969
- return;
2970
- }
2971
- const structured = {
2972
- queue,
2973
- routingKey: rawMsg.fields.routingKey,
2974
- exchange: rawMsg.fields.exchange,
2975
- content: deserialize(rawMsg.content),
2976
- properties: rawMsg.properties,
2977
- deliveryTag: rawMsg.fields.deliveryTag,
2978
- redelivered: rawMsg.fields.redelivered,
2979
- timestampNs: wallClockNs()
2980
- };
2981
- if (autoAck) {
2982
- a.emit(structured);
2983
- try {
2984
- channel.ack(rawMsg);
2985
- } catch (err) {
2986
- reportAckError(err);
2987
- }
2988
- } else {
2989
- let settled = false;
2990
- const channelWithNack = channel;
2991
- const envelope = {
2992
- value: structured,
2993
- ack() {
2994
- if (settled) return;
2995
- settled = true;
2996
- try {
2997
- channel.ack(rawMsg);
2998
- } catch (err) {
2999
- reportAckError(err);
3000
- }
3001
- },
3002
- nack(nackOpts) {
3003
- if (settled) return;
3004
- settled = true;
3005
- const requeue = nackOpts?.requeue;
3006
- if (!channelWithNack.nack) {
3007
- reportAckError(
3008
- new Error("RabbitMQ channel does not expose `nack`; cannot negative-ack")
3009
- );
3010
- return;
3011
- }
3012
- try {
3013
- channelWithNack.nack(rawMsg, false, requeue);
3014
- } catch (err) {
3015
- reportAckError(err);
3016
- }
3017
- }
3018
- };
3019
- a.emit(envelope);
3020
- }
3021
- },
3022
- { noAck: false }
3023
- );
3024
- consumerTag = result.consumerTag;
3025
- } catch (err) {
3026
- if (active) a.down([[ERROR, err]]);
3027
- }
3028
- };
3029
- void start();
3030
- return () => {
3031
- active = false;
3032
- if (consumerTag !== void 0) {
3033
- void channel.cancel(consumerTag);
3034
- }
3035
- };
3036
- }, sourceOpts2(rest));
3037
- }
3038
- function toRabbitMQ(source, channel, exchange, opts) {
3039
- const {
3040
- serialize = (v) => Buffer.from(JSON.stringify(v)),
3041
- routingKeyExtractor = () => "",
3042
- onTransportError
3043
- } = opts ?? {};
3044
- return reactiveSink(source, {
3045
- onTransportError,
3046
- send: (value) => {
3047
- const routingKey = routingKeyExtractor(value);
3048
- const content = serialize(value);
3049
- channel.publish(exchange, routingKey, content);
3050
- }
3051
- });
3052
- }
3053
- function toFile(source, writer, opts) {
3054
- const {
3055
- serialize = (v) => `${JSON.stringify(v)}
3056
- `,
3057
- flushIntervalMs = 0,
3058
- batchSize = Number.POSITIVE_INFINITY,
3059
- onTransportError,
3060
- mode: _mode
3061
- } = opts ?? {};
3062
- const buffered = flushIntervalMs > 0 || batchSize < Number.POSITIVE_INFINITY;
3063
- const handle = buffered ? reactiveSink(source, {
3064
- onTransportError,
3065
- batchSize,
3066
- flushIntervalMs,
3067
- serialize,
3068
- sendBatch: (chunk) => {
3069
- writer.write(chunk.join(""));
3070
- }
3071
- }) : reactiveSink(source, {
3072
- onTransportError,
3073
- serialize,
3074
- send: (line) => {
3075
- writer.write(line);
3076
- }
3077
- });
3078
- const originalDispose = handle.dispose;
3079
- handle.dispose = () => {
3080
- originalDispose();
3081
- try {
3082
- writer.end();
3083
- } catch {
3084
- }
3085
- };
3086
- return handle;
3087
- }
3088
- function escapeCSVField(value, delimiter) {
3089
- if (value.includes(delimiter) || value.includes('"') || value.includes("\n")) {
3090
- return `"${value.replace(/"/g, '""')}"`;
3091
- }
3092
- return value;
3093
- }
3094
- function toCSV(source, writer, opts) {
3095
- const {
3096
- columns,
3097
- delimiter = ",",
3098
- writeHeader = true,
3099
- cellExtractor = (row, col) => String(row[col] ?? ""),
3100
- flushIntervalMs = 0,
3101
- batchSize = Number.POSITIVE_INFINITY,
3102
- onTransportError,
3103
- ...rest
3104
- } = opts;
3105
- let headerWritten = false;
3106
- const serializeRow = (row) => {
3107
- if (!headerWritten && writeHeader) {
3108
- headerWritten = true;
3109
- const header = columns.map((c) => escapeCSVField(c, delimiter)).join(delimiter);
3110
- const data = columns.map((c) => escapeCSVField(cellExtractor(row, c), delimiter)).join(delimiter);
3111
- return `${header}
3112
- ${data}
3113
- `;
3114
- }
3115
- return `${columns.map((c) => escapeCSVField(cellExtractor(row, c), delimiter)).join(delimiter)}
3116
- `;
3117
- };
3118
- return toFile(source, writer, {
3119
- serialize: serializeRow,
3120
- flushIntervalMs,
3121
- batchSize,
3122
- onTransportError,
3123
- ...rest
3124
- });
3125
- }
3126
- function toClickHouse(source, client, table, opts) {
3127
- const {
3128
- batchSize = 1e3,
3129
- flushIntervalMs = 5e3,
3130
- format = "JSONEachRow",
3131
- transform = (v) => v,
3132
- onTransportError
3133
- } = opts ?? {};
3134
- return reactiveSink(source, {
3135
- onTransportError,
3136
- batchSize,
3137
- flushIntervalMs,
3138
- serialize: transform,
3139
- sendBatch: async (batch2) => {
3140
- await client.insert({ table, values: batch2, format });
3141
- }
3142
- });
3143
- }
3144
- function toS3(source, client, bucket, opts) {
3145
- const {
3146
- format = "ndjson",
3147
- keyGenerator = (seq2, timestampNs) => {
3148
- const ms = Math.floor(timestampNs / 1e6);
3149
- const ts = new Date(ms).toISOString().replace(/[:.]/g, "-");
3150
- return `data/${ts}-${seq2}.${format === "ndjson" ? "ndjson" : "json"}`;
3151
- },
3152
- batchSize = 1e3,
3153
- flushIntervalMs = 1e4,
3154
- transform = (v) => v,
3155
- onTransportError
3156
- } = opts ?? {};
3157
- const contentType = format === "ndjson" ? "application/x-ndjson" : "application/json";
3158
- let seq = 0;
3159
- return reactiveSink(source, {
3160
- onTransportError,
3161
- batchSize,
3162
- flushIntervalMs,
3163
- serialize: transform,
3164
- sendBatch: async (batch2) => {
3165
- seq += 1;
3166
- const body = format === "ndjson" ? `${batch2.map((v) => JSON.stringify(v)).join("\n")}
3167
- ` : JSON.stringify(batch2);
3168
- const key = keyGenerator(seq, wallClockNs());
3169
- await client.putObject({ Bucket: bucket, Key: key, Body: body, ContentType: contentType });
3170
- }
3171
- });
3172
- }
3173
- function toPostgres(source, client, table, opts) {
3174
- const {
3175
- toSQL = (v, t) => ({
3176
- sql: `INSERT INTO "${t.replace(/"/g, '""')}" (data) VALUES ($1)`,
3177
- params: [JSON.stringify(v)]
3178
- }),
3179
- onTransportError
3180
- } = opts ?? {};
3181
- return reactiveSink(source, {
3182
- onTransportError,
3183
- serialize: (value) => toSQL(value, table),
3184
- send: async (q) => {
3185
- const query = q;
3186
- await client.query(query.sql, query.params);
3187
- }
3188
- });
3189
- }
3190
- function toMongo(source, collection, opts) {
3191
- const { toDocument = (v) => v, onTransportError } = opts ?? {};
3192
- return reactiveSink(source, {
3193
- onTransportError,
3194
- serialize: toDocument,
3195
- send: async (doc) => {
3196
- await collection.insertOne(doc);
3197
- }
3198
- });
3199
- }
3200
- function toLoki(source, client, opts) {
3201
- const {
3202
- labels = {},
3203
- toLine = (v) => JSON.stringify(v),
3204
- toLabels,
3205
- onTransportError
3206
- } = opts ?? {};
3207
- return reactiveSink(source, {
3208
- onTransportError,
3209
- serialize: (value) => ({
3210
- line: toLine(value),
3211
- labels: toLabels ? { ...labels, ...toLabels(value) } : labels
3212
- }),
3213
- send: async (payload) => {
3214
- const { line, labels: streamLabels } = payload;
3215
- const ts = `${wallClockNs()}`;
3216
- await client.push({ streams: [{ stream: streamLabels, values: [[ts, line]] }] });
3217
- }
3218
- });
3219
- }
3220
- function toTempo(source, client, opts) {
3221
- const { toResourceSpans = (v) => [v], onTransportError } = opts ?? {};
3222
- return reactiveSink(source, {
3223
- onTransportError,
3224
- serialize: toResourceSpans,
3225
- send: async (spans) => {
3226
- await client.push({ resourceSpans: spans });
3227
- }
3228
- });
3229
- }
3230
- function checkpointToS3(graph, client, bucket, opts) {
3231
- const { prefix = "checkpoints/", debounceMs = 500, compactEvery = 10, onError } = opts ?? {};
3232
- const tier = {
3233
- debounceMs,
3234
- compactEvery,
3235
- save(_key, data) {
3236
- const ms = Math.floor(wallClockNs() / 1e6);
3237
- const s3Key = `${prefix}${graph.name}/checkpoint-${ms}.json`;
3238
- let body;
3239
- try {
3240
- body = JSON.stringify(data);
3241
- } catch (err) {
3242
- onError?.(err);
3243
- return;
3244
- }
3245
- void client.putObject({
3246
- Bucket: bucket,
3247
- Key: s3Key,
3248
- Body: body,
3249
- ContentType: "application/json"
3250
- }).catch((err) => onError?.(err));
3251
- },
3252
- load() {
3253
- return null;
3254
- }
3255
- };
3256
- return graph.attachStorage([tier], { onError: (err) => onError?.(err) });
3257
- }
3258
- function checkpointToRedis(graph, client, opts) {
3259
- const {
3260
- prefix = "graphrefly:checkpoint:",
3261
- debounceMs = 500,
3262
- compactEvery = 10,
3263
- onError
3264
- } = opts ?? {};
3265
- const redisKey = `${prefix}${graph.name}`;
3266
- const tier = {
3267
- debounceMs,
3268
- compactEvery,
3269
- save(_key, data) {
3270
- let body;
3271
- try {
3272
- body = JSON.stringify(data);
3273
- } catch (err) {
3274
- onError?.(err);
3275
- return;
3276
- }
3277
- void client.set(redisKey, body).catch((err) => onError?.(err));
3278
- },
3279
- async load() {
3280
- const raw = await client.get(redisKey);
3281
- if (raw == null) return null;
3282
- try {
3283
- return JSON.parse(raw);
3284
- } catch {
3285
- return null;
3286
- }
3287
- }
3288
- };
3289
- return graph.attachStorage([tier], { onError: (err) => onError?.(err) });
3290
- }
3291
- function fromSqlite(db, query, opts) {
3292
- const { mapRow = (r) => r, params, ...rest } = opts ?? {};
3293
- return producer(
3294
- (a) => {
3295
- try {
3296
- const rows = db.query(query, params);
3297
- const mapped = rows.map(mapRow);
3298
- a.emit(mapped);
3299
- a.down([[COMPLETE]]);
3300
- } catch (err) {
3301
- a.down([[ERROR, err instanceof Error ? err : new Error(String(err))]]);
3302
- }
3303
- return void 0;
3304
- },
3305
- { describeKind: "producer", completeWhenDepsComplete: false, ...rest }
3306
- );
3307
- }
3308
- function fromSqliteCursor(db, query, opts) {
3309
- const { mapRow = (r) => r, params, ...rest } = opts ?? {};
3310
- return producer(
3311
- (a) => {
3312
- try {
3313
- const it = db.iterate(query, params);
3314
- batch(() => {
3315
- for (const row of it) a.emit(mapRow(row));
3316
- a.down([[COMPLETE]]);
3317
- });
3318
- } catch (err) {
3319
- a.down([[ERROR, err instanceof Error ? err : new Error(String(err))]]);
3320
- }
3321
- return void 0;
3322
- },
3323
- { describeKind: "producer", completeWhenDepsComplete: false, ...rest }
3324
- );
3325
- }
3326
- function toSqlite(source, db, table, opts) {
3327
- if (table.includes("\0") || table.length === 0) {
3328
- throw new Error(`toSqlite: invalid table name: ${JSON.stringify(table)}`);
3329
- }
3330
- const {
3331
- toSQL = (v, t) => ({
3332
- sql: `INSERT INTO "${t.replace(/"/g, '""')}" (data) VALUES (?)`,
3333
- params: [JSON.stringify(v)]
3334
- }),
3335
- onTransportError,
3336
- batchInsert = false,
3337
- maxBatchSize = 1e3,
3338
- flushIntervalMs = 0
3339
- } = opts ?? {};
3340
- const serialize = (value) => toSQL(value, table);
3341
- if (!batchInsert) {
3342
- return reactiveSink(source, {
3343
- onTransportError,
3344
- serialize,
3345
- send: (q) => {
3346
- const query = q;
3347
- db.query(query.sql, query.params);
3348
- }
3349
- });
3350
- }
3351
- const errorsNode = state(null);
3352
- const sentNode = state(void 0, { equals: () => false });
3353
- const failedNode = state(null);
3354
- const inFlightNode = state(0);
3355
- const bufferedNode = state(0);
3356
- const reportError = (err) => {
3357
- try {
3358
- onTransportError?.(err);
3359
- } catch {
3360
- }
3361
- try {
3362
- errorsNode.down([[DATA, err]]);
3363
- } catch {
3364
- }
3365
- };
3366
- let pending = [];
3367
- let flushing = false;
3368
- let timer;
3369
- let disposed = false;
3370
- const updateBuffered = () => bufferedNode.down([[DATA, pending.length]]);
3371
- const safeEmitSent = (v) => {
3372
- if (disposed) return;
3373
- sentNode.down([[DATA, v]]);
3374
- };
3375
- const safeEmitFailed = (f) => {
3376
- if (disposed) return;
3377
- failedNode.down([[DATA, f]]);
3378
- };
3379
- const safeSetInFlight = (n) => {
3380
- if (disposed) return;
3381
- inFlightNode.down([[DATA, n]]);
3382
- };
3383
- const safeReportError = (err) => {
3384
- if (disposed) return;
3385
- reportError(err);
3386
- };
3387
- const flushTransaction = () => {
3388
- if (pending.length === 0 || flushing) return;
3389
- flushing = true;
3390
- safeSetInFlight(1);
3391
- try {
3392
- db.query("BEGIN", []);
3393
- } catch (err) {
3394
- flushing = false;
3395
- safeSetInFlight(0);
3396
- safeReportError({
3397
- stage: "send",
3398
- error: err instanceof Error ? err : new Error(String(err)),
3399
- value: void 0
3400
- });
3401
- return;
3402
- }
3403
- const chunk = pending;
3404
- pending = [];
3405
- updateBuffered();
3406
- let firstError;
3407
- let committedCount = 0;
3408
- for (const entry of chunk) {
3409
- try {
3410
- db.query(entry.query.sql, entry.query.params);
3411
- committedCount += 1;
3412
- } catch (err) {
3413
- firstError = err instanceof Error ? err : new Error(String(err));
3414
- break;
3415
- }
3416
- }
3417
- if (firstError) {
3418
- try {
3419
- db.query("ROLLBACK", []);
3420
- } catch {
3421
- }
3422
- safeReportError({ stage: "send", error: firstError, value: void 0 });
3423
- for (const entry of chunk) {
3424
- safeEmitFailed({ value: entry.value, error: firstError, attempts: 1 });
3425
- }
3426
- } else {
3427
- try {
3428
- db.query("COMMIT", []);
3429
- for (const entry of chunk) safeEmitSent(entry.value);
3430
- } catch (err) {
3431
- const error = err instanceof Error ? err : new Error(String(err));
3432
- safeReportError({ stage: "send", error, value: void 0 });
3433
- for (let i = 0; i < committedCount; i++) {
3434
- safeEmitFailed({ value: chunk[i].value, error, attempts: 1 });
3435
- }
3436
- }
3437
- }
3438
- flushing = false;
3439
- safeSetInFlight(0);
3440
- };
3441
- const scheduleFlush = () => {
3442
- if (flushIntervalMs > 0 && timer === void 0 && !disposed) {
3443
- timer = setTimeout(() => {
3444
- timer = void 0;
3445
- flushTransaction();
3446
- }, flushIntervalMs);
3447
- }
3448
- };
3449
- const unsub = source.subscribe((msgs) => {
3450
- for (const msg of msgs) {
3451
- const t = msg[0];
3452
- if (t === DATA) {
3453
- const value = msg[1];
3454
- let query;
3455
- try {
3456
- query = serialize(value);
3457
- } catch (err) {
3458
- const error = err instanceof Error ? err : new Error(String(err));
3459
- reportError({ stage: "serialize", error, value });
3460
- failedNode.down([[DATA, { value, error, attempts: 0 }]]);
3461
- continue;
3462
- }
3463
- pending.push({ value, query });
3464
- updateBuffered();
3465
- if (pending.length >= maxBatchSize) flushTransaction();
3466
- else scheduleFlush();
3467
- } else if (defaultConfig.messageTier(t) >= 3) {
3468
- flushTransaction();
3469
- }
3470
- }
3471
- });
3472
- const dispose = () => {
3473
- if (disposed) return;
3474
- if (timer !== void 0) {
3475
- clearTimeout(timer);
3476
- timer = void 0;
3477
- }
3478
- flushTransaction();
3479
- disposed = true;
3480
- unsub();
3481
- for (const n of [errorsNode, sentNode, failedNode, inFlightNode, bufferedNode]) {
3482
- try {
3483
- n.down([[TEARDOWN]]);
3484
- } catch {
3485
- }
3486
- }
3487
- };
3488
- return {
3489
- dispose,
3490
- sent: sentNode,
3491
- failed: failedNode,
3492
- inFlight: inFlightNode,
3493
- errors: errorsNode,
3494
- buffered: bufferedNode,
3495
- flush: async () => {
3496
- if (!disposed) flushTransaction();
3497
- }
3498
- };
3499
- }
3500
- function fromPrisma(model, opts) {
3501
- const { args, mapRow = (r) => r, ...rest } = opts ?? {};
3502
- return producer(
3503
- (a) => {
3504
- let active = true;
3505
- void model.findMany(args).then((rows) => {
3506
- if (!active) return;
3507
- a.emit(rows.map(mapRow));
3508
- a.down([[COMPLETE]]);
3509
- }).catch((err) => {
3510
- if (!active) return;
3511
- try {
3512
- a.down([[ERROR, err instanceof Error ? err : new Error(String(err))]]);
3513
- } catch {
3514
- }
3515
- });
3516
- return () => {
3517
- active = false;
3518
- };
3519
- },
3520
- { ...rest, describeKind: "producer", completeWhenDepsComplete: false }
3521
- );
3522
- }
3523
- function fromDrizzle(query, opts) {
3524
- const { mapRow = (r) => r, ...rest } = opts ?? {};
3525
- return producer(
3526
- (a) => {
3527
- let active = true;
3528
- void query.execute().then((rows) => {
3529
- if (!active) return;
3530
- a.emit(rows.map(mapRow));
3531
- a.down([[COMPLETE]]);
3532
- }).catch((err) => {
3533
- if (!active) return;
3534
- try {
3535
- a.down([[ERROR, err instanceof Error ? err : new Error(String(err))]]);
3536
- } catch {
3537
- }
3538
- });
3539
- return () => {
3540
- active = false;
3541
- };
3542
- },
3543
- { ...rest, describeKind: "producer", completeWhenDepsComplete: false }
3544
- );
3545
- }
3546
- function fromKysely(query, opts) {
3547
- const { mapRow = (r) => r, ...rest } = opts ?? {};
3548
- return producer(
3549
- (a) => {
3550
- let active = true;
3551
- void query.execute().then((rows) => {
3552
- if (!active) return;
3553
- a.emit(rows.map(mapRow));
3554
- a.down([[COMPLETE]]);
3555
- }).catch((err) => {
3556
- if (!active) return;
3557
- try {
3558
- a.down([[ERROR, err instanceof Error ? err : new Error(String(err))]]);
3559
- } catch {
3560
- }
3561
- });
3562
- return () => {
3563
- active = false;
3564
- };
3565
- },
3566
- { ...rest, describeKind: "producer", completeWhenDepsComplete: false }
3567
- );
3568
- }
3569
-
3570
- // src/extra/cascading-cache.ts
3571
- function lru() {
3572
- const map2 = /* @__PURE__ */ new Map();
3573
- let head = null;
3574
- let tail = null;
3575
- function unlink(n) {
3576
- if (n.prev) n.prev.next = n.next;
3577
- else head = n.next;
3578
- if (n.next) n.next.prev = n.prev;
3579
- else tail = n.prev;
3580
- n.prev = null;
3581
- n.next = null;
3582
- }
3583
- function pushFront(n) {
3584
- n.next = head;
3585
- n.prev = null;
3586
- if (head) head.prev = n;
3587
- head = n;
3588
- if (tail === null) tail = n;
3589
- }
3590
- return {
3591
- insert(key) {
3592
- if (map2.has(key)) {
3593
- this.touch(key);
3594
- return;
3595
- }
3596
- const n = { key, prev: null, next: null };
3597
- map2.set(key, n);
3598
- pushFront(n);
3599
- },
3600
- touch(key) {
3601
- const n = map2.get(key);
3602
- if (!n) return;
3603
- unlink(n);
3604
- pushFront(n);
3605
- },
3606
- delete(key) {
3607
- const n = map2.get(key);
3608
- if (!n) return;
3609
- unlink(n);
3610
- map2.delete(key);
3611
- },
3612
- evict(count) {
3613
- const victims = [];
3614
- for (let i = 0; i < count && tail !== null; i++) {
3615
- const n = tail;
3616
- victims.push(n.key);
3617
- unlink(n);
3618
- map2.delete(n.key);
3619
- }
3620
- return victims;
3621
- },
3622
- size() {
3623
- return map2.size;
3624
- }
3625
- };
3626
- }
3627
- function isPromiseLike(v) {
3628
- return v != null && typeof v.then === "function";
3629
- }
3630
- function fireAndForget(result) {
3631
- if (isPromiseLike(result)) {
3632
- result.catch(() => {
3633
- });
3634
- }
3635
- }
3636
- function cascadingCache(tiers, opts) {
3637
- const entries = /* @__PURE__ */ new Map();
3638
- const maxSize = opts?.maxSize ?? 0;
3639
- const policy = maxSize > 0 ? opts?.eviction ?? lru() : null;
3640
- const writeThrough = opts?.writeThrough ?? false;
3641
- function promote(key, value, hitTierIndex) {
3642
- for (let i = 0; i < hitTierIndex; i++) {
3643
- try {
3644
- fireAndForget(tiers[i].save(key, value));
3645
- } catch {
3646
- }
3647
- }
3648
- }
3649
- function cascade(key, nd, startTier = 0) {
3650
- for (let tierIndex = startTier; tierIndex < tiers.length; tierIndex++) {
3651
- let result;
3652
- try {
3653
- result = tiers[tierIndex].load(key);
3654
- } catch {
3655
- continue;
3656
- }
3657
- if (isPromiseLike(result)) {
3658
- const captured = tierIndex;
3659
- result.then(
3660
- (val) => {
3661
- if (val !== void 0 && val !== null) {
3662
- nd.down([[DATA, val]]);
3663
- promote(key, val, captured);
3664
- } else {
3665
- cascade(key, nd, captured + 1);
3666
- }
3667
- },
3668
- () => {
3669
- cascade(key, nd, captured + 1);
3670
- }
3671
- );
3672
- return;
3673
- }
3674
- if (result !== void 0 && result !== null) {
3675
- nd.down([[DATA, result]]);
3676
- promote(key, result, tierIndex);
3677
- return;
3678
- }
3679
- }
3680
- }
3681
- function evictIfNeeded() {
3682
- if (!policy || maxSize <= 0) return;
3683
- while (policy.size() >= maxSize) {
3684
- const victims = policy.evict(1);
3685
- if (victims.length === 0) break;
3686
- for (const key of victims) {
3687
- const nd = entries.get(key);
3688
- if (nd) {
3689
- const value = nd.cache;
3690
- if (nd.status !== "sentinel" && tiers.length > 0) {
3691
- const lastIndex = tiers.length - 1;
3692
- try {
3693
- fireAndForget(tiers[lastIndex].save(key, value));
3694
- } catch {
3695
- }
3696
- for (let j = 0; j < lastIndex; j++) {
3697
- try {
3698
- const clearFn = tiers[j].clear;
3699
- if (clearFn) fireAndForget(clearFn.call(tiers[j], key));
3700
- } catch {
3701
- }
3702
- }
3703
- }
3704
- nd.down([[TEARDOWN]]);
3705
- }
3706
- entries.delete(key);
3707
- }
3708
- }
3709
- }
3710
- return {
3711
- load(key) {
3712
- const existing = entries.get(key);
3713
- if (existing) {
3714
- policy?.touch(key);
3715
- return existing;
3716
- }
3717
- if (policy && maxSize > 0 && policy.size() >= maxSize) {
3718
- evictIfNeeded();
3719
- }
3720
- const nd = state(void 0);
3721
- entries.set(key, nd);
3722
- policy?.insert(key);
3723
- cascade(key, nd);
3724
- return nd;
3725
- },
3726
- save(key, value) {
3727
- if (writeThrough) {
3728
- for (const tier of tiers) {
3729
- try {
3730
- fireAndForget(tier.save(key, value));
3731
- } catch {
3732
- }
3733
- }
3734
- } else if (tiers[0]) {
3735
- try {
3736
- fireAndForget(tiers[0].save(key, value));
3737
- } catch {
3738
- }
3739
- }
3740
- const existing = entries.get(key);
3741
- if (existing) {
3742
- existing.down([[DATA, value]]);
3743
- policy?.touch(key);
3744
- } else {
3745
- if (policy && maxSize > 0 && policy.size() >= maxSize) {
3746
- evictIfNeeded();
3747
- }
3748
- const nd = state(value);
3749
- entries.set(key, nd);
3750
- policy?.insert(key);
3751
- }
3752
- },
3753
- invalidate(key) {
3754
- const existing = entries.get(key);
3755
- if (existing) cascade(key, existing);
3756
- },
3757
- delete(key) {
3758
- policy?.delete(key);
3759
- const nd = entries.get(key);
3760
- if (nd) nd.down([[TEARDOWN]]);
3761
- entries.delete(key);
3762
- for (const tier of tiers) {
3763
- try {
3764
- const clearFn = tier.clear;
3765
- if (clearFn) fireAndForget(clearFn.call(tier, key));
3766
- } catch {
3767
- }
3768
- }
3769
- },
3770
- has(key) {
3771
- return entries.has(key);
3772
- },
3773
- get size() {
3774
- return entries.size;
3775
- }
3776
- };
3777
- }
3778
-
3779
- // src/extra/pubsub.ts
3780
- var NativePubSubBackend = class {
3781
- _version = 0;
3782
- _topics = /* @__PURE__ */ new Set();
3783
- get version() {
3784
- return this._version;
3785
- }
3786
- get topicCount() {
3787
- return this._topics.size;
3788
- }
3789
- hasTopic(name) {
3790
- return this._topics.has(name);
3791
- }
3792
- topicNames() {
3793
- return this._topics.values();
3794
- }
3795
- createTopic(name) {
3796
- if (this._topics.has(name)) return false;
3797
- this._topics.add(name);
3798
- this._version += 1;
3799
- return true;
3800
- }
3801
- removeTopic(name) {
3802
- const had = this._topics.delete(name);
3803
- if (had) this._version += 1;
3804
- return had;
3805
- }
3806
- };
3807
- function pubsub(options = {}) {
3808
- const { backend: userBackend } = options;
3809
- const backend = userBackend ?? new NativePubSubBackend();
3810
- const nodes = /* @__PURE__ */ new Map();
3811
- function ensureTopic(name) {
3812
- let n = nodes.get(name);
3813
- if (n === void 0) {
3814
- n = node({ describeKind: "state" });
3815
- nodes.set(name, n);
3816
- backend.createTopic(name);
3817
- }
3818
- return n;
3819
- }
3820
- return {
3821
- topic(name) {
3822
- return ensureTopic(name);
3823
- },
3824
- publish(name, value) {
3825
- ensureTopic(name).emit(value);
3826
- },
3827
- publishMany(entries) {
3828
- batch(() => {
3829
- for (const [name, value] of entries) {
3830
- ensureTopic(name).emit(value);
3831
- }
3832
- });
3833
- },
3834
- removeTopic(name) {
3835
- const n = nodes.get(name);
3836
- if (n === void 0) return false;
3837
- nodes.delete(name);
3838
- backend.removeTopic(name);
3839
- n.down([[TEARDOWN]]);
3840
- return true;
3841
- },
3842
- has(name) {
3843
- return backend.hasTopic(name);
3844
- },
3845
- get size() {
3846
- return backend.topicCount;
3847
- },
3848
- topicNames() {
3849
- return backend.topicNames();
3850
- }
3851
- };
3852
- }
3853
-
3854
- // src/extra/reactive-index.ts
3855
- function cmpOrd(a, b) {
3856
- if (a === b) return 0;
3857
- const ta = typeof a;
3858
- const tb = typeof b;
3859
- if (ta === tb && (ta === "number" || ta === "string" || ta === "boolean" || ta === "bigint")) {
3860
- const ax = a;
3861
- const bx = b;
3862
- if (ax < bx) return -1;
3863
- if (ax > bx) return 1;
3864
- return 0;
3865
- }
3866
- return String(a).localeCompare(String(b));
3867
- }
3868
- function compareKeys(a, b) {
3869
- const c = cmpOrd(a[0], b[0]);
3870
- if (c !== 0) return c;
3871
- return cmpOrd(a[1], b[1]);
3872
- }
3873
- function rowKey(row) {
3874
- return [row.secondary, row.primary];
3875
- }
3876
- function bisectLeft(rows, row) {
3877
- const k = rowKey(row);
3878
- let lo = 0;
3879
- let hi = rows.length;
3880
- while (lo < hi) {
3881
- const mid = lo + hi >> 1;
3882
- if (compareKeys(k, rowKey(rows[mid])) > 0) lo = mid + 1;
3883
- else hi = mid;
3884
- }
3885
- return lo;
3886
- }
3887
- var NativeIndexBackend = class {
3888
- _version = 0;
3889
- _buf = [];
3890
- _byPrimary = /* @__PURE__ */ new Map();
3891
- get version() {
3892
- return this._version;
3893
- }
3894
- get size() {
3895
- return this._buf.length;
3896
- }
3897
- has(primary) {
3898
- return this._byPrimary.has(primary);
3899
- }
3900
- get(primary) {
3901
- return this._byPrimary.get(primary)?.value;
3902
- }
3903
- upsert(primary, secondary, value, opts) {
3904
- const existing = this._byPrimary.get(primary);
3905
- const row = { primary, secondary, value };
3906
- if (existing !== void 0 && opts?.equals?.(existing, row)) {
3907
- return false;
3908
- }
3909
- if (existing !== void 0) {
3910
- const oldPos = bisectLeft(this._buf, existing);
3911
- this._buf.splice(oldPos, 1);
3912
- }
3913
- const newPos = bisectLeft(this._buf, row);
3914
- this._buf.splice(newPos, 0, row);
3915
- this._byPrimary.set(primary, row);
3916
- this._version += 1;
3917
- return existing === void 0;
3918
- }
3919
- upsertMany(rows, opts) {
3920
- let changed = 0;
3921
- try {
3922
- for (const r of rows) {
3923
- const existing = this._byPrimary.get(r.primary);
3924
- const row = {
3925
- primary: r.primary,
3926
- secondary: r.secondary,
3927
- value: r.value
3928
- };
3929
- if (existing !== void 0 && opts?.equals?.(existing, row)) {
3930
- continue;
3931
- }
3932
- if (existing !== void 0) {
3933
- const oldPos = bisectLeft(this._buf, existing);
3934
- this._buf.splice(oldPos, 1);
3935
- }
3936
- const newPos = bisectLeft(this._buf, row);
3937
- this._buf.splice(newPos, 0, row);
3938
- this._byPrimary.set(r.primary, row);
3939
- changed += 1;
3940
- }
3941
- } finally {
3942
- if (changed > 0) this._version += 1;
3943
- }
3944
- return changed;
3945
- }
3946
- delete(primary) {
3947
- const existing = this._byPrimary.get(primary);
3948
- if (existing === void 0) return false;
3949
- const pos = bisectLeft(this._buf, existing);
3950
- this._buf.splice(pos, 1);
3951
- this._byPrimary.delete(primary);
3952
- this._version += 1;
3953
- return true;
3954
- }
3955
- deleteMany(primaries) {
3956
- let removed = 0;
3957
- try {
3958
- for (const primary of primaries) {
3959
- const existing = this._byPrimary.get(primary);
3960
- if (existing === void 0) continue;
3961
- const pos = bisectLeft(this._buf, existing);
3962
- this._buf.splice(pos, 1);
3963
- this._byPrimary.delete(primary);
3964
- removed += 1;
3965
- }
3966
- } finally {
3967
- if (removed > 0) this._version += 1;
3968
- }
3969
- return removed;
3970
- }
3971
- clear() {
3972
- const n = this._buf.length;
3973
- if (n === 0) return 0;
3974
- this._buf.length = 0;
3975
- this._byPrimary.clear();
3976
- this._version += 1;
3977
- return n;
3978
- }
3979
- toArray() {
3980
- return [...this._buf];
3981
- }
3982
- toPrimaryMap() {
3983
- const m = /* @__PURE__ */ new Map();
3984
- for (const r of this._buf) m.set(r.primary, r.value);
3985
- return m;
3986
- }
3987
- };
3988
- function keepaliveDerived(n) {
3989
- return n.subscribe(() => {
3990
- });
3991
- }
3992
- function reactiveIndex(options = {}) {
3993
- const { name, versioning, equals: defaultEquals, backend: userBackend } = options;
3994
- const backend = userBackend ?? new NativeIndexBackend();
3995
- function withDefaultEquals(opts) {
3996
- if (opts?.equals !== void 0) return opts;
3997
- if (defaultEquals === void 0) return opts;
3998
- return { ...opts, equals: defaultEquals };
3999
- }
4000
- const ordered = state([], {
4001
- name,
4002
- describeKind: "state",
4003
- equals: (a, b) => a === b,
4004
- ...versioning != null ? { versioning } : {}
4005
- });
4006
- const byPrimary = derived(
4007
- [ordered],
4008
- ([s]) => {
4009
- const rows = s;
4010
- const m = /* @__PURE__ */ new Map();
4011
- for (const r of rows) m.set(r.primary, r.value);
4012
- return m;
4013
- },
4014
- { initial: backend.toPrimaryMap(), describeKind: "derived" }
4015
- );
4016
- const disposeByPrimaryKeepalive = keepaliveDerived(byPrimary);
4017
- let disposed = false;
4018
- function pushSnapshot() {
4019
- const snapshot = backend.toArray();
4020
- batch(() => {
4021
- ordered.down([[DIRTY]]);
4022
- ordered.down([[DATA, snapshot]]);
4023
- });
4024
- }
4025
- function wrapMutation(op) {
4026
- const prev = backend.version;
4027
- try {
4028
- return op();
4029
- } finally {
4030
- if (backend.version !== prev) pushSnapshot();
4031
- }
4032
- }
4033
- return {
4034
- ordered,
4035
- byPrimary,
4036
- has(primary) {
4037
- return backend.has(primary);
4038
- },
4039
- get(primary) {
4040
- return backend.get(primary);
4041
- },
4042
- get size() {
4043
- return backend.size;
4044
- },
4045
- upsert(primary, secondary, value, opts) {
4046
- return wrapMutation(() => backend.upsert(primary, secondary, value, withDefaultEquals(opts)));
4047
- },
4048
- upsertMany(rows, opts) {
4049
- const list = [...rows];
4050
- if (list.length === 0) return;
4051
- wrapMutation(() => backend.upsertMany(list, withDefaultEquals(opts)));
4052
- },
4053
- delete(primary) {
4054
- wrapMutation(() => backend.delete(primary));
4055
- },
4056
- deleteMany(primaries) {
4057
- const list = [...primaries];
4058
- if (list.length === 0) return;
4059
- wrapMutation(() => backend.deleteMany(list));
4060
- },
4061
- clear() {
4062
- wrapMutation(() => backend.clear());
4063
- },
4064
- dispose() {
4065
- if (disposed) return;
4066
- disposed = true;
4067
- disposeByPrimaryKeepalive();
4068
- }
4069
- };
4070
- }
4071
-
4072
- // src/extra/sources-fs.ts
4073
- import { existsSync, watch } from "node:fs";
4074
- import { resolve as resolvePath } from "node:path";
4075
- function sourceOpts3(opts) {
4076
- return { describeKind: "producer", ...opts };
4077
- }
4078
- function fromFSWatch(paths, opts) {
4079
- const list = Array.isArray(paths) ? paths : [paths];
4080
- if (list.length === 0) {
4081
- throw new RangeError("fromFSWatch expects at least one path");
4082
- }
4083
- const { recursive = true, debounce: debounce2 = 100, include, exclude, ...rest } = opts ?? {};
4084
- const includePatterns = include?.map(globToRegExp) ?? [];
4085
- const excludePatterns = (exclude ?? ["**/node_modules/**", "**/.git/**", "**/dist/**"]).map(
4086
- globToRegExp
4087
- );
4088
- return producer((a) => {
4089
- const pending = /* @__PURE__ */ new Map();
4090
- const watchers = [];
4091
- let stopped = false;
4092
- let terminalEmitted = false;
4093
- let generation = 0;
4094
- const closeWatchers = () => {
4095
- for (const watcher of watchers.splice(0)) watcher.close();
4096
- };
4097
- const emitError = (err) => {
4098
- if (terminalEmitted) return;
4099
- terminalEmitted = true;
4100
- stopped = true;
4101
- if (timer !== void 0) clearTimeout(timer);
4102
- timer = void 0;
4103
- pending.clear();
4104
- closeWatchers();
4105
- a.down([[ERROR, err]]);
4106
- };
4107
- let timer;
4108
- const flush = (token) => {
4109
- timer = void 0;
4110
- if (stopped || terminalEmitted) return;
4111
- if (pending.size === 0) return;
4112
- const batchMessages = [];
4113
- for (const evt of pending.values()) batchMessages.push([DATA, evt]);
4114
- pending.clear();
4115
- if (stopped || terminalEmitted || token !== generation) return;
4116
- a.down(batchMessages);
4117
- };
4118
- try {
4119
- for (const basePath of list) {
4120
- const watcher = watch(
4121
- basePath,
4122
- { recursive },
4123
- (eventType, fileName) => {
4124
- if (stopped || terminalEmitted) return;
4125
- if (fileName == null) return;
4126
- const rel = String(fileName).replaceAll("\\", "/");
4127
- const abs = resolvePath(basePath, String(fileName));
4128
- const normalized = abs.replaceAll("\\", "/");
4129
- const root = resolvePath(basePath).replaceAll("\\", "/");
4130
- const relForMatch = rel.startsWith("./") ? rel.slice(2) : rel;
4131
- const included = includePatterns.length === 0 || matchesAnyPattern(normalized, includePatterns) || matchesAnyPattern(relForMatch, includePatterns);
4132
- if (!included) return;
4133
- const excluded = matchesAnyPattern(normalized, excludePatterns) || matchesAnyPattern(relForMatch, excludePatterns);
4134
- if (excluded) return;
4135
- let kind = "change";
4136
- if (eventType === "rename") {
4137
- try {
4138
- kind = existsSync(normalized) ? "create" : "delete";
4139
- } catch {
4140
- kind = "rename";
4141
- }
4142
- }
4143
- pending.set(normalized, {
4144
- type: kind,
4145
- path: normalized,
4146
- root,
4147
- relative_path: relForMatch,
4148
- timestamp_ns: wallClockNs()
4149
- });
4150
- if (timer !== void 0) clearTimeout(timer);
4151
- const token = generation;
4152
- timer = setTimeout(() => flush(token), debounce2);
4153
- }
4154
- );
4155
- watcher.on("error", (err) => emitError(err));
4156
- watchers.push(watcher);
4157
- }
4158
- } catch (err) {
4159
- emitError(err);
4160
- }
4161
- return () => {
4162
- stopped = true;
4163
- generation += 1;
4164
- if (timer !== void 0) clearTimeout(timer);
4165
- timer = void 0;
4166
- closeWatchers();
4167
- pending.clear();
4168
- };
4169
- }, sourceOpts3(rest));
4170
- }
4171
-
4172
- // src/extra/storage.ts
4173
- import { randomBytes } from "node:crypto";
4174
- import {
4175
- mkdirSync,
4176
- readdirSync,
4177
- readFileSync,
4178
- renameSync,
4179
- unlinkSync,
4180
- writeFileSync
4181
- } from "node:fs";
4182
- import { basename, dirname, join } from "node:path";
4183
- import { DatabaseSync } from "node:sqlite";
4184
- function sortJsonValue(value) {
4185
- if (value === null || typeof value !== "object") return value;
4186
- if (Array.isArray(value)) return value.map(sortJsonValue);
4187
- const obj = value;
4188
- const keys = Object.keys(obj).sort();
4189
- const out = {};
4190
- for (const k of keys) out[k] = sortJsonValue(obj[k]);
4191
- return out;
4192
- }
4193
- function stableJsonString(data) {
4194
- return JSON.stringify(sortJsonValue(data), void 0, 0);
4195
- }
4196
- function memoryStorage() {
4197
- const data = /* @__PURE__ */ new Map();
4198
- return {
4199
- save(key, record) {
4200
- data.set(key, JSON.parse(JSON.stringify(record)));
4201
- },
4202
- load(key) {
4203
- const v = data.get(key);
4204
- return v === void 0 ? null : JSON.parse(JSON.stringify(v));
4205
- },
4206
- clear(key) {
4207
- data.delete(key);
4208
- },
4209
- list() {
4210
- return [...data.keys()].sort();
4211
- }
4212
- };
4213
- }
4214
- function dictStorage(storage) {
4215
- return {
4216
- save(key, record) {
4217
- storage[key] = JSON.parse(JSON.stringify(record));
4218
- },
4219
- load(key) {
4220
- const raw = storage[key];
4221
- return raw === void 0 ? null : JSON.parse(JSON.stringify(raw));
4222
- },
4223
- clear(key) {
4224
- delete storage[key];
4225
- },
4226
- list() {
4227
- return Object.keys(storage).sort();
4228
- }
4229
- };
4230
- }
4231
- function fileStorage(dir) {
4232
- const encoder = new TextEncoder();
4233
- const decoder = new TextDecoder("utf-8", { fatal: true });
4234
- const pathFor = (key) => {
4235
- let out = "";
4236
- for (const ch of key) {
4237
- if (ch.length === 1 && /[a-zA-Z0-9_-]/.test(ch)) {
4238
- out += ch;
4239
- continue;
4240
- }
4241
- for (const byte of encoder.encode(ch)) {
4242
- out += `%${byte.toString(16).padStart(2, "0")}`;
4243
- }
4244
- }
4245
- return join(dir, `${out}.json`);
4246
- };
4247
- const keyFromFilename = (filename) => {
4248
- if (!filename.endsWith(".json")) return null;
4249
- const stem = filename.slice(0, -".json".length);
4250
- const bytes = [];
4251
- const encodeAscii = (s) => {
4252
- for (let i2 = 0; i2 < s.length; i2++) bytes.push(s.charCodeAt(i2));
4253
- };
4254
- let i = 0;
4255
- while (i < stem.length) {
4256
- const ch = stem[i];
4257
- if (ch === "%" && i + 2 < stem.length) {
4258
- const hex = stem.slice(i + 1, i + 3);
4259
- if (/^[0-9a-f]{2}$/i.test(hex)) {
4260
- bytes.push(Number.parseInt(hex, 16));
4261
- i += 3;
4262
- continue;
4263
- }
4264
- }
4265
- encodeAscii(ch);
4266
- i += 1;
4267
- }
4268
- try {
4269
- return decoder.decode(new Uint8Array(bytes));
4270
- } catch {
4271
- return null;
4272
- }
4273
- };
4274
- return {
4275
- save(key, record) {
4276
- mkdirSync(dir, { recursive: true });
4277
- const filePath = pathFor(key);
4278
- const payload = `${stableJsonString(record)}
4279
- `;
4280
- const base = basename(filePath);
4281
- const d = dirname(filePath);
4282
- const tmp = join(d, `.${base}.${randomBytes(8).toString("hex")}.tmp`);
4283
- try {
4284
- writeFileSync(tmp, payload, "utf8");
4285
- renameSync(tmp, filePath);
4286
- } catch (e) {
4287
- try {
4288
- unlinkSync(tmp);
4289
- } catch {
4290
- }
4291
- throw e;
4292
- }
4293
- },
4294
- load(key) {
4295
- try {
4296
- const text = readFileSync(pathFor(key), "utf8").trim();
4297
- if (!text) return null;
4298
- return JSON.parse(text);
4299
- } catch {
4300
- return null;
4301
- }
4302
- },
4303
- clear(key) {
4304
- try {
4305
- unlinkSync(pathFor(key));
4306
- } catch (e) {
4307
- if (e.code !== "ENOENT") throw e;
4308
- }
4309
- },
4310
- list() {
4311
- try {
4312
- const entries = readdirSync(dir);
4313
- const keys = [];
4314
- for (const entry of entries) {
4315
- if (entry.startsWith(".")) continue;
4316
- const k = keyFromFilename(entry);
4317
- if (k !== null) keys.push(k);
4318
- }
4319
- return keys.sort();
4320
- } catch (e) {
4321
- if (e.code === "ENOENT") return [];
4322
- throw e;
4323
- }
4324
- }
4325
- };
4326
- }
4327
- function sqliteStorage(path) {
4328
- const db = new DatabaseSync(path);
4329
- db.exec(`CREATE TABLE IF NOT EXISTS graphrefly_checkpoint (k TEXT PRIMARY KEY, v TEXT NOT NULL)`);
4330
- return {
4331
- save(key, record) {
4332
- const payload = stableJsonString(record);
4333
- db.prepare(`INSERT OR REPLACE INTO graphrefly_checkpoint (k, v) VALUES (?, ?)`).run(
4334
- key,
4335
- payload
4336
- );
4337
- },
4338
- load(key) {
4339
- const row = db.prepare(`SELECT v FROM graphrefly_checkpoint WHERE k = ?`).get(key);
4340
- if (row === void 0 || typeof row.v !== "string" || row.v.trim() === "") return null;
4341
- return JSON.parse(row.v);
4342
- },
4343
- clear(key) {
4344
- db.prepare(`DELETE FROM graphrefly_checkpoint WHERE k = ?`).run(key);
4345
- },
4346
- list() {
4347
- const rows = db.prepare(`SELECT k FROM graphrefly_checkpoint ORDER BY k`).all();
4348
- return rows.map((r) => r.k);
4349
- },
4350
- close() {
4351
- try {
4352
- db.close();
4353
- } catch {
4354
- }
4355
- }
4356
- };
4357
- }
4358
- function fromIDBRequest(req) {
4359
- return producer((a) => {
4360
- let done = false;
4361
- const clear = () => {
4362
- req.onsuccess = null;
4363
- req.onerror = null;
4364
- };
4365
- req.onsuccess = () => {
4366
- if (done) return;
4367
- done = true;
4368
- clear();
4369
- a.down([[DATA, req.result], [COMPLETE]]);
4370
- };
4371
- req.onerror = () => {
4372
- if (done) return;
4373
- done = true;
4374
- clear();
4375
- a.down([[ERROR, req.error ?? new Error("IndexedDB request failed")]]);
4376
- };
4377
- return () => {
4378
- done = true;
4379
- clear();
4380
- };
4381
- });
4382
- }
4383
- function fromIDBTransaction(tx) {
4384
- return producer((a) => {
4385
- let done = false;
4386
- const clear = () => {
4387
- tx.oncomplete = null;
4388
- tx.onerror = null;
4389
- tx.onabort = null;
4390
- };
4391
- tx.oncomplete = () => {
4392
- if (done) return;
4393
- done = true;
4394
- clear();
4395
- a.down([[DATA, void 0], [COMPLETE]]);
4396
- };
4397
- tx.onerror = () => {
4398
- if (done) return;
4399
- done = true;
4400
- clear();
4401
- a.down([[ERROR, tx.error ?? new Error("IndexedDB transaction failed")]]);
4402
- };
4403
- tx.onabort = () => {
4404
- if (done) return;
4405
- done = true;
4406
- clear();
4407
- a.down([[ERROR, tx.error ?? new Error("IndexedDB transaction aborted")]]);
4408
- };
4409
- return () => {
4410
- done = true;
4411
- clear();
4412
- };
4413
- });
4414
- }
4415
- function openIdb(dbName, storeName, version) {
4416
- return new Promise((resolve, reject) => {
4417
- if (typeof indexedDB === "undefined") {
4418
- reject(new TypeError("indexedDB is not available in this environment"));
4419
- return;
4420
- }
4421
- const req = indexedDB.open(dbName, version);
4422
- req.onupgradeneeded = () => {
4423
- const db = req.result;
4424
- if (!db.objectStoreNames.contains(storeName)) {
4425
- db.createObjectStore(storeName);
4426
- }
4427
- };
4428
- req.onsuccess = () => resolve(req.result);
4429
- req.onerror = () => reject(req.error ?? new Error("IndexedDB open failed"));
4430
- });
4431
- }
4432
- function idbOp(dbName, storeName, version, mode, op) {
4433
- return openIdb(dbName, storeName, version).then(
4434
- (db) => new Promise((resolve, reject) => {
4435
- const tx = db.transaction(storeName, mode);
4436
- const store = tx.objectStore(storeName);
4437
- const req = op(store);
4438
- let reqResult;
4439
- let reqDone = false;
4440
- let txDone = false;
4441
- const finish = () => {
4442
- if (!reqDone || !txDone) return;
4443
- db.close();
4444
- resolve(reqResult);
4445
- };
4446
- req.onsuccess = () => {
4447
- reqResult = req.result;
4448
- reqDone = true;
4449
- finish();
4450
- };
4451
- req.onerror = () => {
4452
- db.close();
4453
- reject(req.error ?? new Error("IndexedDB request failed"));
4454
- };
4455
- tx.oncomplete = () => {
4456
- txDone = true;
4457
- if (!reqDone) {
4458
- db.close();
4459
- reject(new Error("IndexedDB transaction completed without request result"));
4460
- return;
4461
- }
4462
- finish();
4463
- };
4464
- tx.onerror = () => {
4465
- db.close();
4466
- reject(tx.error ?? new Error("IndexedDB transaction failed"));
4467
- };
4468
- tx.onabort = () => {
4469
- db.close();
4470
- reject(tx.error ?? new Error("IndexedDB transaction aborted"));
4471
- };
4472
- })
4473
- );
4474
- }
4475
- function indexedDbStorage(spec) {
4476
- const { dbName, storeName } = spec;
4477
- const version = spec.version ?? 1;
4478
- const recordKey = spec.key ?? "graphrefly_checkpoint";
4479
- return {
4480
- async save(_key, record) {
4481
- await idbOp(
4482
- dbName,
4483
- storeName,
4484
- version,
4485
- "readwrite",
4486
- (store) => store.put(record, recordKey)
4487
- );
4488
- },
4489
- async load(_key) {
4490
- const raw = await idbOp(
4491
- dbName,
4492
- storeName,
4493
- version,
4494
- "readonly",
4495
- (store) => store.get(recordKey)
4496
- );
4497
- if (raw === void 0 || raw === null) return null;
4498
- if (typeof raw !== "object" || Array.isArray(raw)) return null;
4499
- return raw;
4500
- },
4501
- async clear(_key) {
4502
- await idbOp(dbName, storeName, version, "readwrite", (store) => store.delete(recordKey));
4503
- }
4504
- };
4505
- }
4506
-
4507
- // src/extra/worker/protocol.ts
4508
- var signalToNameMap = /* @__PURE__ */ new Map([
4509
- [INVALIDATE, "INVALIDATE"],
4510
- [PAUSE, "PAUSE"],
4511
- [RESUME, "RESUME"],
4512
- [TEARDOWN, "TEARDOWN"],
4513
- [COMPLETE, "COMPLETE"],
4514
- [ERROR, "ERROR"]
4515
- ]);
4516
- var nameToSignalMap = /* @__PURE__ */ new Map([
4517
- ["INVALIDATE", INVALIDATE],
4518
- ["PAUSE", PAUSE],
4519
- ["RESUME", RESUME],
4520
- ["TEARDOWN", TEARDOWN],
4521
- ["COMPLETE", COMPLETE],
4522
- ["ERROR", ERROR]
4523
- ]);
4524
- function signalToName(s) {
4525
- const known = signalToNameMap.get(s);
4526
- if (known) return known;
4527
- const key = Symbol.keyFor(s);
4528
- return key ?? "UNKNOWN";
4529
- }
4530
- function nameToSignal(name) {
4531
- const known = nameToSignalMap.get(name);
4532
- if (known) return known;
4533
- if (name && name !== "UNKNOWN") return Symbol.for(name);
4534
- return void 0;
4535
- }
4536
- function serializeError(err) {
4537
- if (err instanceof Error) {
4538
- return { message: err.message, name: err.name, stack: err.stack };
4539
- }
4540
- return { message: String(err), name: "Error" };
4541
- }
4542
- function deserializeError(payload) {
4543
- const err = new Error(payload.message);
4544
- err.name = payload.name;
4545
- if (payload.stack) err.stack = payload.stack;
4546
- return err;
4547
- }
4548
-
4549
- // src/extra/worker/transport.ts
4550
- function createTransport(target) {
4551
- if (typeof MessagePort !== "undefined" && target instanceof MessagePort) {
4552
- return {
4553
- post(data, transfer) {
4554
- target.postMessage(data, transfer ?? []);
4555
- },
4556
- listen(handler) {
4557
- const h = (e) => handler(e.data);
4558
- target.addEventListener("message", h);
4559
- target.start();
4560
- return () => target.removeEventListener("message", h);
4561
- },
4562
- terminate() {
4563
- target.close();
4564
- }
4565
- };
4566
- }
4567
- if (typeof SharedWorker !== "undefined" && target instanceof SharedWorker) {
4568
- return createTransport(target.port);
4569
- }
4570
- if (typeof Worker !== "undefined" && target instanceof Worker) {
4571
- return {
4572
- post(data, transfer) {
4573
- target.postMessage(data, transfer ?? []);
4574
- },
4575
- listen(handler) {
4576
- const h = (e) => handler(e.data);
4577
- target.addEventListener("message", h);
4578
- return () => target.removeEventListener("message", h);
4579
- },
4580
- terminate() {
4581
- target.terminate();
4582
- }
4583
- };
4584
- }
4585
- if (typeof BroadcastChannel !== "undefined" && target instanceof BroadcastChannel) {
4586
- return {
4587
- post(data, transfer) {
4588
- if (transfer && transfer.length > 0) {
4589
- console.warn(
4590
- "[graphrefly] WorkerTransport: BroadcastChannel does not support Transferable objects. The transfer argument is ignored and objects will be cloned instead."
4591
- );
4592
- }
4593
- target.postMessage(data);
4594
- },
4595
- listen(handler) {
4596
- const h = (e) => handler(e.data);
4597
- target.addEventListener("message", h);
4598
- return () => target.removeEventListener("message", h);
4599
- },
4600
- terminate() {
4601
- target.close();
4602
- }
4603
- };
4604
- }
4605
- if (typeof ServiceWorker !== "undefined" && target instanceof ServiceWorker) {
4606
- return {
4607
- post(data, transfer) {
4608
- target.postMessage(data, transfer ?? []);
4609
- },
4610
- listen(handler) {
4611
- const h = (e) => {
4612
- if (e.source === target) handler(e.data);
4613
- };
4614
- navigator.serviceWorker.addEventListener("message", h);
4615
- return () => navigator.serviceWorker.removeEventListener("message", h);
4616
- }
4617
- };
4618
- }
4619
- throw new Error(
4620
- "createTransport: unsupported target type. Expected Worker, SharedWorker, ServiceWorker, BroadcastChannel, or MessagePort."
4621
- );
4622
- }
4623
-
4624
- // src/extra/worker/bridge.ts
4625
- function isTransport(t) {
4626
- return typeof t === "object" && t !== null && typeof t.post === "function" && typeof t.listen === "function";
4627
- }
4628
- function workerBridge(target, opts) {
4629
- const transport = isTransport(target) ? target : createTransport(target);
4630
- const bridgeName = opts.name ?? "workerBridge";
4631
- const exposeEntries = Object.entries(opts.expose ?? {});
4632
- const importNames = opts.import ?? [];
4633
- const transferFns = opts.transfer ?? {};
4634
- const statusNode = state("connecting", {
4635
- name: `${bridgeName}::meta::status`
4636
- });
4637
- const errorNode = state(null, {
4638
- name: `${bridgeName}::meta::error`
4639
- });
4640
- const proxyNodes = /* @__PURE__ */ new Map();
4641
- const lastSeenImportVersions = /* @__PURE__ */ new Map();
4642
- for (const name of importNames) {
4643
- const proxy = state(void 0, { name: `${bridgeName}::${name}` });
4644
- proxyNodes.set(name, proxy);
4645
- }
4646
- let effectUnsub;
4647
- if (exposeEntries.length > 0) {
4648
- const exposedNodes = exposeEntries.map(([, n]) => n);
4649
- const aggregated = node(
4650
- exposedNodes,
4651
- (data, a) => {
4652
- const updates = {};
4653
- for (let i = 0; i < exposeEntries.length; i++) {
4654
- const [name] = exposeEntries[i];
4655
- const batch0 = data[i];
4656
- if (batch0 != null && batch0.length > 0) {
4657
- updates[name] = batch0.at(-1);
4658
- }
4659
- }
4660
- if (Object.keys(updates).length === 0) return;
4661
- a.emit(updates);
4662
- },
4663
- // Each `updates` object is a fresh allocation, so default reference
4664
- // equality correctly propagates every aggregation wave — no
4665
- // `equals: () => false` override needed.
4666
- { name: `${bridgeName}::aggregated` }
4667
- );
4668
- const effectNode = effect([aggregated], (data) => {
4669
- const updates = data[0];
4670
- if (updates == null || Object.keys(updates).length === 0) return;
4671
- const transferList = [];
4672
- for (const name of Object.keys(updates)) {
4673
- const fn = transferFns[name];
4674
- if (fn) transferList.push(...fn(updates[name]));
4675
- }
4676
- let versions;
4677
- for (const [name, n] of exposeEntries) {
4678
- if (name in updates && n.v != null) {
4679
- if (versions == null) versions = {};
4680
- versions[name] = n.v.version;
4681
- }
4682
- }
4683
- const msg = { t: "b", u: updates, ...versions ? { v: versions } : {} };
4684
- try {
4685
- transport.post(msg, transferList.length > 0 ? transferList : void 0);
4686
- } catch (err) {
4687
- errorNode.down([[DATA, err instanceof Error ? err : new Error(String(err))]]);
4688
- }
4689
- });
4690
- effectUnsub = effectNode.subscribe(() => {
4691
- });
4692
- }
4693
- let destroyed = false;
4694
- const unlisten = transport.listen((data) => {
4695
- if (destroyed) return;
4696
- const msg = data;
4697
- switch (msg.t) {
4698
- // Worker ready — set proxy nodes with initial values.
4699
- // The handshake deadline auto-cancels via the reactive race
4700
- // (`statusNode → "connected"` wins) — no explicit clearTimeout.
4701
- case "r": {
4702
- batch(() => {
4703
- for (const [name, value] of Object.entries(msg.stores)) {
4704
- const proxy = proxyNodes.get(name);
4705
- if (proxy) proxy.down([[DATA, value]]);
4706
- }
4707
- });
4708
- statusNode.down([[DATA, "connected"]]);
4709
- const initValues = {};
4710
- for (const [name, n] of exposeEntries) {
4711
- initValues[name] = n.cache;
4712
- }
4713
- transport.post({ t: "i", stores: initValues });
4714
- break;
4715
- }
4716
- // Single value update from worker
4717
- case "v": {
4718
- const proxy = proxyNodes.get(msg.s);
4719
- if (proxy) proxy.down([[DATA, msg.d]]);
4720
- break;
4721
- }
4722
- // Batch value update from worker
4723
- case "b": {
4724
- batch(() => {
4725
- for (const [name, value] of Object.entries(msg.u)) {
4726
- const incomingVersion = msg.v?.[name];
4727
- if (incomingVersion != null) {
4728
- const lastSeen = lastSeenImportVersions.get(name);
4729
- if (lastSeen != null && incomingVersion <= lastSeen) continue;
4730
- lastSeenImportVersions.set(name, incomingVersion);
4731
- }
4732
- const proxy = proxyNodes.get(name);
4733
- if (proxy) proxy.down([[DATA, value]]);
4734
- }
4735
- });
4736
- break;
4737
- }
4738
- // Error from worker node
4739
- case "e": {
4740
- const proxy = proxyNodes.get(msg.s);
4741
- if (proxy) proxy.down([[ERROR, deserializeError(msg.err)]]);
4742
- break;
4743
- }
4744
- // Lifecycle signal from worker
4745
- case "s": {
4746
- const sig = nameToSignal(msg.sig);
4747
- if (!sig) break;
4748
- const targets = msg.s === "*" ? [...proxyNodes.values()] : proxyNodes.has(msg.s) ? [proxyNodes.get(msg.s)] : [];
4749
- for (const proxy of targets) {
4750
- proxy.down(msg.d === void 0 ? [[sig]] : [[sig, msg.d]]);
4751
- }
4752
- break;
4753
- }
4754
- }
4755
- });
4756
- const exposeUnsubs = [];
4757
- for (const [name, n] of exposeEntries) {
4758
- const unsub = n.subscribe(((msgs) => {
4759
- if (destroyed) return;
4760
- for (const m of msgs) {
4761
- const type = m[0];
4762
- if (type === DATA) continue;
4763
- if (defaultConfig.isLocalOnly(type)) continue;
4764
- if (type === ERROR) {
4765
- transport.post({
4766
- t: "e",
4767
- s: name,
4768
- err: serializeError(m[1])
4769
- });
4770
- } else {
4771
- transport.post({
4772
- t: "s",
4773
- s: name,
4774
- sig: signalToName(type),
4775
- d: m.length > 1 ? m[1] : void 0
4776
- });
4777
- }
4778
- }
4779
- }));
4780
- exposeUnsubs.push(unsub);
4781
- }
4782
- let handshakeUnsub;
4783
- if (opts.timeoutMs != null && opts.timeoutMs > 0) {
4784
- const deadline$ = fromTimer(opts.timeoutMs);
4785
- const ready$ = filter(statusNode, (s) => s === "connected");
4786
- const race$ = first(
4787
- merge(
4788
- map(deadline$, () => "timeout"),
4789
- map(ready$, () => "ready")
4790
- )
4791
- );
4792
- handshakeUnsub = race$.subscribe((msgs) => {
4793
- for (const m of msgs) {
4794
- if (m[0] === DATA && m[1] === "timeout") {
4795
- errorNode.down([[DATA, new Error("Worker bridge handshake timeout")]]);
4796
- destroy();
4797
- }
4798
- }
4799
- });
4800
- }
4801
- function destroy() {
4802
- if (destroyed) return;
4803
- destroyed = true;
4804
- handshakeUnsub?.();
4805
- transport.post({
4806
- t: "s",
4807
- s: "*",
4808
- sig: signalToName(TEARDOWN)
4809
- });
4810
- if (effectUnsub) effectUnsub();
4811
- for (const unsub of exposeUnsubs) unsub();
4812
- exposeUnsubs.length = 0;
4813
- unlisten();
4814
- statusNode.down([[DATA, "closed"]]);
4815
- lastSeenImportVersions.clear();
4816
- proxyNodes.clear();
4817
- }
4818
- const result = {
4819
- meta: { status: statusNode, error: errorNode },
4820
- destroy
4821
- };
4822
- for (const [name, proxy] of proxyNodes) {
4823
- result[name] = proxy;
4824
- }
4825
- return result;
4826
- }
4827
-
4828
- // src/extra/worker/self.ts
4829
- function isTransport2(t) {
4830
- return typeof t === "object" && t !== null && typeof t.post === "function" && typeof t.listen === "function";
4831
- }
4832
- function workerSelf(target, opts) {
4833
- const transport = isTransport2(target) ? target : createTransport(target);
4834
- const importNames = opts.import ?? [];
4835
- const transferFns = opts.transfer ?? {};
4836
- const proxyNodes = /* @__PURE__ */ new Map();
4837
- const lastSeenImportVersions = /* @__PURE__ */ new Map();
4838
- const importedObj = {};
4839
- for (const name of importNames) {
4840
- const s = state(void 0, { name: `worker::${name}` });
4841
- proxyNodes.set(name, s);
4842
- importedObj[name] = s;
4843
- }
4844
- const exposedNodes = opts.expose(importedObj);
4845
- const exposeEntries = Object.entries(exposedNodes);
4846
- let effectUnsub;
4847
- let destroyed = false;
4848
- if (exposeEntries.length > 0) {
4849
- const nodes = exposeEntries.map(([, n]) => n);
4850
- const aggregated = node(
4851
- nodes,
4852
- (data, a) => {
4853
- const updates = {};
4854
- for (let i = 0; i < exposeEntries.length; i++) {
4855
- const [name] = exposeEntries[i];
4856
- const batch0 = data[i];
4857
- if (batch0 != null && batch0.length > 0) {
4858
- updates[name] = batch0.at(-1);
4859
- }
4860
- }
4861
- if (Object.keys(updates).length === 0) return;
4862
- a.emit(updates);
4863
- },
4864
- // Fresh `updates` object per wave → default reference equality is
4865
- // correct; no `equals: () => false` override needed.
4866
- { name: "workerSelf::aggregated" }
4867
- );
4868
- const effectNode = effect([aggregated], (data) => {
4869
- if (destroyed) return;
4870
- const updates = data[0];
4871
- if (updates == null || Object.keys(updates).length === 0) return;
4872
- const transferList = [];
4873
- for (const name of Object.keys(updates)) {
4874
- const fn = transferFns[name];
4875
- if (fn) transferList.push(...fn(updates[name]));
4876
- }
4877
- let versions;
4878
- for (const [name, n] of exposeEntries) {
4879
- if (name in updates && n.v != null) {
4880
- if (versions == null) versions = {};
4881
- versions[name] = n.v.version;
4882
- }
4883
- }
4884
- const msg = { t: "b", u: updates, ...versions ? { v: versions } : {} };
4885
- try {
4886
- transport.post(msg, transferList.length > 0 ? transferList : void 0);
4887
- } catch (_err) {
4888
- }
4889
- });
4890
- effectUnsub = effectNode.subscribe(() => {
4891
- });
4892
- }
4893
- const exposeUnsubs = [];
4894
- for (const [name, n] of exposeEntries) {
4895
- const unsub = n.subscribe(((msgs) => {
4896
- if (destroyed) return;
4897
- for (const m of msgs) {
4898
- const type = m[0];
4899
- if (type === DATA) continue;
4900
- if (defaultConfig.isLocalOnly(type)) continue;
4901
- if (type === ERROR) {
4902
- transport.post({
4903
- t: "e",
4904
- s: name,
4905
- err: serializeError(m[1])
4906
- });
4907
- } else {
4908
- transport.post({
4909
- t: "s",
4910
- s: name,
4911
- sig: signalToName(type),
4912
- d: m.length > 1 ? m[1] : void 0
4913
- });
4914
- }
4915
- }
4916
- }));
4917
- exposeUnsubs.push(unsub);
4918
- }
4919
- const unlisten = transport.listen((data) => {
4920
- if (destroyed) return;
4921
- const msg = data;
4922
- switch (msg.t) {
4923
- // Init from main — set proxy node values
4924
- case "i": {
4925
- batch(() => {
4926
- for (const [name, value] of Object.entries(msg.stores)) {
4927
- const proxy = proxyNodes.get(name);
4928
- if (proxy) proxy.down([[DATA, value]]);
4929
- }
4930
- });
4931
- break;
4932
- }
4933
- // Single value update from main
4934
- case "v": {
4935
- const proxy = proxyNodes.get(msg.s);
4936
- if (proxy) proxy.down([[DATA, msg.d]]);
4937
- break;
4938
- }
4939
- // Batch value update from main
4940
- case "b": {
4941
- batch(() => {
4942
- for (const [name, value] of Object.entries(msg.u)) {
4943
- const incomingVersion = msg.v?.[name];
4944
- if (incomingVersion != null) {
4945
- const lastSeen = lastSeenImportVersions.get(name);
4946
- if (lastSeen != null && incomingVersion <= lastSeen) continue;
4947
- lastSeenImportVersions.set(name, incomingVersion);
4948
- }
4949
- const proxy = proxyNodes.get(name);
4950
- if (proxy) proxy.down([[DATA, value]]);
4951
- }
4952
- });
4953
- break;
4954
- }
4955
- // Error from main node
4956
- case "e": {
4957
- const proxy = proxyNodes.get(msg.s);
4958
- if (proxy) proxy.down([[ERROR, deserializeError(msg.err)]]);
4959
- break;
4960
- }
4961
- // Lifecycle signal from main
4962
- case "s": {
4963
- const sig = nameToSignal(msg.sig);
4964
- if (!sig) break;
4965
- if (sig === TEARDOWN && msg.s === "*") {
4966
- destroy();
4967
- return;
4968
- }
4969
- const targets = msg.s === "*" ? [...proxyNodes.values()] : proxyNodes.has(msg.s) ? [proxyNodes.get(msg.s)] : [];
4970
- for (const proxy of targets) {
4971
- proxy.down(msg.d === void 0 ? [[sig]] : [[sig, msg.d]]);
4972
- }
4973
- break;
4974
- }
4975
- }
4976
- });
4977
- const readyValues = {};
4978
- for (const [name, n] of exposeEntries) {
4979
- readyValues[name] = n.cache;
4980
- }
4981
- transport.post({ t: "r", stores: readyValues });
4982
- function destroy() {
4983
- if (destroyed) return;
4984
- destroyed = true;
4985
- if (effectUnsub) effectUnsub();
4986
- for (const unsub of exposeUnsubs) unsub();
4987
- exposeUnsubs.length = 0;
4988
- unlisten();
4989
- transport.terminate?.();
4990
- lastSeenImportVersions.clear();
4991
- proxyNodes.clear();
4992
- }
4993
- return { destroy };
4994
- }
4995
-
4996
- export {
4997
- externalProducer,
4998
- externalBundle,
4999
- reactiveSink,
5000
- retry,
5001
- retrySource,
5002
- CircuitOpenError,
5003
- circuitBreaker,
5004
- withBreaker,
5005
- tokenBucket,
5006
- RateLimiterOverflowError,
5007
- rateLimiter,
5008
- withStatus,
5009
- TimeoutError,
5010
- fallback,
5011
- timeout,
5012
- fromWebSocket,
5013
- fromWebhook,
5014
- fromHTTP,
5015
- toHTTP,
5016
- toSSE,
5017
- toSSEBytes,
5018
- toReadableStream,
5019
- fromSSE,
5020
- fromHTTPStream,
5021
- fromHTTPPoll,
5022
- toWebSocket,
5023
- fromWebSocketReconnect,
5024
- fromMCP,
5025
- fromGitHook,
5026
- fromOTel,
5027
- fromSyslog,
5028
- parseSyslog,
5029
- fromStatsD,
5030
- parseStatsD,
5031
- fromPrometheus,
5032
- parsePrometheusText,
5033
- fromKafka,
5034
- toKafka,
5035
- fromRedisStream,
5036
- toRedisStream,
5037
- fromCSV,
5038
- csvRows,
5039
- ndjsonRows,
5040
- fromNDJSON,
5041
- fromClickHouseWatch,
5042
- fromPulsar,
5043
- toPulsar,
5044
- fromNATS,
5045
- toNATS,
5046
- fromRabbitMQ,
5047
- toRabbitMQ,
5048
- toFile,
5049
- toCSV,
5050
- toClickHouse,
5051
- toS3,
5052
- toPostgres,
5053
- toMongo,
5054
- toLoki,
5055
- toTempo,
5056
- checkpointToS3,
5057
- checkpointToRedis,
5058
- fromSqlite,
5059
- fromSqliteCursor,
5060
- toSqlite,
5061
- fromPrisma,
5062
- fromDrizzle,
5063
- fromKysely,
5064
- lru,
5065
- cascadingCache,
5066
- NativePubSubBackend,
5067
- pubsub,
5068
- NativeIndexBackend,
5069
- reactiveIndex,
5070
- fromFSWatch,
5071
- memoryStorage,
5072
- dictStorage,
5073
- fileStorage,
5074
- sqliteStorage,
5075
- fromIDBRequest,
5076
- fromIDBTransaction,
5077
- indexedDbStorage,
5078
- signalToName,
5079
- nameToSignal,
5080
- serializeError,
5081
- deserializeError,
5082
- createTransport,
5083
- workerBridge,
5084
- workerSelf,
5085
- extra_exports
5086
- };
5087
- //# sourceMappingURL=chunk-BQ6RQQFF.js.map