@raphy-js/raph 1.0.0-dev.2 → 1.0.1-dev.25

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 (246) hide show
  1. package/README.md +1096 -0
  2. package/dist/api/Raph.d.ts +59 -190
  3. package/dist/api/RaphFacadeSession.d.ts +90 -0
  4. package/dist/api/RaphReactivityInstance.d.ts +72 -0
  5. package/dist/api/errors.d.ts +9 -4
  6. package/dist/api/types.d.ts +162 -17
  7. package/dist/core-CClhT8WR.js +1044 -0
  8. package/dist/core-cPQWYD4K.cjs +1 -0
  9. package/dist/debug/api/Raph.cjs +1 -1
  10. package/dist/debug/api/Raph.js +368 -367
  11. package/dist/debug/api/RaphFacadeSession.cjs +1 -0
  12. package/dist/debug/api/RaphFacadeSession.js +302 -0
  13. package/dist/debug/api/RaphReactivityInstance.cjs +1 -0
  14. package/dist/debug/api/RaphReactivityInstance.js +146 -0
  15. package/dist/debug/api/errors.cjs +1 -1
  16. package/dist/debug/api/errors.js +10 -7
  17. package/dist/debug/path/DataPath.cjs +1 -0
  18. package/dist/debug/path/DataPath.js +390 -0
  19. package/dist/debug/path/PathRouter.cjs +1 -0
  20. package/dist/debug/path/PathRouter.js +80 -0
  21. package/dist/debug/path/RaphKernel.cjs +1 -1
  22. package/dist/debug/path/RaphKernel.js +316 -236
  23. package/dist/debug/path/data-path.utils.cjs +1 -0
  24. package/dist/debug/path/data-path.utils.js +56 -0
  25. package/dist/debug/path/derived/DerivedRegistry.cjs +1 -0
  26. package/dist/debug/path/derived/DerivedRegistry.js +143 -0
  27. package/dist/debug/path/derived/RaphDerivedHandle.cjs +1 -0
  28. package/dist/debug/path/{RaphDerivedHandle.js → derived/RaphDerivedHandle.js} +19 -22
  29. package/dist/debug/path/derived/derived-collection.utils.cjs +1 -0
  30. package/dist/debug/path/{derived-collection.js → derived/derived-collection.utils.js} +71 -71
  31. package/dist/debug/path/derived/derived-strategy.types.cjs +1 -0
  32. package/dist/debug/path/derived/derived-strategy.types.js +1 -0
  33. package/dist/debug/path/meta/MetaController.cjs +1 -0
  34. package/dist/debug/path/{MetaController.js → meta/MetaController.js} +58 -66
  35. package/dist/debug/path/meta/RaphMeta.cjs +1 -0
  36. package/dist/debug/path/meta/RaphMeta.js +62 -0
  37. package/dist/debug/path/meta/RaphMetaStore.cjs +1 -0
  38. package/dist/debug/path/{RaphMetaStore.js → meta/RaphMetaStore.js} +24 -30
  39. package/dist/debug/path/meta/meta.types.cjs +1 -0
  40. package/dist/debug/path/meta/meta.types.js +1 -0
  41. package/dist/debug/path/storage/AdapterPathStore.cjs +1 -0
  42. package/dist/debug/path/storage/AdapterPathStore.js +128 -0
  43. package/dist/debug/path/storage/DefaultDataAdapter.cjs +1 -0
  44. package/dist/debug/path/{data-adapter.js → storage/DefaultDataAdapter.js} +47 -57
  45. package/dist/debug/path/storage/PathEventHub.cjs +1 -0
  46. package/dist/debug/path/storage/PathEventHub.js +161 -0
  47. package/dist/debug/path/storage/PathStore.cjs +1 -0
  48. package/dist/debug/path/{PathStore.js → storage/PathStore.js} +88 -98
  49. package/dist/debug/path/storage/createDataDraft.cjs +1 -0
  50. package/dist/debug/path/{data-draft.js → storage/createDataDraft.js} +24 -28
  51. package/dist/debug/path/storage/data-adapter.types.cjs +1 -0
  52. package/dist/debug/path/storage/data-adapter.types.js +1 -0
  53. package/dist/debug/reactivity/disposal.cjs +1 -0
  54. package/dist/debug/reactivity/disposal.js +32 -0
  55. package/dist/debug/reactivity/engine.cjs +1 -1
  56. package/dist/debug/reactivity/engine.js +888 -321
  57. package/dist/debug/reactivity/reactive-object.cjs +1 -0
  58. package/dist/debug/reactivity/reactive-object.js +265 -0
  59. package/dist/debug/reactivity/scope.cjs +1 -1
  60. package/dist/debug/reactivity/scope.js +221 -117
  61. package/dist/debug/reactivity/watch.cjs +1 -1
  62. package/dist/debug/reactivity/watch.js +1 -1
  63. package/dist/debug/runtime/RaphRuntime.cjs +1 -1
  64. package/dist/debug/runtime/RaphRuntime.js +1134 -502
  65. package/dist/debug/runtime/diagnostics/RaphDebug.cjs +1 -0
  66. package/dist/debug/runtime/diagnostics/RaphDebug.js +287 -0
  67. package/dist/debug/runtime/errors.cjs +1 -1
  68. package/dist/debug/runtime/errors.js +6 -3
  69. package/dist/debug/runtime/ownership/RaphEffectScope.cjs +1 -0
  70. package/dist/debug/runtime/ownership/RaphEffectScope.js +304 -0
  71. package/dist/debug/runtime/ownership/RaphNode.cjs +1 -0
  72. package/dist/debug/runtime/ownership/RaphNode.js +665 -0
  73. package/dist/debug/runtime/ownership/RaphScope.cjs +1 -0
  74. package/dist/debug/runtime/ownership/RaphScope.js +236 -0
  75. package/dist/debug/runtime/ownership/parent-graph.types.cjs +1 -0
  76. package/dist/debug/runtime/ownership/parent-graph.types.js +1 -0
  77. package/dist/debug/runtime/phases/RaphFrameLoop.cjs +1 -0
  78. package/dist/debug/runtime/{RaphFrameLoop.js → phases/RaphFrameLoop.js} +13 -17
  79. package/dist/debug/runtime/phases/RaphPhasePipeline.cjs +1 -0
  80. package/dist/debug/runtime/phases/RaphPhasePipeline.js +848 -0
  81. package/dist/debug/runtime/phases/RaphPhaseTaskRecord.cjs +1 -0
  82. package/dist/debug/runtime/phases/RaphPhaseTaskRecord.js +176 -0
  83. package/dist/debug/runtime/phases/RaphPhaseWatch.cjs +1 -0
  84. package/dist/debug/runtime/phases/RaphPhaseWatch.js +20 -0
  85. package/dist/debug/runtime/phases/orderPhaseTasks.cjs +1 -0
  86. package/dist/debug/runtime/phases/orderPhaseTasks.js +59 -0
  87. package/dist/debug/runtime/reactivity/PathHandle.cjs +1 -0
  88. package/dist/debug/runtime/reactivity/PathHandle.js +165 -0
  89. package/dist/debug/runtime/reactivity/RaphMetaSource.cjs +1 -0
  90. package/dist/debug/runtime/reactivity/RaphMetaSource.js +108 -0
  91. package/dist/debug/runtime/reactivity/RaphSelector.cjs +1 -0
  92. package/dist/debug/runtime/reactivity/RaphSelector.js +503 -0
  93. package/dist/debug/runtime/reactivity/RaphWorkGraph.cjs +1 -0
  94. package/dist/debug/runtime/reactivity/RaphWorkGraph.js +1157 -0
  95. package/dist/debug/runtime/reactivity/RuntimeReactivity.cjs +1 -0
  96. package/dist/debug/runtime/reactivity/RuntimeReactivity.js +550 -0
  97. package/dist/debug/runtime/reactivity/RuntimeWatch.cjs +1 -0
  98. package/dist/debug/runtime/reactivity/RuntimeWatch.js +77 -0
  99. package/dist/debug/runtime/reactivity/disposal-sweep.utils.cjs +1 -0
  100. package/dist/debug/runtime/reactivity/disposal-sweep.utils.js +42 -0
  101. package/dist/debug/runtime/reactivity/runtime-reactivity.types.cjs +1 -0
  102. package/dist/debug/runtime/reactivity/runtime-reactivity.types.js +1 -0
  103. package/dist/entrypoints/machine-testing.d.ts +2 -0
  104. package/dist/entrypoints/machine.d.ts +5 -0
  105. package/dist/entrypoints/path.d.ts +14 -0
  106. package/dist/entrypoints/reactivity.d.ts +1 -0
  107. package/dist/entrypoints/runtime.d.ts +18 -0
  108. package/dist/index.cjs +1 -1
  109. package/dist/index.js +46 -38
  110. package/dist/machine/compiler.d.ts +71 -0
  111. package/dist/machine/core.d.ts +50 -0
  112. package/dist/machine/persistence.d.ts +5 -0
  113. package/dist/machine/runtime.d.ts +4 -0
  114. package/dist/machine/testing.d.ts +43 -0
  115. package/dist/machine/types.d.ts +155 -0
  116. package/dist/machine-testing.cjs +1 -0
  117. package/dist/machine-testing.js +188 -0
  118. package/dist/machine.cjs +1 -0
  119. package/dist/machine.js +822 -0
  120. package/dist/main.d.ts +20 -0
  121. package/dist/path/{data-path.d.ts → DataPath.d.ts} +16 -40
  122. package/dist/path/{path-router.d.ts → PathRouter.d.ts} +1 -1
  123. package/dist/path/RaphKernel.d.ts +37 -10
  124. package/dist/path/data-path.types.d.ts +34 -0
  125. package/dist/path/data-path.utils.d.ts +9 -0
  126. package/dist/path/{DerivedRegistry.d.ts → derived/DerivedRegistry.d.ts} +2 -2
  127. package/dist/path/{RaphDerivedHandle.d.ts → derived/RaphDerivedHandle.d.ts} +3 -3
  128. package/dist/path/derived/derived-collection.types.d.ts +12 -0
  129. package/dist/path/{derived-collection.d.ts → derived/derived-collection.utils.d.ts} +3 -13
  130. package/dist/path/{derived-strategies.d.ts → derived/derived-strategy.types.d.ts} +0 -3
  131. package/dist/path/derived/derived-strategy.utils.d.ts +4 -0
  132. package/dist/path/{MetaController.d.ts → meta/MetaController.d.ts} +4 -4
  133. package/dist/path/{RaphMeta.d.ts → meta/RaphMeta.d.ts} +2 -2
  134. package/dist/path/{RaphMetaStore.d.ts → meta/RaphMetaStore.d.ts} +1 -1
  135. package/dist/path/{meta.types.d.ts → meta/meta.types.d.ts} +2 -4
  136. package/dist/path/path.types.d.ts +3 -2
  137. package/dist/path/{segment-key.d.ts → pathSegmentKey.d.ts} +1 -1
  138. package/dist/path/{AdapterPathStore.d.ts → storage/AdapterPathStore.d.ts} +4 -4
  139. package/dist/path/{data-adapter.d.ts → storage/DefaultDataAdapter.d.ts} +2 -17
  140. package/dist/path/storage/PathEventHub.d.ts +62 -0
  141. package/dist/path/{PathStore.d.ts → storage/PathStore.d.ts} +7 -7
  142. package/dist/path/storage/data-adapter.types.d.ts +17 -0
  143. package/dist/path.cjs +1 -1
  144. package/dist/path.js +16 -16
  145. package/dist/raph.cjs +1 -1
  146. package/dist/raph.js +46 -38
  147. package/dist/reactivity/disposal.d.ts +14 -0
  148. package/dist/reactivity/engine.d.ts +193 -6
  149. package/dist/reactivity/reactive-object.d.ts +36 -0
  150. package/dist/reactivity/scope.d.ts +108 -30
  151. package/dist/reactivity/types.d.ts +25 -0
  152. package/dist/reactivity.cjs +1 -1
  153. package/dist/reactivity.js +12 -12
  154. package/dist/runtime/RaphRuntime.d.ts +319 -160
  155. package/dist/runtime/diagnostics/RaphDebug.d.ts +239 -0
  156. package/dist/runtime/errors.d.ts +5 -0
  157. package/dist/runtime/ownership/RaphEffectScope.d.ts +98 -0
  158. package/dist/runtime/ownership/RaphNode.d.ts +310 -0
  159. package/dist/runtime/ownership/RaphScope.d.ts +168 -0
  160. package/dist/runtime/{parent-graph.d.ts → ownership/parent-graph.types.d.ts} +0 -1
  161. package/dist/runtime/ownership/parentGraph.d.ts +3 -0
  162. package/dist/runtime/phases/RaphPhasePipeline.d.ts +253 -0
  163. package/dist/runtime/phases/RaphPhaseTaskRecord.d.ts +195 -0
  164. package/dist/runtime/phases/RaphPhaseWatch.d.ts +22 -0
  165. package/dist/runtime/phases/orderPhaseTasks.d.ts +6 -0
  166. package/dist/runtime/phases/phase.types.d.ts +171 -0
  167. package/dist/runtime/{PathHandle.d.ts → reactivity/PathHandle.d.ts} +14 -6
  168. package/dist/runtime/reactivity/RaphMetaSource.d.ts +32 -0
  169. package/dist/runtime/reactivity/RaphSelector.d.ts +338 -0
  170. package/dist/runtime/reactivity/RaphWorkGraph.d.ts +309 -0
  171. package/dist/runtime/reactivity/RuntimeReactivity.d.ts +293 -0
  172. package/dist/runtime/{RuntimeWatch.d.ts → reactivity/RuntimeWatch.d.ts} +12 -6
  173. package/dist/runtime/reactivity/disposal-sweep.utils.d.ts +19 -0
  174. package/dist/runtime/reactivity/runtime-reactivity.types.d.ts +56 -0
  175. package/dist/runtime.cjs +1 -1
  176. package/dist/runtime.js +21 -16
  177. package/package.json +76 -35
  178. package/ReadMe.md +0 -153
  179. package/dist/api/public.d.ts +0 -22
  180. package/dist/debug/api/public.cjs +0 -1
  181. package/dist/debug/api/public.js +0 -40
  182. package/dist/debug/path/AdapterPathStore.cjs +0 -1
  183. package/dist/debug/path/AdapterPathStore.js +0 -133
  184. package/dist/debug/path/DerivedRegistry.cjs +0 -1
  185. package/dist/debug/path/DerivedRegistry.js +0 -157
  186. package/dist/debug/path/MetaController.cjs +0 -1
  187. package/dist/debug/path/PathEventHub.cjs +0 -1
  188. package/dist/debug/path/PathEventHub.js +0 -148
  189. package/dist/debug/path/PathStore.cjs +0 -1
  190. package/dist/debug/path/RaphDerivedHandle.cjs +0 -1
  191. package/dist/debug/path/RaphMeta.cjs +0 -1
  192. package/dist/debug/path/RaphMeta.js +0 -68
  193. package/dist/debug/path/RaphMetaStore.cjs +0 -1
  194. package/dist/debug/path/data-adapter.cjs +0 -1
  195. package/dist/debug/path/data-draft.cjs +0 -1
  196. package/dist/debug/path/data-path.cjs +0 -1
  197. package/dist/debug/path/data-path.js +0 -423
  198. package/dist/debug/path/derived-collection.cjs +0 -1
  199. package/dist/debug/path/path-router.cjs +0 -1
  200. package/dist/debug/path/path-router.js +0 -86
  201. package/dist/debug/path/public.cjs +0 -1
  202. package/dist/debug/path/public.js +0 -18
  203. package/dist/debug/runtime/PathHandle.cjs +0 -1
  204. package/dist/debug/runtime/PathHandle.js +0 -139
  205. package/dist/debug/runtime/RaphDebug.cjs +0 -1
  206. package/dist/debug/runtime/RaphDebug.js +0 -15
  207. package/dist/debug/runtime/RaphFrameLoop.cjs +0 -1
  208. package/dist/debug/runtime/RaphNode.cjs +0 -1
  209. package/dist/debug/runtime/RaphNode.js +0 -143
  210. package/dist/debug/runtime/RaphPhasePipeline.cjs +0 -1
  211. package/dist/debug/runtime/RaphPhasePipeline.js +0 -526
  212. package/dist/debug/runtime/RaphScope.cjs +0 -1
  213. package/dist/debug/runtime/RaphScope.js +0 -64
  214. package/dist/debug/runtime/RuntimeReactivity.cjs +0 -1
  215. package/dist/debug/runtime/RuntimeReactivity.js +0 -154
  216. package/dist/debug/runtime/RuntimeWatch.cjs +0 -1
  217. package/dist/debug/runtime/RuntimeWatch.js +0 -71
  218. package/dist/debug/runtime/public.cjs +0 -1
  219. package/dist/debug/runtime/public.js +0 -18
  220. package/dist/path/PathEventHub.d.ts +0 -48
  221. package/dist/path/public.d.ts +0 -14
  222. package/dist/runtime/RaphDebug.d.ts +0 -32
  223. package/dist/runtime/RaphNode.d.ts +0 -68
  224. package/dist/runtime/RaphPhasePipeline.d.ts +0 -133
  225. package/dist/runtime/RaphScope.d.ts +0 -50
  226. package/dist/runtime/RuntimeReactivity.d.ts +0 -40
  227. package/dist/runtime/phase.types.d.ts +0 -49
  228. package/dist/runtime/public.d.ts +0 -13
  229. package/dist/runtime/runtime-reactivity.types.d.ts +0 -9
  230. /package/dist/debug/path/{meta.types.cjs → data-path.types.cjs} +0 -0
  231. /package/dist/debug/path/{meta.types.js → data-path.types.js} +0 -0
  232. /package/dist/debug/{runtime/runtime-reactivity.types.cjs → path/derived/derived-collection.types.cjs} +0 -0
  233. /package/dist/debug/{runtime/runtime-reactivity.types.js → path/derived/derived-collection.types.js} +0 -0
  234. /package/dist/debug/path/{derived-strategies.cjs → derived/derived-strategy.utils.cjs} +0 -0
  235. /package/dist/debug/path/{derived-strategies.js → derived/derived-strategy.utils.js} +0 -0
  236. /package/dist/debug/path/{segment-key.cjs → pathSegmentKey.cjs} +0 -0
  237. /package/dist/debug/path/{segment-key.js → pathSegmentKey.js} +0 -0
  238. /package/dist/debug/runtime/{parent-graph.cjs → ownership/parentGraph.cjs} +0 -0
  239. /package/dist/debug/runtime/{parent-graph.js → ownership/parentGraph.js} +0 -0
  240. /package/dist/debug/runtime/{disposal.cjs → ownership/throwDisposalErrors.cjs} +0 -0
  241. /package/dist/debug/runtime/{disposal.js → ownership/throwDisposalErrors.js} +0 -0
  242. /package/dist/debug/runtime/{phase.types.cjs → phases/phase.types.cjs} +0 -0
  243. /package/dist/debug/runtime/{phase.types.js → phases/phase.types.js} +0 -0
  244. /package/dist/path/{data-draft.d.ts → storage/createDataDraft.d.ts} +0 -0
  245. /package/dist/runtime/{disposal.d.ts → ownership/throwDisposalErrors.d.ts} +0 -0
  246. /package/dist/runtime/{RaphFrameLoop.d.ts → phases/RaphFrameLoop.d.ts} +0 -0
@@ -1,700 +1,1332 @@
1
- var W = Object.defineProperty;
2
- var b = (a, t, e) => t in a ? W(a, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : a[t] = e;
3
- var h = (a, t, e) => b(a, typeof t != "symbol" ? t + "" : t, e);
4
- import { RaphDisposedError as R, RaphCrossRuntimeError as k, RaphActionError as T } from "./errors.js";
5
- import { parentGraph as x } from "./parent-graph.js";
6
- import { PathHandle as L } from "./PathHandle.js";
7
- import { RaphSchedulerType as d } from "./phase.types.js";
8
- import { RaphNode as m } from "./RaphNode.js";
9
- import { parseDataPath as q, DataPath as A } from "../path/data-path.js";
10
- import { RaphKernel as O } from "../path/RaphKernel.js";
11
- import { RaphMeta as M } from "../path/RaphMeta.js";
12
- import { watchWithReactivity as $ } from "../reactivity/watch.js";
13
- import { throwDisposalErrors as D } from "./disposal.js";
14
- import { createOwnerSnapshot as y } from "./RaphDebug.js";
15
- import { RaphFrameLoop as H } from "./RaphFrameLoop.js";
16
- import { RaphPhasePipeline as F } from "./RaphPhasePipeline.js";
17
- import { RaphScope as S } from "./RaphScope.js";
18
- import { RuntimeReactivity as U } from "./RuntimeReactivity.js";
19
- import { RuntimeWatch as g } from "./RuntimeWatch.js";
20
- const v = class v {
21
- /**
22
- * Создаёт изолированный execution graph поверх собственного или shared Kernel.
23
- */
24
- constructor(t = {}) {
25
- // Публикуют immutable configuration и корневых lifecycle owners.
26
- h(this, "configuration");
27
- h(this, "rootScope");
28
- h(this, "root");
29
- // Владеют изолированным reactive graph и его runtime policy.
30
- h(this, "_reactivity");
31
- h(this, "_signalLifecycle");
32
- // Лениво создают adapters и diagnostics только по запросу consumer.
33
- h(this, "_pathHandles");
34
- h(this, "_meta");
35
- h(this, "_phases");
36
- h(this, "_frameLoop");
37
- h(this, "_frameRevision");
38
- h(this, "_frameRevisionValue", !1);
39
- h(this, "_debug");
40
- h(this, "_parentGraph");
41
- // Регистрируют всех lifecycle owners runtime.
42
- h(this, "_owners", /* @__PURE__ */ new Set());
43
- // Координируют вложенные write boundaries и execution requests.
44
- h(this, "_transactionDepth", 0);
45
- h(this, "_mutationDepth", 0);
46
- h(this, "_kernelTransactionDepth", 0);
47
- h(this, "_actionDepth", 0);
48
- h(this, "_executionRequested", !1);
49
- // Хранят окончательное состояние runtime и dispose listeners.
50
- h(this, "_disposed", !1);
51
- h(this, "_disposedListeners", /* @__PURE__ */ new Set());
52
- const e = t.id ?? `runtime-${v._runtimeCounter++}`, s = t.enforceActions ?? !1, i = t.scheduler ?? d.Sync;
53
- if (!I(i))
1
+ import { parseDataPath as N } from "../path/data-path.utils.js";
2
+ import { DataPath as B } from "../path/DataPath.js";
3
+ import { RaphMeta as W } from "../path/meta/RaphMeta.js";
4
+ import { RaphKernel as G } from "../path/RaphKernel.js";
5
+ import { configureReactiveObjectPolicy as q, disposeReactiveObjectContext as L } from "../reactivity/reactive-object.js";
6
+ import { RaphDebugController as M, createOwnerSnapshot as D, createOwnerTree as S } from "./diagnostics/RaphDebug.js";
7
+ import { RaphDisposedError as A, RaphCrossRuntimeError as b, RaphActionError as F } from "./errors.js";
8
+ import { parentGraph as $ } from "./ownership/parentGraph.js";
9
+ import { RaphNode as v, createProvisionalNode as H } from "./ownership/RaphNode.js";
10
+ import { RaphScope as O } from "./ownership/RaphScope.js";
11
+ import { throwDisposalErrors as m } from "./ownership/throwDisposalErrors.js";
12
+ import { RaphSchedulerType as f } from "./phases/phase.types.js";
13
+ import { RaphFrameLoop as z } from "./phases/RaphFrameLoop.js";
14
+ import { RaphPhasePipeline as j } from "./phases/RaphPhasePipeline.js";
15
+ import { TASK_ACTIVE as E, TASK_TASKLESS as U, GROUP_NODES as k, TASK_PENDING as C, TASK_REQUESTED as K } from "./phases/RaphPhaseTaskRecord.js";
16
+ import { createPhaseWatch as V } from "./phases/RaphPhaseWatch.js";
17
+ import { enqueueSweeper as Y, dequeueSweeper as P, postponeFirstSweeper as Q } from "./reactivity/disposal-sweep.utils.js";
18
+ import { PathHandle as X } from "./reactivity/PathHandle.js";
19
+ import { RaphMetaSource as J } from "./reactivity/RaphMetaSource.js";
20
+ import { RaphWorkGraph as Z } from "./reactivity/RaphWorkGraph.js";
21
+ import { RuntimeReactivity as ee } from "./reactivity/RuntimeReactivity.js";
22
+ const y = Object.freeze({}), I = 2 ** 32 - 1 - k;
23
+ class T {
24
+ static _runtimeCounter = 0;
25
+ mode = "runtime";
26
+ configuration;
27
+ rootScope;
28
+ root;
29
+ frameTick;
30
+ _reactivity;
31
+ _signalLifecycle;
32
+ _workGraph;
33
+ // Записываемый frame signal; наружу выдаётся только его read-only wrapper.
34
+ _frameTickSignal;
35
+ _pathHandles;
36
+ _meta;
37
+ _phases;
38
+ _frameLoop;
39
+ _debug;
40
+ _debugController;
41
+ _parentGraph;
42
+ // Владельцы вне списков детей в порядке регистрации: plain scopes и nodes
43
+ // без parent. Node с parent сюда не входит: её достигает обход детей, поэтому
44
+ // её создание и освобождение не стоят операции с Set.
45
+ _topOwners = /* @__PURE__ */ new Set();
46
+ // Число владельцев, зарегистрированных за всё время жизни Runtime; оно же —
47
+ // порядковый номер последнего из них.
48
+ _ownerRegistrations = 0;
49
+ // Runtime освободил владельцев и живых больше не числит.
50
+ _ownersReleased = !1;
51
+ _batchDepth = 0;
52
+ _mutationDepth = 0;
53
+ _kernelBatchDepth = 0;
54
+ _ownerDisposalDepth = 0;
55
+ // Node, чей dispose открыл границу освобождения, на месте глубины этой
56
+ // границы; у границы, открытой не node, место пусто. Node, вышедшая из списка
57
+ // parent до конца своего dispose, остаётся перечислимой только отсюда.
58
+ _disposingNodes = [];
59
+ // Число владельцев, освобождённых за всё время жизни Runtime.
60
+ _ownerDisposals = 0;
61
+ // Очередь участников уборки после освобождения владельцев, ближайший срок в
62
+ // начале, и число освобождений, при котором этот срок наступает; без
63
+ // участников поле пусто и срок не наступает.
64
+ _disposalSweepers;
65
+ _nextDisposalSweep = Number.POSITIVE_INFINITY;
66
+ _actionDepth = 0;
67
+ _actionCounter = 0;
68
+ _traceCauseStack = [];
69
+ _phaseTraceOperations;
70
+ _executionRequested = !1;
71
+ _disposed = !1;
72
+ _disposedListeners = /* @__PURE__ */ new Set();
73
+ constructor(e = {}) {
74
+ const t = e.id ?? `runtime-${T._runtimeCounter++}`, s = e.adaptiveDependencyIndex ?? !1, r = e.enforceActions ?? !1, i = e.scheduler ?? f.Sync;
75
+ if (!oe(i))
54
76
  throw new Error(`[Raph] Unsupported scheduler "${String(i)}".`);
55
- const r = t.kernel ?? new O({ id: `${e}-kernel` });
56
- this.configuration = Object.freeze({ id: e, kernel: r, enforceActions: s, scheduler: i });
57
- const o = `[Raph] Runtime "${e}" is disposed.`;
77
+ const o = e.kernel ?? new G({ id: `${t}-kernel` });
78
+ this.configuration = Object.freeze({
79
+ adaptiveDependencyIndex: s,
80
+ ...e.debug === void 0 ? {} : { debug: e.debug },
81
+ id: t,
82
+ kernel: o,
83
+ enforceActions: r,
84
+ scheduler: i
85
+ }), this._debugController = new M(e.debug);
86
+ const a = `[Raph] Runtime "${t}" is disposed.`;
58
87
  this._signalLifecycle = {
59
88
  owner: this,
60
- runWrite: (n) => this._runWrite(n),
61
- ...s ? { assertWriteAllowed: () => this._assertWriteAllowed() } : {},
89
+ assertDependencyAllowed: (h, u) => {
90
+ this._assertImplicitDependency(h, u);
91
+ },
92
+ ...r ? { assertWriteAllowed: () => this._assertWriteAllowed() } : {},
62
93
  throwDisposed: () => {
63
- throw new R(o);
94
+ throw new A(a);
95
+ },
96
+ throwCrossRuntime: (h) => this._throwCrossRuntime(h)
97
+ }, this._reactivity = new ee(this._signalLifecycle, { adaptiveDependencyIndex: s }), this._workGraph = new Z(this), o._attachRuntime(this), this.rootScope = new O(`${t}:root-scope`, this), this.root = new v(null, { id: `${t}:root` }, this), q(this._reactivity, {
98
+ owner: this,
99
+ assertRead: () => {
100
+ this._assertAlive();
101
+ const h = this._reactivity.getActiveOwner();
102
+ h !== void 0 && h !== this && this._throwCrossRuntime(h);
103
+ const u = this._reactivity.getActiveConsumerOwner();
104
+ u !== void 0 && this._assertImplicitDependency(this.rootScope, u);
64
105
  },
65
- throwCrossRuntime: (n) => this._throwCrossRuntime(n)
66
- }, this._reactivity = new U(this._signalLifecycle), r._attachRuntime(this), this.rootScope = new S(`${e}:root-scope`, this), this.root = new m(null, { id: `${e}:root` }, this);
106
+ assertWrite: () => this._assertWriteAllowed(),
107
+ runWrite: (h) => this._runWrite(h),
108
+ throwForeign: (h) => {
109
+ throw h instanceof T && this._throwCrossRuntime(h), new b(
110
+ "[Raph] Reactive object belongs to another reactivity engine."
111
+ );
112
+ }
113
+ });
114
+ const n = this._reactivity.signalForOwner(0, this.rootScope, "frame", !1);
115
+ this._frameTickSignal = n, this.frameTick = this._workGraph.attachProducer(n, {
116
+ get: () => n.get(),
117
+ peek: () => n.peek()
118
+ });
67
119
  }
68
- /**
69
- * Возвращает внутренний runtime reactivity adapter.
70
- * @internal
71
- */
120
+ /** @internal */
72
121
  _getReactivity() {
73
122
  return this._reactivity;
74
123
  }
75
124
  /**
76
- * Возвращает стабильный идентификатор runtime.
125
+ * Возвращает внутренний WorkGraph для optional execution layers.
126
+ *
127
+ * @internal
77
128
  */
129
+ _getWorkGraph() {
130
+ return this._workGraph;
131
+ }
78
132
  get id() {
79
133
  return this.configuration.id;
80
134
  }
81
- /**
82
- * Возвращает data/meta Kernel этого runtime.
83
- */
84
135
  get kernel() {
85
136
  return this.configuration.kernel;
86
137
  }
87
- /**
88
- * Возвращает лениво созданный runtime-owned metadata facade.
89
- */
90
- get meta() {
91
- return this._assertAlive(), this._meta ?? (this._meta = new M(this.kernel, {
92
- assertReadable: () => this._assertAlive(),
93
- assertWritable: () => this._assertWriteAllowed(),
94
- runWrite: (t, e) => this._runWrite(t, e),
95
- watch: (t, e, s) => this._own(
96
- this._watchMeta(t, e, s),
97
- this.rootScope
98
- )
99
- }));
100
- }
101
- /**
102
- * Показывает, освобождён ли runtime.
103
- */
104
138
  get disposed() {
105
139
  return this._disposed;
106
140
  }
107
- /**
108
- * Возвращает лениво созданное read-only представление ownership graph.
109
- */
110
141
  get graph() {
111
- return this._parentGraph ?? (this._parentGraph = x());
142
+ return this._parentGraph ??= $();
112
143
  }
113
- /**
114
- * Показывает, удерживается ли автоматический frame-loop.
115
- */
116
144
  get loopEnabled() {
117
- var t;
118
- return ((t = this._frameLoop) == null ? void 0 : t.running) ?? !1;
145
+ return this._frameLoop?.running ?? !1;
119
146
  }
120
- /**
121
- * Возвращает последний frame context runtime pipeline.
122
- */
123
147
  get frame() {
124
- var t;
125
- return ((t = this._phases) == null ? void 0 : t.frame) ?? { now: 0, delta: 0, elapsed: 0, frame: 0 };
148
+ return this._phases?.frame ?? { now: 0, delta: 0, elapsed: 0, frame: 0 };
126
149
  }
127
- /**
128
- * Возвращает текущее определение runtime phases.
129
- */
130
150
  get phases() {
131
- var t;
132
- return ((t = this._phases) == null ? void 0 : t.phases) ?? [];
151
+ return this._phases?.phases ?? [];
152
+ }
153
+ /** Runtime metadata facade intentionally excludes unphased watch(). */
154
+ get meta() {
155
+ if (this._assertAlive(), this._meta !== void 0)
156
+ return this._meta;
157
+ const e = new W(this.kernel, {
158
+ assertReadable: () => this._assertAlive(),
159
+ assertWritable: () => this._assertWriteAllowed(),
160
+ runWrite: (t, s) => this._runWrite(t, s)
161
+ });
162
+ return this._meta = Object.freeze({
163
+ delete: e.delete.bind(e),
164
+ get: e.get.bind(e),
165
+ has: e.has.bind(e),
166
+ merge: e.merge.bind(e),
167
+ set: e.set.bind(e)
168
+ });
133
169
  }
134
- /**
135
- * Формирует диагностический снимок materialized derived registry.
136
- */
137
170
  getDerivedSnapshot() {
138
171
  return this.kernel.getDerivedSnapshot();
139
172
  }
140
- /**
141
- * Возвращает лениво созданную read-only диагностику runtime и ownership tree.
142
- */
143
173
  get debug() {
144
- return this._debug ?? (this._debug = Object.freeze({
174
+ return this._debug ??= Object.freeze({
145
175
  snapshot: () => this._createDebugSnapshot(),
146
- getTree: () => y(this.root)
147
- }));
176
+ getTree: () => this._createDebugTree(),
177
+ stats: () => this._createDebugStats(),
178
+ trace: this._debugController.trace,
179
+ machines: this._debugController.machines
180
+ });
181
+ }
182
+ signal(e, t = this.rootScope) {
183
+ return this._assertOwnerRuntime(t), this._reactivity.signalForOwner(e, t);
148
184
  }
149
185
  /**
150
- * Создаёт writable signal, принадлежащий указанному owner.
186
+ * Creates a deep reactive Proxy owned by this Runtime root scope.
187
+ * Property dependencies use the intrusive graph directly and intentionally
188
+ * do not create per-property WorkGraph producers or phase causes.
151
189
  */
152
- signal(t, e = this.rootScope) {
153
- return this._assertOwnerRuntime(e), this._reactivity.signalForOwner(t, e);
190
+ reactive(e) {
191
+ return this._assertAlive(), this._reactivity.reactive(e);
192
+ }
193
+ computed(e, t = this.rootScope) {
194
+ this._assertOwnerRuntime(t);
195
+ const s = this._workGraph.createProducer(t), r = typeof e == "function" ? e : e.get, i = this._reactivity.computedForOwner(
196
+ () => this._runTracked(t, r),
197
+ t,
198
+ this._workGraph.producerHooks(s)
199
+ );
200
+ if (this._workGraph.setProducerActivation(s, () => {
201
+ i.peek();
202
+ }), typeof e == "function")
203
+ return this._workGraph.attachProducer(s, i);
204
+ const o = this._attachWritableComputed(i, e.set, t);
205
+ return this._workGraph.attachProducer(s, o);
206
+ }
207
+ /** Low-level adapter form. Prefer consumer.effect(). */
208
+ effect(e, t, s, r = y) {
209
+ return te(
210
+ this._effectRegistration(e, t, s, r)
211
+ );
154
212
  }
155
- computed(t, e = this.rootScope) {
213
+ /**
214
+ * Регистрирует один implicit phase effect. Возвращаемая регистрация является
215
+ * записью binding: она одновременно ресурс владельца, задача engine и элемент
216
+ * очереди pipeline, поэтому на effect больше ничего не выделяется. Тело
217
+ * записи engine у всех bindings графа одно — `RuntimeReactivity._phaseBody`:
218
+ * свой binding оно находит через engine, а не через собственную closure.
219
+ *
220
+ * При `taskless` тело вызывается без task: запись получает `TASK_TASKLESS`,
221
+ * общее тело не читает `record.task`, и frozen facade этого binding не
222
+ * создаётся, пока его не запросит `process` своей phase. Режим — бит поля
223
+ * `state`: запись от него не растёт.
224
+ *
225
+ * @internal
226
+ */
227
+ _effectRegistration(e, t, s, r = y, i = !1, o = !1, a, n) {
156
228
  this._assertOwnerRuntime(e);
157
- const s = typeof t == "function" ? t : t.get, i = this._reactivity.computedForOwner(
158
- () => this._runTracked(s),
159
- e
160
- );
161
- return typeof t == "function" ? i : this._attachWritableComputed(i, t.set, e);
162
- }
163
- effect(t, e, s = {}, i = this.rootScope) {
164
- const r = typeof t == "string" ? e : t, o = typeof t == "string" ? i : e ?? this.rootScope;
165
- if (this._assertOwnerRuntime(o), typeof t == "string") {
166
- const n = t.trim(), c = this._execution;
167
- c.requirePhase(n);
168
- const p = s.priority ?? 0, u = s.initial ?? "scheduled";
169
- if (!Number.isFinite(p))
170
- throw new TypeError("[Raph] Effect priority must be finite.");
171
- if (u !== "scheduled" && u !== "sync")
172
- throw new TypeError(`[Raph] Unsupported effect initial mode "${String(u)}".`);
173
- u === "sync" && c.lockConfiguration();
174
- const l = c.phaseMode(n) === "always" ? this._frameRevision ?? (this._frameRevision = this._reactivity.signal(!1)) : void 0, w = this._reactivity.withEffectBinding(
175
- (_) => c.bindEffect(
176
- n,
177
- p,
178
- _,
179
- o instanceof m ? o : void 0
180
- ),
181
- u,
182
- () => this._reactivity.effect(() => (l == null || l.get(), this._runTracked(r)))
229
+ const h = this._execution, u = this._validatePhaseBinding(h, t, s, r), c = h.bindTask(u, e, s, r.priority ?? 0);
230
+ o && (c.state = E | U);
231
+ const d = this._reactivity, _ = r.initial === "sync", l = _ && this.configuration.scheduler !== f.Sync;
232
+ let g = "Effect registration and cleanup failed.", w = !1;
233
+ try {
234
+ i && c.pause();
235
+ const R = d._allocateTaskEffect(d._phaseBody, c);
236
+ if (c.node = R, l && h._queue(c, !1), w = !0, d._requestTaskEffect(R, !l), n?.())
237
+ return c.dispose(), c;
238
+ w = !1, g = "[Raph] Resource registration and cleanup failed.", (c.state & E) !== 0 && c.node !== void 0 ? e._adoptRecord(c) : (e._assertAlive(), c.dispose()), g = "[Raph] Phase effect registration and rollback failed.", w = !0, _ ? this.flush() : this._requestExecution(), n?.() && c.dispose();
239
+ } catch (R) {
240
+ this._rollbackRegistration(
241
+ c,
242
+ R,
243
+ g,
244
+ w ? a : void 0
183
245
  );
184
- return this._own(w, o);
185
246
  }
186
- return this._own(
187
- this._reactivity._effectImmediate(() => this._runTracked(r)),
188
- o
189
- );
247
+ return c;
248
+ }
249
+ /**
250
+ * Регистрирует группу из `count` implicit phase effects на одной записи
251
+ * binding. Каждый slot получает собственную запись графа engine, то есть
252
+ * собственный набор зависимостей и собственный признак invalidation, а
253
+ * запись binding и её место в очереди phase и в списке ресурсов владельца у
254
+ * группы одни. Тело записи engine у slots то же, что у всех bindings графа.
255
+ * Возвращаемая регистрация — эта запись; она же handle группы.
256
+ *
257
+ * Регистрация ничего не исполняет: каждый slot запускает `_startGroupSlot`.
258
+ * Запись входит в список владельца сразу, поэтому владелец освобождает
259
+ * группу после ресурсов, которые зарегистрируют тела её slots.
260
+ *
261
+ * @internal
262
+ */
263
+ _effectGroupRegistration(e, t, s, r, i, o = y, a = !1) {
264
+ this._assertOwnerRuntime(e);
265
+ const n = this._execution, h = r, u = this._validatePhaseBinding(n, t, h, o);
266
+ if (!Number.isInteger(s) || s < 1)
267
+ throw new RangeError("[Raph] Effect group slot count must be a positive integer.");
268
+ if (s > I)
269
+ throw new RangeError(`[Raph] Effect group slot count must not exceed ${I}.`);
270
+ const c = n.bindGroup(u, e, h, i, s, o.priority ?? 0);
271
+ try {
272
+ a && c.pause();
273
+ const d = c.group, _ = this._reactivity, l = _._phaseBody, g = k + s;
274
+ for (let w = k; w < g; w++)
275
+ d[w] = _._allocateTaskEffect(l, c);
276
+ e._adoptRecord(c);
277
+ } catch (d) {
278
+ this._rollbackRegistration(c, d, "[Raph] Resource registration and cleanup failed.");
279
+ }
280
+ return c;
190
281
  }
191
- watch(t, e, s = {}, i = this.rootScope) {
192
- return this._assertOwnerRuntime(i), z(t) ? this._own(this._watchPath(t, e), i) : this._own(
193
- $(
194
- this._reactivity._effectImmediate,
195
- this._reactivity.untracked,
282
+ /**
283
+ * Запускает один slot группы: планирует его запись графа, ставит запись
284
+ * группы в очередь и, при `initial: 'sync'`, выполняет flush. Шаги те же, что
285
+ * у регистрации одиночного implicit effect после создания его записи.
286
+ *
287
+ * Сбой внутри вызова останавливает только этот slot и бросается вызывающему,
288
+ * как сбой первой доставки откатывает регистрацию одиночного binding; группа
289
+ * и остальные её slots остаются. Группа, у которой остановлен последний slot,
290
+ * освобождается.
291
+ *
292
+ * Запуск на освобождённом владельце бросает `RaphDisposedError`, как
293
+ * `bindEffect()`: и когда владелец освобождён до вызова, и когда его
294
+ * освободила первая доставка внутри вызова, при любом scheduler. Молчит
295
+ * только запуск slot группы, освобождённой при живом владельце.
296
+ *
297
+ * @internal
298
+ */
299
+ _startGroupSlot(e, t, s, r) {
300
+ const i = e.group;
301
+ if (i === void 0) {
302
+ e.consumerOwner._assertAlive();
303
+ return;
304
+ }
305
+ const o = t >= 0 ? i[k + t] : void 0;
306
+ if (o === void 0)
307
+ throw new RangeError(`[Raph] Effect group has no slot ${String(t)}.`);
308
+ if (s !== "scheduled" && s !== "sync")
309
+ throw new TypeError(`[Raph] Unsupported effect initial mode "${String(s)}".`);
310
+ if (o === null || o.firstDep !== null)
311
+ return;
312
+ const a = e.phaseState.pipeline, n = s === "sync", h = n && this.configuration.scheduler !== f.Sync;
313
+ let u = !1;
314
+ try {
315
+ u = !0, this._reactivity._requestTaskEffect(o, !1), h ? e.state & C || a._queue(e, !1) : e.schedule(), u = !1, e.state & (C | K) || e.consumerOwner._assertAlive(), n ? a._running ? this._executionRequested = !1 : (u = !0, this.flush(), u = !1, e.state & E || e.consumerOwner._assertAlive()) : (u = !0, this._requestExecution());
316
+ } catch (c) {
317
+ let d = c;
318
+ try {
319
+ this._reactivity._disposeTaskEffect(o);
320
+ } catch (_) {
321
+ d = new AggregateError(
322
+ [c, _],
323
+ "[Raph] Phase effect registration and rollback failed."
324
+ );
325
+ }
326
+ throw u && r !== void 0 && r(d), d;
327
+ }
328
+ }
329
+ /** Low-level adapter form. Prefer consumer.watch(). */
330
+ watch(e, t, s, r, i = y) {
331
+ const o = this._watchRegistration(e, t, s, r, i).watch;
332
+ return o === void 0 ? re : se(o);
333
+ }
334
+ /**
335
+ * Регистрирует один explicit phase watch. Возвращаемая запись binding является
336
+ * pausable-регистрацией и одновременно ресурсом владельца этого watch.
337
+ *
338
+ * @internal
339
+ */
340
+ _watchRegistration(e, t, s, r, i = y, o = !1, a, n) {
341
+ this._assertOwnerRuntime(e);
342
+ const h = this._execution, u = this._validatePhaseBinding(h, s, r, i, !0);
343
+ this._workGraph.assertSubscriptionAllowed(e, t);
344
+ const c = h.bindTask(u, e, r, i.priority ?? 0), d = V((l) => this._runUntracked(l), c);
345
+ c.watch = d, o && c.pause();
346
+ try {
347
+ if (d.source = this._workGraph.subscribe(
196
348
  t,
197
- e,
198
- s,
199
- (r) => this._runTracked(r)
349
+ i.include,
350
+ (l, g, w) => d.record?.enqueue(l, g, w)
351
+ ), n?.())
352
+ return c.dispose(), c;
353
+ } catch (l) {
354
+ throw c.dispose(), l;
355
+ }
356
+ try {
357
+ e._adoptRecord(c);
358
+ } catch (l) {
359
+ this._rollbackRegistration(c, l, "[Raph] Resource registration and cleanup failed.");
360
+ }
361
+ const _ = i.initial ?? "scheduled";
362
+ try {
363
+ _ !== "none" && c.schedule(), _ === "sync" && this.flush(), n?.() && c.dispose();
364
+ } catch (l) {
365
+ this._rollbackRegistration(
366
+ c,
367
+ l,
368
+ "[Raph] Phase watch registration and rollback failed.",
369
+ a
370
+ );
371
+ }
372
+ return c;
373
+ }
374
+ aggregate(e, t) {
375
+ return this._assertOwnerRuntime(e), this._workGraph.createAggregate(e, t);
376
+ }
377
+ /** Creates a lazy root-owned metadata event source for phase watches. */
378
+ metaSource(e, t = {}) {
379
+ this._assertAlive(), ae(e, t);
380
+ const s = this._workGraph.createProducer(this.rootScope, "path"), r = this._workGraph.producerHooks(s).onDispose, i = J._create(
381
+ this.rootScope,
382
+ e,
383
+ t,
384
+ () => this.kernel._watchMeta(
385
+ i.masks,
386
+ ({ events: o }) => this._workGraph.notifyProducerEvents(s, o, !1),
387
+ i.options,
388
+ (o) => {
389
+ o && this._execution.request();
390
+ }
200
391
  ),
201
- i
392
+ () => r(!1)
202
393
  );
394
+ i._bindOwner(this.rootScope._adoptResource(() => i._disposeOwned()));
395
+ try {
396
+ return this._workGraph.setProducerActivation(s, () => i._activate(), !0), this._workGraph.attachProducer(s, i), i;
397
+ } catch (o) {
398
+ try {
399
+ i.dispose();
400
+ } catch (a) {
401
+ throw new AggregateError(
402
+ [o, a],
403
+ "[Raph] Meta source activation and rollback failed."
404
+ );
405
+ }
406
+ throw o;
407
+ }
203
408
  }
204
- /**
205
- * Возвращает кешируемый runtime-owned handle canonical path.
206
- */
207
- path(t, e = {}) {
409
+ path(e, t = {}) {
208
410
  this._assertAlive();
209
- const s = q(t, e), i = this._pathHandles ?? (this._pathHandles = /* @__PURE__ */ new Map()), r = i.get(s.canonical);
210
- if (r !== void 0)
211
- return r;
212
- const o = new L(
411
+ const s = N(e, t), r = this._pathHandles ??= /* @__PURE__ */ new Map(), i = r.get(s.canonical);
412
+ if (i !== void 0)
413
+ return i;
414
+ const o = this._workGraph.createProducer(this.rootScope, "path"), a = this._workGraph.producerHooks(o), n = new X(
213
415
  this.kernel,
214
416
  s,
215
- e,
216
- (n) => this._releasePathHandle(n),
417
+ t,
418
+ (h) => this._releasePathHandle(h),
217
419
  this._reactivity,
218
420
  () => this._assertAlive(),
219
421
  () => this._assertTrackedRead(),
220
422
  this.configuration.enforceActions ? () => this._assertWriteAllowed() : void 0,
221
- (n) => this._runWrite(n)
423
+ (h) => this._runWrite(h),
424
+ { token: o, onDispose: a.onDispose },
425
+ ({ events: h }, u) => this._workGraph.notifyProducerEvents(o, h, !0, u)
222
426
  );
223
- return i.set(s.canonical, o), o;
427
+ try {
428
+ return this._workGraph.setProducerActivation(o, () => n._activate(), !0), this._workGraph.attachProducer(o, n), r.set(s.canonical, n), n;
429
+ } catch (h) {
430
+ let u, c = !1;
431
+ try {
432
+ n.dispose();
433
+ } catch (d) {
434
+ c = !0, u = d;
435
+ }
436
+ throw r.size === 0 && this._pathHandles === r && (this._pathHandles = void 0), c ? new AggregateError(
437
+ [h, u],
438
+ "[Raph] Path source activation and rollback failed."
439
+ ) : h;
440
+ }
224
441
  }
225
- get(t, e) {
442
+ get(e, t) {
226
443
  this._assertTrackedRead();
227
- const s = t ?? "";
228
- return this._reactivity._isTracking() ? this.path(s, e)._getTracked() : this.kernel.get(s, e);
444
+ const s = e ?? "";
445
+ return this._reactivity._isTracking() ? this.path(s, t)._getTracked() : this.kernel.get(s, t);
229
446
  }
230
- peek(t, e) {
231
- return this._assertAlive(), this.kernel.peek(t ?? "", e);
447
+ peek(e, t) {
448
+ return this._assertAlive(), this.kernel.peek(e ?? "", t);
232
449
  }
233
- /**
234
- * Проверяет наличие значения Kernel по пути.
235
- */
236
- has(t, e) {
237
- return this._assertAlive(), this.kernel.has(t, e);
450
+ has(e, t) {
451
+ return this._assertAlive(), this.kernel.has(e, t);
238
452
  }
239
- /**
240
- * Записывает значение Kernel внутри runtime write policy.
241
- */
242
- set(t, e, s) {
243
- this._assertWriteAllowed(), this._runWrite(() => this.kernel.set(t, e, s));
453
+ set(e, t, s) {
454
+ this._assertWriteAllowed(), this._runWrite(() => this.kernel.set(e, t, s));
244
455
  }
245
- /**
246
- * Объединяет значение Kernel внутри runtime write policy.
247
- */
248
- merge(t, e, s) {
249
- this._assertWriteAllowed(), this._runWrite(() => this.kernel.merge(t, e, s));
456
+ merge(e, t, s) {
457
+ this._assertWriteAllowed(), this._runWrite(() => this.kernel.merge(e, t, s));
250
458
  }
251
- /**
252
- * Удаляет значение Kernel внутри runtime write policy.
253
- */
254
- delete(t, e) {
255
- this._assertWriteAllowed(), this._runWrite(() => this.kernel.delete(t, e));
459
+ delete(e, t) {
460
+ this._assertWriteAllowed(), this._runWrite(() => this.kernel.delete(e, t));
256
461
  }
257
- /**
258
- * Выполняет операцию в общей синхронной transaction boundary.
259
- */
260
- transaction(t) {
261
- this._assertAlive(), this._transactionDepth++;
462
+ batch(e) {
463
+ return this._batch(e, !0);
464
+ }
465
+ /** Batches an internal reactive-only commit without opening an unused Kernel boundary. @internal */
466
+ _batchReactive(e) {
467
+ return this._batch(e, !1);
468
+ }
469
+ _batch(e, t) {
470
+ this._assertAlive(), this._batchDepth++;
471
+ let s, r, i = !1;
262
472
  try {
263
- return this._reactivity.batch(() => this.kernel.transaction(t));
264
- } finally {
265
- this._transactionDepth--, this._requestExecution();
473
+ s = this._reactivity.batch(() => t ? this.kernel.batch(e) : e());
474
+ } catch (o) {
475
+ i = !0, r = o;
266
476
  }
477
+ return this._closeBatch(i, r), s;
267
478
  }
268
479
  /**
269
- * Создаёт именованную action boundary для разрешённых записей.
480
+ * Закрывает один уровень batch: внешний уровень очищает transient causes и
481
+ * запускает фазы. Бросает ошибку операции, ошибки закрытия либо все вместе;
482
+ * после успешной операции и закрытия возвращает управление.
270
483
  */
271
- action(t, e, s = this.rootScope) {
272
- if (this._assertOwnerRuntime(s), !t.trim())
273
- throw new Error("[Raph] Action name must not be empty.");
274
- return (...i) => (s._assertAlive(), this.runInAction(t, () => e(...i)));
484
+ _closeBatch(e, t) {
485
+ if (this._batchDepth--, this._executionBoundaryOpen()) {
486
+ if (e)
487
+ throw t;
488
+ return;
489
+ }
490
+ const s = this._finishExecutionBoundary();
491
+ if (e)
492
+ throw s !== void 0 ? new AggregateError(
493
+ [t, ...s],
494
+ "[Raph] Batch and scheduled phase execution failed."
495
+ ) : t;
496
+ s !== void 0 && m(s, "[Raph] Batch phase execution failed.");
275
497
  }
276
498
  /**
277
- * Выполняет операцию внутри action boundary.
499
+ * Исполняет тело action: `batch(() => _runUntracked(() => operation(...args)))`
500
+ * без closures и без промежуточных вызовов слоёв. Runtime, который один
501
+ * владеет своим Kernel без derived handles, metadata watchers и adapter,
502
+ * открывает границы reactive batch, Kernel и path batch явными вызовами и
503
+ * закрывает их в том же порядке и с теми же ошибками, что вложенные
504
+ * `batch()` этих слоёв. В любом другом состоянии исполняется сам `batch()`.
278
505
  */
279
- runInAction(t, e) {
280
- this._assertAlive(), this._actionDepth++;
506
+ _applyBatch(e, t) {
507
+ this._assertAlive();
508
+ const s = this.kernel, r = s._openSoleRuntimeBatch(this);
509
+ if (r === void 0)
510
+ return this._batch(() => this._runUntracked(() => e(...t)), !0);
511
+ const i = this._reactivity;
512
+ this._batchDepth++, i._startBatch();
513
+ let o, a, n = !1;
281
514
  try {
282
- return this.transaction(() => this._runUntracked(e));
283
- } finally {
284
- this._actionDepth--;
515
+ o = i._applyUntrackedWithOwner(e, t);
516
+ } catch (h) {
517
+ n = !0, a = h;
518
+ }
519
+ try {
520
+ s._closeSoleRuntimeBatch(this, r, n, a);
521
+ } catch (h) {
522
+ n = !0, a = h;
523
+ }
524
+ try {
525
+ i._endBatch();
526
+ } catch (h) {
527
+ a = n ? new AggregateError([a, h], "Batch operation and effect queue processing failed.") : h, n = !0;
285
528
  }
529
+ return this._closeBatch(n, a), o;
286
530
  }
287
- /**
288
- * Выполняет операцию без регистрации реактивных зависимостей.
289
- */
290
- untracked(t) {
291
- return this._assertAlive(), this._reactivity.untrackedWithOwner(t);
531
+ action(e, t, s) {
532
+ const r = typeof e == "function" ? e : t, i = typeof e == "function" ? t instanceof O ? t : this.rootScope : s ?? this.rootScope, o = typeof e == "string" ? e : `action#${++this._actionCounter}`;
533
+ if (this._assertOwnerRuntime(i), typeof r != "function")
534
+ throw new TypeError("[Raph] Action operation must be a function.");
535
+ if (!o.trim())
536
+ throw new Error("[Raph] Action name must not be empty.");
537
+ return (...a) => {
538
+ i._assertAlive();
539
+ const n = this._debugController, h = this._traceCauseStack, u = n.nextOperationId("action"), d = (h.length === 0 ? void 0 : h[h.length - 1]) ?? u;
540
+ n.traces("action") && n.record({
541
+ ...d === void 0 ? {} : { causeId: d },
542
+ kind: "action",
543
+ name: o,
544
+ ...u === void 0 ? {} : { operationId: u },
545
+ status: "start"
546
+ }), d !== void 0 && h.push(d), this._actionDepth++;
547
+ try {
548
+ const _ = this._applyBatch(r, a);
549
+ return n.traces("action") && n.record({
550
+ ...d === void 0 ? {} : { causeId: d },
551
+ kind: "action",
552
+ name: o,
553
+ ...u === void 0 ? {} : { operationId: u },
554
+ status: "end"
555
+ }), _;
556
+ } catch (_) {
557
+ throw this._debugController.record({
558
+ ...d === void 0 ? {} : { causeId: d },
559
+ details: { message: x(_) },
560
+ kind: "action",
561
+ name: o,
562
+ ...u === void 0 ? {} : { operationId: u },
563
+ status: "error"
564
+ }), this._debugController.record({
565
+ ...d === void 0 ? {} : { causeId: d },
566
+ details: { message: x(_) },
567
+ kind: "error",
568
+ name: `action:${o}`,
569
+ ...u === void 0 ? {} : { operationId: u },
570
+ status: "error"
571
+ }), _;
572
+ } finally {
573
+ this._actionDepth--, d !== void 0 && h.pop();
574
+ }
575
+ };
292
576
  }
293
- /**
294
- * Создаёт дочерний lifecycle scope.
295
- */
296
- scope(t) {
297
- return this._assertAlive(), new S(t, this);
577
+ untracked(e) {
578
+ return this._assertAlive(), this._runUntracked(e);
579
+ }
580
+ scope(e) {
581
+ return this._assertAlive(), new O(e, this);
582
+ }
583
+ node(e, t) {
584
+ this._assertAlive(), this._enterWrite();
585
+ let s;
586
+ try {
587
+ s = this._createCommittedNode(e, t);
588
+ } catch (r) {
589
+ throw this._failWrite(r);
590
+ }
591
+ return this._exitWrite(), s._assertAlive(), s;
298
592
  }
299
593
  /**
300
- * Создаёт дочерний execution node.
594
+ * Создаёт provisional node, выполняет setup и публикует результат; при ошибке
595
+ * setup откатывает node до выхода из границы mutation.
301
596
  */
302
- node(t, e) {
303
- this._assertAlive();
304
- const s = t.parent ?? this.root, i = new m(s, t, this);
597
+ _createCommittedNode(e, t) {
598
+ const s = e.parent ?? this.root, r = H(s, e, this);
305
599
  try {
306
- return i._setApi(e(i)), i;
307
- } catch (r) {
600
+ const i = t?.(r);
601
+ return r._assertAlive(), s._assertAlive(), r._setApi(i), r._publishCreation(), r;
602
+ } catch (i) {
308
603
  try {
309
- i.dispose();
604
+ r.dispose();
310
605
  } catch (o) {
311
- throw new AggregateError(
312
- [r, o],
313
- `[Raph] Node "${i.id}" setup and cleanup failed.`
314
- );
606
+ throw new AggregateError([i, o], `[Raph] Node "${r.id}" setup and cleanup failed.`);
315
607
  }
316
- throw r;
608
+ throw i;
317
609
  }
318
610
  }
319
- /**
320
- * Находит принадлежащий runtime node по id для диагностики.
321
- */
322
- getNode(t) {
323
- this._assertAlive();
324
- const e = [this.root];
325
- for (; e.length !== 0; ) {
326
- const s = e.pop();
327
- if (s.id === t)
328
- return s;
329
- e.push(...s.children);
330
- }
611
+ getNode(e) {
612
+ return this._assertAlive(), this.root._findNode(e);
331
613
  }
332
- /**
333
- * Заменяет полное определение phase pipeline до его первого выполнения.
334
- */
335
- definePhases(t) {
336
- this._execution.definePhases(t);
614
+ definePhases(e) {
615
+ this._execution.definePhases(e);
337
616
  }
338
- /**
339
- * Добавляет phase до первого выполнения pipeline.
340
- */
341
- addPhase(t) {
342
- this._execution.addPhase(t);
617
+ addPhase(e) {
618
+ this._execution.addPhase(e);
343
619
  }
344
- /**
345
- * Удаляет пользовательские phases до первого выполнения pipeline.
346
- */
347
620
  clearPhases() {
348
- var t;
349
- this._assertAlive(), (t = this._phases) == null || t.clearPhases();
621
+ this._assertAlive(), this._phases?.clearPhases();
350
622
  }
351
- /**
352
- * Регистрирует path observer в phase pipeline.
353
- */
354
- observeData(t, e, s) {
355
- return this._assertOwnerRuntime(t), this._own(this._execution.observeData(t, e, s), t);
623
+ requestExecution() {
624
+ this._assertAlive(), this._phases?.request();
356
625
  }
357
- /**
358
- * Регистрирует tracked executor указанной phase.
359
- */
360
- track(t, e, s = {}) {
361
- return this._assertOwnerRuntime(t), this._own(this._execution.track(t, e, s), t);
362
- }
363
- /**
364
- * Помечает node для выполнения в pipeline.
365
- */
366
- invalidateNode(t, e) {
367
- this._assertOwnerRuntime(t), this._execution.invalidate(t, e);
368
- }
369
- /**
370
- * Синхронно выполняет все готовые очереди pipeline.
371
- */
372
626
  flush() {
373
- var t;
374
- this._assertAlive(), this._executionRequested = !1, (t = this._phases) == null || t.flush();
627
+ this._assertAlive(), this._executionRequested = !1, this._phases?.flush();
375
628
  }
376
- /**
377
- * Получает lease автоматического frame-loop.
378
- */
379
- acquireLoop(t) {
380
- return this._assertAlive(), this._clock.acquire(t);
629
+ afterFlush() {
630
+ return this._assertAlive(), this._phases?.afterFlush() ?? Promise.resolve();
631
+ }
632
+ acquireLoop(e) {
633
+ return this._assertAlive(), this._clock.acquire(e);
381
634
  }
382
- /**
383
- * Запускает manual lease автоматического frame-loop.
384
- */
385
635
  startLoop() {
386
636
  this._assertAlive(), this._clock.start();
387
637
  }
388
- /**
389
- * Останавливает manual lease автоматического frame-loop.
390
- */
391
638
  stopLoop() {
392
- var t;
393
- (t = this._frameLoop) == null || t.stop();
639
+ this._frameLoop?.stop();
394
640
  }
395
- /**
396
- * Создаёт управляемое derived-представление source path в target path.
397
- */
398
- derive(t) {
641
+ derive(e) {
399
642
  this._assertAlive();
400
- const e = t.compute, s = this.kernel.derive({
401
- ...t,
402
- compute: (i) => this._runUntracked(() => e(i))
643
+ const t = e.compute, s = this.kernel.derive({
644
+ ...e,
645
+ compute: (r) => this._runUntracked(() => t(r))
403
646
  });
404
647
  return this._own(() => s.dispose(), this.rootScope), s;
405
648
  }
406
- /**
407
- * Освобождает execution graph и отсоединяет runtime от shared Kernel.
408
- */
409
649
  dispose() {
410
- var r, o;
411
650
  if (this._disposed)
412
651
  return;
413
652
  this._disposed = !0, this._executionRequested = !1, this._signalLifecycle.owner = void 0;
414
- const t = [], e = [...this._owners];
653
+ const e = [];
415
654
  try {
416
- (r = this._frameLoop) == null || r.dispose();
417
- } catch (n) {
418
- t.push(n);
655
+ this._frameLoop?.dispose();
656
+ } catch (a) {
657
+ e.push(a);
419
658
  }
420
659
  this._frameLoop = void 0;
421
660
  try {
422
- (o = this._phases) == null || o.dispose();
423
- } catch (n) {
424
- t.push(n);
661
+ this._phases?.dispose();
662
+ } catch (a) {
663
+ e.push(a);
425
664
  }
426
665
  this._phases = void 0;
427
666
  try {
428
667
  this.root.dispose();
429
- } catch (n) {
430
- t.push(n);
668
+ } catch (a) {
669
+ e.push(a);
431
670
  }
432
- for (const n of e.reverse())
433
- if (!(n === this.root || n === this.rootScope || n.disposed))
671
+ const t = this._collectOwners().sort(ie);
672
+ for (const a of t)
673
+ if (!(a === this.root || a === this.rootScope || a.disposed))
434
674
  try {
435
- n.dispose();
436
- } catch (c) {
437
- t.push(c);
675
+ a.dispose();
676
+ } catch (n) {
677
+ e.push(n);
438
678
  }
439
679
  try {
440
680
  this.rootScope.dispose();
441
- } catch (n) {
442
- t.push(n);
681
+ } catch (a) {
682
+ e.push(a);
683
+ }
684
+ const s = `[Raph] Runtime "${this.id}" is disposed.`, r = () => {
685
+ throw new A(s);
686
+ };
687
+ try {
688
+ L(this._reactivity, {
689
+ assertRead: r,
690
+ assertWrite: r,
691
+ throwForeign: r
692
+ });
693
+ } catch (a) {
694
+ e.push(a);
443
695
  }
444
- this._owners.clear(), this._meta = void 0, this._frameRevision = void 0;
445
- const s = this._pathHandles;
446
- if (this._pathHandles = void 0, s !== void 0) {
447
- for (const n of s.values())
696
+ this._topOwners.clear(), this._ownersReleased = !0, this._meta = void 0;
697
+ const i = this._pathHandles;
698
+ if (this._pathHandles = void 0, i !== void 0) {
699
+ for (const a of i.values())
448
700
  try {
449
- n.dispose();
450
- } catch (c) {
451
- t.push(c);
701
+ a.dispose();
702
+ } catch (n) {
703
+ e.push(n);
452
704
  }
453
- s.clear();
705
+ i.clear();
706
+ }
707
+ try {
708
+ this._workGraph.dispose();
709
+ } catch (a) {
710
+ e.push(a);
454
711
  }
455
712
  try {
456
713
  this.kernel._detachRuntime(this);
457
- } catch (n) {
458
- t.push(n);
714
+ } catch (a) {
715
+ e.push(a);
459
716
  }
460
- const i = [...this._disposedListeners];
717
+ const o = [...this._disposedListeners];
461
718
  this._disposedListeners.clear();
462
- for (const n of i)
719
+ for (const a of o)
463
720
  try {
464
- n();
465
- } catch (c) {
466
- t.push(c);
721
+ a();
722
+ } catch (n) {
723
+ e.push(n);
467
724
  }
468
- D(t, `[Raph] Runtime "${this.id}" disposal failed.`);
725
+ m(e, `[Raph] Runtime "${this.id}" disposal failed.`);
726
+ }
727
+ /** @internal */
728
+ _onDisposed(e) {
729
+ return this._disposed ? (e(), () => {
730
+ }) : (this._disposedListeners.add(e), () => {
731
+ this._disposedListeners.delete(e);
732
+ });
733
+ }
734
+ /** @internal */
735
+ _notifyNodeStructure(e, t, s, r) {
736
+ if (!this._workGraph._hasStructuralDemand(e)) {
737
+ this._touchMutationBoundary();
738
+ return;
739
+ }
740
+ this._runNodeMutation(() => {
741
+ this._workGraph.notifyNode(e, "structure", { structure: t, oldAncestors: s, newAncestors: r });
742
+ });
469
743
  }
470
744
  /**
471
- * Регистрирует listener освобождения runtime.
745
+ * Сообщает, может ли structural publication этой node дойти до подписчика;
746
+ * `false` позволяет не строить structure cause и списки ancestors.
747
+ *
472
748
  * @internal
473
749
  */
474
- _onDisposed(t) {
475
- return this._disposed ? (t(), () => {
476
- }) : (this._disposedListeners.add(t), () => {
477
- this._disposedListeners.delete(t);
478
- });
750
+ _hasNodeStructureDemand(e) {
751
+ return this._workGraph._hasStructuralDemand(e);
479
752
  }
480
- _watchPath(t, e) {
481
- const s = new g((r) => this._runUntracked(r)), i = this.kernel.watch(t, (r) => {
482
- s.deliver(() => e(r));
483
- });
484
- return () => s.stop(i);
753
+ /**
754
+ * Сообщает, есть ли у Runtime хотя бы один подписчик на node: runtime-,
755
+ * subtree- или self-watcher. Пока он есть, node поддерживает выданный массив
756
+ * детей на месте, потому что structure cause берёт из него индексы.
757
+ *
758
+ * @internal
759
+ */
760
+ _hasNodeSubscribers() {
761
+ return this._workGraph._hasNodeSubscribers();
762
+ }
763
+ /** @internal */
764
+ _notifyNodeTouch(e, t) {
765
+ this._runNodeMutation(() => this._workGraph.notifyNode(e, "touch", { metadata: t }));
766
+ }
767
+ /** @internal */
768
+ _assertNodeReparentAllowed(e, t) {
769
+ this._workGraph.assertReparentAllowed(e, t);
770
+ }
771
+ /** @internal */
772
+ _releaseNode(e) {
773
+ this._workGraph.releaseNode(e);
774
+ }
775
+ /** @internal */
776
+ _runNodeMutation(e) {
777
+ return this._runWrite(e);
778
+ }
779
+ /**
780
+ * Выполняет границу пустой node mutation без аллокаций: эквивалент
781
+ * `_runWrite(noop)` с тем же запросом исполнения и flush на внешней границе.
782
+ *
783
+ * @internal
784
+ */
785
+ _touchMutationBoundary() {
786
+ if (this.configuration.scheduler === f.Sync && (this._executionRequested = !0), this._executionBoundaryOpen())
787
+ return;
788
+ const e = this._finishExecutionBoundary();
789
+ e !== void 0 && m(e, "[Raph] Mutation phase execution failed.");
790
+ }
791
+ /** @internal */
792
+ _runPhaseTransition(e) {
793
+ return this._runWrite(e, !1);
794
+ }
795
+ /**
796
+ * Открывает границу освобождения. `node` передаёт только dispose самой node:
797
+ * Runtime помнит её до парного `_endOwnerDisposal`.
798
+ *
799
+ * @internal
800
+ */
801
+ _beginOwnerDisposal(e) {
802
+ this._disposingNodes[this._ownerDisposalDepth++] = e;
803
+ }
804
+ /** @internal */
805
+ _endOwnerDisposal() {
806
+ const e = this._ownerDisposalDepth;
807
+ e !== 0 && (this._ownerDisposalDepth = e - 1, this._disposingNodes[e - 1] = void 0, this._ownerDisposals >= this._nextDisposalSweep && e === 1 && this._sweepAfterDisposals(), this._clearTransientCausesIfSettled(), this._disposed || this._requestExecution());
808
+ }
809
+ /**
810
+ * Возвращает число владельцев, освобождённых этим Runtime за всё время.
811
+ *
812
+ * @internal
813
+ */
814
+ _ownerDisposalCount() {
815
+ return this._ownerDisposals;
816
+ }
817
+ /**
818
+ * Подключает участника уборки: Runtime вызовет его на первой внешней границе
819
+ * освобождения, к которой число освобождённых владельцев достигнет `due`.
820
+ * Подключённый участник остаётся в очереди, пока сам не откажется от
821
+ * следующего срока либо не будет отключён.
822
+ *
823
+ * @internal
824
+ */
825
+ _addDisposalSweeper(e, t) {
826
+ const s = this._disposalSweepers;
827
+ if (s === void 0) {
828
+ e._sweepSlot = 0, e._sweepDue = t, this._disposalSweepers = [e], this._nextDisposalSweep = t;
829
+ return;
830
+ }
831
+ Y(s, e, t), this._nextDisposalSweep = s[0]._sweepDue;
832
+ }
833
+ /**
834
+ * Отключает участника уборки; отключение неизвестного участника безопасно.
835
+ *
836
+ * @internal
837
+ */
838
+ _removeDisposalSweeper(e) {
839
+ const t = this._disposalSweepers;
840
+ t === void 0 || !P(t, e) || (t.length === 0 ? (this._disposalSweepers = void 0, this._nextDisposalSweep = Number.POSITIVE_INFINITY) : this._nextDisposalSweep = t[0]._sweepDue);
841
+ }
842
+ /**
843
+ * Вызывает участников уборки, чей срок подошёл, и назначает ближайший
844
+ * следующий срок. Участник, чей срок не подошёл, вызова не получает:
845
+ * освобождение владельца стоит участникам работы, только когда подходит их
846
+ * собственный срок.
847
+ */
848
+ _sweepAfterDisposals() {
849
+ const e = this._disposalSweepers;
850
+ if (e === void 0)
851
+ return;
852
+ const t = this._ownerDisposals;
853
+ if (e.length === 1) {
854
+ const s = e[0], r = s._afterOwnerDisposals(t);
855
+ r > t ? (s._sweepDue = r, this._nextDisposalSweep = r) : (s._sweepSlot = -1, this._disposalSweepers = void 0, this._nextDisposalSweep = Number.POSITIVE_INFINITY);
856
+ return;
857
+ }
858
+ for (let s = e[0]; s._sweepDue <= t; s = e[0]) {
859
+ const r = s._afterOwnerDisposals(t);
860
+ if (r > t)
861
+ Q(e, r);
862
+ else if (P(e, s), e.length === 0) {
863
+ this._disposalSweepers = void 0, this._nextDisposalSweep = Number.POSITIVE_INFINITY;
864
+ return;
865
+ }
866
+ }
867
+ this._nextDisposalSweep = e[0]._sweepDue;
868
+ }
869
+ /** @internal */
870
+ _ownerDisposalActive() {
871
+ return this._ownerDisposalDepth !== 0;
872
+ }
873
+ /**
874
+ * Учитывает нового владельца и возвращает его порядковый номер регистрации.
875
+ * Plain scope сразу входит в набор владельцев вне списков детей; node входит
876
+ * в него сама через `_addTopOwner`, и только если у неё нет parent.
877
+ *
878
+ * @internal
879
+ */
880
+ _registerOwner(e) {
881
+ return this._assertAlive(), e._isNode || this._topOwners.add(e), ++this._ownerRegistrations;
882
+ }
883
+ /**
884
+ * Снимает владельца с учёта. Plain scope выходит и из набора владельцев вне
885
+ * списков детей; node без parent выходит из него сама через
886
+ * `_removeTopOwner`, а node с parent в нём не состоит.
887
+ *
888
+ * @internal
889
+ */
890
+ _unregisterOwner(e) {
891
+ e._isNode || this._topOwners.delete(e), this._ownerDisposals++;
892
+ }
893
+ /**
894
+ * Вносит node без parent в набор владельцев вне списков детей.
895
+ *
896
+ * @internal
897
+ */
898
+ _addTopOwner(e) {
899
+ this._topOwners.add(e);
900
+ }
901
+ /**
902
+ * Убирает node из набора владельцев вне списков детей: она освобождена либо
903
+ * получила parent. Повторный вызов и вызов после освобождения Runtime
904
+ * безопасны.
905
+ *
906
+ * @internal
907
+ */
908
+ _removeTopOwner(e) {
909
+ this._topOwners.delete(e);
910
+ }
911
+ /** @internal */
912
+ _assertOwnerRuntime(e) {
913
+ if (this._assertAlive(), e.runtime !== this)
914
+ throw new b("[Raph] Owner belongs to another runtime.");
915
+ e._assertAlive();
916
+ }
917
+ /** @internal */
918
+ _beginKernelBatch() {
919
+ this._disposed || this._kernelBatchDepth++;
920
+ }
921
+ /** @internal */
922
+ _endKernelBatch() {
923
+ this._kernelBatchDepth !== 0 && (this._kernelBatchDepth--, this._clearTransientCausesIfSettled(), this._disposed || this._requestExecution());
924
+ }
925
+ /** Регистрирует read-only diagnostics projection optional Machine. @internal */
926
+ _registerMachineDebug(e) {
927
+ return this._assertAlive(), this._debugController.registerMachine(e);
928
+ }
929
+ /**
930
+ * Проверяет optional diagnostic identity без создания public facade.
931
+ *
932
+ * @internal
933
+ */
934
+ _hasMachineDebug(e) {
935
+ return this._debugController.hasMachine(e);
936
+ }
937
+ /**
938
+ * Проверяет optional trace path без выделения operation ID.
939
+ *
940
+ * @internal
941
+ */
942
+ _traces(e) {
943
+ return this._debugController.traces(e);
944
+ }
945
+ /** Возвращает наследуемый cause для optional execution layers. @internal */
946
+ _currentTraceCauseId() {
947
+ return this._traceCauseStack.at(-1);
948
+ }
949
+ /** Выдаёт operation id только на активном trace path. @internal */
950
+ _nextTraceOperation(e) {
951
+ return this._debugController.nextOperationId(e);
952
+ }
953
+ /**
954
+ * Проверяет, должен ли untracked work изолировать reactive или Runtime owner context.
955
+ *
956
+ * @internal
957
+ */
958
+ _hasActiveReactiveContext() {
959
+ return this._assertAlive(), this._reactivity.hasActiveContext();
960
+ }
961
+ /** Записывает optional trace event без machine dependency. @internal */
962
+ _recordTrace(e) {
963
+ this._debugController.record(e);
964
+ }
965
+ /** Наследует cause через outputs/tasks optional execution layers. @internal */
966
+ _runWithTraceCause(e, t) {
967
+ if (e === void 0)
968
+ return t();
969
+ this._traceCauseStack.push(e);
970
+ try {
971
+ return t();
972
+ } finally {
973
+ this._traceCauseStack.pop();
974
+ }
975
+ }
976
+ /**
977
+ * Выполняет единственную проверку binding: pipeline доверяет её результату.
978
+ */
979
+ _validatePhaseBinding(e, t, s, r, i = !1) {
980
+ if (typeof s != "function")
981
+ throw new TypeError("[Raph] Phase callback must be a function.");
982
+ const o = e.resolvePhase(t), a = r.priority ?? 0;
983
+ if (!Number.isFinite(a))
984
+ throw new TypeError("[Raph] Effect priority must be finite.");
985
+ const n = r.initial ?? "scheduled";
986
+ if (n !== "scheduled" && n !== "sync" && !(i && n === "none"))
987
+ throw new TypeError(`[Raph] Unsupported effect initial mode "${String(n)}".`);
988
+ return o;
989
+ }
990
+ /**
991
+ * Освобождает binding, регистрация которого не удалась, и повторно бросает
992
+ * причину сбоя; ошибка самого освобождения присоединяется к ней.
993
+ */
994
+ _rollbackRegistration(e, t, s, r) {
995
+ let i = t;
996
+ try {
997
+ e.dispose();
998
+ } catch (o) {
999
+ i = new AggregateError([t, o], s);
1000
+ }
1001
+ throw r !== void 0 && r(i), i;
485
1002
  }
486
1003
  _createDebugSnapshot() {
487
- var s, i, r;
488
- const t = ((s = this._frameLoop) == null ? void 0 : s._debugState()) ?? { running: !1, manual: !1, leases: 0 }, e = [...this._owners].filter((o) => o !== this.rootScope && !(o instanceof m)).map(y);
1004
+ const e = this._frameLoop?._debugState() ?? { running: !1, manual: !1, leases: 0 }, t = [...this._topOwners].filter((s) => s !== this.rootScope && !(s instanceof v)).map(D);
489
1005
  return Object.freeze({
490
1006
  id: this.id,
491
1007
  disposed: this._disposed,
492
- pending: !this._disposed && (this._executionRequested || (((i = this._phases) == null ? void 0 : i._debugPending()) ?? !1)),
493
- transactionDepth: this._transactionDepth,
494
- kernelTransactionDepth: this._kernelTransactionDepth,
495
- owners: this._owners.size,
496
- pathHandles: ((r = this._pathHandles) == null ? void 0 : r.size) ?? 0,
497
- rootScope: y(this.rootScope),
498
- scopes: Object.freeze(e),
499
- root: y(this.root),
500
- frameLoop: Object.freeze(t)
1008
+ pending: !this._disposed && (this._executionRequested || (this._phases?._debugPending() ?? !1)),
1009
+ batchDepth: this._batchDepth,
1010
+ kernelBatchDepth: this._kernelBatchDepth,
1011
+ owners: this._liveOwnerCount(),
1012
+ pathHandles: this._pathHandles?.size ?? 0,
1013
+ rootScope: D(this.rootScope),
1014
+ scopes: Object.freeze(t),
1015
+ root: D(this.root),
1016
+ frameLoop: Object.freeze(e),
1017
+ actionDepth: this._actionDepth,
1018
+ machines: this._debugController.machineCount,
1019
+ traceEvents: this._debugController.traceSize
501
1020
  });
502
1021
  }
503
- _watchMeta(t, e, s) {
504
- if (s.phase !== void 0)
505
- return this._watchMetaInPhase(t, e, s);
506
- if (s.priority !== void 0)
507
- throw new TypeError("[RaphMeta] watch priority requires a phase.");
508
- const i = new g((o) => this._runUntracked(o)), r = this.kernel._watchMeta(t, (o) => {
509
- i.deliver(() => e(o));
510
- }, s);
511
- return () => i.stop(r);
512
- }
513
- _watchMetaInPhase(t, e, s) {
514
- const i = s.phase.trim(), r = this._execution;
515
- r.requirePhase(i);
516
- const o = s.priority ?? 0;
517
- if (!Number.isFinite(o))
518
- throw new TypeError("[RaphMeta] watch priority must be finite.");
519
- const n = r.retainPhase(i), c = new g((_) => this._runUntracked(_));
520
- let p = [], u;
521
- const l = () => {
522
- u = void 0;
523
- const _ = p;
524
- p = [], c.deliver(() => e({ events: _ }));
525
- };
526
- let w;
527
- try {
528
- w = this.kernel._watchMeta(t, ({ events: _ }) => {
529
- c.stopped || (p.push(..._), u === void 0 && (u = r.queueEffect(i, o, l, !1)));
530
- }, s, (_) => {
531
- !c.stopped && _ && u !== void 0 && r.request();
532
- });
533
- } catch (_) {
534
- throw n(), _;
535
- }
536
- return () => {
537
- if (c.stopped)
538
- return;
539
- const _ = [];
540
- try {
541
- c.stop(w);
542
- } catch (f) {
543
- _.push(f);
544
- }
545
- try {
546
- u == null || u();
547
- } catch (f) {
548
- _.push(f);
549
- }
550
- try {
551
- n();
552
- } catch (f) {
553
- _.push(f);
1022
+ _createDebugTree() {
1023
+ const e = this._debugController.machineTreeNodesByOwner(), t = [
1024
+ S(this.rootScope, e),
1025
+ S(this.root, e),
1026
+ ...[...this._topOwners].filter((s) => s !== this.rootScope && s !== this.root && !(s instanceof v)).map((s) => S(s, e))
1027
+ ];
1028
+ return Object.freeze({
1029
+ children: Object.freeze(t),
1030
+ disposed: this._disposed,
1031
+ id: this.id,
1032
+ kind: "runtime"
1033
+ });
1034
+ }
1035
+ _createDebugStats() {
1036
+ const e = this._liveOwnerCount();
1037
+ let t = 0;
1038
+ const s = { resources: 0, sources: 0 };
1039
+ if (!this._ownersReleased) {
1040
+ const r = this._topOwners;
1041
+ for (const a of r)
1042
+ a._isNode ? a._countSubtree(s) : (t++, s.resources += a._debugResourceCount(), s.sources += a._debugSourceCount());
1043
+ const i = this._disposingNodes, o = this._ownerDisposalDepth;
1044
+ for (let a = 0; a < o; a++) {
1045
+ const n = i[a];
1046
+ n === void 0 || n._isLinked() || r.has(n) || n._countSubtree(s);
554
1047
  }
555
- u = void 0, p = [], D(_, "[RaphMeta] Phase watch disposal failed.");
556
- };
1048
+ }
1049
+ return Object.freeze({
1050
+ actors: this._debugController.actorCount,
1051
+ machines: this._debugController.machineCount,
1052
+ // Каждый учтённый владелец, который не plain scope, — node.
1053
+ nodes: e - t,
1054
+ owners: e,
1055
+ pathHandles: this._pathHandles?.size ?? 0,
1056
+ pending: !this._disposed && (this._executionRequested || (this._phases?._debugPending() ?? !1)),
1057
+ resources: s.resources,
1058
+ scopes: t,
1059
+ sources: s.sources,
1060
+ traceEvents: this._debugController.traceSize
1061
+ });
557
1062
  }
558
- _releasePathHandle(t) {
559
- const e = this._pathHandles;
560
- (e == null ? void 0 : e.get(t.path)) === t && (e.delete(t.path), e.size === 0 && (this._pathHandles = void 0));
1063
+ /**
1064
+ * Возвращает число владельцев, которых Runtime числит живыми: зарегистрированных
1065
+ * и ещё не снятых с учёта. После освобождения Runtime их нет.
1066
+ */
1067
+ _liveOwnerCount() {
1068
+ return this._ownersReleased ? 0 : this._ownerRegistrations - this._ownerDisposals;
1069
+ }
1070
+ /**
1071
+ * Собирает всех владельцев, которых Runtime числит живыми. Владельцы вне
1072
+ * списков детей идут в порядке регистрации, каждый — вместе с потомками по
1073
+ * спискам детей. Node, чей dispose ещё исполняется, из списка parent уже
1074
+ * вышла либо потеряла parent, который сбросил свой список: её и оставшихся
1075
+ * у неё детей добавляют места границ освобождения.
1076
+ */
1077
+ _collectOwners() {
1078
+ const e = [];
1079
+ if (this._ownersReleased)
1080
+ return e;
1081
+ const t = this._topOwners;
1082
+ for (const i of t)
1083
+ e.push(i), i._isNode && i._collectDescendants(e);
1084
+ const s = this._disposingNodes, r = this._ownerDisposalDepth;
1085
+ for (let i = 0; i < r; i++) {
1086
+ const o = s[i];
1087
+ o === void 0 || o._isLinked() || t.has(o) || (e.push(o), o._collectDescendants(e));
1088
+ }
1089
+ return e;
1090
+ }
1091
+ _releasePathHandle(e) {
1092
+ const t = this._pathHandles;
1093
+ t?.get(e.path) === e && (t.delete(e.path), t.size === 0 && (this._pathHandles = void 0));
561
1094
  }
562
1095
  get _execution() {
563
- return this._assertAlive(), this._phases ?? (this._phases = new F(
564
- this.kernel,
565
- this.root,
1096
+ return this._assertAlive(), this._phases ??= new j(
566
1097
  this.configuration.scheduler,
567
- (t) => this._runUntracked(t),
1098
+ this._reactivity,
1099
+ (e) => this._workGraph.causeForToken(e),
568
1100
  () => {
569
- const t = this._mutationDepth !== 0 || this._transactionDepth !== 0 || this._kernelTransactionDepth !== 0 || this._reactivity._isFlushingEffects();
570
- return t && this.configuration.scheduler === d.Sync && (this._executionRequested = !0), t;
1101
+ const e = this._mutationDepth !== 0 || this._batchDepth !== 0 || this._kernelBatchDepth !== 0 || this._ownerDisposalDepth !== 0 || this._reactivity._isFlushingEffects();
1102
+ return e && this.configuration.scheduler === f.Sync && (this._executionRequested = !0), e;
1103
+ },
1104
+ (e, t, s) => {
1105
+ if (this._phaseTraceOperations === void 0 && !this._debugController.traces("phase"))
1106
+ return;
1107
+ let r;
1108
+ t === "start" ? (r = this._debugController.nextOperationId("phase"), r !== void 0 && (this._phaseTraceOperations ??= /* @__PURE__ */ new Map()).set(e, r)) : (r = this._phaseTraceOperations?.get(e), this._phaseTraceOperations?.delete(e), this._phaseTraceOperations?.size === 0 && (this._phaseTraceOperations = void 0)), this._debugController.record({
1109
+ ...r === void 0 ? {} : { causeId: r },
1110
+ ...s === void 0 ? {} : { details: { message: x(s) } },
1111
+ kind: "phase",
1112
+ name: e,
1113
+ ...r === void 0 ? {} : { operationId: r },
1114
+ status: t
1115
+ });
571
1116
  }
572
- ));
1117
+ );
573
1118
  }
574
1119
  get _clock() {
575
- return this._frameLoop ?? (this._frameLoop = new H(() => this._tickFrameLoop()));
1120
+ return this._frameLoop ??= new z(() => this._tickFrameLoop());
576
1121
  }
577
1122
  _tickFrameLoop() {
578
- var t;
579
- this._disposed || (this._frameRevision !== void 0 && (this._frameRevisionValue = !this._frameRevisionValue, this._frameRevision.set(this._frameRevisionValue)), (t = this._phases) == null || t.requestAlwaysPhases(), this._requestExecution());
1123
+ this._disposed || this._setFrameTick(this._frameTickSignal.peek() + 1);
1124
+ }
1125
+ /**
1126
+ * Записывает frame signal в собственной границе записи, минуя политику
1127
+ * actions: кадр продвигает сам Runtime.
1128
+ */
1129
+ _setFrameTick(e) {
1130
+ this._enterWrite();
1131
+ try {
1132
+ this._frameTickSignal._writeInBoundary(e);
1133
+ } catch (t) {
1134
+ throw this._failWrite(t);
1135
+ }
1136
+ this._exitWrite();
580
1137
  }
581
- _attachWritableComputed(t, e, s) {
582
- let i = e;
1138
+ _attachWritableComputed(e, t, s) {
1139
+ let r = t;
583
1140
  this._own(() => {
584
- i = void 0;
1141
+ r = void 0;
585
1142
  }, s);
586
- const r = t;
587
- return r.set = (o) => {
588
- s._assertAlive(), this._assertWriteAllowed(), i(o);
589
- }, r;
1143
+ const i = e;
1144
+ return i.set = (o) => {
1145
+ s._assertAlive(), this._assertWriteAllowed(), this._runWrite(() => r(o));
1146
+ }, i;
590
1147
  }
591
- _own(t, e) {
1148
+ _own(e, t) {
592
1149
  try {
593
- return e._adoptResource(t);
1150
+ return t._adoptResource(e);
594
1151
  } catch (s) {
595
1152
  try {
596
- t();
597
- } catch (i) {
598
- throw new AggregateError(
599
- [s, i],
600
- "[Raph] Resource registration and cleanup failed."
601
- );
1153
+ e();
1154
+ } catch (r) {
1155
+ throw new AggregateError([s, r], "[Raph] Resource registration and cleanup failed.");
602
1156
  }
603
1157
  throw s;
604
1158
  }
605
1159
  }
1160
+ _runTracked(e, t) {
1161
+ return this._reactivity.runWithOwner(this._signalLifecycle, e, t);
1162
+ }
1163
+ _runUntracked(e) {
1164
+ return this._reactivity.untrackedWithOwner(e);
1165
+ }
1166
+ _runWrite(e, t = !0) {
1167
+ t && this.configuration.scheduler === f.Sync && (this._executionRequested = !0), this._mutationDepth++;
1168
+ let s, r, i = !1;
1169
+ try {
1170
+ s = e();
1171
+ } catch (a) {
1172
+ i = !0, r = a;
1173
+ }
1174
+ if (this._mutationDepth--, this._executionBoundaryOpen()) {
1175
+ if (i)
1176
+ throw r;
1177
+ return s;
1178
+ }
1179
+ const o = this._finishExecutionBoundary();
1180
+ if (i)
1181
+ throw o !== void 0 ? new AggregateError(
1182
+ [r, ...o],
1183
+ "[Raph] Mutation and scheduled phase execution failed."
1184
+ ) : r;
1185
+ return o !== void 0 && m(o, "[Raph] Mutation phase execution failed."), s;
1186
+ }
606
1187
  /**
607
- * Регистрирует lifecycle owner в runtime registry.
1188
+ * Открывает границу записи без closure; повторяет начало `_runWrite`.
1189
+ *
608
1190
  * @internal
609
1191
  */
610
- _registerOwner(t) {
611
- this._assertAlive(), this._owners.add(t);
1192
+ _enterWrite() {
1193
+ this.configuration.scheduler === f.Sync && (this._executionRequested = !0), this._mutationDepth++;
612
1194
  }
613
1195
  /**
614
- * Удаляет lifecycle owner из runtime registry.
1196
+ * Закрывает успешную запись, открытую `_enterWrite`; внешняя граница очищает
1197
+ * transient causes и запускает фазы с теми же ошибками, что и `_runWrite`.
1198
+ *
615
1199
  * @internal
616
1200
  */
617
- _unregisterOwner(t) {
618
- this._owners.delete(t);
1201
+ _exitWrite() {
1202
+ if (this._mutationDepth--, this._executionBoundaryOpen())
1203
+ return;
1204
+ const e = this._finishExecutionBoundary();
1205
+ e !== void 0 && m(e, "[Raph] Mutation phase execution failed.");
619
1206
  }
620
1207
  /**
621
- * Проверяет, что owner принадлежит этому живому runtime.
1208
+ * Закрывает запись после ошибки операции и возвращает ошибку для throw:
1209
+ * исходную либо AggregateError, если упало и закрытие внешней границы.
1210
+ *
622
1211
  * @internal
623
1212
  */
624
- _assertOwnerRuntime(t) {
625
- if (this._assertAlive(), t.runtime !== this)
626
- throw new k("[Raph] Owner belongs to another runtime.");
627
- t._assertAlive();
628
- }
629
- _runTracked(t) {
630
- return this._reactivity.runWithOwner(this._signalLifecycle, t);
1213
+ _failWrite(e) {
1214
+ if (this._mutationDepth--, this._executionBoundaryOpen())
1215
+ return e;
1216
+ const t = this._finishExecutionBoundary();
1217
+ return t === void 0 ? e : new AggregateError(
1218
+ [e, ...t],
1219
+ "[Raph] Mutation and scheduled phase execution failed."
1220
+ );
631
1221
  }
632
- _runUntracked(t) {
633
- return this._reactivity.untrackedWithOwner(t);
1222
+ /**
1223
+ * Сообщает, что внешняя write-, batch-, Kernel- или disposal-граница ещё открыта.
1224
+ * В этом состоянии оба шага `_finishExecutionBoundary` заведомо ничего не делают:
1225
+ * transient causes очищаются и фазы запускаются только при нулевых глубинах.
1226
+ */
1227
+ _executionBoundaryOpen() {
1228
+ return this._mutationDepth !== 0 || this._batchDepth !== 0 || this._kernelBatchDepth !== 0 || this._ownerDisposalDepth !== 0;
634
1229
  }
635
- _runWrite(t, e = !0) {
636
- e && this.configuration.scheduler === d.Sync && (this._executionRequested = !0), this._mutationDepth++;
1230
+ /** Закрывает внешнюю границу; массив ошибок создаётся только при первой ошибке. */
1231
+ _finishExecutionBoundary() {
1232
+ let e;
637
1233
  try {
638
- return t();
639
- } finally {
640
- this._mutationDepth--, this._requestExecution();
1234
+ this._clearTransientCausesIfSettled();
1235
+ } catch (t) {
1236
+ e = [t];
641
1237
  }
1238
+ try {
1239
+ this._requestExecution();
1240
+ } catch (t) {
1241
+ e === void 0 ? e = [t] : e.push(t);
1242
+ }
1243
+ return e;
1244
+ }
1245
+ _clearTransientCausesIfSettled() {
1246
+ this._mutationDepth === 0 && this._batchDepth === 0 && this._kernelBatchDepth === 0 && this._ownerDisposalDepth === 0 && !this._reactivity._isFlushingEffects() && this._workGraph.clearTransientCauses();
642
1247
  }
643
1248
  _requestExecution() {
644
- var t;
645
- this.configuration.scheduler !== d.Sync || this._mutationDepth !== 0 || this._transactionDepth !== 0 || this._kernelTransactionDepth !== 0 || this._reactivity._isFlushingEffects() || this._executionRequested && (this._executionRequested = !1, (t = this._phases) == null || t.flush());
1249
+ this._disposed || this.configuration.scheduler !== f.Sync || this._mutationDepth !== 0 || this._batchDepth !== 0 || this._kernelBatchDepth !== 0 || this._ownerDisposalDepth !== 0 || this._reactivity._isFlushingEffects() || this._executionRequested && (this._executionRequested = !1, this._phases?.flush());
646
1250
  }
647
- /**
648
- * Открывает shared Kernel transaction для runtime.
649
- * @internal
650
- */
651
- _beginKernelTransaction() {
652
- this._disposed || this._kernelTransactionDepth++;
1251
+ _assertTrackedRead() {
1252
+ this._assertAlive();
1253
+ const e = this._reactivity.getActiveOwner();
1254
+ e !== void 0 && e !== this && this._throwCrossRuntime(e);
1255
+ const t = this._reactivity.getActiveConsumerOwner();
1256
+ t !== void 0 && this._assertImplicitDependency(this.rootScope, t);
653
1257
  }
654
1258
  /**
655
- * Закрывает shared Kernel transaction и запускает отложенное выполнение.
1259
+ * Проверяет tracked read из optional owned source.
1260
+ *
656
1261
  * @internal
657
1262
  */
658
- _endKernelTransaction() {
659
- this._kernelTransactionDepth !== 0 && (this._kernelTransactionDepth--, this._disposed || this._requestExecution());
660
- }
661
- _assertTrackedRead() {
1263
+ _assertSourceReadable(e) {
662
1264
  this._assertAlive();
663
1265
  const t = this._reactivity.getActiveOwner();
664
1266
  t !== void 0 && t !== this && this._throwCrossRuntime(t);
1267
+ const s = this._reactivity.getActiveConsumerOwner();
1268
+ s !== void 0 && this._assertImplicitDependency(e, s), e._assertAlive();
1269
+ }
1270
+ _assertImplicitDependency(e, t) {
1271
+ if (e.runtime !== this || t.runtime !== this)
1272
+ throw new b("[Raph] Implicit dependency crosses runtime boundaries.");
1273
+ if (!(e === this.rootScope || e === t)) {
1274
+ if (e instanceof v && t instanceof v) {
1275
+ for (let s = t.parent; s !== null; s = s.parent)
1276
+ if (s === e)
1277
+ return;
1278
+ }
1279
+ throw new Error(
1280
+ `[Raph] Implicit dependency from "${t.id}" to "${e.id}" is not allowed; use watch().`
1281
+ );
1282
+ }
665
1283
  }
666
1284
  _assertWriteAllowed() {
667
- if (this._assertAlive(), this.configuration.enforceActions && this._actionDepth === 0 && this._transactionDepth === 0)
668
- throw new T(
669
- "[Raph] Writes are allowed only inside action() or transaction()."
670
- );
1285
+ if (this._assertAlive(), this.configuration.enforceActions && this._batchDepth === 0)
1286
+ throw new F("[Raph] Writes are allowed only inside action() or batch().");
671
1287
  }
672
- _throwCrossRuntime(t) {
673
- throw new k(
674
- `[Raph] Runtime "${this.id}" cannot be tracked by runtime "${t.id}".`
1288
+ _throwCrossRuntime(e) {
1289
+ throw new b(
1290
+ `[Raph] Runtime "${this.id}" cannot be tracked by runtime "${e.id}".`
675
1291
  );
676
1292
  }
677
- _throwDisposed() {
678
- throw new R(`[Raph] Runtime "${this.id}" is disposed.`);
679
- }
680
1293
  _assertAlive() {
681
- this._disposed && this._throwDisposed();
1294
+ if (this._disposed)
1295
+ throw new A(`[Raph] Runtime "${this.id}" is disposed.`);
682
1296
  }
683
- };
684
- // Формирует локальный id для runtime без явно заданного имени.
685
- h(v, "_runtimeCounter", 0);
686
- let P = v;
687
- function z(a) {
688
- return typeof a == "string" || a instanceof A || E(a) ? !0 : Array.isArray(a) && a.every(
689
- (t) => typeof t == "string" || t instanceof A || E(t)
690
- );
691
1297
  }
692
- function E(a) {
693
- return typeof a == "object" && a !== null && "segs" in a && a.segs !== void 0 && Array.isArray(a.segs);
1298
+ function te(p) {
1299
+ let e = p;
1300
+ return () => {
1301
+ const t = e;
1302
+ t !== void 0 && (e = void 0, t.dispose());
1303
+ };
1304
+ }
1305
+ function se(p) {
1306
+ return () => {
1307
+ p.record?.dispose();
1308
+ };
1309
+ }
1310
+ function re() {
1311
+ }
1312
+ function ie(p, e) {
1313
+ return e._order - p._order;
1314
+ }
1315
+ function oe(p) {
1316
+ return p === f.Sync || p === f.Microtask || p === f.AnimationFrame;
1317
+ }
1318
+ function ae(p, e) {
1319
+ const t = Array.isArray(p) ? p : [p];
1320
+ if (t.length === 0)
1321
+ throw new TypeError("[RaphMeta] watch requires at least one mask.");
1322
+ if (e.namespace !== void 0 && !e.namespace.trim())
1323
+ throw new Error("[RaphMeta] namespace must not be empty.");
1324
+ for (const s of t)
1325
+ B.from(s, e)._asMask();
694
1326
  }
695
- function I(a) {
696
- return a === d.Sync || a === d.Microtask || a === d.AnimationFrame;
1327
+ function x(p) {
1328
+ return p instanceof Error ? p.message : String(p);
697
1329
  }
698
1330
  export {
699
- P as RaphRuntime
1331
+ T as RaphRuntime
700
1332
  };