@logixjs/core 0.0.1

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 (345) hide show
  1. package/dist/Action-BkRHy2vg.d.cts +10 -0
  2. package/dist/Action-mqVvtEHt.d.ts +10 -0
  3. package/dist/Action.cjs +57 -0
  4. package/dist/Action.cjs.map +1 -0
  5. package/dist/Action.d.cts +2 -0
  6. package/dist/Action.d.ts +2 -0
  7. package/dist/Action.js +9 -0
  8. package/dist/Action.js.map +1 -0
  9. package/dist/Actions-AsQ07yTP.d.cts +22 -0
  10. package/dist/Actions-AsQ07yTP.d.ts +22 -0
  11. package/dist/Actions.cjs +19 -0
  12. package/dist/Actions.cjs.map +1 -0
  13. package/dist/Actions.d.cts +2 -0
  14. package/dist/Actions.d.ts +2 -0
  15. package/dist/Actions.js +2 -0
  16. package/dist/Actions.js.map +1 -0
  17. package/dist/Bound-BN1DQ_lM.d.ts +23 -0
  18. package/dist/Bound-BPIfH9SS.d.cts +23 -0
  19. package/dist/Bound.cjs +1532 -0
  20. package/dist/Bound.cjs.map +1 -0
  21. package/dist/Bound.d.cts +7 -0
  22. package/dist/Bound.d.ts +7 -0
  23. package/dist/Bound.js +25 -0
  24. package/dist/Bound.js.map +1 -0
  25. package/dist/Debug-B5q5Bkzx.d.ts +320 -0
  26. package/dist/Debug-Bq8Sqjcr.d.cts +320 -0
  27. package/dist/Debug.cjs +1821 -0
  28. package/dist/Debug.cjs.map +1 -0
  29. package/dist/Debug.d.cts +13 -0
  30. package/dist/Debug.d.ts +13 -0
  31. package/dist/Debug.js +76 -0
  32. package/dist/Debug.js.map +1 -0
  33. package/dist/EffectOp.cjs +169 -0
  34. package/dist/EffectOp.cjs.map +1 -0
  35. package/dist/EffectOp.d.cts +118 -0
  36. package/dist/EffectOp.d.ts +118 -0
  37. package/dist/EffectOp.js +28 -0
  38. package/dist/EffectOp.js.map +1 -0
  39. package/dist/Env-DuJ6JrU2.d.cts +10 -0
  40. package/dist/Env-DuJ6JrU2.d.ts +10 -0
  41. package/dist/Env.cjs +60 -0
  42. package/dist/Env.cjs.map +1 -0
  43. package/dist/Env.d.cts +1 -0
  44. package/dist/Env.d.ts +1 -0
  45. package/dist/Env.js +11 -0
  46. package/dist/Env.js.map +1 -0
  47. package/dist/Flow-1fZT8MpX.d.cts +152 -0
  48. package/dist/Flow-BhpjE22E.d.ts +152 -0
  49. package/dist/Flow.cjs +504 -0
  50. package/dist/Flow.cjs.map +1 -0
  51. package/dist/Flow.d.cts +8 -0
  52. package/dist/Flow.d.ts +8 -0
  53. package/dist/Flow.js +15 -0
  54. package/dist/Flow.js.map +1 -0
  55. package/dist/Handle-D8D1zPb_.d.cts +30 -0
  56. package/dist/Handle-D_cLW1Z3.d.ts +30 -0
  57. package/dist/Handle.cjs +42 -0
  58. package/dist/Handle.cjs.map +1 -0
  59. package/dist/Handle.d.cts +7 -0
  60. package/dist/Handle.d.ts +7 -0
  61. package/dist/Handle.js +10 -0
  62. package/dist/Handle.js.map +1 -0
  63. package/dist/Kernel-8kC-jOda.d.cts +171 -0
  64. package/dist/Kernel-CnGE1Fyk.d.ts +171 -0
  65. package/dist/Kernel.cjs +284 -0
  66. package/dist/Kernel.cjs.map +1 -0
  67. package/dist/Kernel.d.cts +14 -0
  68. package/dist/Kernel.d.ts +14 -0
  69. package/dist/Kernel.js +36 -0
  70. package/dist/Kernel.js.map +1 -0
  71. package/dist/Link-Db7975nU.d.ts +45 -0
  72. package/dist/Link-fX8x1eCK.d.cts +45 -0
  73. package/dist/Link.cjs +542 -0
  74. package/dist/Link.cjs.map +1 -0
  75. package/dist/Link.d.cts +7 -0
  76. package/dist/Link.d.ts +7 -0
  77. package/dist/Link.js +35 -0
  78. package/dist/Link.js.map +1 -0
  79. package/dist/Logic-BRjEMr-W.d.ts +38 -0
  80. package/dist/Logic-DRh4sDZj.d.cts +38 -0
  81. package/dist/Logic.cjs +37 -0
  82. package/dist/Logic.cjs.map +1 -0
  83. package/dist/Logic.d.cts +7 -0
  84. package/dist/Logic.d.ts +7 -0
  85. package/dist/Logic.js +10 -0
  86. package/dist/Logic.js.map +1 -0
  87. package/dist/MatchBuilder-0QOc-nlU.d.ts +14 -0
  88. package/dist/MatchBuilder-CJk5oCkR.d.cts +14 -0
  89. package/dist/MatchBuilder.cjs +85 -0
  90. package/dist/MatchBuilder.cjs.map +1 -0
  91. package/dist/MatchBuilder.d.cts +8 -0
  92. package/dist/MatchBuilder.d.ts +8 -0
  93. package/dist/MatchBuilder.js +11 -0
  94. package/dist/MatchBuilder.js.map +1 -0
  95. package/dist/Middleware.cjs +411 -0
  96. package/dist/Middleware.cjs.map +1 -0
  97. package/dist/Middleware.d.cts +88 -0
  98. package/dist/Middleware.d.ts +88 -0
  99. package/dist/Middleware.js +27 -0
  100. package/dist/Middleware.js.map +1 -0
  101. package/dist/Module-B_0xRDMR.d.cts +203 -0
  102. package/dist/Module-DnzluX2J.d.ts +203 -0
  103. package/dist/Module.cjs +13512 -0
  104. package/dist/Module.cjs.map +1 -0
  105. package/dist/Module.d.cts +8 -0
  106. package/dist/Module.d.ts +8 -0
  107. package/dist/Module.js +53 -0
  108. package/dist/Module.js.map +1 -0
  109. package/dist/ModuleTag-C8FHY_sY.d.ts +93 -0
  110. package/dist/ModuleTag-EGbgBMpZ.d.cts +93 -0
  111. package/dist/ModuleTag.cjs +12231 -0
  112. package/dist/ModuleTag.cjs.map +1 -0
  113. package/dist/ModuleTag.d.cts +8 -0
  114. package/dist/ModuleTag.d.ts +8 -0
  115. package/dist/ModuleTag.js +39 -0
  116. package/dist/ModuleTag.js.map +1 -0
  117. package/dist/Observability-COqEvp2C.d.cts +713 -0
  118. package/dist/Observability-cY4kLn0S.d.ts +713 -0
  119. package/dist/Observability.cjs +5865 -0
  120. package/dist/Observability.cjs.map +1 -0
  121. package/dist/Observability.d.cts +9 -0
  122. package/dist/Observability.d.ts +9 -0
  123. package/dist/Observability.js +41 -0
  124. package/dist/Observability.js.map +1 -0
  125. package/dist/Platform-C49Pv956.d.cts +21 -0
  126. package/dist/Platform-C49Pv956.d.ts +21 -0
  127. package/dist/Platform-CHX8o-U4.d.ts +51 -0
  128. package/dist/Platform-CVlv0xLQ.d.cts +51 -0
  129. package/dist/Platform.cjs +58 -0
  130. package/dist/Platform.cjs.map +1 -0
  131. package/dist/Platform.d.cts +4 -0
  132. package/dist/Platform.d.ts +4 -0
  133. package/dist/Platform.js +15 -0
  134. package/dist/Platform.js.map +1 -0
  135. package/dist/Process-CM9xbMdP.d.ts +92 -0
  136. package/dist/Process-mL8fHDSB.d.cts +92 -0
  137. package/dist/Process.cjs +575 -0
  138. package/dist/Process.cjs.map +1 -0
  139. package/dist/Process.d.cts +8 -0
  140. package/dist/Process.d.ts +8 -0
  141. package/dist/Process.js +42 -0
  142. package/dist/Process.js.map +1 -0
  143. package/dist/ReadQuery-BlMwhe-F.d.ts +30 -0
  144. package/dist/ReadQuery-CL5XlXts.d.cts +30 -0
  145. package/dist/ReadQuery-SinbStGF.d.cts +38 -0
  146. package/dist/ReadQuery-SinbStGF.d.ts +38 -0
  147. package/dist/ReadQuery.cjs +377 -0
  148. package/dist/ReadQuery.cjs.map +1 -0
  149. package/dist/ReadQuery.d.cts +2 -0
  150. package/dist/ReadQuery.d.ts +2 -0
  151. package/dist/ReadQuery.js +14 -0
  152. package/dist/ReadQuery.js.map +1 -0
  153. package/dist/Reflection-CQnKwPXj.d.ts +182 -0
  154. package/dist/Reflection-Kabo1mlU.d.cts +182 -0
  155. package/dist/Reflection.cjs +2954 -0
  156. package/dist/Reflection.cjs.map +1 -0
  157. package/dist/Reflection.d.cts +17 -0
  158. package/dist/Reflection.d.ts +17 -0
  159. package/dist/Reflection.js +40 -0
  160. package/dist/Reflection.js.map +1 -0
  161. package/dist/Resource-Dy1xD_DG.d.cts +75 -0
  162. package/dist/Resource-Dy1xD_DG.d.ts +75 -0
  163. package/dist/Resource.cjs +166 -0
  164. package/dist/Resource.cjs.map +1 -0
  165. package/dist/Resource.d.cts +3 -0
  166. package/dist/Resource.d.ts +3 -0
  167. package/dist/Resource.js +21 -0
  168. package/dist/Resource.js.map +1 -0
  169. package/dist/Root-7ADUMk4t.d.cts +29 -0
  170. package/dist/Root-7ADUMk4t.d.ts +29 -0
  171. package/dist/Root.cjs +125 -0
  172. package/dist/Root.cjs.map +1 -0
  173. package/dist/Root.d.cts +4 -0
  174. package/dist/Root.d.ts +4 -0
  175. package/dist/Root.js +12 -0
  176. package/dist/Root.js.map +1 -0
  177. package/dist/Runtime-B-aL-f29.d.cts +274 -0
  178. package/dist/Runtime-CtyzZG4i.d.ts +274 -0
  179. package/dist/Runtime.cjs +5740 -0
  180. package/dist/Runtime.cjs.map +1 -0
  181. package/dist/Runtime.d.cts +19 -0
  182. package/dist/Runtime.d.ts +19 -0
  183. package/dist/Runtime.js +62 -0
  184. package/dist/Runtime.js.map +1 -0
  185. package/dist/ScopeRegistry-D1owDNSm.d.cts +61 -0
  186. package/dist/ScopeRegistry-D1owDNSm.d.ts +61 -0
  187. package/dist/ScopeRegistry.cjs +152 -0
  188. package/dist/ScopeRegistry.cjs.map +1 -0
  189. package/dist/ScopeRegistry.d.cts +2 -0
  190. package/dist/ScopeRegistry.d.ts +2 -0
  191. package/dist/ScopeRegistry.js +16 -0
  192. package/dist/ScopeRegistry.js.map +1 -0
  193. package/dist/State-CU50R26M.d.cts +19 -0
  194. package/dist/State-CU50R26M.d.ts +19 -0
  195. package/dist/State.cjs +19 -0
  196. package/dist/State.cjs.map +1 -0
  197. package/dist/State.d.cts +2 -0
  198. package/dist/State.d.ts +2 -0
  199. package/dist/State.js +2 -0
  200. package/dist/State.js.map +1 -0
  201. package/dist/StateTrait-BGsZghTz.d.ts +122 -0
  202. package/dist/StateTrait-OWhbj12c.d.cts +122 -0
  203. package/dist/StateTrait.cjs +2737 -0
  204. package/dist/StateTrait.cjs.map +1 -0
  205. package/dist/StateTrait.d.cts +9 -0
  206. package/dist/StateTrait.d.ts +9 -0
  207. package/dist/StateTrait.js +39 -0
  208. package/dist/StateTrait.js.map +1 -0
  209. package/dist/TraitLifecycle-CwV5WPFX.d.cts +88 -0
  210. package/dist/TraitLifecycle-LdIWmKlg.d.ts +88 -0
  211. package/dist/TraitLifecycle.cjs +581 -0
  212. package/dist/TraitLifecycle.cjs.map +1 -0
  213. package/dist/TraitLifecycle.d.cts +8 -0
  214. package/dist/TraitLifecycle.d.ts +8 -0
  215. package/dist/TraitLifecycle.js +24 -0
  216. package/dist/TraitLifecycle.js.map +1 -0
  217. package/dist/action-DiMDD_0v.d.cts +35 -0
  218. package/dist/action-DiMDD_0v.d.ts +35 -0
  219. package/dist/chunk-24VULZ7A.js +76 -0
  220. package/dist/chunk-24VULZ7A.js.map +1 -0
  221. package/dist/chunk-3IYZ5IGG.js +17 -0
  222. package/dist/chunk-3IYZ5IGG.js.map +1 -0
  223. package/dist/chunk-3QMIVH35.js +43 -0
  224. package/dist/chunk-3QMIVH35.js.map +1 -0
  225. package/dist/chunk-3RMKLXHX.js +83 -0
  226. package/dist/chunk-3RMKLXHX.js.map +1 -0
  227. package/dist/chunk-3TMODYZV.js +111 -0
  228. package/dist/chunk-3TMODYZV.js.map +1 -0
  229. package/dist/chunk-3VG5TWQR.js +27 -0
  230. package/dist/chunk-3VG5TWQR.js.map +1 -0
  231. package/dist/chunk-4CQAV7YB.js +37 -0
  232. package/dist/chunk-4CQAV7YB.js.map +1 -0
  233. package/dist/chunk-4SO6JMZL.js +7 -0
  234. package/dist/chunk-4SO6JMZL.js.map +1 -0
  235. package/dist/chunk-66ALHVEX.js +40 -0
  236. package/dist/chunk-66ALHVEX.js.map +1 -0
  237. package/dist/chunk-76WT3HOR.js +397 -0
  238. package/dist/chunk-76WT3HOR.js.map +1 -0
  239. package/dist/chunk-ANLBCBDC.js +285 -0
  240. package/dist/chunk-ANLBCBDC.js.map +1 -0
  241. package/dist/chunk-AUIR5O6W.js +75 -0
  242. package/dist/chunk-AUIR5O6W.js.map +1 -0
  243. package/dist/chunk-BABLDP24.js +445 -0
  244. package/dist/chunk-BABLDP24.js.map +1 -0
  245. package/dist/chunk-BE3HW4FY.js +1099 -0
  246. package/dist/chunk-BE3HW4FY.js.map +1 -0
  247. package/dist/chunk-BZ2SHDN2.js +54 -0
  248. package/dist/chunk-BZ2SHDN2.js.map +1 -0
  249. package/dist/chunk-CW6T36TN.js +393 -0
  250. package/dist/chunk-CW6T36TN.js.map +1 -0
  251. package/dist/chunk-DFNM3WX2.js +632 -0
  252. package/dist/chunk-DFNM3WX2.js.map +1 -0
  253. package/dist/chunk-DMBALCE2.js +1034 -0
  254. package/dist/chunk-DMBALCE2.js.map +1 -0
  255. package/dist/chunk-EGK3KN7B.js +406 -0
  256. package/dist/chunk-EGK3KN7B.js.map +1 -0
  257. package/dist/chunk-EY4NZKDR.js +19 -0
  258. package/dist/chunk-EY4NZKDR.js.map +1 -0
  259. package/dist/chunk-G5ZBFPNU.js +23 -0
  260. package/dist/chunk-G5ZBFPNU.js.map +1 -0
  261. package/dist/chunk-GMPEOUP2.js +31 -0
  262. package/dist/chunk-GMPEOUP2.js.map +1 -0
  263. package/dist/chunk-IHVBV5C2.js +279 -0
  264. package/dist/chunk-IHVBV5C2.js.map +1 -0
  265. package/dist/chunk-IPF7E66P.js +23 -0
  266. package/dist/chunk-IPF7E66P.js.map +1 -0
  267. package/dist/chunk-JCXGZRMU.js +204 -0
  268. package/dist/chunk-JCXGZRMU.js.map +1 -0
  269. package/dist/chunk-JGIWG6SR.js +6359 -0
  270. package/dist/chunk-JGIWG6SR.js.map +1 -0
  271. package/dist/chunk-JWOYLO27.js +241 -0
  272. package/dist/chunk-JWOYLO27.js.map +1 -0
  273. package/dist/chunk-KIXAU3GM.js +137 -0
  274. package/dist/chunk-KIXAU3GM.js.map +1 -0
  275. package/dist/chunk-KL5ACTCT.js +8 -0
  276. package/dist/chunk-KL5ACTCT.js.map +1 -0
  277. package/dist/chunk-KP7MUZNX.js +83 -0
  278. package/dist/chunk-KP7MUZNX.js.map +1 -0
  279. package/dist/chunk-LEU6UA5J.js +1 -0
  280. package/dist/chunk-LEU6UA5J.js.map +1 -0
  281. package/dist/chunk-M2RGJPXX.js +35 -0
  282. package/dist/chunk-M2RGJPXX.js.map +1 -0
  283. package/dist/chunk-M3BFQ7HK.js +13 -0
  284. package/dist/chunk-M3BFQ7HK.js.map +1 -0
  285. package/dist/chunk-M3WTHJHJ.js +1051 -0
  286. package/dist/chunk-M3WTHJHJ.js.map +1 -0
  287. package/dist/chunk-M7IYCTJV.js +79 -0
  288. package/dist/chunk-M7IYCTJV.js.map +1 -0
  289. package/dist/chunk-NBD3KUOZ.js +838 -0
  290. package/dist/chunk-NBD3KUOZ.js.map +1 -0
  291. package/dist/chunk-NQZ2OSGR.js +151 -0
  292. package/dist/chunk-NQZ2OSGR.js.map +1 -0
  293. package/dist/chunk-NZJKFF45.js +106 -0
  294. package/dist/chunk-NZJKFF45.js.map +1 -0
  295. package/dist/chunk-OFADUJWJ.js +175 -0
  296. package/dist/chunk-OFADUJWJ.js.map +1 -0
  297. package/dist/chunk-OGWBVHB3.js +461 -0
  298. package/dist/chunk-OGWBVHB3.js.map +1 -0
  299. package/dist/chunk-PAYXCY6A.js +1696 -0
  300. package/dist/chunk-PAYXCY6A.js.map +1 -0
  301. package/dist/chunk-PYOE4VSI.js +1924 -0
  302. package/dist/chunk-PYOE4VSI.js.map +1 -0
  303. package/dist/chunk-PZ5AY32C.js +10 -0
  304. package/dist/chunk-PZ5AY32C.js.map +1 -0
  305. package/dist/chunk-QCHIQWAJ.js +21 -0
  306. package/dist/chunk-QCHIQWAJ.js.map +1 -0
  307. package/dist/chunk-QMM6O4CD.js +71 -0
  308. package/dist/chunk-QMM6O4CD.js.map +1 -0
  309. package/dist/chunk-RNFE3ML2.js +22 -0
  310. package/dist/chunk-RNFE3ML2.js.map +1 -0
  311. package/dist/chunk-TAAPQVZN.js +23 -0
  312. package/dist/chunk-TAAPQVZN.js.map +1 -0
  313. package/dist/chunk-THATMZXD.js +21 -0
  314. package/dist/chunk-THATMZXD.js.map +1 -0
  315. package/dist/chunk-TKZ7MEIA.js +27 -0
  316. package/dist/chunk-TKZ7MEIA.js.map +1 -0
  317. package/dist/chunk-TQOBJYDP.js +7 -0
  318. package/dist/chunk-TQOBJYDP.js.map +1 -0
  319. package/dist/chunk-VZB726PE.js +93 -0
  320. package/dist/chunk-VZB726PE.js.map +1 -0
  321. package/dist/chunk-W3TEWHLO.js +568 -0
  322. package/dist/chunk-W3TEWHLO.js.map +1 -0
  323. package/dist/chunk-YS3AZQ2G.js +52 -0
  324. package/dist/chunk-YS3AZQ2G.js.map +1 -0
  325. package/dist/chunk-ZDTRWK5F.js +40 -0
  326. package/dist/chunk-ZDTRWK5F.js.map +1 -0
  327. package/dist/chunk-ZFLHVFUC.js +192 -0
  328. package/dist/chunk-ZFLHVFUC.js.map +1 -0
  329. package/dist/chunk-ZFY7U2FR.js +133 -0
  330. package/dist/chunk-ZFY7U2FR.js.map +1 -0
  331. package/dist/chunk-ZGDVUPTM.js +270 -0
  332. package/dist/chunk-ZGDVUPTM.js.map +1 -0
  333. package/dist/index.cjs +19700 -0
  334. package/dist/index.cjs.map +1 -0
  335. package/dist/index.d.cts +195 -0
  336. package/dist/index.d.ts +195 -0
  337. package/dist/index.js +286 -0
  338. package/dist/index.js.map +1 -0
  339. package/dist/ir-BMP7yxJJ.d.cts +39 -0
  340. package/dist/ir-DUOz6H-5.d.ts +39 -0
  341. package/dist/module-B8CBqIZ_.d.cts +1191 -0
  342. package/dist/module-k7m3txak.d.ts +1191 -0
  343. package/dist/protocol-g_1897M2.d.cts +127 -0
  344. package/dist/protocol-g_1897M2.d.ts +127 -0
  345. package/package.json +162 -0
@@ -0,0 +1,2737 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from2, except, desc) => {
13
+ if (from2 && typeof from2 === "object" || typeof from2 === "function") {
14
+ for (let key of __getOwnPropNames(from2))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/StateTrait.ts
31
+ var StateTrait_exports = {};
32
+ __export(StateTrait_exports, {
33
+ $root: () => $root,
34
+ build: () => build2,
35
+ computed: () => computed,
36
+ exportStaticIr: () => exportStaticIr2,
37
+ from: () => from,
38
+ install: () => install2,
39
+ link: () => link,
40
+ list: () => list,
41
+ node: () => node,
42
+ source: () => source
43
+ });
44
+ module.exports = __toCommonJS(StateTrait_exports);
45
+
46
+ // src/internal/state-trait/rowid.ts
47
+ var parseSegments = (path) => {
48
+ if (!path) return [];
49
+ return path.split(".").map((seg) => /^[0-9]+$/.test(seg) ? Number(seg) : seg);
50
+ };
51
+ var getAtPath = (state, path) => {
52
+ if (!path || state == null) return state;
53
+ const segments = parseSegments(path);
54
+ let current = state;
55
+ for (const seg of segments) {
56
+ if (current == null) return void 0;
57
+ if (typeof seg === "number") {
58
+ current = Array.isArray(current) ? current[seg] : current[String(seg)];
59
+ continue;
60
+ }
61
+ current = current[seg];
62
+ }
63
+ return current;
64
+ };
65
+ var setAtPathMutating = (draft, path, value) => {
66
+ if (!path) return;
67
+ const segments = parseSegments(path);
68
+ if (segments.length === 0) return;
69
+ let current = draft;
70
+ for (let i = 0; i < segments.length - 1; i++) {
71
+ const key = segments[i];
72
+ const nextKey = segments[i + 1];
73
+ const next = current?.[key];
74
+ if (next == null || typeof next !== "object") {
75
+ current[key] = typeof nextKey === "number" ? [] : {};
76
+ }
77
+ current = current[key];
78
+ }
79
+ const last = segments[segments.length - 1];
80
+ current[last] = value;
81
+ };
82
+ var parseListItemFieldPath = (fieldPath) => {
83
+ const raw = typeof fieldPath === "string" ? fieldPath.trim() : "";
84
+ if (!raw) return void 0;
85
+ const segments = raw.split(".").filter(Boolean);
86
+ let lastListSeg = -1;
87
+ for (let i = 0; i < segments.length; i++) {
88
+ if (segments[i].endsWith("[]")) lastListSeg = i;
89
+ }
90
+ if (lastListSeg < 0) return void 0;
91
+ const strip = (seg) => seg.endsWith("[]") ? seg.slice(0, -2) : seg;
92
+ const listPath = segments.slice(0, lastListSeg + 1).map(strip).join(".");
93
+ const itemPath = segments.slice(lastListSeg + 1).map(strip).join(".");
94
+ return { listPath, itemPath };
95
+ };
96
+ var toListItemValuePath = (listPath, index, itemPath) => itemPath ? `${listPath}.${index}.${itemPath}` : `${listPath}.${index}`;
97
+
98
+ // src/internal/state-trait/build.ts
99
+ var SchemaAST = __toESM(require("effect/SchemaAST"), 1);
100
+
101
+ // src/internal/state-trait/meta.ts
102
+ var uniqSortedStrings = (input) => {
103
+ const set = /* @__PURE__ */ new Set();
104
+ for (const item of input) {
105
+ const v = item.trim();
106
+ if (!v) continue;
107
+ set.add(v);
108
+ }
109
+ return Array.from(set).sort((a, b) => a.localeCompare(b));
110
+ };
111
+ var isPlainRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
112
+ var sanitizeJsonValue = (input, depth) => {
113
+ if (input === null) return null;
114
+ if (typeof input === "string") return input;
115
+ if (typeof input === "boolean") return input;
116
+ if (typeof input === "number") {
117
+ return Number.isFinite(input) ? input : void 0;
118
+ }
119
+ if (depth >= 6) return void 0;
120
+ if (Array.isArray(input)) {
121
+ const out = [];
122
+ for (const item of input) {
123
+ const v = sanitizeJsonValue(item, depth + 1);
124
+ if (v !== void 0) out.push(v);
125
+ }
126
+ return out;
127
+ }
128
+ if (isPlainRecord(input)) {
129
+ const keys = Object.keys(input).sort();
130
+ const out = {};
131
+ for (const key of keys) {
132
+ const v = sanitizeJsonValue(input[key], depth + 1);
133
+ if (v !== void 0) out[key] = v;
134
+ }
135
+ return out;
136
+ }
137
+ return void 0;
138
+ };
139
+ var sanitize = (input) => {
140
+ if (input === null || input === void 0) return void 0;
141
+ if (typeof input !== "object" || Array.isArray(input)) return void 0;
142
+ const record2 = input;
143
+ const out = {};
144
+ const pickString = (key) => {
145
+ const value = record2[key];
146
+ if (typeof value !== "string") return;
147
+ const trimmed = value.trim();
148
+ if (!trimmed) return;
149
+ out[key] = trimmed;
150
+ };
151
+ pickString("label");
152
+ pickString("description");
153
+ pickString("group");
154
+ pickString("docsUrl");
155
+ pickString("cacheGroup");
156
+ const canonical = record2.canonical;
157
+ if (typeof canonical === "boolean") {
158
+ out.canonical = canonical;
159
+ }
160
+ const tagsRaw = record2.tags;
161
+ if (typeof tagsRaw === "string") {
162
+ const tags = uniqSortedStrings([tagsRaw]);
163
+ if (tags.length > 0) out.tags = tags;
164
+ } else if (Array.isArray(tagsRaw)) {
165
+ const tags = uniqSortedStrings(tagsRaw.filter((x) => typeof x === "string"));
166
+ if (tags.length > 0) out.tags = tags;
167
+ }
168
+ const annotations = {};
169
+ const annotationKeys = Object.keys(record2).filter((k) => k.startsWith("x-")).sort((a, b) => a.localeCompare(b));
170
+ for (const key of annotationKeys) {
171
+ const v = sanitizeJsonValue(record2[key], 0);
172
+ if (v !== void 0) annotations[key] = v;
173
+ }
174
+ const annotationsRaw = record2.annotations;
175
+ if (isPlainRecord(annotationsRaw)) {
176
+ const keys = Object.keys(annotationsRaw).filter((k) => k.startsWith("x-")).sort((a, b) => a.localeCompare(b));
177
+ for (const key of keys) {
178
+ const v = sanitizeJsonValue(annotationsRaw[key], 0);
179
+ if (v !== void 0) annotations[key] = v;
180
+ }
181
+ }
182
+ if (Object.keys(annotations).length > 0) out.annotations = annotations;
183
+ return Object.keys(out).length > 0 ? out : void 0;
184
+ };
185
+ var stableStringify = (meta) => {
186
+ const out = {};
187
+ const keys = Object.keys(meta).sort();
188
+ for (const k of keys) {
189
+ out[k] = meta[k];
190
+ }
191
+ return JSON.stringify(out);
192
+ };
193
+ var equals = (a, b) => {
194
+ if (a === b) return true;
195
+ if (!a || !b) return false;
196
+ return stableStringify(a) === stableStringify(b);
197
+ };
198
+ var mergeCanonical = (current, incoming) => {
199
+ const existing = current.meta;
200
+ if (!existing) {
201
+ return {
202
+ meta: incoming.meta,
203
+ origin: incoming.origin,
204
+ conflicts: current.conflicts
205
+ };
206
+ }
207
+ if (equals(existing, incoming.meta)) {
208
+ return current;
209
+ }
210
+ const conflicts = [...current.conflicts ?? []];
211
+ const push = (conflict) => {
212
+ const exists = conflicts.some((c) => c.origin === conflict.origin && equals(c.meta, conflict.meta));
213
+ if (!exists) conflicts.push(conflict);
214
+ };
215
+ const existingCanonical = existing.canonical === true;
216
+ const incomingCanonical = incoming.meta.canonical === true;
217
+ if (!existingCanonical && incomingCanonical) {
218
+ push({
219
+ origin: current.origin ?? "unknown",
220
+ meta: existing
221
+ });
222
+ return {
223
+ meta: incoming.meta,
224
+ origin: incoming.origin,
225
+ conflicts
226
+ };
227
+ }
228
+ push({
229
+ origin: incoming.origin,
230
+ meta: incoming.meta
231
+ });
232
+ return {
233
+ meta: existing,
234
+ origin: current.origin ?? incoming.origin,
235
+ conflicts
236
+ };
237
+ };
238
+
239
+ // src/internal/state-trait/model.ts
240
+ var normalizeSpec = (spec) => {
241
+ const entries = [];
242
+ const isNode = (value) => typeof value === "object" && value !== null && value._tag === "StateTraitNode";
243
+ const isList = (value) => typeof value === "object" && value !== null && value._tag === "StateTraitList";
244
+ const joinPath = (prefix, suffix) => {
245
+ if (!prefix) return suffix;
246
+ if (!suffix) return prefix;
247
+ return `${prefix}.${suffix}`;
248
+ };
249
+ const prefixDeps = (deps, prefix) => {
250
+ if (!deps || deps.length === 0) return [];
251
+ return deps.map((d) => prefix ? joinPath(prefix, d) : d);
252
+ };
253
+ const normalizeEntry = (entry, fieldPath, depPrefix) => {
254
+ if (entry.kind === "computed") {
255
+ const meta = entry.meta;
256
+ const rawDeps = meta.deps;
257
+ const deps = rawDeps !== void 0 ? prefixDeps(rawDeps, depPrefix) : void 0;
258
+ return {
259
+ ...entry,
260
+ fieldPath,
261
+ meta: { ...meta, deps }
262
+ };
263
+ }
264
+ if (entry.kind === "source") {
265
+ const meta = entry.meta;
266
+ const rawDeps = meta.deps;
267
+ const deps = rawDeps !== void 0 ? prefixDeps(rawDeps, depPrefix) : void 0;
268
+ return {
269
+ ...entry,
270
+ fieldPath,
271
+ meta: { ...meta, deps, _fieldPath: fieldPath }
272
+ };
273
+ }
274
+ if (entry.kind === "link") {
275
+ const meta = entry.meta;
276
+ const from2 = prefixDeps([meta.from], depPrefix)[0] ?? meta.from;
277
+ return {
278
+ ...entry,
279
+ fieldPath,
280
+ meta: { ...meta, from: from2 }
281
+ };
282
+ }
283
+ return {
284
+ ...entry,
285
+ fieldPath
286
+ };
287
+ };
288
+ const expandNode = (scopeId, joinPrefix, node2, options) => {
289
+ const addEntry = (relativeTarget, raw) => {
290
+ const rel = raw.fieldPath ?? relativeTarget;
291
+ const fieldPath = joinPrefix ? joinPath(joinPrefix, String(rel)) : String(rel);
292
+ entries.push(normalizeEntry(raw, fieldPath, joinPrefix));
293
+ };
294
+ const expandMaybeRecord = (value) => {
295
+ if (!value) return;
296
+ if (typeof value.kind === "string") {
297
+ addEntry("", value);
298
+ return;
299
+ }
300
+ const record2 = value;
301
+ for (const key in record2) {
302
+ if (!Object.prototype.hasOwnProperty.call(record2, key)) continue;
303
+ const entry = record2[key];
304
+ if (!entry) continue;
305
+ addEntry(key, entry);
306
+ }
307
+ };
308
+ expandMaybeRecord(node2.computed);
309
+ expandMaybeRecord(node2.source);
310
+ expandMaybeRecord(node2.link);
311
+ if (node2.check) {
312
+ const rules = {};
313
+ const checkDepsPrefix = options?.checkDepsPrefix ?? (joinPrefix.endsWith("[]") ? joinPrefix : "");
314
+ const prefixCheckDeps = (deps) => {
315
+ if (!deps || deps.length === 0) return [];
316
+ return deps.map((d) => d === "" ? scopeId : checkDepsPrefix ? joinPath(checkDepsPrefix, d) : d);
317
+ };
318
+ for (const name of Object.keys(node2.check)) {
319
+ const rule = node2.check[name];
320
+ if (typeof rule === "function") {
321
+ rules[name] = rule;
322
+ continue;
323
+ }
324
+ if (rule && typeof rule === "object") {
325
+ const meta = sanitize(rule.meta);
326
+ rules[name] = {
327
+ ...rule,
328
+ deps: prefixCheckDeps(rule.deps),
329
+ meta
330
+ };
331
+ continue;
332
+ }
333
+ }
334
+ entries.push({
335
+ fieldPath: scopeId,
336
+ kind: "check",
337
+ meta: {
338
+ rules,
339
+ writeback: { kind: "errors" }
340
+ }
341
+ });
342
+ }
343
+ };
344
+ for (const key in spec) {
345
+ if (!Object.prototype.hasOwnProperty.call(spec, key)) continue;
346
+ const raw = spec[key];
347
+ if (!raw) continue;
348
+ if (isList(raw)) {
349
+ const listPath = key;
350
+ if (raw.item) {
351
+ expandNode(`${listPath}[]`, `${listPath}[]`, raw.item);
352
+ }
353
+ if (raw.list) {
354
+ expandNode(listPath, listPath, raw.list, {
355
+ checkDepsPrefix: `${listPath}[]`
356
+ });
357
+ }
358
+ continue;
359
+ }
360
+ if (isNode(raw)) {
361
+ if (key === "$root") {
362
+ expandNode("$root", "", raw);
363
+ } else {
364
+ expandNode(key, key, raw);
365
+ }
366
+ continue;
367
+ }
368
+ const entry = raw;
369
+ const fieldPath = entry.fieldPath ?? key;
370
+ entries.push(normalizeEntry(entry, String(fieldPath), ""));
371
+ }
372
+ return entries;
373
+ };
374
+ var collectNodeMeta = (spec) => {
375
+ const out = /* @__PURE__ */ new Map();
376
+ const isNode = (value) => typeof value === "object" && value !== null && value._tag === "StateTraitNode";
377
+ const isList = (value) => typeof value === "object" && value !== null && value._tag === "StateTraitList";
378
+ const add = (scopeId, node2) => {
379
+ const meta = sanitize(node2.meta);
380
+ if (meta) out.set(scopeId, meta);
381
+ };
382
+ for (const key in spec) {
383
+ if (!Object.prototype.hasOwnProperty.call(spec, key)) continue;
384
+ const raw = spec[key];
385
+ if (!raw) continue;
386
+ if (isList(raw)) {
387
+ const listPath = key;
388
+ if (raw.item) add(`${listPath}[]`, raw.item);
389
+ if (raw.list) add(listPath, raw.list);
390
+ continue;
391
+ }
392
+ if (isNode(raw)) {
393
+ if (key === "$root") add("$root", raw);
394
+ else add(key, raw);
395
+ continue;
396
+ }
397
+ }
398
+ return out;
399
+ };
400
+
401
+ // src/internal/field-path.ts
402
+ var isFieldPathSegment = (seg) => {
403
+ if (!seg) return false;
404
+ if (seg === "*") return false;
405
+ if (/^\d+$/.test(seg)) return false;
406
+ if (seg.includes("[") || seg.includes("]")) return false;
407
+ return true;
408
+ };
409
+ var normalizeFieldPath = (input) => {
410
+ if (typeof input === "string") {
411
+ const segs = splitSegments(input);
412
+ if (!segs || segs.length === 0) return void 0;
413
+ const normalized2 = segs.filter(isFieldPathSegment);
414
+ return normalized2.length > 0 ? normalized2 : void 0;
415
+ }
416
+ if (input.length === 0) return void 0;
417
+ let needsFilter = false;
418
+ for (const seg of input) {
419
+ if (!isFieldPathSegment(seg)) {
420
+ needsFilter = true;
421
+ break;
422
+ }
423
+ }
424
+ if (!needsFilter) return input;
425
+ const normalized = input.filter(isFieldPathSegment);
426
+ return normalized.length > 0 ? normalized : void 0;
427
+ };
428
+ var compareFieldPath = (a, b) => {
429
+ const len = Math.min(a.length, b.length);
430
+ for (let i = 0; i < len; i++) {
431
+ const as = a[i];
432
+ const bs = b[i];
433
+ if (as === bs) continue;
434
+ return as < bs ? -1 : 1;
435
+ }
436
+ return a.length - b.length;
437
+ };
438
+ var makeFieldPathIdRegistry = (fieldPaths) => {
439
+ const root = { children: /* @__PURE__ */ new Map() };
440
+ const pathStringToId = /* @__PURE__ */ new Map();
441
+ const ambiguousPathStrings = /* @__PURE__ */ new Set();
442
+ for (let id = 0; id < fieldPaths.length; id++) {
443
+ const path = fieldPaths[id];
444
+ let node2 = root;
445
+ for (const seg of path) {
446
+ const children = node2.children;
447
+ let next = children.get(seg);
448
+ if (!next) {
449
+ next = { children: /* @__PURE__ */ new Map() };
450
+ children.set(seg, next);
451
+ }
452
+ node2 = next;
453
+ }
454
+ node2.id = id;
455
+ if (path.length > 0 && path.some((seg) => seg.includes("."))) {
456
+ const key = path.join(".");
457
+ ambiguousPathStrings.add(key);
458
+ pathStringToId.delete(key);
459
+ }
460
+ if (path.length > 0 && path.every((seg) => !seg.includes(".") && !seg.includes("[") && !seg.includes("]"))) {
461
+ const key = path.join(".");
462
+ if (ambiguousPathStrings.has(key)) continue;
463
+ if (pathStringToId.has(key)) {
464
+ ambiguousPathStrings.add(key);
465
+ pathStringToId.delete(key);
466
+ continue;
467
+ }
468
+ pathStringToId.set(key, id);
469
+ }
470
+ }
471
+ return { fieldPaths, root, pathStringToId };
472
+ };
473
+ var getFieldPathId = (registry, path) => {
474
+ let node2 = registry.root;
475
+ for (const seg of path) {
476
+ const next = node2.children.get(seg);
477
+ if (!next) return void 0;
478
+ node2 = next;
479
+ }
480
+ return node2.id;
481
+ };
482
+ var splitSegments = (path) => {
483
+ if (!path) return void 0;
484
+ if (path === "*") return void 0;
485
+ const parts = path.split(".").filter((p) => p.length > 0);
486
+ const segs = [];
487
+ for (const part of parts) {
488
+ if (!part) continue;
489
+ if (part === "*") {
490
+ return void 0;
491
+ }
492
+ if (part.endsWith("[]")) {
493
+ const base = part.slice(0, -2);
494
+ if (base) segs.push(base);
495
+ continue;
496
+ }
497
+ const bracket = /^(.+)\[(\d+)\]$/.exec(part);
498
+ if (bracket) {
499
+ segs.push(bracket[1]);
500
+ continue;
501
+ }
502
+ if (/^\d+$/.test(part)) {
503
+ continue;
504
+ }
505
+ if (part.includes("[") || part.includes("]")) {
506
+ return void 0;
507
+ }
508
+ segs.push(part);
509
+ }
510
+ return segs;
511
+ };
512
+
513
+ // src/internal/digest.ts
514
+ var stableStringify2 = (value) => {
515
+ if (value === null) return "null";
516
+ const t = typeof value;
517
+ if (t === "string") return JSON.stringify(value);
518
+ if (t === "number") return Number.isFinite(value) ? String(value) : "null";
519
+ if (t === "boolean") return value ? "true" : "false";
520
+ if (Array.isArray(value)) {
521
+ return `[${value.map(stableStringify2).join(",")}]`;
522
+ }
523
+ if (t === "object") {
524
+ const record2 = value;
525
+ const keys = Object.keys(record2).sort((a, b) => a.localeCompare(b));
526
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify2(record2[k])}`).join(",")}}`;
527
+ }
528
+ return "null";
529
+ };
530
+ var fnv1a32 = (input) => {
531
+ let hash = 2166136261;
532
+ for (let i = 0; i < input.length; i++) {
533
+ hash ^= input.charCodeAt(i);
534
+ hash = hash * 16777619 >>> 0;
535
+ }
536
+ return hash.toString(16).padStart(8, "0");
537
+ };
538
+
539
+ // src/internal/state-trait/build.ts
540
+ var nowPerf = () => typeof globalThis.performance !== "undefined" && typeof globalThis.performance.now === "function" ? globalThis.performance.now() : Date.now();
541
+ var getConvergeWriterDeps = (entry) => {
542
+ if (entry.kind === "computed") {
543
+ return entry.meta?.deps ?? [];
544
+ }
545
+ return [entry.meta.from];
546
+ };
547
+ var computeConvergeTopoOrder = (writers) => {
548
+ const writerByPath = /* @__PURE__ */ new Map();
549
+ for (const entry of writers) {
550
+ const existing = writerByPath.get(entry.fieldPath);
551
+ if (existing) {
552
+ return {
553
+ order: [],
554
+ configError: {
555
+ code: "MULTIPLE_WRITERS",
556
+ message: `[StateTrait.converge] Multiple writers for field "${entry.fieldPath}" (${existing.kind} + ${entry.kind}).`,
557
+ fields: [entry.fieldPath]
558
+ }
559
+ };
560
+ }
561
+ writerByPath.set(entry.fieldPath, entry);
562
+ }
563
+ const nodes = /* @__PURE__ */ new Set();
564
+ for (const entry of writers) {
565
+ nodes.add(entry.fieldPath);
566
+ }
567
+ const indegree = /* @__PURE__ */ new Map();
568
+ const forward = /* @__PURE__ */ new Map();
569
+ for (const node2 of nodes) {
570
+ indegree.set(node2, 0);
571
+ forward.set(node2, []);
572
+ }
573
+ for (const entry of writers) {
574
+ const to = entry.fieldPath;
575
+ const deps = getConvergeWriterDeps(entry);
576
+ for (const dep of deps) {
577
+ if (!nodes.has(dep)) continue;
578
+ forward.get(dep).push(to);
579
+ indegree.set(to, (indegree.get(to) ?? 0) + 1);
580
+ }
581
+ }
582
+ const queue = [];
583
+ for (const [node2, deg] of indegree.entries()) {
584
+ if (deg === 0) queue.push(node2);
585
+ }
586
+ const order = [];
587
+ while (queue.length) {
588
+ const n = queue.shift();
589
+ order.push(n);
590
+ const outs = forward.get(n);
591
+ for (const to of outs) {
592
+ const next = (indegree.get(to) ?? 0) - 1;
593
+ indegree.set(to, next);
594
+ if (next === 0) queue.push(to);
595
+ }
596
+ }
597
+ if (order.length !== nodes.size) {
598
+ const remaining = Array.from(nodes).filter((n) => !order.includes(n));
599
+ return {
600
+ order: [],
601
+ configError: {
602
+ code: "CYCLE_DETECTED",
603
+ message: `[StateTrait.converge] Cycle detected in computed/link graph: ${remaining.join(", ")}`,
604
+ fields: remaining
605
+ }
606
+ };
607
+ }
608
+ return { order };
609
+ };
610
+ var collectSchemaFieldPaths = (schema) => {
611
+ const byKey = /* @__PURE__ */ new Map();
612
+ const add = (path) => {
613
+ const normalized = normalizeFieldPath(path);
614
+ if (!normalized) return;
615
+ byKey.set(JSON.stringify(normalized), normalized);
616
+ };
617
+ const visit = (ast, prefix, seen) => {
618
+ let current = ast;
619
+ while (true) {
620
+ if (SchemaAST.isSuspend(current)) {
621
+ if (seen.has(current)) return;
622
+ seen.add(current);
623
+ current = current.f();
624
+ continue;
625
+ }
626
+ if (SchemaAST.isRefinement(current)) {
627
+ current = current.from;
628
+ continue;
629
+ }
630
+ break;
631
+ }
632
+ if (SchemaAST.isTransformation(current)) {
633
+ visit(current.to, prefix, seen);
634
+ visit(current.from, prefix, seen);
635
+ return;
636
+ }
637
+ if (SchemaAST.isUnion(current)) {
638
+ for (const t of current.types) {
639
+ visit(t, prefix, seen);
640
+ }
641
+ return;
642
+ }
643
+ if (SchemaAST.isTupleType(current)) {
644
+ for (const e of current.elements) {
645
+ visit(e.type, prefix, seen);
646
+ }
647
+ for (const r of current.rest) {
648
+ visit(r.type, prefix, seen);
649
+ }
650
+ return;
651
+ }
652
+ if (SchemaAST.isTypeLiteral(current)) {
653
+ for (const ps of current.propertySignatures) {
654
+ const seg = String(ps.name);
655
+ if (!seg) continue;
656
+ const next = [...prefix, seg];
657
+ add(next);
658
+ visit(ps.type, next, seen);
659
+ }
660
+ return;
661
+ }
662
+ };
663
+ visit(schema.ast, [], /* @__PURE__ */ new Set());
664
+ return Array.from(byKey.values()).sort(compareFieldPath);
665
+ };
666
+ var buildConvergeIr = (stateSchema, entries) => {
667
+ const startedAt = nowPerf();
668
+ const generation = 0;
669
+ const writers = entries.filter((e) => e.kind === "computed" || e.kind === "link");
670
+ const writersKey = writers.map((entry) => `${entry.kind}:${entry.fieldPath}`).sort().join("|");
671
+ const depsKey = writers.map((entry) => {
672
+ const deps = getConvergeWriterDeps(entry).slice().sort().join(",");
673
+ const scheduling = entry.meta?.scheduling === "deferred" ? "d" : "i";
674
+ return `${entry.kind}:${entry.fieldPath}@${scheduling}=>${deps}`;
675
+ }).sort().join("|");
676
+ const writerByPath = /* @__PURE__ */ new Map();
677
+ for (const entry of writers) {
678
+ writerByPath.set(entry.fieldPath, entry);
679
+ }
680
+ const topo = writers.length > 0 ? computeConvergeTopoOrder(writers) : { order: [] };
681
+ const stepsById = topo.configError ? [] : topo.order.map((path) => writerByPath.get(path));
682
+ const fieldPathTable = /* @__PURE__ */ new Map();
683
+ const addPath = (path) => {
684
+ for (let i = 1; i <= path.length; i++) {
685
+ const prefix = path.slice(0, i);
686
+ const key = JSON.stringify(prefix);
687
+ if (!fieldPathTable.has(key)) fieldPathTable.set(key, prefix);
688
+ }
689
+ };
690
+ for (const schemaPath of collectSchemaFieldPaths(stateSchema)) {
691
+ addPath(schemaPath);
692
+ }
693
+ for (const entry of writers) {
694
+ const out = normalizeFieldPath(entry.fieldPath);
695
+ if (out) addPath(out);
696
+ for (const dep of getConvergeWriterDeps(entry)) {
697
+ const depPath = normalizeFieldPath(dep);
698
+ if (depPath) addPath(depPath);
699
+ }
700
+ }
701
+ const fieldPaths = Array.from(fieldPathTable.values()).sort(compareFieldPath);
702
+ const fieldPathIdRegistry = makeFieldPathIdRegistry(fieldPaths);
703
+ const fieldPathsKey = fnv1a32(stableStringify2(fieldPaths));
704
+ const stepOutFieldPathIdByStepId = [];
705
+ const stepDepsFieldPathIdsByStepId = [];
706
+ const stepSchedulingByStepId = [];
707
+ for (const entry of stepsById) {
708
+ const out = normalizeFieldPath(entry.fieldPath);
709
+ const outId = out != null ? getFieldPathId(fieldPathIdRegistry, out) : void 0;
710
+ if (outId == null) {
711
+ throw new Error(`[StateTrait.build] Failed to map converge output fieldPath "${entry.fieldPath}" to FieldPathId.`);
712
+ }
713
+ const depIds = [];
714
+ for (const dep of getConvergeWriterDeps(entry)) {
715
+ const depPath = normalizeFieldPath(dep);
716
+ if (!depPath) continue;
717
+ const depId = getFieldPathId(fieldPathIdRegistry, depPath);
718
+ if (depId != null) depIds.push(depId);
719
+ }
720
+ stepOutFieldPathIdByStepId.push(outId);
721
+ stepDepsFieldPathIdsByStepId.push(depIds);
722
+ stepSchedulingByStepId.push(entry.meta?.scheduling === "deferred" ? "deferred" : "immediate");
723
+ }
724
+ const topoOrder = stepsById.map((_, i) => i);
725
+ const buildDurationMs = Math.max(0, nowPerf() - startedAt);
726
+ return {
727
+ generation,
728
+ writersKey,
729
+ depsKey,
730
+ fieldPathsKey,
731
+ fieldPaths,
732
+ fieldPathIdRegistry,
733
+ ...topo.configError ? { configError: topo.configError } : null,
734
+ stepsById,
735
+ stepOutFieldPathIdByStepId,
736
+ stepDepsFieldPathIdsByStepId,
737
+ stepSchedulingByStepId,
738
+ topoOrder,
739
+ buildDurationMs
740
+ };
741
+ };
742
+ var toFieldTrait = (entry) => {
743
+ const deps = [];
744
+ if (entry.kind === "computed") {
745
+ const meta = entry.meta;
746
+ const list2 = meta.deps;
747
+ if (list2) deps.push(...list2);
748
+ } else if (entry.kind === "source") {
749
+ const meta = entry.meta;
750
+ const list2 = meta.deps;
751
+ if (list2) deps.push(...list2);
752
+ } else if (entry.kind === "link") {
753
+ deps.push(entry.meta.from);
754
+ } else if (entry.kind === "check") {
755
+ const meta = entry.meta;
756
+ const rules = meta?.rules ?? {};
757
+ for (const name of Object.keys(rules)) {
758
+ const rule = rules[name];
759
+ if (rule && typeof rule === "object") {
760
+ const list2 = rule.deps;
761
+ if (list2) deps.push(...list2);
762
+ }
763
+ }
764
+ }
765
+ return {
766
+ fieldId: entry.fieldPath,
767
+ kind: entry.kind,
768
+ // Keep meta identical to Entry.meta at runtime so install can reuse it directly.
769
+ meta: entry.meta,
770
+ deps
771
+ };
772
+ };
773
+ var buildGraph = (entries, nodeMetaByFieldPath) => {
774
+ const fieldMap = /* @__PURE__ */ new Map();
775
+ const nodes = [];
776
+ const edges = [];
777
+ const resourcesById = /* @__PURE__ */ new Map();
778
+ const planSteps = [];
779
+ const ensureField = (fieldPath) => {
780
+ let field = fieldMap.get(fieldPath);
781
+ if (!field) {
782
+ field = {
783
+ id: fieldPath,
784
+ path: fieldPath,
785
+ traits: []
786
+ };
787
+ fieldMap.set(fieldPath, field);
788
+ }
789
+ return field;
790
+ };
791
+ for (const entry of entries) {
792
+ const fieldPath = entry.fieldPath;
793
+ const field = ensureField(fieldPath);
794
+ const trait = toFieldTrait(entry);
795
+ field.traits.push(trait);
796
+ if (entry.kind === "computed") {
797
+ const stepId = `computed:${fieldPath}`;
798
+ planSteps.push({
799
+ id: stepId,
800
+ kind: "computed-update",
801
+ targetFieldPath: fieldPath
802
+ // Note: the current version does not statically analyze computed dependencies; sourceFieldPaths remains empty.
803
+ });
804
+ const deps = entry.meta.deps;
805
+ if (deps) {
806
+ for (const dep of deps) {
807
+ ensureField(dep);
808
+ edges.push({
809
+ id: `computed:${dep}->${fieldPath}`,
810
+ from: dep,
811
+ to: fieldPath,
812
+ kind: "computed"
813
+ });
814
+ }
815
+ }
816
+ } else if (entry.kind === "link") {
817
+ const from2 = entry.meta.from;
818
+ ensureField(from2);
819
+ const edgeId = `link:${from2}->${fieldPath}`;
820
+ edges.push({
821
+ id: edgeId,
822
+ from: from2,
823
+ to: fieldPath,
824
+ kind: "link"
825
+ });
826
+ planSteps.push({
827
+ id: `link:${fieldPath}`,
828
+ kind: "link-propagate",
829
+ targetFieldPath: fieldPath,
830
+ sourceFieldPaths: [from2],
831
+ debugInfo: {
832
+ graphEdgeId: edgeId
833
+ }
834
+ });
835
+ } else if (entry.kind === "source") {
836
+ const resourceId = entry.meta.resource;
837
+ const resourceMeta = sanitize(entry.meta.meta);
838
+ const existing = resourcesById.get(resourceId);
839
+ if (existing) {
840
+ const ownerFields = [...existing.ownerFields, fieldPath];
841
+ let meta = existing.meta;
842
+ let metaOrigin = existing.metaOrigin;
843
+ let metaConflicts = existing.metaConflicts;
844
+ if (resourceMeta) {
845
+ const merged = mergeCanonical(
846
+ { meta, origin: metaOrigin, conflicts: metaConflicts },
847
+ { origin: fieldPath, meta: resourceMeta }
848
+ );
849
+ meta = merged.meta;
850
+ metaOrigin = merged.origin;
851
+ metaConflicts = merged.conflicts;
852
+ }
853
+ resourcesById.set(resourceId, {
854
+ ...existing,
855
+ ownerFields,
856
+ meta,
857
+ metaOrigin,
858
+ metaConflicts
859
+ });
860
+ } else {
861
+ resourcesById.set(resourceId, {
862
+ resourceId,
863
+ // Use a simple identifier string for now; may evolve into a structured form based on key rules.
864
+ keySelector: `StateTrait.source@${fieldPath}`,
865
+ ownerFields: [fieldPath],
866
+ meta: resourceMeta,
867
+ metaOrigin: resourceMeta ? fieldPath : void 0
868
+ });
869
+ }
870
+ planSteps.push({
871
+ id: `source:${fieldPath}`,
872
+ kind: "source-refresh",
873
+ targetFieldPath: fieldPath,
874
+ resourceId,
875
+ keySelectorId: `StateTrait.source@${fieldPath}`
876
+ });
877
+ const deps = entry.meta.deps;
878
+ if (deps) {
879
+ for (const dep of deps) {
880
+ ensureField(dep);
881
+ edges.push({
882
+ id: `source-dep:${dep}->${fieldPath}`,
883
+ from: dep,
884
+ to: fieldPath,
885
+ kind: "source-dep"
886
+ });
887
+ }
888
+ }
889
+ } else if (entry.kind === "check") {
890
+ planSteps.push({
891
+ id: `check:${fieldPath}`,
892
+ kind: "check-validate",
893
+ targetFieldPath: fieldPath
894
+ });
895
+ if (trait.deps.length > 0) {
896
+ for (const dep of trait.deps) {
897
+ ensureField(dep);
898
+ edges.push({
899
+ id: `check-dep:${dep}->${fieldPath}`,
900
+ from: dep,
901
+ to: fieldPath,
902
+ kind: "check-dep"
903
+ });
904
+ }
905
+ }
906
+ }
907
+ }
908
+ for (const field of fieldMap.values()) {
909
+ nodes.push({
910
+ id: field.id,
911
+ field,
912
+ traits: field.traits,
913
+ meta: nodeMetaByFieldPath.get(field.id)
914
+ });
915
+ }
916
+ const graph = {
917
+ _tag: "StateTraitGraph",
918
+ nodes,
919
+ edges,
920
+ resources: Array.from(resourcesById.values())
921
+ };
922
+ const plan = {
923
+ _tag: "StateTraitPlan",
924
+ steps: planSteps
925
+ };
926
+ return { graph, plan };
927
+ };
928
+ var assertNoLinkCycles = (edges) => {
929
+ const adjacency = /* @__PURE__ */ new Map();
930
+ for (const edge of edges) {
931
+ if (edge.kind !== "link") continue;
932
+ const list2 = adjacency.get(edge.from) ?? [];
933
+ list2.push(edge.to);
934
+ adjacency.set(edge.from, list2);
935
+ }
936
+ const visited = /* @__PURE__ */ new Set();
937
+ const stack = /* @__PURE__ */ new Set();
938
+ const dfs = (node2) => {
939
+ if (stack.has(node2)) {
940
+ throw new Error(
941
+ `[StateTrait.build] link cycle detected at field "${node2}". Please check link traits for circular dependencies.`
942
+ );
943
+ }
944
+ if (visited.has(node2)) return;
945
+ visited.add(node2);
946
+ stack.add(node2);
947
+ const nexts = adjacency.get(node2);
948
+ if (nexts) {
949
+ for (const to of nexts) {
950
+ dfs(to);
951
+ }
952
+ }
953
+ stack.delete(node2);
954
+ };
955
+ for (const node2 of adjacency.keys()) {
956
+ if (!visited.has(node2)) {
957
+ dfs(node2);
958
+ }
959
+ }
960
+ };
961
+ var collectSchemaPaths = (entries) => {
962
+ const byKey = /* @__PURE__ */ new Map();
963
+ const add = (ref) => {
964
+ if (!ref.path) return;
965
+ const k = `${ref.kind}|${ref.entryKind}|${ref.entryFieldPath}|${ref.ruleName ?? ""}|${ref.path}`;
966
+ byKey.set(k, ref);
967
+ };
968
+ const getCheckWritebackPath = (entry) => {
969
+ const wb = entry.meta?.writeback;
970
+ const p = wb && typeof wb === "object" ? wb.path : void 0;
971
+ const writebackPath = typeof p === "string" && p.startsWith("errors.") ? p : void 0;
972
+ if (writebackPath) return writebackPath;
973
+ const fieldPath = entry.fieldPath;
974
+ if (fieldPath.endsWith("[]")) {
975
+ return `errors.${fieldPath.slice(0, -2)}`;
976
+ }
977
+ return `errors.${fieldPath}`;
978
+ };
979
+ for (const entry of entries) {
980
+ add({
981
+ kind: "fieldPath",
982
+ entryKind: entry.kind,
983
+ entryFieldPath: entry.fieldPath,
984
+ path: entry.fieldPath
985
+ });
986
+ if (entry.kind === "computed" || entry.kind === "source") {
987
+ const deps = entry.meta?.deps ?? [];
988
+ for (const dep of deps) {
989
+ add({
990
+ kind: "dep",
991
+ entryKind: entry.kind,
992
+ entryFieldPath: entry.fieldPath,
993
+ path: dep
994
+ });
995
+ }
996
+ }
997
+ if (entry.kind === "link") {
998
+ add({
999
+ kind: "link_from",
1000
+ entryKind: "link",
1001
+ entryFieldPath: entry.fieldPath,
1002
+ path: entry.meta.from
1003
+ });
1004
+ }
1005
+ if (entry.kind === "check") {
1006
+ add({
1007
+ kind: "check_writeback",
1008
+ entryKind: "check",
1009
+ entryFieldPath: entry.fieldPath,
1010
+ path: getCheckWritebackPath(entry)
1011
+ });
1012
+ const rules = entry.meta?.rules ?? {};
1013
+ for (const name of Object.keys(rules)) {
1014
+ const rule = rules[name];
1015
+ if (!rule || typeof rule !== "object") continue;
1016
+ const deps = rule.deps ?? [];
1017
+ for (const dep of deps) {
1018
+ add({
1019
+ kind: "dep",
1020
+ entryKind: "check",
1021
+ entryFieldPath: entry.fieldPath,
1022
+ ruleName: name,
1023
+ path: dep
1024
+ });
1025
+ }
1026
+ }
1027
+ }
1028
+ }
1029
+ return Array.from(byKey.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([, v]) => v);
1030
+ };
1031
+ var build = (stateSchema, spec) => {
1032
+ const entries = normalizeSpec(spec);
1033
+ const nodeMetaByFieldPath = collectNodeMeta(spec);
1034
+ for (const entry of entries) {
1035
+ if (entry.kind === "computed") {
1036
+ const deps = entry.meta.deps;
1037
+ if (deps === void 0) {
1038
+ throw new Error(
1039
+ `[StateTrait.build] Missing explicit deps for computed "${entry.fieldPath}". Please use StateTrait.computed({ deps: [...], get: ... }).`
1040
+ );
1041
+ }
1042
+ }
1043
+ if (entry.kind === "source") {
1044
+ const deps = entry.meta.deps;
1045
+ if (deps === void 0) {
1046
+ throw new Error(
1047
+ `[StateTrait.build] Missing explicit deps for source "${entry.fieldPath}". Please provide meta.deps for StateTrait.source({ deps: [...], ... }).`
1048
+ );
1049
+ }
1050
+ }
1051
+ if (entry.kind === "check") {
1052
+ const rules = entry.meta?.rules ?? {};
1053
+ for (const name of Object.keys(rules)) {
1054
+ const rule = rules[name];
1055
+ if (typeof rule === "function" || !rule || typeof rule !== "object") {
1056
+ throw new Error(
1057
+ `[StateTrait.build] Missing explicit deps for check "${entry.fieldPath}" rule "${name}". Please use { deps: [...], validate: ... } form.`
1058
+ );
1059
+ }
1060
+ if (rule.deps === void 0) {
1061
+ throw new Error(
1062
+ `[StateTrait.build] Missing explicit deps for check "${entry.fieldPath}" rule "${name}". Please provide deps: [...].`
1063
+ );
1064
+ }
1065
+ }
1066
+ }
1067
+ }
1068
+ const { graph, plan } = buildGraph(entries, nodeMetaByFieldPath);
1069
+ assertNoLinkCycles(graph.edges);
1070
+ return {
1071
+ stateSchema,
1072
+ spec,
1073
+ entries,
1074
+ graph,
1075
+ plan,
1076
+ convergeIr: buildConvergeIr(stateSchema, entries),
1077
+ schemaPaths: collectSchemaPaths(entries)
1078
+ };
1079
+ };
1080
+
1081
+ // src/internal/state-trait/install.ts
1082
+ var import_effect11 = require("effect");
1083
+
1084
+ // src/internal/runtime/core/env.ts
1085
+ var import_effect = require("effect");
1086
+ var getNodeEnv = () => {
1087
+ try {
1088
+ const env = globalThis?.process?.env;
1089
+ return typeof env?.NODE_ENV === "string" ? env.NODE_ENV : void 0;
1090
+ } catch {
1091
+ return void 0;
1092
+ }
1093
+ };
1094
+ var isDevEnv = () => getNodeEnv() !== "production";
1095
+ var StateTransactionConfigTagImpl = class extends import_effect.Context.Tag("@logixjs/core/StateTransactionRuntimeConfig")() {
1096
+ };
1097
+ var ReadQueryStrictGateConfigTagImpl = class extends import_effect.Context.Tag("@logixjs/core/ReadQueryStrictGateRuntimeConfig")() {
1098
+ };
1099
+ var ReplayModeConfigTagImpl = class extends import_effect.Context.Tag("@logixjs/core/ReplayModeConfig")() {
1100
+ };
1101
+ var ReplayModeConfigTag = ReplayModeConfigTagImpl;
1102
+ var StateTransactionOverridesTagImpl = class extends import_effect.Context.Tag("@logixjs/core/StateTransactionOverrides")() {
1103
+ };
1104
+ var ConcurrencyPolicyTagImpl = class extends import_effect.Context.Tag("@logixjs/core/ConcurrencyPolicy")() {
1105
+ };
1106
+ var ConcurrencyPolicyOverridesTagImpl = class extends import_effect.Context.Tag("@logixjs/core/ConcurrencyPolicyOverrides")() {
1107
+ };
1108
+
1109
+ // src/internal/runtime/core/runtimeInternalsAccessor.ts
1110
+ var BOUND_INTERNALS = /* @__PURE__ */ Symbol.for("@logixjs/core/boundInternals");
1111
+ var getBoundInternals = (bound) => {
1112
+ const internals = bound[BOUND_INTERNALS];
1113
+ if (!internals) {
1114
+ const msg = isDevEnv() ? [
1115
+ "[MissingBoundInternals] Bound internals not installed on Bound API instance.",
1116
+ "fix:",
1117
+ "- Ensure BoundApiRuntime attaches internals (020 foundation).",
1118
+ "- If you created a mock bound for tests, attach internals or avoid calling internal-only APIs."
1119
+ ].join("\n") : "Bound internals not installed";
1120
+ throw new Error(msg);
1121
+ }
1122
+ return internals;
1123
+ };
1124
+
1125
+ // src/internal/state-trait/source.ts
1126
+ var import_effect10 = require("effect");
1127
+ var import_mutative = require("mutative");
1128
+
1129
+ // src/internal/effect-op.ts
1130
+ var import_effect4 = require("effect");
1131
+
1132
+ // src/internal/runtime/core/EffectOpCore.ts
1133
+ var import_effect2 = require("effect");
1134
+ var currentLinkId = import_effect2.FiberRef.unsafeMake(void 0);
1135
+ var EffectOpMiddlewareTag = class extends import_effect2.Context.Tag("Logix/EffectOpMiddleware")() {
1136
+ };
1137
+ var composeMiddleware = (stack) => {
1138
+ return (op) => stack.reduceRight(
1139
+ (eff, mw) => mw({ ...op, effect: eff }),
1140
+ op.effect
1141
+ );
1142
+ };
1143
+ var runWithMiddleware = (op, stack) => {
1144
+ return import_effect2.Effect.gen(function* () {
1145
+ const existing = yield* import_effect2.FiberRef.get(currentLinkId);
1146
+ const metaLinkId = op.meta?.linkId;
1147
+ const linkId = typeof metaLinkId === "string" && metaLinkId.length > 0 ? metaLinkId : existing ?? op.id;
1148
+ const nextOp = {
1149
+ ...op,
1150
+ meta: {
1151
+ ...op.meta ?? {},
1152
+ linkId
1153
+ }
1154
+ };
1155
+ const program = stack.length ? composeMiddleware(stack)(nextOp) : nextOp.effect;
1156
+ return yield* import_effect2.Effect.locally(currentLinkId, linkId)(program);
1157
+ });
1158
+ };
1159
+
1160
+ // src/internal/observability/runSession.ts
1161
+ var import_effect3 = require("effect");
1162
+
1163
+ // src/internal/observability/jsonValue.ts
1164
+ var defaultOptions = {
1165
+ maxDepth: 6,
1166
+ maxObjectKeys: 32,
1167
+ maxArrayLength: 32,
1168
+ maxStringLength: 256,
1169
+ maxJsonBytes: 4 * 1024,
1170
+ oversizedPreviewBytes: 256
1171
+ };
1172
+
1173
+ // src/internal/observability/runSession.ts
1174
+ var RunSessionTagImpl = class extends import_effect3.Context.Tag("@logixjs/core/RunSession")() {
1175
+ };
1176
+ var RunSessionTag = RunSessionTagImpl;
1177
+
1178
+ // src/internal/effect-op.ts
1179
+ var nextGlobalOpSeq = 0;
1180
+ var nextOpSeq = () => {
1181
+ nextGlobalOpSeq += 1;
1182
+ return nextGlobalOpSeq;
1183
+ };
1184
+ var makeId = (instanceId, opSeq) => instanceId ? `${instanceId}::o${opSeq}` : `o${opSeq}`;
1185
+ var make = (params) => ({
1186
+ ...params.id ? { id: params.id, meta: params.meta } : (() => {
1187
+ const meta = params.meta ?? {};
1188
+ const instanceId = meta.instanceId;
1189
+ const opSeq = typeof meta.opSeq === "number" && Number.isFinite(meta.opSeq) ? Math.floor(meta.opSeq) : nextOpSeq();
1190
+ return {
1191
+ id: makeId(instanceId, opSeq),
1192
+ meta: meta.opSeq === opSeq ? meta : { ...meta, opSeq }
1193
+ };
1194
+ })(),
1195
+ kind: params.kind,
1196
+ name: params.name,
1197
+ payload: params.payload,
1198
+ effect: params.effect
1199
+ });
1200
+ var run = (op, stack) => runWithMiddleware(op, stack);
1201
+
1202
+ // src/internal/resource.ts
1203
+ var import_effect5 = require("effect");
1204
+ var stableStringify3 = (value) => {
1205
+ const seen = /* @__PURE__ */ new WeakSet();
1206
+ const encode = (input) => {
1207
+ if (input === null) return null;
1208
+ if (typeof input === "string" || typeof input === "number" || typeof input === "boolean") {
1209
+ return input;
1210
+ }
1211
+ if (typeof input === "bigint") return input.toString();
1212
+ if (typeof input === "undefined") return "__undefined__";
1213
+ if (typeof input === "symbol") return `__symbol__:${String(input)}`;
1214
+ if (typeof input === "function") return "__function__";
1215
+ if (Array.isArray(input)) {
1216
+ return input.map((v) => encode(v));
1217
+ }
1218
+ if (input instanceof Date) {
1219
+ return `__date__:${input.toISOString()}`;
1220
+ }
1221
+ if (input instanceof Error) {
1222
+ return {
1223
+ _tag: "Error",
1224
+ name: input.name,
1225
+ message: input.message
1226
+ };
1227
+ }
1228
+ if (input && typeof input === "object") {
1229
+ const obj = input;
1230
+ if (seen.has(obj)) return "__cycle__";
1231
+ seen.add(obj);
1232
+ const record2 = input;
1233
+ const keys = Object.keys(record2).sort();
1234
+ const out = {};
1235
+ for (const k of keys) {
1236
+ out[k] = encode(record2[k]);
1237
+ }
1238
+ return out;
1239
+ }
1240
+ return String(input);
1241
+ };
1242
+ try {
1243
+ return JSON.stringify(encode(value));
1244
+ } catch {
1245
+ return String(value);
1246
+ }
1247
+ };
1248
+ var keyHash = (key) => stableStringify3(key);
1249
+ var Snapshot = {
1250
+ idle: () => ({
1251
+ status: "idle",
1252
+ keyHash: void 0,
1253
+ data: void 0,
1254
+ error: void 0
1255
+ }),
1256
+ loading: (params) => ({
1257
+ status: "loading",
1258
+ keyHash: params.keyHash,
1259
+ data: void 0,
1260
+ error: void 0
1261
+ }),
1262
+ success: (params) => ({
1263
+ status: "success",
1264
+ keyHash: params.keyHash,
1265
+ data: params.data,
1266
+ error: void 0
1267
+ }),
1268
+ error: (params) => ({
1269
+ status: "error",
1270
+ keyHash: params.keyHash,
1271
+ data: void 0,
1272
+ error: params.error
1273
+ })
1274
+ };
1275
+ var ResourceRegistryTag = class extends import_effect5.Context.Tag("@logixjs/core/ResourceRegistry")() {
1276
+ };
1277
+ var internal = {
1278
+ ResourceRegistryTag
1279
+ };
1280
+
1281
+ // src/internal/runtime/core/DebugSink.ts
1282
+ var import_effect7 = require("effect");
1283
+
1284
+ // src/internal/runtime/core/errorSummary.ts
1285
+ var import_effect6 = require("effect");
1286
+
1287
+ // src/internal/runtime/core/DebugSink.ts
1288
+ var currentDebugSinks = import_effect7.FiberRef.unsafeMake([]);
1289
+ var currentRuntimeLabel = import_effect7.FiberRef.unsafeMake(void 0);
1290
+ var currentTxnId = import_effect7.FiberRef.unsafeMake(void 0);
1291
+ var currentOpSeq = import_effect7.FiberRef.unsafeMake(void 0);
1292
+ var currentDiagnosticsLevel = import_effect7.FiberRef.unsafeMake("off");
1293
+ var currentTraitConvergeDiagnosticsSampling = import_effect7.FiberRef.unsafeMake({
1294
+ sampleEveryN: 32,
1295
+ topK: 3
1296
+ });
1297
+ var browserLifecycleSeen = /* @__PURE__ */ new Set();
1298
+ var browserDiagnosticSeen = /* @__PURE__ */ new Set();
1299
+ var lifecycleErrorLog = (event) => {
1300
+ const moduleId = event.moduleId ?? "unknown";
1301
+ const causePretty = (() => {
1302
+ try {
1303
+ return import_effect7.Cause.pretty(event.cause, {
1304
+ renderErrorCause: true
1305
+ });
1306
+ } catch {
1307
+ try {
1308
+ return JSON.stringify(event.cause, null, 2);
1309
+ } catch {
1310
+ return String(event.cause);
1311
+ }
1312
+ }
1313
+ })();
1314
+ const message = `[Logix][module=${moduleId}] lifecycle:error
1315
+ ${causePretty}`;
1316
+ return import_effect7.Effect.logError(message).pipe(
1317
+ import_effect7.Effect.annotateLogs({
1318
+ "logix.moduleId": moduleId,
1319
+ "logix.event": "lifecycle:error",
1320
+ "logix.cause": causePretty
1321
+ })
1322
+ );
1323
+ };
1324
+ var diagnosticLog = (event) => {
1325
+ const moduleId = event.moduleId ?? "unknown";
1326
+ const header = `[Logix][module=${moduleId}] diagnostic(${event.severity})`;
1327
+ const detail = `code=${event.code} message=${event.message}${event.actionTag ? ` action=${event.actionTag}` : ""}${event.hint ? `
1328
+ hint: ${event.hint}` : ""}`;
1329
+ const msg = `${header}
1330
+ ${detail}`;
1331
+ const base = event.severity === "warning" ? import_effect7.Effect.logWarning(msg) : event.severity === "info" ? import_effect7.Effect.logInfo(msg) : import_effect7.Effect.logError(msg);
1332
+ const annotations = {
1333
+ "logix.moduleId": moduleId,
1334
+ "logix.event": `diagnostic(${event.severity})`,
1335
+ "logix.diagnostic.code": event.code,
1336
+ "logix.diagnostic.message": event.message
1337
+ };
1338
+ if (event.hint) {
1339
+ annotations["logix.diagnostic.hint"] = event.hint;
1340
+ }
1341
+ if (event.actionTag) {
1342
+ annotations["logix.diagnostic.actionTag"] = event.actionTag;
1343
+ }
1344
+ return base.pipe(import_effect7.Effect.annotateLogs(annotations));
1345
+ };
1346
+ var noopLayer = import_effect7.Layer.locallyScoped(currentDebugSinks, []);
1347
+ var errorOnlySink = {
1348
+ record: (event) => event.type === "lifecycle:error" ? lifecycleErrorLog(event) : event.type === "diagnostic" && event.severity !== "info" ? diagnosticLog(event) : import_effect7.Effect.void
1349
+ };
1350
+ var errorOnlyLayer = import_effect7.Layer.locallyScoped(currentDebugSinks, [errorOnlySink]);
1351
+ var isErrorOnlyOnlySinks = (sinks) => sinks.length === 1 && sinks[0] === errorOnlySink;
1352
+ var consoleSink = {
1353
+ record: (event) => event.type === "lifecycle:error" ? lifecycleErrorLog(event) : event.type === "diagnostic" ? diagnosticLog(event) : import_effect7.Effect.logDebug({ debugEvent: event })
1354
+ };
1355
+ var consoleLayer = import_effect7.Layer.locallyScoped(currentDebugSinks, [consoleSink]);
1356
+ var isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
1357
+ var renderBrowserConsoleEvent = (event) => {
1358
+ if (typeof event.type === "string" && event.type.startsWith("trace:")) {
1359
+ const moduleId = event.moduleId ?? "unknown";
1360
+ const type = event.type;
1361
+ return import_effect7.Effect.sync(() => {
1362
+ console.groupCollapsed(
1363
+ "%c[Logix]%c trace %c" + moduleId + "%c " + String(type),
1364
+ "color:#6b7280;font-weight:bold",
1365
+ // tag
1366
+ "color:#3b82f6",
1367
+ // label
1368
+ "color:#9ca3af",
1369
+ // module id
1370
+ "color:#6b7280"
1371
+ // type
1372
+ );
1373
+ console.log(event);
1374
+ console.groupEnd();
1375
+ });
1376
+ }
1377
+ if (event.type === "lifecycle:error") {
1378
+ const moduleId = event.moduleId ?? "unknown";
1379
+ const causePretty = (() => {
1380
+ try {
1381
+ return import_effect7.Cause.pretty(event.cause, { renderErrorCause: true });
1382
+ } catch {
1383
+ try {
1384
+ return JSON.stringify(event.cause, null, 2);
1385
+ } catch {
1386
+ return String(event.cause);
1387
+ }
1388
+ }
1389
+ })();
1390
+ const key = `${moduleId}|${causePretty}`;
1391
+ if (browserLifecycleSeen.has(key)) {
1392
+ return import_effect7.Effect.void;
1393
+ }
1394
+ browserLifecycleSeen.add(key);
1395
+ return import_effect7.Effect.sync(() => {
1396
+ console.groupCollapsed(
1397
+ "%c[Logix]%c lifecycle:error %c" + moduleId,
1398
+ "color:#ef4444;font-weight:bold",
1399
+ // tag
1400
+ "color:#ef4444",
1401
+ // label
1402
+ "color:#9ca3af"
1403
+ // module id
1404
+ );
1405
+ console.error(causePretty);
1406
+ console.groupEnd();
1407
+ });
1408
+ }
1409
+ if (event.type === "diagnostic") {
1410
+ const moduleId = event.moduleId ?? "unknown";
1411
+ const detail = `code=${event.code} message=${event.message}${event.actionTag ? ` action=${event.actionTag}` : ""}${event.hint ? `
1412
+ hint: ${event.hint}` : ""}`;
1413
+ const color = event.severity === "warning" ? "color:#d97706" : event.severity === "info" ? "color:#3b82f6" : "color:#ef4444";
1414
+ const label = event.severity === "warning" ? "diagnostic(warning)" : event.severity === "info" ? "diagnostic(info)" : "diagnostic(error)";
1415
+ const key = `${moduleId}|${event.code}|${event.message}`;
1416
+ if (browserDiagnosticSeen.has(key)) {
1417
+ return import_effect7.Effect.void;
1418
+ }
1419
+ browserDiagnosticSeen.add(key);
1420
+ return import_effect7.Effect.sync(() => {
1421
+ console.groupCollapsed(
1422
+ "%c[Logix]%c " + label + "%c module=" + moduleId,
1423
+ "color:#6b7280;font-weight:bold",
1424
+ color,
1425
+ "color:#9ca3af"
1426
+ );
1427
+ if (event.severity === "warning") {
1428
+ console.warn(detail);
1429
+ } else if (event.severity === "info") {
1430
+ console.info(detail);
1431
+ } else {
1432
+ console.error(detail);
1433
+ }
1434
+ console.groupEnd();
1435
+ });
1436
+ }
1437
+ return import_effect7.Effect.void;
1438
+ };
1439
+ var browserConsoleSink = {
1440
+ record: (event) => {
1441
+ if (!isBrowser) {
1442
+ return event.type === "lifecycle:error" ? lifecycleErrorLog(event) : event.type === "diagnostic" ? diagnosticLog(event) : import_effect7.Effect.logDebug({ debugEvent: event });
1443
+ }
1444
+ return renderBrowserConsoleEvent(event);
1445
+ }
1446
+ };
1447
+ var browserConsoleLayer = import_effect7.Layer.locallyScoped(currentDebugSinks, [browserConsoleSink]);
1448
+ var browserDiagnosticConsoleSink = {
1449
+ record: (event) => {
1450
+ if (!isBrowser) {
1451
+ return event.type === "lifecycle:error" ? lifecycleErrorLog(event) : event.type === "diagnostic" && event.severity !== "info" ? diagnosticLog(event) : import_effect7.Effect.void;
1452
+ }
1453
+ return event.type === "lifecycle:error" || event.type === "diagnostic" && event.severity !== "info" ? renderBrowserConsoleEvent(event) : import_effect7.Effect.void;
1454
+ }
1455
+ };
1456
+ var browserDiagnosticConsoleLayer = import_effect7.Layer.locallyScoped(currentDebugSinks, [browserDiagnosticConsoleSink]);
1457
+ var browserPrettyLoggerLayer = import_effect7.Logger.replace(
1458
+ import_effect7.Logger.defaultLogger,
1459
+ import_effect7.Logger.prettyLogger({ mode: "browser", colors: true })
1460
+ );
1461
+ var record = (event) => import_effect7.Effect.gen(function* () {
1462
+ const sinks = yield* import_effect7.FiberRef.get(currentDebugSinks);
1463
+ if (isErrorOnlyOnlySinks(sinks)) {
1464
+ if (event.type === "lifecycle:error") {
1465
+ yield* lifecycleErrorLog(event);
1466
+ return;
1467
+ }
1468
+ if (event.type === "diagnostic") {
1469
+ if (event.severity !== "info") {
1470
+ yield* diagnosticLog(event);
1471
+ } else {
1472
+ yield* import_effect7.Effect.void;
1473
+ }
1474
+ return;
1475
+ }
1476
+ yield* import_effect7.Effect.void;
1477
+ return;
1478
+ }
1479
+ if (sinks.length === 0) {
1480
+ if (isBrowser) {
1481
+ if (event.type === "lifecycle:error" || event.type === "diagnostic") {
1482
+ yield* renderBrowserConsoleEvent(event);
1483
+ return;
1484
+ }
1485
+ yield* import_effect7.Effect.void;
1486
+ return;
1487
+ }
1488
+ if (event.type === "lifecycle:error") {
1489
+ yield* lifecycleErrorLog(event);
1490
+ return;
1491
+ }
1492
+ if (event.type === "diagnostic") {
1493
+ yield* diagnosticLog(event);
1494
+ return;
1495
+ }
1496
+ yield* import_effect7.Effect.void;
1497
+ return;
1498
+ }
1499
+ const enriched = event;
1500
+ const diagnosticsLevel = yield* import_effect7.FiberRef.get(currentDiagnosticsLevel);
1501
+ let now;
1502
+ const getNow = () => {
1503
+ if (now === void 0) now = Date.now();
1504
+ return now;
1505
+ };
1506
+ if (enriched.timestamp === void 0 && (diagnosticsLevel !== "off" || enriched.type === "lifecycle:error" || enriched.type === "diagnostic")) {
1507
+ ;
1508
+ enriched.timestamp = getNow();
1509
+ }
1510
+ if (diagnosticsLevel !== "off" && enriched.runtimeLabel === void 0) {
1511
+ const runtimeLabel = yield* import_effect7.FiberRef.get(currentRuntimeLabel);
1512
+ if (runtimeLabel) {
1513
+ ;
1514
+ enriched.runtimeLabel = runtimeLabel;
1515
+ }
1516
+ }
1517
+ if (enriched.type === "diagnostic" && enriched.txnId === void 0) {
1518
+ const txnId = yield* import_effect7.FiberRef.get(currentTxnId);
1519
+ if (txnId) {
1520
+ ;
1521
+ enriched.txnId = txnId;
1522
+ }
1523
+ }
1524
+ if (diagnosticsLevel !== "off" && enriched.type === "trace:effectop" && enriched.linkId === void 0) {
1525
+ const linkId = yield* import_effect7.FiberRef.get(currentLinkId);
1526
+ if (linkId) {
1527
+ ;
1528
+ enriched.linkId = linkId;
1529
+ }
1530
+ }
1531
+ if (sinks.length === 1) {
1532
+ yield* sinks[0].record(enriched);
1533
+ return;
1534
+ }
1535
+ yield* import_effect7.Effect.forEach(sinks, (sink) => sink.record(enriched), { discard: true });
1536
+ });
1537
+
1538
+ // src/internal/runtime/core/TaskRunner.ts
1539
+ var import_effect8 = require("effect");
1540
+ var inSyncTransactionFiber = import_effect8.FiberRef.unsafeMake(false);
1541
+ var forceSourceRefresh = import_effect8.FiberRef.unsafeMake(false);
1542
+
1543
+ // src/internal/runtime/core/ReplayLog.ts
1544
+ var import_effect9 = require("effect");
1545
+ var ReplayLog = class extends import_effect9.Context.Tag("@logixjs/core/ReplayLog")() {
1546
+ };
1547
+ var snapshot = import_effect9.Effect.gen(function* () {
1548
+ const log = yield* ReplayLog;
1549
+ return yield* log.snapshot;
1550
+ });
1551
+ var resetCursor = import_effect9.Effect.gen(function* () {
1552
+ const log = yield* ReplayLog;
1553
+ yield* log.resetCursor;
1554
+ });
1555
+
1556
+ // src/internal/state-trait/deps-trace.ts
1557
+ var isTraceableObject = (value) => {
1558
+ if (!value || typeof value !== "object") return false;
1559
+ if (Array.isArray(value)) return true;
1560
+ if (value instanceof Date) return false;
1561
+ if (value instanceof RegExp) return false;
1562
+ if (value instanceof Error) return false;
1563
+ if (value instanceof Map) return false;
1564
+ if (value instanceof Set) return false;
1565
+ if (value instanceof WeakMap) return false;
1566
+ if (value instanceof WeakSet) return false;
1567
+ return true;
1568
+ };
1569
+ var shouldIgnoreKey = (key) => key === "__proto__" || key === "prototype" || key === "constructor";
1570
+ var normalizeReads = (reads) => {
1571
+ const all = Array.from(reads).filter((p) => typeof p === "string" && p.length > 0);
1572
+ all.sort();
1573
+ const isPrefix = (prefix, full) => full !== prefix && full.startsWith(prefix + ".");
1574
+ const pruned = [];
1575
+ for (const p of all) {
1576
+ let hasMoreSpecific = false;
1577
+ for (const other of all) {
1578
+ if (isPrefix(p, other)) {
1579
+ hasMoreSpecific = true;
1580
+ break;
1581
+ }
1582
+ }
1583
+ if (!hasMoreSpecific) {
1584
+ pruned.push(p);
1585
+ }
1586
+ }
1587
+ pruned.sort();
1588
+ return pruned;
1589
+ };
1590
+ var covers = (declared, read) => declared === read || read.startsWith(declared + ".");
1591
+ var diffDeps = (declared, reads) => {
1592
+ const declaredList = Array.from(new Set(declared)).filter((p) => typeof p === "string" && p.length > 0);
1593
+ declaredList.sort();
1594
+ const readList = Array.from(new Set(reads)).filter((p) => typeof p === "string" && p.length > 0);
1595
+ readList.sort();
1596
+ const missing = readList.filter((r) => declaredList.every((d) => !covers(d, r)));
1597
+ const unused = declaredList.filter((d) => readList.every((r) => !covers(d, r)));
1598
+ if (missing.length === 0 && unused.length === 0) return void 0;
1599
+ return {
1600
+ reads: readList,
1601
+ declared: declaredList,
1602
+ missing,
1603
+ unused
1604
+ };
1605
+ };
1606
+ var trace = (fn, state) => {
1607
+ if (!isTraceableObject(state)) {
1608
+ return { value: fn(state), reads: [] };
1609
+ }
1610
+ const reads = /* @__PURE__ */ new Set();
1611
+ const proxyCache = /* @__PURE__ */ new WeakMap();
1612
+ const proxyToTarget = /* @__PURE__ */ new WeakMap();
1613
+ const wrap = (value2, path) => {
1614
+ if (!isTraceableObject(value2)) return value2;
1615
+ return getProxy(value2, path);
1616
+ };
1617
+ const unwrap = (value2) => {
1618
+ if (value2 && (typeof value2 === "object" || typeof value2 === "function")) {
1619
+ const target = proxyToTarget.get(value2);
1620
+ if (target) return target;
1621
+ }
1622
+ return value2;
1623
+ };
1624
+ const getProxy = (target, basePath) => {
1625
+ let byPath = proxyCache.get(target);
1626
+ if (!byPath) {
1627
+ byPath = /* @__PURE__ */ new Map();
1628
+ proxyCache.set(target, byPath);
1629
+ }
1630
+ const cached = byPath.get(basePath);
1631
+ if (cached) return cached;
1632
+ const record2 = (path) => {
1633
+ if (path) reads.add(path);
1634
+ };
1635
+ const proxy = new Proxy(target, {
1636
+ get: (t, prop, receiver) => {
1637
+ if (typeof prop === "symbol") {
1638
+ return Reflect.get(t, prop, receiver);
1639
+ }
1640
+ const key = String(prop);
1641
+ if (shouldIgnoreKey(key)) {
1642
+ return Reflect.get(t, prop, receiver);
1643
+ }
1644
+ const nextPath = basePath ? `${basePath}.${key}` : key;
1645
+ record2(nextPath);
1646
+ const value2 = Reflect.get(t, prop, receiver);
1647
+ return wrap(value2, nextPath);
1648
+ },
1649
+ has: (t, prop) => {
1650
+ if (typeof prop === "symbol") return Reflect.has(t, prop);
1651
+ const key = String(prop);
1652
+ if (!shouldIgnoreKey(key)) {
1653
+ const nextPath = basePath ? `${basePath}.${key}` : key;
1654
+ record2(nextPath);
1655
+ }
1656
+ return Reflect.has(t, prop);
1657
+ },
1658
+ ownKeys: (t) => {
1659
+ if (basePath) record2(basePath);
1660
+ return Reflect.ownKeys(t);
1661
+ },
1662
+ getOwnPropertyDescriptor: (t, prop) => {
1663
+ if (typeof prop === "symbol") {
1664
+ return Reflect.getOwnPropertyDescriptor(t, prop);
1665
+ }
1666
+ const key = String(prop);
1667
+ if (!shouldIgnoreKey(key)) {
1668
+ const nextPath = basePath ? `${basePath}.${key}` : key;
1669
+ record2(nextPath);
1670
+ }
1671
+ return Reflect.getOwnPropertyDescriptor(t, prop);
1672
+ },
1673
+ set: () => {
1674
+ throw new Error(
1675
+ "[deps-trace] Attempted to mutate state during deps tracing (state is readonly in dev-mode diagnostics)."
1676
+ );
1677
+ },
1678
+ defineProperty: () => {
1679
+ throw new Error(
1680
+ "[deps-trace] Attempted to define property on state during deps tracing (state is readonly in dev-mode diagnostics)."
1681
+ );
1682
+ },
1683
+ deleteProperty: () => {
1684
+ throw new Error(
1685
+ "[deps-trace] Attempted to delete property on state during deps tracing (state is readonly in dev-mode diagnostics)."
1686
+ );
1687
+ }
1688
+ });
1689
+ byPath.set(basePath, proxy);
1690
+ proxyToTarget.set(proxy, target);
1691
+ return proxy;
1692
+ };
1693
+ const root = getProxy(state, "");
1694
+ const value = unwrap(fn(root));
1695
+ return {
1696
+ value,
1697
+ reads: normalizeReads(reads)
1698
+ };
1699
+ };
1700
+
1701
+ // src/internal/state-trait/source.ts
1702
+ var onceInRunSession = (key) => import_effect10.Effect.serviceOption(RunSessionTag).pipe(
1703
+ import_effect10.Effect.map((maybe) => import_effect10.Option.isSome(maybe) ? maybe.value.local.once(key) : true)
1704
+ );
1705
+ var formatList = (items, limit = 10) => {
1706
+ if (items.length === 0) return "";
1707
+ if (items.length <= limit) return items.join(", ");
1708
+ return `${items.slice(0, limit).join(", ")}, \u2026(+${items.length - limit})`;
1709
+ };
1710
+ var emitDepsMismatch = (params) => import_effect10.Effect.gen(function* () {
1711
+ const key = `${params.instanceId ?? "unknown"}::${params.kind}::${params.fieldPath}`;
1712
+ const shouldEmit = yield* onceInRunSession(`deps_mismatch:${key}`);
1713
+ if (!shouldEmit) return;
1714
+ yield* record({
1715
+ type: "diagnostic",
1716
+ moduleId: params.moduleId,
1717
+ instanceId: params.instanceId,
1718
+ code: "state_trait::deps_mismatch",
1719
+ severity: "warning",
1720
+ message: `[deps] ${params.kind} "${params.fieldPath}" declared=[${formatList(params.diff.declared)}] reads=[${formatList(params.diff.reads)}] missing=[${formatList(params.diff.missing)}] unused=[${formatList(params.diff.unused)}]`,
1721
+ hint: 'deps is the single source of truth for dependencies: incremental scheduling / reverse closures / performance optimizations rely on deps only. Keep deps consistent with actual reads; if you really depend on the whole object, declare a coarser-grained dep (e.g. "profile") to cover sub-field reads.',
1722
+ kind: `deps_mismatch:${params.kind}`
1723
+ });
1724
+ });
1725
+ var getMiddlewareStack = () => import_effect10.Effect.serviceOption(EffectOpMiddlewareTag).pipe(
1726
+ import_effect10.Effect.map((maybe) => import_effect10.Option.isSome(maybe) ? maybe.value.stack : [])
1727
+ );
1728
+ var recordTraitPatch = (bound, path, reason, from2, to, traitNodeId) => {
1729
+ const normalized = normalizeFieldPath(path) ?? [];
1730
+ try {
1731
+ const internals = getBoundInternals(bound);
1732
+ internals.txn.recordStatePatch(normalized, reason, from2, to, traitNodeId);
1733
+ } catch {
1734
+ }
1735
+ };
1736
+ var recordReplayEvent = (bound, event) => {
1737
+ try {
1738
+ const internals = getBoundInternals(bound);
1739
+ internals.txn.recordReplayEvent(event);
1740
+ } catch {
1741
+ }
1742
+ };
1743
+ var getBoundScope = (bound) => {
1744
+ try {
1745
+ const internals = getBoundInternals(bound);
1746
+ return { moduleId: internals.moduleId, instanceId: internals.instanceId };
1747
+ } catch {
1748
+ return { moduleId: void 0, instanceId: void 0 };
1749
+ }
1750
+ };
1751
+ var setSnapshotInTxn = (bound, fieldPath, next, reason, stepId, traitNodeId) => import_effect10.Effect.gen(function* () {
1752
+ let wrote = false;
1753
+ yield* bound.state.mutate((draft) => {
1754
+ const prev = getAtPath(draft, fieldPath);
1755
+ if (Object.is(prev, next)) return;
1756
+ wrote = true;
1757
+ setAtPathMutating(draft, fieldPath, next);
1758
+ recordTraitPatch(bound, fieldPath, reason, prev, next, traitNodeId);
1759
+ });
1760
+ return wrote;
1761
+ });
1762
+ var writebackIfCurrentKeyHash = (bound, fieldPath, keyHash2, next, reason, stepId, traitNodeId, replayEvent) => import_effect10.Effect.gen(function* () {
1763
+ let wrote = false;
1764
+ yield* bound.state.mutate((draft) => {
1765
+ const current = getAtPath(draft, fieldPath);
1766
+ const currentKeyHash = current && typeof current === "object" ? current.keyHash : void 0;
1767
+ if (currentKeyHash !== keyHash2) return;
1768
+ const prev = current;
1769
+ if (Object.is(prev, next)) return;
1770
+ wrote = true;
1771
+ setAtPathMutating(draft, fieldPath, next);
1772
+ if (replayEvent) {
1773
+ recordReplayEvent(bound, replayEvent);
1774
+ }
1775
+ recordTraitPatch(bound, fieldPath, reason, prev, next, traitNodeId);
1776
+ });
1777
+ return wrote;
1778
+ });
1779
+ var installSourceRefresh = (bound, step, entry) => {
1780
+ if (!step.targetFieldPath) return import_effect10.Effect.void;
1781
+ const fieldPath = step.targetFieldPath;
1782
+ const resourceId = step.resourceId ?? entry.meta.resource;
1783
+ const listItem = parseListItemFieldPath(fieldPath);
1784
+ let internals;
1785
+ try {
1786
+ internals = getBoundInternals(bound);
1787
+ } catch {
1788
+ return import_effect10.Effect.void;
1789
+ }
1790
+ const register = internals.traits.registerSourceRefresh;
1791
+ const recordSnapshot = (replayMode, replayLog, input) => {
1792
+ if (!replayLog) return import_effect10.Effect.void;
1793
+ if (replayMode !== "live") return import_effect10.Effect.void;
1794
+ const event = input && typeof input === "object" && input._tag === "ResourceSnapshot" ? input : {
1795
+ _tag: "ResourceSnapshot",
1796
+ resourceId,
1797
+ fieldPath: input.fieldPath,
1798
+ keyHash: input.keyHash,
1799
+ concurrency: input.concurrency,
1800
+ phase: input.phase,
1801
+ snapshot: input.snapshot,
1802
+ timestamp: Date.now(),
1803
+ moduleId: input.moduleId,
1804
+ instanceId: input.instanceId
1805
+ };
1806
+ return replayLog.record(event);
1807
+ };
1808
+ if (listItem) {
1809
+ const store = internals.traits.rowIdStore;
1810
+ if (!store) {
1811
+ return import_effect10.Effect.void;
1812
+ }
1813
+ const listPath = listItem.listPath;
1814
+ const itemPath = listItem.itemPath;
1815
+ if (!itemPath) {
1816
+ return import_effect10.Effect.void;
1817
+ }
1818
+ const concurrency2 = entry.meta.concurrency;
1819
+ const mode2 = concurrency2 ?? "switch";
1820
+ const inFlight2 = /* @__PURE__ */ new Map();
1821
+ const trailing2 = /* @__PURE__ */ new Map();
1822
+ let gen2 = 0;
1823
+ store.onRemoved(listPath, (rowId) => {
1824
+ trailing2.delete(rowId);
1825
+ inFlight2.delete(rowId);
1826
+ });
1827
+ const setSnapshotForRowInTxn = (rowId, next, reason, stepId) => import_effect10.Effect.gen(function* () {
1828
+ let wrotePath;
1829
+ yield* bound.state.mutate((draft) => {
1830
+ const index = store.getIndex(listPath, rowId);
1831
+ if (index === void 0) return;
1832
+ const concretePath = toListItemValuePath(listPath, index, itemPath);
1833
+ const prev = getAtPath(draft, concretePath);
1834
+ if (Object.is(prev, next)) return;
1835
+ wrotePath = concretePath;
1836
+ setAtPathMutating(draft, concretePath, next);
1837
+ recordTraitPatch(bound, concretePath, reason, prev, next, step.debugInfo?.graphNodeId);
1838
+ });
1839
+ return wrotePath;
1840
+ });
1841
+ const writebackIfCurrentKeyHashForRow = (rowId, keyHash2, next, reason, stepId, phase) => import_effect10.Effect.gen(function* () {
1842
+ let wrotePath;
1843
+ yield* bound.state.mutate((draft) => {
1844
+ const index = store.getIndex(listPath, rowId);
1845
+ if (index === void 0) return;
1846
+ const concretePath = toListItemValuePath(listPath, index, itemPath);
1847
+ const current = getAtPath(draft, concretePath);
1848
+ const currentKeyHash = current && typeof current === "object" ? current.keyHash : void 0;
1849
+ if (currentKeyHash !== keyHash2) return;
1850
+ const prev = current;
1851
+ if (Object.is(prev, next)) return;
1852
+ wrotePath = concretePath;
1853
+ setAtPathMutating(draft, concretePath, next);
1854
+ if (phase) {
1855
+ const { moduleId, instanceId } = getBoundScope(bound);
1856
+ recordReplayEvent(bound, {
1857
+ _tag: "ResourceSnapshot",
1858
+ resourceId,
1859
+ fieldPath: concretePath,
1860
+ keyHash: keyHash2,
1861
+ concurrency: mode2,
1862
+ phase,
1863
+ snapshot: next,
1864
+ timestamp: Date.now(),
1865
+ moduleId,
1866
+ instanceId
1867
+ });
1868
+ }
1869
+ recordTraitPatch(bound, concretePath, reason, prev, next, step.debugInfo?.graphNodeId);
1870
+ });
1871
+ return wrotePath;
1872
+ });
1873
+ const startFetch2 = (rowId, key, keyHash2, replayMode, replayLog) => import_effect10.Effect.gen(function* () {
1874
+ const { moduleId, instanceId } = getBoundScope(bound);
1875
+ const indexForLog = store.getIndex(listPath, rowId);
1876
+ const logFieldPath = indexForLog === void 0 ? void 0 : toListItemValuePath(listPath, indexForLog, itemPath);
1877
+ let loadingSnapshot = Snapshot.loading({ keyHash: keyHash2 });
1878
+ if (replayMode === "replay" && replayLog && logFieldPath) {
1879
+ const replayLoading = yield* replayLog.consumeNextResourceSnapshot({
1880
+ resourceId,
1881
+ fieldPath: logFieldPath,
1882
+ keyHash: keyHash2,
1883
+ phase: "loading"
1884
+ });
1885
+ if (replayLoading) {
1886
+ loadingSnapshot = replayLoading.snapshot;
1887
+ }
1888
+ }
1889
+ const wroteLoadingPath = yield* setSnapshotForRowInTxn(
1890
+ rowId,
1891
+ loadingSnapshot,
1892
+ "source-refresh",
1893
+ `source:${fieldPath}:${rowId}:loading`
1894
+ );
1895
+ if (wroteLoadingPath) {
1896
+ const event = {
1897
+ _tag: "ResourceSnapshot",
1898
+ resourceId,
1899
+ fieldPath: wroteLoadingPath,
1900
+ keyHash: keyHash2,
1901
+ concurrency: mode2,
1902
+ phase: "loading",
1903
+ snapshot: loadingSnapshot,
1904
+ timestamp: Date.now(),
1905
+ moduleId,
1906
+ instanceId
1907
+ };
1908
+ recordReplayEvent(bound, event);
1909
+ yield* recordSnapshot(replayMode, replayLog, event);
1910
+ }
1911
+ const io = import_effect10.Effect.gen(function* () {
1912
+ if (replayMode === "replay" && replayLog) {
1913
+ yield* import_effect10.Effect.yieldNow();
1914
+ const consumePath = wroteLoadingPath ?? logFieldPath;
1915
+ if (!consumePath) return yield* import_effect10.Effect.void;
1916
+ const replayed = yield* replayLog.consumeNextResourceSnapshot({
1917
+ resourceId,
1918
+ fieldPath: consumePath,
1919
+ keyHash: keyHash2
1920
+ });
1921
+ if (!replayed) return yield* import_effect10.Effect.void;
1922
+ if (replayed.phase === "success") {
1923
+ yield* writebackIfCurrentKeyHashForRow(
1924
+ rowId,
1925
+ keyHash2,
1926
+ replayed.snapshot,
1927
+ "source-refresh",
1928
+ `source:${fieldPath}:${rowId}:success`,
1929
+ "success"
1930
+ );
1931
+ } else if (replayed.phase === "error") {
1932
+ yield* writebackIfCurrentKeyHashForRow(
1933
+ rowId,
1934
+ keyHash2,
1935
+ replayed.snapshot,
1936
+ "source-refresh",
1937
+ `source:${fieldPath}:${rowId}:error`,
1938
+ "error"
1939
+ );
1940
+ }
1941
+ return yield* import_effect10.Effect.void;
1942
+ }
1943
+ const stack = yield* getMiddlewareStack();
1944
+ const registryOpt = yield* import_effect10.Effect.serviceOption(internal.ResourceRegistryTag);
1945
+ const registry = import_effect10.Option.isSome(registryOpt) ? registryOpt.value : void 0;
1946
+ const spec = registry?.specs.get(resourceId);
1947
+ if (!spec) {
1948
+ return yield* import_effect10.Effect.void;
1949
+ }
1950
+ const loadEffect = spec.load(key);
1951
+ const meta = {
1952
+ moduleId,
1953
+ instanceId,
1954
+ fieldPath,
1955
+ resourceId,
1956
+ key,
1957
+ keyHash: keyHash2,
1958
+ rowId,
1959
+ traitNodeId: step.debugInfo?.graphNodeId,
1960
+ stepId: step.id
1961
+ };
1962
+ if (!(typeof meta.opSeq === "number" && Number.isFinite(meta.opSeq))) {
1963
+ const sessionOpt = yield* import_effect10.Effect.serviceOption(RunSessionTag);
1964
+ if (import_effect10.Option.isSome(sessionOpt)) {
1965
+ const seqKey = instanceId ?? "global";
1966
+ meta.opSeq = sessionOpt.value.local.nextSeq("opSeq", seqKey);
1967
+ }
1968
+ }
1969
+ const op = make({
1970
+ kind: "service",
1971
+ name: resourceId,
1972
+ effect: loadEffect,
1973
+ meta
1974
+ });
1975
+ const exit = yield* import_effect10.Effect.exit(run(op, stack));
1976
+ if (exit._tag === "Success") {
1977
+ const successSnapshot = Snapshot.success({ keyHash: keyHash2, data: exit.value });
1978
+ const wroteSuccessPath = yield* writebackIfCurrentKeyHashForRow(
1979
+ rowId,
1980
+ keyHash2,
1981
+ successSnapshot,
1982
+ "source-refresh",
1983
+ `source:${fieldPath}:${rowId}:success`,
1984
+ "success"
1985
+ );
1986
+ if (wroteSuccessPath) {
1987
+ yield* recordSnapshot(replayMode, replayLog, {
1988
+ _tag: "ResourceSnapshot",
1989
+ resourceId,
1990
+ fieldPath: wroteSuccessPath,
1991
+ keyHash: keyHash2,
1992
+ concurrency: mode2,
1993
+ phase: "success",
1994
+ snapshot: successSnapshot,
1995
+ timestamp: Date.now(),
1996
+ moduleId,
1997
+ instanceId
1998
+ });
1999
+ }
2000
+ } else {
2001
+ const errorSnapshot = Snapshot.error({ keyHash: keyHash2, error: exit.cause });
2002
+ const wroteErrorPath = yield* writebackIfCurrentKeyHashForRow(
2003
+ rowId,
2004
+ keyHash2,
2005
+ errorSnapshot,
2006
+ "source-refresh",
2007
+ `source:${fieldPath}:${rowId}:error`,
2008
+ "error"
2009
+ );
2010
+ if (wroteErrorPath) {
2011
+ yield* recordSnapshot(replayMode, replayLog, {
2012
+ _tag: "ResourceSnapshot",
2013
+ resourceId,
2014
+ fieldPath: wroteErrorPath,
2015
+ keyHash: keyHash2,
2016
+ concurrency: mode2,
2017
+ phase: "error",
2018
+ snapshot: errorSnapshot,
2019
+ timestamp: Date.now(),
2020
+ moduleId,
2021
+ instanceId
2022
+ });
2023
+ }
2024
+ }
2025
+ }).pipe(import_effect10.Effect.catchAllCause(() => import_effect10.Effect.void));
2026
+ const fiber = yield* import_effect10.Effect.forkScoped(import_effect10.Effect.locally(inSyncTransactionFiber, false)(io));
2027
+ const myGen = gen2 += 1;
2028
+ inFlight2.set(rowId, { gen: myGen, fiber, keyHash: keyHash2 });
2029
+ yield* import_effect10.Effect.forkScoped(
2030
+ import_effect10.Effect.locally(
2031
+ inSyncTransactionFiber,
2032
+ false
2033
+ )(
2034
+ import_effect10.Fiber.await(fiber).pipe(
2035
+ import_effect10.Effect.zipRight(
2036
+ import_effect10.Effect.sync(() => {
2037
+ const current = inFlight2.get(rowId);
2038
+ if (current && current.gen === myGen) {
2039
+ inFlight2.delete(rowId);
2040
+ }
2041
+ })
2042
+ ),
2043
+ import_effect10.Effect.zipRight(
2044
+ mode2 === "exhaust-trailing" ? import_effect10.Effect.gen(function* () {
2045
+ const next = trailing2.get(rowId);
2046
+ trailing2.delete(rowId);
2047
+ if (next) {
2048
+ yield* startFetch2(rowId, next.key, next.keyHash, replayMode, replayLog);
2049
+ }
2050
+ }) : import_effect10.Effect.void
2051
+ ),
2052
+ import_effect10.Effect.catchAllCause(() => import_effect10.Effect.void)
2053
+ )
2054
+ )
2055
+ );
2056
+ });
2057
+ register(
2058
+ fieldPath,
2059
+ (state) => import_effect10.Effect.gen(function* () {
2060
+ const { moduleId, instanceId } = getBoundScope(bound);
2061
+ const replayModeOpt = yield* import_effect10.Effect.serviceOption(ReplayModeConfigTag);
2062
+ const replayMode = import_effect10.Option.isSome(replayModeOpt) ? replayModeOpt.value.mode : "live";
2063
+ const replayLogOpt = yield* import_effect10.Effect.serviceOption(ReplayLog);
2064
+ const replayLog = import_effect10.Option.isSome(replayLogOpt) ? replayLogOpt.value : void 0;
2065
+ const force = yield* import_effect10.FiberRef.get(forceSourceRefresh);
2066
+ const listValue = getAtPath(state, listPath);
2067
+ const items = Array.isArray(listValue) ? listValue : [];
2068
+ const ids = store.ensureList(listPath, items);
2069
+ const traceKey = `${instanceId ?? "unknown"}::source::${fieldPath}`;
2070
+ if (isDevEnv() && (yield* onceInRunSession(`deps_trace_settled:${traceKey}`))) {
2071
+ try {
2072
+ const sample = items[0];
2073
+ if (sample !== void 0) {
2074
+ const traced = trace((s) => entry.meta.key(s), sample);
2075
+ const prefixedReads = traced.reads.map((r) => r ? `${listPath}[].${r}` : `${listPath}[]`);
2076
+ const diff = diffDeps(entry.meta.deps ?? [], prefixedReads);
2077
+ if (diff) {
2078
+ yield* emitDepsMismatch({
2079
+ moduleId,
2080
+ instanceId,
2081
+ kind: "source",
2082
+ fieldPath,
2083
+ diff
2084
+ });
2085
+ }
2086
+ }
2087
+ } catch {
2088
+ }
2089
+ }
2090
+ for (let index = 0; index < items.length; index++) {
2091
+ const rowId = ids[index];
2092
+ if (!rowId) continue;
2093
+ const concretePath = toListItemValuePath(listPath, index, itemPath);
2094
+ const prevSnapshot = getAtPath(state, concretePath);
2095
+ let key;
2096
+ try {
2097
+ key = entry.meta.key(items[index]);
2098
+ } catch {
2099
+ key = void 0;
2100
+ }
2101
+ const current = inFlight2.get(rowId);
2102
+ if (key === void 0) {
2103
+ trailing2.delete(rowId);
2104
+ inFlight2.delete(rowId);
2105
+ if (prevSnapshot && typeof prevSnapshot === "object" && prevSnapshot.status === "idle" && prevSnapshot.data === void 0 && prevSnapshot.error === void 0) {
2106
+ continue;
2107
+ }
2108
+ const idleSnapshot = Snapshot.idle();
2109
+ const wroteIdlePath = yield* setSnapshotForRowInTxn(
2110
+ rowId,
2111
+ idleSnapshot,
2112
+ "source-refresh",
2113
+ `source:${fieldPath}:${rowId}:idle`
2114
+ );
2115
+ if (wroteIdlePath) {
2116
+ const event = {
2117
+ _tag: "ResourceSnapshot",
2118
+ resourceId,
2119
+ fieldPath: wroteIdlePath,
2120
+ keyHash: void 0,
2121
+ concurrency: mode2,
2122
+ phase: "idle",
2123
+ snapshot: idleSnapshot,
2124
+ timestamp: Date.now(),
2125
+ moduleId,
2126
+ instanceId
2127
+ };
2128
+ recordReplayEvent(bound, event);
2129
+ yield* recordSnapshot(replayMode, replayLog, event);
2130
+ }
2131
+ continue;
2132
+ }
2133
+ const h = keyHash(key);
2134
+ if (!force && current && current.keyHash === h) {
2135
+ continue;
2136
+ }
2137
+ const prevKeyHash = prevSnapshot && typeof prevSnapshot === "object" ? prevSnapshot.keyHash : void 0;
2138
+ if (!force && !current && prevKeyHash === h) {
2139
+ continue;
2140
+ }
2141
+ if (mode2 === "exhaust-trailing" && current) {
2142
+ trailing2.set(rowId, { key, keyHash: h });
2143
+ const loadingSnapshot = Snapshot.loading({ keyHash: h });
2144
+ const wroteLoadingPath = yield* setSnapshotForRowInTxn(
2145
+ rowId,
2146
+ loadingSnapshot,
2147
+ "source-refresh",
2148
+ `source:${fieldPath}:${rowId}:loading`
2149
+ );
2150
+ if (wroteLoadingPath) {
2151
+ const event = {
2152
+ _tag: "ResourceSnapshot",
2153
+ resourceId,
2154
+ fieldPath: wroteLoadingPath,
2155
+ keyHash: h,
2156
+ concurrency: mode2,
2157
+ phase: "loading",
2158
+ snapshot: loadingSnapshot,
2159
+ timestamp: Date.now(),
2160
+ moduleId,
2161
+ instanceId
2162
+ };
2163
+ recordReplayEvent(bound, event);
2164
+ yield* recordSnapshot(replayMode, replayLog, event);
2165
+ }
2166
+ continue;
2167
+ }
2168
+ if (mode2 === "switch" && current) {
2169
+ trailing2.delete(rowId);
2170
+ inFlight2.delete(rowId);
2171
+ }
2172
+ yield* startFetch2(rowId, key, h, replayMode, replayLog);
2173
+ }
2174
+ })
2175
+ );
2176
+ return import_effect10.Effect.void;
2177
+ }
2178
+ let inFlight;
2179
+ let gen = 0;
2180
+ let trailing;
2181
+ const concurrency = entry.meta.concurrency;
2182
+ const mode = concurrency ?? "switch";
2183
+ const startFetch = (key, keyHash2, replayMode, replayLog) => import_effect10.Effect.gen(function* () {
2184
+ const { moduleId, instanceId } = getBoundScope(bound);
2185
+ let loadingSnapshot = Snapshot.loading({ keyHash: keyHash2 });
2186
+ if (replayMode === "replay" && replayLog) {
2187
+ const replayLoading = yield* replayLog.consumeNextResourceSnapshot({
2188
+ resourceId,
2189
+ fieldPath,
2190
+ keyHash: keyHash2,
2191
+ phase: "loading"
2192
+ });
2193
+ if (replayLoading) {
2194
+ loadingSnapshot = replayLoading.snapshot;
2195
+ }
2196
+ }
2197
+ const wroteLoading = yield* setSnapshotInTxn(
2198
+ bound,
2199
+ fieldPath,
2200
+ loadingSnapshot,
2201
+ "source-refresh",
2202
+ `source:${fieldPath}:loading`,
2203
+ step.debugInfo?.graphNodeId
2204
+ );
2205
+ if (wroteLoading) {
2206
+ const event = {
2207
+ _tag: "ResourceSnapshot",
2208
+ resourceId,
2209
+ fieldPath,
2210
+ keyHash: keyHash2,
2211
+ concurrency: mode,
2212
+ phase: "loading",
2213
+ snapshot: loadingSnapshot,
2214
+ timestamp: Date.now(),
2215
+ moduleId,
2216
+ instanceId
2217
+ };
2218
+ recordReplayEvent(bound, event);
2219
+ yield* recordSnapshot(replayMode, replayLog, event);
2220
+ }
2221
+ const io = import_effect10.Effect.gen(function* () {
2222
+ if (replayMode === "replay" && replayLog) {
2223
+ yield* import_effect10.Effect.yieldNow();
2224
+ const replayed = yield* replayLog.consumeNextResourceSnapshot({
2225
+ resourceId,
2226
+ fieldPath,
2227
+ keyHash: keyHash2
2228
+ });
2229
+ if (!replayed) return yield* import_effect10.Effect.void;
2230
+ if (replayed.phase === "success") {
2231
+ const event = {
2232
+ _tag: "ResourceSnapshot",
2233
+ resourceId,
2234
+ fieldPath,
2235
+ keyHash: keyHash2,
2236
+ concurrency: mode,
2237
+ phase: "success",
2238
+ snapshot: replayed.snapshot,
2239
+ timestamp: Date.now(),
2240
+ moduleId,
2241
+ instanceId
2242
+ };
2243
+ yield* writebackIfCurrentKeyHash(
2244
+ bound,
2245
+ fieldPath,
2246
+ keyHash2,
2247
+ replayed.snapshot,
2248
+ "source-refresh",
2249
+ `source:${fieldPath}:success`,
2250
+ step.debugInfo?.graphNodeId,
2251
+ event
2252
+ );
2253
+ } else if (replayed.phase === "error") {
2254
+ const event = {
2255
+ _tag: "ResourceSnapshot",
2256
+ resourceId,
2257
+ fieldPath,
2258
+ keyHash: keyHash2,
2259
+ concurrency: mode,
2260
+ phase: "error",
2261
+ snapshot: replayed.snapshot,
2262
+ timestamp: Date.now(),
2263
+ moduleId,
2264
+ instanceId
2265
+ };
2266
+ yield* writebackIfCurrentKeyHash(
2267
+ bound,
2268
+ fieldPath,
2269
+ keyHash2,
2270
+ replayed.snapshot,
2271
+ "source-refresh",
2272
+ `source:${fieldPath}:error`,
2273
+ step.debugInfo?.graphNodeId,
2274
+ event
2275
+ );
2276
+ }
2277
+ return yield* import_effect10.Effect.void;
2278
+ }
2279
+ const stack = yield* getMiddlewareStack();
2280
+ const registryOpt = yield* import_effect10.Effect.serviceOption(internal.ResourceRegistryTag);
2281
+ const registry = import_effect10.Option.isSome(registryOpt) ? registryOpt.value : void 0;
2282
+ const spec = registry?.specs.get(resourceId);
2283
+ if (!spec) {
2284
+ return yield* import_effect10.Effect.void;
2285
+ }
2286
+ const loadEffect = spec.load(key);
2287
+ const meta = {
2288
+ moduleId,
2289
+ instanceId,
2290
+ fieldPath,
2291
+ resourceId,
2292
+ key,
2293
+ keyHash: keyHash2,
2294
+ traitNodeId: step.debugInfo?.graphNodeId,
2295
+ stepId: step.id
2296
+ };
2297
+ if (!(typeof meta.opSeq === "number" && Number.isFinite(meta.opSeq))) {
2298
+ const sessionOpt = yield* import_effect10.Effect.serviceOption(RunSessionTag);
2299
+ if (import_effect10.Option.isSome(sessionOpt)) {
2300
+ const seqKey = instanceId ?? "global";
2301
+ meta.opSeq = sessionOpt.value.local.nextSeq("opSeq", seqKey);
2302
+ }
2303
+ }
2304
+ const op = make({
2305
+ kind: "trait-source",
2306
+ name: resourceId,
2307
+ effect: loadEffect,
2308
+ meta
2309
+ });
2310
+ const exit = yield* import_effect10.Effect.exit(run(op, stack));
2311
+ if (exit._tag === "Success") {
2312
+ const successSnapshot = Snapshot.success({ keyHash: keyHash2, data: exit.value });
2313
+ const event = {
2314
+ _tag: "ResourceSnapshot",
2315
+ resourceId,
2316
+ fieldPath,
2317
+ keyHash: keyHash2,
2318
+ concurrency: mode,
2319
+ phase: "success",
2320
+ snapshot: successSnapshot,
2321
+ timestamp: Date.now(),
2322
+ moduleId,
2323
+ instanceId
2324
+ };
2325
+ const wroteSuccess = yield* writebackIfCurrentKeyHash(
2326
+ bound,
2327
+ fieldPath,
2328
+ keyHash2,
2329
+ successSnapshot,
2330
+ "source-refresh",
2331
+ `source:${fieldPath}:success`,
2332
+ step.debugInfo?.graphNodeId,
2333
+ event
2334
+ );
2335
+ if (wroteSuccess) {
2336
+ yield* recordSnapshot(replayMode, replayLog, event);
2337
+ }
2338
+ } else {
2339
+ const errorSnapshot = Snapshot.error({ keyHash: keyHash2, error: exit.cause });
2340
+ const event = {
2341
+ _tag: "ResourceSnapshot",
2342
+ resourceId,
2343
+ fieldPath,
2344
+ keyHash: keyHash2,
2345
+ concurrency: mode,
2346
+ phase: "error",
2347
+ snapshot: errorSnapshot,
2348
+ timestamp: Date.now(),
2349
+ moduleId,
2350
+ instanceId
2351
+ };
2352
+ const wroteError = yield* writebackIfCurrentKeyHash(
2353
+ bound,
2354
+ fieldPath,
2355
+ keyHash2,
2356
+ errorSnapshot,
2357
+ "source-refresh",
2358
+ `source:${fieldPath}:error`,
2359
+ step.debugInfo?.graphNodeId,
2360
+ event
2361
+ );
2362
+ if (wroteError) {
2363
+ yield* recordSnapshot(replayMode, replayLog, event);
2364
+ }
2365
+ }
2366
+ }).pipe(import_effect10.Effect.catchAllCause(() => import_effect10.Effect.void));
2367
+ const fiber = yield* import_effect10.Effect.forkScoped(import_effect10.Effect.locally(inSyncTransactionFiber, false)(io));
2368
+ const myGen = gen += 1;
2369
+ inFlight = { gen: myGen, fiber, keyHash: keyHash2 };
2370
+ yield* import_effect10.Effect.forkScoped(
2371
+ import_effect10.Effect.locally(
2372
+ inSyncTransactionFiber,
2373
+ false
2374
+ )(
2375
+ import_effect10.Fiber.await(fiber).pipe(
2376
+ import_effect10.Effect.zipRight(
2377
+ import_effect10.Effect.sync(() => {
2378
+ if (inFlight && inFlight.gen === myGen) {
2379
+ inFlight = void 0;
2380
+ }
2381
+ })
2382
+ ),
2383
+ import_effect10.Effect.zipRight(
2384
+ mode === "exhaust-trailing" ? import_effect10.Effect.gen(function* () {
2385
+ const next = trailing;
2386
+ trailing = void 0;
2387
+ if (next) {
2388
+ yield* startFetch(next.key, next.keyHash, replayMode, replayLog);
2389
+ }
2390
+ }) : import_effect10.Effect.void
2391
+ ),
2392
+ import_effect10.Effect.catchAllCause(() => import_effect10.Effect.void)
2393
+ )
2394
+ )
2395
+ );
2396
+ });
2397
+ register(
2398
+ fieldPath,
2399
+ (state) => import_effect10.Effect.gen(function* () {
2400
+ const { moduleId, instanceId } = getBoundScope(bound);
2401
+ const replayModeOpt = yield* import_effect10.Effect.serviceOption(ReplayModeConfigTag);
2402
+ const replayMode = import_effect10.Option.isSome(replayModeOpt) ? replayModeOpt.value.mode : "live";
2403
+ const replayLogOpt = yield* import_effect10.Effect.serviceOption(ReplayLog);
2404
+ const replayLog = import_effect10.Option.isSome(replayLogOpt) ? replayLogOpt.value : void 0;
2405
+ const force = yield* import_effect10.FiberRef.get(forceSourceRefresh);
2406
+ let key;
2407
+ try {
2408
+ key = entry.meta.key(state);
2409
+ } catch {
2410
+ key = void 0;
2411
+ }
2412
+ const traceKey = `${instanceId ?? "unknown"}::source::${fieldPath}`;
2413
+ if (isDevEnv() && (yield* onceInRunSession(`deps_trace_settled:${traceKey}`))) {
2414
+ try {
2415
+ const traced = trace((s) => entry.meta.key(s), state);
2416
+ const diff = diffDeps(entry.meta.deps ?? [], traced.reads);
2417
+ if (diff) {
2418
+ yield* emitDepsMismatch({
2419
+ moduleId,
2420
+ instanceId,
2421
+ kind: "source",
2422
+ fieldPath,
2423
+ diff
2424
+ });
2425
+ }
2426
+ } catch {
2427
+ }
2428
+ }
2429
+ if (key === void 0) {
2430
+ if (inFlight) {
2431
+ yield* import_effect10.Fiber.interruptFork(inFlight.fiber);
2432
+ inFlight = void 0;
2433
+ }
2434
+ trailing = void 0;
2435
+ const idleSnapshot = Snapshot.idle();
2436
+ const wroteIdle = yield* setSnapshotInTxn(
2437
+ bound,
2438
+ fieldPath,
2439
+ idleSnapshot,
2440
+ "source-refresh",
2441
+ `source:${fieldPath}:idle`,
2442
+ step.debugInfo?.graphNodeId
2443
+ );
2444
+ if (wroteIdle) {
2445
+ const event = {
2446
+ _tag: "ResourceSnapshot",
2447
+ resourceId,
2448
+ fieldPath,
2449
+ keyHash: void 0,
2450
+ concurrency: mode,
2451
+ phase: "idle",
2452
+ snapshot: idleSnapshot,
2453
+ timestamp: Date.now(),
2454
+ moduleId,
2455
+ instanceId
2456
+ };
2457
+ recordReplayEvent(bound, event);
2458
+ yield* recordSnapshot(replayMode, replayLog, event);
2459
+ }
2460
+ return;
2461
+ }
2462
+ const h = keyHash(key);
2463
+ if (!force) {
2464
+ if (inFlight && inFlight.keyHash === h) {
2465
+ return;
2466
+ }
2467
+ const currentSnapshot = getAtPath(state, fieldPath);
2468
+ const currentKeyHash = currentSnapshot && typeof currentSnapshot === "object" ? currentSnapshot.keyHash : void 0;
2469
+ const currentStatus = currentSnapshot && typeof currentSnapshot === "object" ? currentSnapshot.status : void 0;
2470
+ if (currentStatus && currentStatus !== "idle" && currentKeyHash === h) {
2471
+ return;
2472
+ }
2473
+ }
2474
+ if (mode === "exhaust-trailing" && inFlight) {
2475
+ trailing = { key, keyHash: h };
2476
+ const loadingSnapshot = Snapshot.loading({ keyHash: h });
2477
+ const wroteLoading = yield* setSnapshotInTxn(
2478
+ bound,
2479
+ fieldPath,
2480
+ loadingSnapshot,
2481
+ "source-refresh",
2482
+ `source:${fieldPath}:loading`,
2483
+ step.debugInfo?.graphNodeId
2484
+ );
2485
+ if (wroteLoading) {
2486
+ const event = {
2487
+ _tag: "ResourceSnapshot",
2488
+ resourceId,
2489
+ fieldPath,
2490
+ keyHash: h,
2491
+ concurrency: mode,
2492
+ phase: "loading",
2493
+ snapshot: loadingSnapshot,
2494
+ timestamp: Date.now(),
2495
+ moduleId,
2496
+ instanceId
2497
+ };
2498
+ recordReplayEvent(bound, event);
2499
+ yield* recordSnapshot(replayMode, replayLog, event);
2500
+ }
2501
+ return;
2502
+ }
2503
+ if (mode === "switch" && inFlight) {
2504
+ yield* import_effect10.Fiber.interruptFork(inFlight.fiber);
2505
+ inFlight = void 0;
2506
+ trailing = void 0;
2507
+ }
2508
+ yield* startFetch(key, h, replayMode, replayLog);
2509
+ })
2510
+ );
2511
+ return import_effect10.Effect.void;
2512
+ };
2513
+
2514
+ // src/internal/state-trait/install.ts
2515
+ var buildEntryIndex = (entries) => {
2516
+ const index = /* @__PURE__ */ new Map();
2517
+ for (const entry of entries) {
2518
+ const list2 = index.get(entry.fieldPath) ?? [];
2519
+ list2.push(entry);
2520
+ index.set(entry.fieldPath, list2);
2521
+ }
2522
+ return index;
2523
+ };
2524
+ var install = (bound, program) => {
2525
+ try {
2526
+ const internals = getBoundInternals(bound);
2527
+ internals.traits.registerStateTraitProgram(program, {
2528
+ bumpReason: "logic_installed"
2529
+ });
2530
+ } catch {
2531
+ }
2532
+ const entryIndex = buildEntryIndex(program.entries);
2533
+ const installStep = (step) => {
2534
+ if (!step.targetFieldPath) {
2535
+ return import_effect11.Effect.void;
2536
+ }
2537
+ if (step.kind !== "source-refresh") {
2538
+ return import_effect11.Effect.void;
2539
+ }
2540
+ const candidates = entryIndex.get(step.targetFieldPath);
2541
+ if (!candidates || candidates.length === 0) {
2542
+ return import_effect11.Effect.void;
2543
+ }
2544
+ const entry = candidates.find((e) => e.kind === "source");
2545
+ if (!entry) {
2546
+ return import_effect11.Effect.void;
2547
+ }
2548
+ return installSourceRefresh(bound, step, entry);
2549
+ };
2550
+ return import_effect11.Effect.forEach(program.plan.steps, (step) => installStep(step)).pipe(import_effect11.Effect.asVoid);
2551
+ };
2552
+
2553
+ // src/internal/state-trait/ir.ts
2554
+ var normalizeFieldPaths = (paths) => {
2555
+ if (!paths || paths.length === 0) return [];
2556
+ const out = [];
2557
+ for (const path of paths) {
2558
+ const normalized = normalizeFieldPath(path);
2559
+ if (normalized) out.push(normalized);
2560
+ }
2561
+ return out;
2562
+ };
2563
+ var normalizeFieldPath2 = (path) => path ? normalizeFieldPath(path) : void 0;
2564
+ var toNodeKind = (step) => {
2565
+ switch (step.kind) {
2566
+ case "computed-update":
2567
+ return "computed";
2568
+ case "link-propagate":
2569
+ return "link";
2570
+ case "source-refresh":
2571
+ return "source";
2572
+ case "check-validate":
2573
+ return "check";
2574
+ }
2575
+ };
2576
+ var findEntryForStep = (program, step) => {
2577
+ const fieldPath = step.targetFieldPath;
2578
+ if (!fieldPath) return void 0;
2579
+ const kind = toNodeKind(step);
2580
+ return program.entries.find(
2581
+ (e) => e.fieldPath === fieldPath && (e.kind === kind || kind === "check" && e.kind === "check" || kind === "source" && e.kind === "source" || kind === "link" && e.kind === "link" || kind === "computed" && e.kind === "computed")
2582
+ );
2583
+ };
2584
+ var getReadsForEntry = (entry) => {
2585
+ if (!entry) return void 0;
2586
+ if (entry.kind === "computed") {
2587
+ return entry.meta.deps;
2588
+ }
2589
+ if (entry.kind === "source") {
2590
+ return entry.meta.deps;
2591
+ }
2592
+ if (entry.kind === "link") {
2593
+ const from2 = entry.meta.from;
2594
+ return from2 ? [from2] : [];
2595
+ }
2596
+ if (entry.kind === "check") {
2597
+ const rules = entry.meta?.rules ?? {};
2598
+ const out = [];
2599
+ for (const name of Object.keys(rules)) {
2600
+ const rule = rules[name];
2601
+ const deps = rule?.deps;
2602
+ if (deps) out.push(...deps);
2603
+ }
2604
+ return out;
2605
+ }
2606
+ return void 0;
2607
+ };
2608
+ var exportStaticIr = (params) => {
2609
+ const moduleId = params.moduleId;
2610
+ const version = params.version ?? "009";
2611
+ const metaByField = /* @__PURE__ */ new Map();
2612
+ for (const node2 of params.program.graph.nodes) {
2613
+ const meta = node2.meta;
2614
+ if (!meta || typeof meta !== "object") continue;
2615
+ const label = typeof meta.label === "string" ? meta.label : void 0;
2616
+ const description = typeof meta.description === "string" ? meta.description : void 0;
2617
+ const tags = Array.isArray(meta.tags) && meta.tags.every((t) => typeof t === "string") ? meta.tags : void 0;
2618
+ const group = typeof meta.group === "string" ? meta.group : void 0;
2619
+ const docsUrl = typeof meta.docsUrl === "string" ? meta.docsUrl : void 0;
2620
+ const cacheGroup = typeof meta.cacheGroup === "string" ? meta.cacheGroup : void 0;
2621
+ const annotationsRaw = meta.annotations;
2622
+ const annotations = annotationsRaw && typeof annotationsRaw === "object" && !Array.isArray(annotationsRaw) ? annotationsRaw : void 0;
2623
+ if (label || description || tags || group || docsUrl || cacheGroup || annotations) {
2624
+ metaByField.set(node2.id, {
2625
+ label,
2626
+ description,
2627
+ tags,
2628
+ group,
2629
+ docsUrl,
2630
+ cacheGroup,
2631
+ annotations
2632
+ });
2633
+ }
2634
+ }
2635
+ const nodes = params.program.plan.steps.map((step) => {
2636
+ const kind = toNodeKind(step);
2637
+ const entry = findEntryForStep(params.program, step);
2638
+ const reads = normalizeFieldPaths(getReadsForEntry(entry));
2639
+ const target = step.targetFieldPath;
2640
+ const write = normalizeFieldPath2(target);
2641
+ const writes = write ? [write] : [];
2642
+ const meta = target ? metaByField.get(target) : void 0;
2643
+ const base2 = {
2644
+ nodeId: step.id,
2645
+ kind,
2646
+ reads,
2647
+ writes: kind === "check" ? [] : writes,
2648
+ meta
2649
+ };
2650
+ if (kind !== "check" && target && !write) {
2651
+ return { ...base2, writesUnknown: true };
2652
+ }
2653
+ return base2;
2654
+ });
2655
+ const edges = params.program.graph.edges.map((edge) => ({
2656
+ edgeId: edge.id,
2657
+ from: edge.from,
2658
+ to: edge.to,
2659
+ kind: edge.kind
2660
+ }));
2661
+ const base = {
2662
+ version,
2663
+ moduleId,
2664
+ nodes,
2665
+ edges
2666
+ };
2667
+ const digest = `stir:${version}:${fnv1a32(stableStringify2(base))}`;
2668
+ return {
2669
+ ...base,
2670
+ digest
2671
+ };
2672
+ };
2673
+
2674
+ // src/StateTrait.ts
2675
+ var $root = "$root";
2676
+ var from = (_schema) => (spec) => spec;
2677
+ var node = (spec) => ({
2678
+ _tag: "StateTraitNode",
2679
+ ...spec
2680
+ });
2681
+ var list = (spec) => ({
2682
+ _tag: "StateTraitList",
2683
+ ...spec
2684
+ });
2685
+ var computed = (input) => {
2686
+ const derive = (state) => {
2687
+ const args = input.deps.map((dep) => getAtPath(state, dep));
2688
+ return input.get(...args);
2689
+ };
2690
+ return {
2691
+ fieldPath: void 0,
2692
+ kind: "computed",
2693
+ meta: {
2694
+ deps: input.deps,
2695
+ derive,
2696
+ equals: input.equals,
2697
+ ...input.scheduling ? { scheduling: input.scheduling } : {}
2698
+ }
2699
+ };
2700
+ };
2701
+ var source = (input) => {
2702
+ const key = (state) => {
2703
+ const args = input.deps.map((dep) => getAtPath(state, dep));
2704
+ return input.key(...args);
2705
+ };
2706
+ return {
2707
+ fieldPath: void 0,
2708
+ kind: "source",
2709
+ meta: { ...input, key }
2710
+ };
2711
+ };
2712
+ var link = (meta) => ({
2713
+ fieldPath: void 0,
2714
+ kind: "link",
2715
+ meta: { ...meta, ...meta.scheduling ? { scheduling: meta.scheduling } : {} }
2716
+ });
2717
+ var build2 = (stateSchema, spec) => build(stateSchema, spec);
2718
+ var install2 = (bound, program) => install(bound, program);
2719
+ var exportStaticIr2 = (program, moduleId, options) => exportStaticIr({
2720
+ program,
2721
+ moduleId,
2722
+ version: options?.version
2723
+ });
2724
+ // Annotate the CommonJS export names for ESM import in node:
2725
+ 0 && (module.exports = {
2726
+ $root,
2727
+ build,
2728
+ computed,
2729
+ exportStaticIr,
2730
+ from,
2731
+ install,
2732
+ link,
2733
+ list,
2734
+ node,
2735
+ source
2736
+ });
2737
+ //# sourceMappingURL=StateTrait.cjs.map