@raphy-js/raph 1.0.1-dev.20 → 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 (107) hide show
  1. package/dist/{core-CyilRD7s.js → core-CClhT8WR.js} +389 -400
  2. package/dist/core-cPQWYD4K.cjs +1 -0
  3. package/dist/debug/api/Raph.cjs +1 -1
  4. package/dist/debug/api/Raph.js +46 -47
  5. package/dist/debug/api/RaphFacadeSession.cjs +1 -1
  6. package/dist/debug/api/RaphFacadeSession.js +85 -89
  7. package/dist/debug/api/RaphReactivityInstance.cjs +1 -1
  8. package/dist/debug/api/RaphReactivityInstance.js +27 -30
  9. package/dist/debug/path/DataPath.cjs +1 -1
  10. package/dist/debug/path/DataPath.js +198 -202
  11. package/dist/debug/path/PathRouter.cjs +1 -1
  12. package/dist/debug/path/PathRouter.js +44 -50
  13. package/dist/debug/path/RaphKernel.cjs +1 -1
  14. package/dist/debug/path/RaphKernel.js +257 -228
  15. package/dist/debug/path/data-path.utils.cjs +1 -1
  16. package/dist/debug/path/data-path.utils.js +41 -41
  17. package/dist/debug/path/derived/DerivedRegistry.cjs +1 -1
  18. package/dist/debug/path/derived/DerivedRegistry.js +52 -66
  19. package/dist/debug/path/derived/RaphDerivedHandle.cjs +1 -1
  20. package/dist/debug/path/derived/RaphDerivedHandle.js +19 -22
  21. package/dist/debug/path/derived/derived-collection.utils.cjs +1 -1
  22. package/dist/debug/path/derived/derived-collection.utils.js +70 -70
  23. package/dist/debug/path/meta/MetaController.cjs +1 -1
  24. package/dist/debug/path/meta/MetaController.js +57 -65
  25. package/dist/debug/path/meta/RaphMeta.cjs +1 -1
  26. package/dist/debug/path/meta/RaphMeta.js +26 -32
  27. package/dist/debug/path/meta/RaphMetaStore.cjs +1 -1
  28. package/dist/debug/path/meta/RaphMetaStore.js +24 -30
  29. package/dist/debug/path/storage/AdapterPathStore.cjs +1 -1
  30. package/dist/debug/path/storage/AdapterPathStore.js +49 -54
  31. package/dist/debug/path/storage/DefaultDataAdapter.cjs +1 -1
  32. package/dist/debug/path/storage/DefaultDataAdapter.js +46 -56
  33. package/dist/debug/path/storage/PathEventHub.cjs +1 -1
  34. package/dist/debug/path/storage/PathEventHub.js +74 -61
  35. package/dist/debug/path/storage/PathStore.cjs +1 -1
  36. package/dist/debug/path/storage/PathStore.js +89 -99
  37. package/dist/debug/path/storage/createDataDraft.cjs +1 -1
  38. package/dist/debug/path/storage/createDataDraft.js +24 -28
  39. package/dist/debug/reactivity/disposal.cjs +1 -0
  40. package/dist/debug/reactivity/disposal.js +32 -0
  41. package/dist/debug/reactivity/engine.cjs +1 -1
  42. package/dist/debug/reactivity/engine.js +787 -392
  43. package/dist/debug/reactivity/reactive-object.cjs +1 -1
  44. package/dist/debug/reactivity/reactive-object.js +81 -96
  45. package/dist/debug/reactivity/scope.cjs +1 -1
  46. package/dist/debug/reactivity/scope.js +221 -117
  47. package/dist/debug/reactivity/watch.cjs +1 -1
  48. package/dist/debug/reactivity/watch.js +1 -1
  49. package/dist/debug/runtime/RaphRuntime.cjs +1 -1
  50. package/dist/debug/runtime/RaphRuntime.js +764 -411
  51. package/dist/debug/runtime/diagnostics/RaphDebug.cjs +1 -1
  52. package/dist/debug/runtime/diagnostics/RaphDebug.js +90 -100
  53. package/dist/debug/runtime/ownership/RaphEffectScope.cjs +1 -1
  54. package/dist/debug/runtime/ownership/RaphEffectScope.js +215 -82
  55. package/dist/debug/runtime/ownership/RaphNode.cjs +1 -1
  56. package/dist/debug/runtime/ownership/RaphNode.js +595 -136
  57. package/dist/debug/runtime/ownership/RaphScope.cjs +1 -1
  58. package/dist/debug/runtime/ownership/RaphScope.js +203 -68
  59. package/dist/debug/runtime/phases/RaphFrameLoop.cjs +1 -1
  60. package/dist/debug/runtime/phases/RaphFrameLoop.js +13 -17
  61. package/dist/debug/runtime/phases/RaphPhasePipeline.cjs +1 -1
  62. package/dist/debug/runtime/phases/RaphPhasePipeline.js +618 -357
  63. package/dist/debug/runtime/phases/RaphPhaseTaskRecord.cjs +1 -0
  64. package/dist/debug/runtime/phases/RaphPhaseTaskRecord.js +176 -0
  65. package/dist/debug/runtime/phases/RaphPhaseWatch.cjs +1 -0
  66. package/dist/debug/runtime/phases/RaphPhaseWatch.js +20 -0
  67. package/dist/debug/runtime/reactivity/PathHandle.cjs +1 -1
  68. package/dist/debug/runtime/reactivity/PathHandle.js +50 -60
  69. package/dist/debug/runtime/reactivity/RaphMetaSource.cjs +1 -1
  70. package/dist/debug/runtime/reactivity/RaphMetaSource.js +28 -32
  71. package/dist/debug/runtime/reactivity/RaphSelector.cjs +1 -0
  72. package/dist/debug/runtime/reactivity/RaphSelector.js +503 -0
  73. package/dist/debug/runtime/reactivity/RaphWorkGraph.cjs +1 -1
  74. package/dist/debug/runtime/reactivity/RaphWorkGraph.js +541 -379
  75. package/dist/debug/runtime/reactivity/RuntimeReactivity.cjs +1 -1
  76. package/dist/debug/runtime/reactivity/RuntimeReactivity.js +484 -90
  77. package/dist/debug/runtime/reactivity/RuntimeWatch.cjs +1 -1
  78. package/dist/debug/runtime/reactivity/RuntimeWatch.js +33 -44
  79. package/dist/debug/runtime/reactivity/disposal-sweep.utils.cjs +1 -0
  80. package/dist/debug/runtime/reactivity/disposal-sweep.utils.js +42 -0
  81. package/dist/entrypoints/runtime.d.ts +2 -1
  82. package/dist/machine-testing.cjs +1 -1
  83. package/dist/machine-testing.js +1 -1
  84. package/dist/machine.cjs +1 -1
  85. package/dist/machine.js +216 -231
  86. package/dist/path/RaphKernel.d.ts +24 -0
  87. package/dist/path/storage/PathEventHub.d.ts +14 -0
  88. package/dist/path/storage/PathStore.d.ts +4 -4
  89. package/dist/reactivity/disposal.d.ts +14 -0
  90. package/dist/reactivity/engine.d.ts +177 -4
  91. package/dist/reactivity/scope.d.ts +108 -30
  92. package/dist/runtime/RaphRuntime.d.ts +236 -17
  93. package/dist/runtime/ownership/RaphEffectScope.d.ts +70 -1
  94. package/dist/runtime/ownership/RaphNode.d.ts +276 -6
  95. package/dist/runtime/ownership/RaphScope.d.ts +144 -14
  96. package/dist/runtime/phases/RaphPhasePipeline.d.ts +202 -28
  97. package/dist/runtime/phases/RaphPhaseTaskRecord.d.ts +195 -0
  98. package/dist/runtime/phases/RaphPhaseWatch.d.ts +22 -0
  99. package/dist/runtime/phases/phase.types.d.ts +83 -4
  100. package/dist/runtime/reactivity/RaphSelector.d.ts +338 -0
  101. package/dist/runtime/reactivity/RaphWorkGraph.d.ts +163 -25
  102. package/dist/runtime/reactivity/RuntimeReactivity.d.ts +258 -10
  103. package/dist/runtime/reactivity/RuntimeWatch.d.ts +8 -8
  104. package/dist/runtime/reactivity/disposal-sweep.utils.d.ts +19 -0
  105. package/dist/runtime/reactivity/runtime-reactivity.types.d.ts +48 -3
  106. package/package.json +9 -1
  107. package/dist/core-ugchZNqC.cjs +0 -1
@@ -1,112 +1,120 @@
1
- var E = Object.defineProperty;
2
- var T = (p, e, t) => e in p ? E(p, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : p[e] = t;
3
- var u = (p, e, t) => T(p, typeof e != "symbol" ? e + "" : e, t);
4
- import { parseDataPath as P } from "../path/data-path.utils.js";
5
- import { DataPath as x } from "../path/DataPath.js";
1
+ import { parseDataPath as N } from "../path/data-path.utils.js";
2
+ import { DataPath as B } from "../path/DataPath.js";
6
3
  import { RaphMeta as W } from "../path/meta/RaphMeta.js";
7
4
  import { RaphKernel as G } from "../path/RaphKernel.js";
8
- import { configureReactiveObjectPolicy as O, disposeReactiveObjectContext as L } from "../reactivity/reactive-object.js";
9
- import { RaphDebugController as M, createOwnerSnapshot as b, createOwnerTree as R } from "./diagnostics/RaphDebug.js";
10
- import { RaphDisposedError as A, RaphCrossRuntimeError as k, RaphActionError as B } from "./errors.js";
11
- import { parentGraph as F } from "./ownership/parentGraph.js";
12
- import { RaphNode as g, createProvisionalNode as q } from "./ownership/RaphNode.js";
13
- import { RaphScope as D } from "./ownership/RaphScope.js";
14
- import { throwDisposalErrors as y } from "./ownership/throwDisposalErrors.js";
15
- import { RaphSchedulerType as w } from "./phases/phase.types.js";
16
- import { RaphFrameLoop as I } from "./phases/RaphFrameLoop.js";
17
- import { RaphPhasePipeline as H } from "./phases/RaphPhasePipeline.js";
18
- import { PathHandle as z } from "./reactivity/PathHandle.js";
19
- import { RaphMetaSource as N } from "./reactivity/RaphMetaSource.js";
20
- import { RaphWorkGraph as $ } from "./reactivity/RaphWorkGraph.js";
21
- import { RuntimeReactivity as j } from "./reactivity/RuntimeReactivity.js";
22
- import { RuntimeWatch as U } from "./reactivity/RuntimeWatch.js";
23
- const v = class v {
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();
24
73
  constructor(e = {}) {
25
- u(this, "mode", "runtime");
26
- u(this, "configuration");
27
- u(this, "rootScope");
28
- u(this, "root");
29
- u(this, "frameTick");
30
- u(this, "_reactivity");
31
- u(this, "_signalLifecycle");
32
- u(this, "_workGraph");
33
- u(this, "_frameTickWritable");
34
- u(this, "_setFrameTick");
35
- u(this, "_pathHandles");
36
- u(this, "_meta");
37
- u(this, "_phases");
38
- u(this, "_frameLoop");
39
- u(this, "_debug");
40
- u(this, "_debugController");
41
- u(this, "_parentGraph");
42
- u(this, "_owners", /* @__PURE__ */ new Set());
43
- u(this, "_batchDepth", 0);
44
- u(this, "_mutationDepth", 0);
45
- u(this, "_kernelBatchDepth", 0);
46
- u(this, "_ownerDisposalDepth", 0);
47
- u(this, "_actionDepth", 0);
48
- u(this, "_actionCounter", 0);
49
- u(this, "_traceCauseStack", []);
50
- u(this, "_phaseTraceOperations");
51
- u(this, "_executionRequested", !1);
52
- u(this, "_disposed", !1);
53
- u(this, "_disposedListeners", /* @__PURE__ */ new Set());
54
- const t = e.id ?? `runtime-${v._runtimeCounter++}`, r = e.adaptiveDependencyIndex ?? !1, s = e.enforceActions ?? !1, i = e.scheduler ?? w.Sync;
55
- if (!K(i))
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))
56
76
  throw new Error(`[Raph] Unsupported scheduler "${String(i)}".`);
57
77
  const o = e.kernel ?? new G({ id: `${t}-kernel` });
58
78
  this.configuration = Object.freeze({
59
- adaptiveDependencyIndex: r,
79
+ adaptiveDependencyIndex: s,
60
80
  ...e.debug === void 0 ? {} : { debug: e.debug },
61
81
  id: t,
62
82
  kernel: o,
63
- enforceActions: s,
83
+ enforceActions: r,
64
84
  scheduler: i
65
85
  }), this._debugController = new M(e.debug);
66
- const c = `[Raph] Runtime "${t}" is disposed.`;
86
+ const a = `[Raph] Runtime "${t}" is disposed.`;
67
87
  this._signalLifecycle = {
68
88
  owner: this,
69
- runWrite: (d) => this._runWrite(d),
70
- assertDependencyAllowed: (d, l) => {
71
- this._assertImplicitDependency(d, l);
89
+ assertDependencyAllowed: (h, u) => {
90
+ this._assertImplicitDependency(h, u);
72
91
  },
73
- ...s ? { assertWriteAllowed: () => this._assertWriteAllowed() } : {},
92
+ ...r ? { assertWriteAllowed: () => this._assertWriteAllowed() } : {},
74
93
  throwDisposed: () => {
75
- throw new A(c);
94
+ throw new A(a);
76
95
  },
77
- throwCrossRuntime: (d) => this._throwCrossRuntime(d)
78
- }, this._reactivity = new j(this._signalLifecycle, { adaptiveDependencyIndex: r }), this._workGraph = new $(this), o._attachRuntime(this), this.rootScope = new D(`${t}:root-scope`, this), this.root = new g(null, { id: `${t}:root` }, this), O(this._reactivity, {
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, {
79
98
  owner: this,
80
99
  assertRead: () => {
81
100
  this._assertAlive();
82
- const d = this._reactivity.getActiveOwner();
83
- d !== void 0 && d !== this && this._throwCrossRuntime(d);
84
- const l = this._reactivity.getActiveConsumerOwner();
85
- l !== void 0 && this._assertImplicitDependency(this.rootScope, l);
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);
86
105
  },
87
106
  assertWrite: () => this._assertWriteAllowed(),
88
- runWrite: (d) => this._runWrite(d),
89
- throwForeign: (d) => {
90
- throw d instanceof v && this._throwCrossRuntime(d), new k(
107
+ runWrite: (h) => this._runWrite(h),
108
+ throwForeign: (h) => {
109
+ throw h instanceof T && this._throwCrossRuntime(h), new b(
91
110
  "[Raph] Reactive object belongs to another reactivity engine."
92
111
  );
93
112
  }
94
113
  });
95
- const n = this._workGraph.createProducer(this.rootScope, "frame", {
96
- includeRuntime: !1
97
- });
98
- let a;
99
- const h = this._reactivity.signalForOwner(
100
- 0,
101
- this.rootScope,
102
- this._workGraph.producerHooks(n),
103
- (d) => {
104
- a = d;
105
- }
106
- );
107
- this._setFrameTick = (d) => this._runWrite(() => a(d)), this._frameTickWritable = h, this.frameTick = this._workGraph.attachProducer(n, {
108
- get: h.get,
109
- peek: h.peek
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()
110
118
  });
111
119
  }
112
120
  /** @internal */
@@ -131,19 +139,16 @@ const v = class v {
131
139
  return this._disposed;
132
140
  }
133
141
  get graph() {
134
- return this._parentGraph ?? (this._parentGraph = F());
142
+ return this._parentGraph ??= $();
135
143
  }
136
144
  get loopEnabled() {
137
- var e;
138
- return ((e = this._frameLoop) == null ? void 0 : e.running) ?? !1;
145
+ return this._frameLoop?.running ?? !1;
139
146
  }
140
147
  get frame() {
141
- var e;
142
- return ((e = this._phases) == null ? void 0 : e.frame) ?? { now: 0, delta: 0, elapsed: 0, frame: 0 };
148
+ return this._phases?.frame ?? { now: 0, delta: 0, elapsed: 0, frame: 0 };
143
149
  }
144
150
  get phases() {
145
- var e;
146
- return ((e = this._phases) == null ? void 0 : e.phases) ?? [];
151
+ return this._phases?.phases ?? [];
147
152
  }
148
153
  /** Runtime metadata facade intentionally excludes unphased watch(). */
149
154
  get meta() {
@@ -152,7 +157,7 @@ const v = class v {
152
157
  const e = new W(this.kernel, {
153
158
  assertReadable: () => this._assertAlive(),
154
159
  assertWritable: () => this._assertWriteAllowed(),
155
- runWrite: (t, r) => this._runWrite(t, r)
160
+ runWrite: (t, s) => this._runWrite(t, s)
156
161
  });
157
162
  return this._meta = Object.freeze({
158
163
  delete: e.delete.bind(e),
@@ -166,22 +171,16 @@ const v = class v {
166
171
  return this.kernel.getDerivedSnapshot();
167
172
  }
168
173
  get debug() {
169
- return this._debug ?? (this._debug = Object.freeze({
174
+ return this._debug ??= Object.freeze({
170
175
  snapshot: () => this._createDebugSnapshot(),
171
176
  getTree: () => this._createDebugTree(),
172
177
  stats: () => this._createDebugStats(),
173
178
  trace: this._debugController.trace,
174
179
  machines: this._debugController.machines
175
- }));
180
+ });
176
181
  }
177
182
  signal(e, t = this.rootScope) {
178
- this._assertOwnerRuntime(t);
179
- const r = this._workGraph.createProducer(t), s = this._reactivity.signalForOwner(
180
- e,
181
- t,
182
- this._workGraph.producerHooks(r)
183
- );
184
- return this._workGraph.attachProducer(r, s);
183
+ return this._assertOwnerRuntime(t), this._reactivity.signalForOwner(e, t);
185
184
  }
186
185
  /**
187
186
  * Creates a deep reactive Proxy owned by this Runtime root scope.
@@ -193,161 +192,214 @@ const v = class v {
193
192
  }
194
193
  computed(e, t = this.rootScope) {
195
194
  this._assertOwnerRuntime(t);
196
- const r = this._workGraph.createProducer(t), s = typeof e == "function" ? e : e.get, i = this._reactivity.computedForOwner(
197
- () => this._runTracked(t, s),
195
+ const s = this._workGraph.createProducer(t), r = typeof e == "function" ? e : e.get, i = this._reactivity.computedForOwner(
196
+ () => this._runTracked(t, r),
198
197
  t,
199
- this._workGraph.producerHooks(r)
198
+ this._workGraph.producerHooks(s)
200
199
  );
201
- if (this._workGraph.setProducerActivation(r, () => {
200
+ if (this._workGraph.setProducerActivation(s, () => {
202
201
  i.peek();
203
202
  }), typeof e == "function")
204
- return this._workGraph.attachProducer(r, i);
203
+ return this._workGraph.attachProducer(s, i);
205
204
  const o = this._attachWritableComputed(i, e.set, t);
206
- return this._workGraph.attachProducer(r, o);
205
+ return this._workGraph.attachProducer(s, o);
207
206
  }
208
207
  /** Low-level adapter form. Prefer consumer.effect(). */
209
- effect(e, t, r, s = {}) {
210
- return this._effectRegistration(e, t, r, s).dispose;
208
+ effect(e, t, s, r = y) {
209
+ return te(
210
+ this._effectRegistration(e, t, s, r)
211
+ );
211
212
  }
212
- /** @internal */
213
- _effectRegistration(e, t, r, s = {}, i = !1) {
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) {
214
228
  this._assertOwnerRuntime(e);
215
- const o = this._validatePhaseBinding(t, r, s), c = this._execution, n = s.initial ?? "scheduled";
216
- let a, h, d = !1;
217
- const l = this._reactivity.withEffectBinding(
218
- (f) => {
219
- const _ = c.bindTask(
220
- o,
221
- e,
222
- r,
223
- s.priority ?? 0,
224
- f
225
- );
226
- return i && _.pause(), a = _;
227
- },
228
- () => this._reactivity.effect(
229
- () => this._runTracked(e, () => {
230
- const f = r(a.task);
231
- return typeof f == "function" ? () => this._runUntracked(f) : f;
232
- }),
233
- () => {
234
- h === void 0 ? d = !0 : h();
235
- }
236
- )
237
- );
238
- h = this._own(l, e), d && h(), a.abort = () => h == null ? void 0 : h();
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
245
+ );
246
+ }
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);
239
271
  try {
240
- n === "sync" ? this.flush() : this._requestExecution();
241
- } catch (f) {
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;
281
+ }
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;
242
318
  try {
243
- h();
319
+ this._reactivity._disposeTaskEffect(o);
244
320
  } catch (_) {
245
- throw new AggregateError(
246
- [f, _],
321
+ d = new AggregateError(
322
+ [c, _],
247
323
  "[Raph] Phase effect registration and rollback failed."
248
324
  );
249
325
  }
250
- throw f;
326
+ throw u && r !== void 0 && r(d), d;
251
327
  }
252
- return {
253
- dispose: () => h == null ? void 0 : h(),
254
- pause: () => a == null ? void 0 : a.pause(),
255
- resume: () => a == null ? void 0 : a.resume()
256
- };
257
328
  }
258
329
  /** Low-level adapter form. Prefer consumer.watch(). */
259
- watch(e, t, r, s, i = {}) {
260
- return this._watchRegistration(e, t, r, s, i).dispose;
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);
261
333
  }
262
- /** @internal */
263
- _watchRegistration(e, t, r, s, i = {}, o = !1) {
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) {
264
341
  this._assertOwnerRuntime(e);
265
- const c = this._validatePhaseBinding(r, s, i, !0);
342
+ const h = this._execution, u = this._validatePhaseBinding(h, s, r, i, !0);
266
343
  this._workGraph.assertSubscriptionAllowed(e, t);
267
- let n;
268
- const a = new U(
269
- (_) => this._runUntracked(_),
270
- () => s(n.task)
271
- );
272
- n = this._execution.bindTask(
273
- c,
274
- e,
275
- s,
276
- i.priority ?? 0,
277
- a.deliver
278
- ), o && n.pause();
279
- let h;
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();
280
346
  try {
281
- h = this._workGraph.subscribe(
347
+ if (d.source = this._workGraph.subscribe(
282
348
  t,
283
349
  i.include,
284
- n.enqueue
285
- );
286
- } catch (_) {
287
- throw n.dispose(), _;
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;
288
355
  }
289
- const d = () => a.stop(() => {
290
- const _ = [];
291
- try {
292
- h();
293
- } catch (m) {
294
- _.push(m);
295
- }
296
- try {
297
- n.dispose();
298
- } catch (m) {
299
- _.push(m);
300
- }
301
- y(_, "[Raph] Phase watch disposal failed.");
302
- }), l = this._own(d, e), f = i.initial ?? "scheduled";
303
356
  try {
304
- f !== "none" && n.schedule(), f === "sync" && this.flush();
305
- } catch (_) {
306
- try {
307
- l();
308
- } catch (m) {
309
- throw new AggregateError(
310
- [_, m],
311
- "[Raph] Phase watch registration and rollback failed."
312
- );
313
- }
314
- throw _;
357
+ e._adoptRecord(c);
358
+ } catch (l) {
359
+ this._rollbackRegistration(c, l, "[Raph] Resource registration and cleanup failed.");
315
360
  }
316
- return {
317
- dispose: l,
318
- pause: n.pause,
319
- resume: n.resume
320
- };
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;
321
373
  }
322
374
  aggregate(e, t) {
323
375
  return this._assertOwnerRuntime(e), this._workGraph.createAggregate(e, t);
324
376
  }
325
377
  /** Creates a lazy root-owned metadata event source for phase watches. */
326
378
  metaSource(e, t = {}) {
327
- this._assertAlive(), J(e, t);
328
- const r = this._workGraph.createProducer(this.rootScope, "path"), s = this._workGraph.producerHooks(r).onDispose, i = N._create(
379
+ this._assertAlive(), ae(e, t);
380
+ const s = this._workGraph.createProducer(this.rootScope, "path"), r = this._workGraph.producerHooks(s).onDispose, i = J._create(
329
381
  this.rootScope,
330
382
  e,
331
383
  t,
332
384
  () => this.kernel._watchMeta(
333
385
  i.masks,
334
- ({ events: o }) => this._workGraph.notifyProducerEvents(r, o, !1),
386
+ ({ events: o }) => this._workGraph.notifyProducerEvents(s, o, !1),
335
387
  i.options,
336
388
  (o) => {
337
389
  o && this._execution.request();
338
390
  }
339
391
  ),
340
- () => s(!1)
392
+ () => r(!1)
341
393
  );
342
394
  i._bindOwner(this.rootScope._adoptResource(() => i._disposeOwned()));
343
395
  try {
344
- return this._workGraph.setProducerActivation(r, () => i._activate(), !0), this._workGraph.attachProducer(r, i), i;
396
+ return this._workGraph.setProducerActivation(s, () => i._activate(), !0), this._workGraph.attachProducer(s, i), i;
345
397
  } catch (o) {
346
398
  try {
347
399
  i.dispose();
348
- } catch (c) {
400
+ } catch (a) {
349
401
  throw new AggregateError(
350
- [o, c],
402
+ [o, a],
351
403
  "[Raph] Meta source activation and rollback failed."
352
404
  );
353
405
  }
@@ -356,41 +408,41 @@ const v = class v {
356
408
  }
357
409
  path(e, t = {}) {
358
410
  this._assertAlive();
359
- const r = P(e, t), s = this._pathHandles ?? (this._pathHandles = /* @__PURE__ */ new Map()), i = s.get(r.canonical);
411
+ const s = N(e, t), r = this._pathHandles ??= /* @__PURE__ */ new Map(), i = r.get(s.canonical);
360
412
  if (i !== void 0)
361
413
  return i;
362
- const o = this._workGraph.createProducer(this.rootScope, "path"), c = this._workGraph.producerHooks(o), n = new z(
414
+ const o = this._workGraph.createProducer(this.rootScope, "path"), a = this._workGraph.producerHooks(o), n = new X(
363
415
  this.kernel,
364
- r,
416
+ s,
365
417
  t,
366
- (a) => this._releasePathHandle(a),
418
+ (h) => this._releasePathHandle(h),
367
419
  this._reactivity,
368
420
  () => this._assertAlive(),
369
421
  () => this._assertTrackedRead(),
370
422
  this.configuration.enforceActions ? () => this._assertWriteAllowed() : void 0,
371
- (a) => this._runWrite(a),
372
- { token: o, onDispose: c.onDispose },
373
- ({ events: a }, h) => this._workGraph.notifyProducerEvents(o, a, !0, h)
423
+ (h) => this._runWrite(h),
424
+ { token: o, onDispose: a.onDispose },
425
+ ({ events: h }, u) => this._workGraph.notifyProducerEvents(o, h, !0, u)
374
426
  );
375
427
  try {
376
- return this._workGraph.setProducerActivation(o, () => n._activate(), !0), this._workGraph.attachProducer(o, n), s.set(r.canonical, n), n;
377
- } catch (a) {
378
- let h, d = !1;
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;
379
431
  try {
380
432
  n.dispose();
381
- } catch (l) {
382
- d = !0, h = l;
433
+ } catch (d) {
434
+ c = !0, u = d;
383
435
  }
384
- throw s.size === 0 && this._pathHandles === s && (this._pathHandles = void 0), d ? new AggregateError(
385
- [a, h],
436
+ throw r.size === 0 && this._pathHandles === r && (this._pathHandles = void 0), c ? new AggregateError(
437
+ [h, u],
386
438
  "[Raph] Path source activation and rollback failed."
387
- ) : a;
439
+ ) : h;
388
440
  }
389
441
  }
390
442
  get(e, t) {
391
443
  this._assertTrackedRead();
392
- const r = e ?? "";
393
- return this._reactivity._isTracking() ? this.path(r, t)._getTracked() : this.kernel.get(r, t);
444
+ const s = e ?? "";
445
+ return this._reactivity._isTracking() ? this.path(s, t)._getTracked() : this.kernel.get(s, t);
394
446
  }
395
447
  peek(e, t) {
396
448
  return this._assertAlive(), this.kernel.peek(e ?? "", t);
@@ -398,11 +450,11 @@ const v = class v {
398
450
  has(e, t) {
399
451
  return this._assertAlive(), this.kernel.has(e, t);
400
452
  }
401
- set(e, t, r) {
402
- this._assertWriteAllowed(), this._runWrite(() => this.kernel.set(e, t, r));
453
+ set(e, t, s) {
454
+ this._assertWriteAllowed(), this._runWrite(() => this.kernel.set(e, t, s));
403
455
  }
404
- merge(e, t, r) {
405
- this._assertWriteAllowed(), this._runWrite(() => this.kernel.merge(e, t, r));
456
+ merge(e, t, s) {
457
+ this._assertWriteAllowed(), this._runWrite(() => this.kernel.merge(e, t, s));
406
458
  }
407
459
  delete(e, t) {
408
460
  this._assertWriteAllowed(), this._runWrite(() => this.kernel.delete(e, t));
@@ -416,64 +468,109 @@ const v = class v {
416
468
  }
417
469
  _batch(e, t) {
418
470
  this._assertAlive(), this._batchDepth++;
419
- let r, s, i = !1;
471
+ let s, r, i = !1;
420
472
  try {
421
- r = this._reactivity.batch(() => t ? this.kernel.batch(e) : e());
422
- } catch (c) {
423
- i = !0, s = c;
473
+ s = this._reactivity.batch(() => t ? this.kernel.batch(e) : e());
474
+ } catch (o) {
475
+ i = !0, r = o;
424
476
  }
425
- this._batchDepth--;
426
- const o = this._finishExecutionBoundary();
427
- if (i)
428
- throw o.length !== 0 ? new AggregateError(
429
- [s, ...o],
477
+ return this._closeBatch(i, r), s;
478
+ }
479
+ /**
480
+ * Закрывает один уровень batch: внешний уровень очищает transient causes и
481
+ * запускает фазы. Бросает ошибку операции, ошибки закрытия либо все вместе;
482
+ * после успешной операции и закрытия возвращает управление.
483
+ */
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],
430
494
  "[Raph] Batch and scheduled phase execution failed."
431
- ) : s;
432
- return y(o, "[Raph] Batch phase execution failed."), r;
495
+ ) : t;
496
+ s !== void 0 && m(s, "[Raph] Batch phase execution failed.");
497
+ }
498
+ /**
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()`.
505
+ */
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;
514
+ try {
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;
528
+ }
529
+ return this._closeBatch(n, a), o;
433
530
  }
434
- action(e, t, r) {
435
- const s = typeof e == "function" ? e : t, i = typeof e == "function" ? t instanceof D ? t : this.rootScope : r ?? this.rootScope, o = typeof e == "string" ? e : `action#${++this._actionCounter}`;
436
- if (this._assertOwnerRuntime(i), typeof s != "function")
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")
437
534
  throw new TypeError("[Raph] Action operation must be a function.");
438
535
  if (!o.trim())
439
536
  throw new Error("[Raph] Action name must not be empty.");
440
- return (...c) => {
537
+ return (...a) => {
441
538
  i._assertAlive();
442
- const n = this._debugController.nextOperationId("action"), h = this._traceCauseStack.at(-1) ?? n;
443
- this._debugController.record({
444
- ...h === void 0 ? {} : { causeId: h },
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 },
445
542
  kind: "action",
446
543
  name: o,
447
- ...n === void 0 ? {} : { operationId: n },
544
+ ...u === void 0 ? {} : { operationId: u },
448
545
  status: "start"
449
- }), h !== void 0 && this._traceCauseStack.push(h), this._actionDepth++;
546
+ }), d !== void 0 && h.push(d), this._actionDepth++;
450
547
  try {
451
- const d = this.batch(() => this._runUntracked(() => s(...c)));
452
- return this._debugController.record({
453
- ...h === void 0 ? {} : { causeId: h },
548
+ const _ = this._applyBatch(r, a);
549
+ return n.traces("action") && n.record({
550
+ ...d === void 0 ? {} : { causeId: d },
454
551
  kind: "action",
455
552
  name: o,
456
- ...n === void 0 ? {} : { operationId: n },
553
+ ...u === void 0 ? {} : { operationId: u },
457
554
  status: "end"
458
- }), d;
459
- } catch (d) {
555
+ }), _;
556
+ } catch (_) {
460
557
  throw this._debugController.record({
461
- ...h === void 0 ? {} : { causeId: h },
462
- details: { message: C(d) },
558
+ ...d === void 0 ? {} : { causeId: d },
559
+ details: { message: x(_) },
463
560
  kind: "action",
464
561
  name: o,
465
- ...n === void 0 ? {} : { operationId: n },
562
+ ...u === void 0 ? {} : { operationId: u },
466
563
  status: "error"
467
564
  }), this._debugController.record({
468
- ...h === void 0 ? {} : { causeId: h },
469
- details: { message: C(d) },
565
+ ...d === void 0 ? {} : { causeId: d },
566
+ details: { message: x(_) },
470
567
  kind: "error",
471
568
  name: `action:${o}`,
472
- ...n === void 0 ? {} : { operationId: n },
569
+ ...u === void 0 ? {} : { operationId: u },
473
570
  status: "error"
474
- }), d;
571
+ }), _;
475
572
  } finally {
476
- this._actionDepth--, h !== void 0 && this._traceCauseStack.pop();
573
+ this._actionDepth--, d !== void 0 && h.pop();
477
574
  }
478
575
  };
479
576
  }
@@ -481,35 +578,38 @@ const v = class v {
481
578
  return this._assertAlive(), this._runUntracked(e);
482
579
  }
483
580
  scope(e) {
484
- return this._assertAlive(), new D(e, this);
581
+ return this._assertAlive(), new O(e, this);
485
582
  }
486
583
  node(e, t) {
487
- this._assertAlive();
488
- const r = this._runNodeMutation(() => {
489
- const s = e.parent ?? this.root, i = q(s, e, this);
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;
592
+ }
593
+ /**
594
+ * Создаёт provisional node, выполняет setup и публикует результат; при ошибке
595
+ * setup откатывает node до выхода из границы mutation.
596
+ */
597
+ _createCommittedNode(e, t) {
598
+ const s = e.parent ?? this.root, r = H(s, e, this);
599
+ try {
600
+ const i = t?.(r);
601
+ return r._assertAlive(), s._assertAlive(), r._setApi(i), r._publishCreation(), r;
602
+ } catch (i) {
490
603
  try {
491
- const o = t == null ? void 0 : t(i);
492
- return i._assertAlive(), s._assertAlive(), i._setApi(o), i._publishCreation(), i;
604
+ r.dispose();
493
605
  } catch (o) {
494
- try {
495
- i.dispose();
496
- } catch (c) {
497
- throw new AggregateError([o, c], `[Raph] Node "${i.id}" setup and cleanup failed.`);
498
- }
499
- throw o;
606
+ throw new AggregateError([i, o], `[Raph] Node "${r.id}" setup and cleanup failed.`);
500
607
  }
501
- });
502
- return r._assertAlive(), r;
608
+ throw i;
609
+ }
503
610
  }
504
611
  getNode(e) {
505
- this._assertAlive();
506
- const t = [this.root];
507
- for (; t.length !== 0; ) {
508
- const r = t.pop();
509
- if (r.id === e)
510
- return r;
511
- t.push(...r.children);
512
- }
612
+ return this._assertAlive(), this.root._findNode(e);
513
613
  }
514
614
  definePhases(e) {
515
615
  this._execution.definePhases(e);
@@ -518,20 +618,16 @@ const v = class v {
518
618
  this._execution.addPhase(e);
519
619
  }
520
620
  clearPhases() {
521
- var e;
522
- this._assertAlive(), (e = this._phases) == null || e.clearPhases();
621
+ this._assertAlive(), this._phases?.clearPhases();
523
622
  }
524
623
  requestExecution() {
525
- var e;
526
- this._assertAlive(), (e = this._phases) == null || e.request();
624
+ this._assertAlive(), this._phases?.request();
527
625
  }
528
626
  flush() {
529
- var e;
530
- this._assertAlive(), this._executionRequested = !1, (e = this._phases) == null || e.flush();
627
+ this._assertAlive(), this._executionRequested = !1, this._phases?.flush();
531
628
  }
532
629
  afterFlush() {
533
- var e;
534
- return this._assertAlive(), ((e = this._phases) == null ? void 0 : e.afterFlush()) ?? Promise.resolve();
630
+ return this._assertAlive(), this._phases?.afterFlush() ?? Promise.resolve();
535
631
  }
536
632
  acquireLoop(e) {
537
633
  return this._assertAlive(), this._clock.acquire(e);
@@ -540,31 +636,29 @@ const v = class v {
540
636
  this._assertAlive(), this._clock.start();
541
637
  }
542
638
  stopLoop() {
543
- var e;
544
- (e = this._frameLoop) == null || e.stop();
639
+ this._frameLoop?.stop();
545
640
  }
546
641
  derive(e) {
547
642
  this._assertAlive();
548
- const t = e.compute, r = this.kernel.derive({
643
+ const t = e.compute, s = this.kernel.derive({
549
644
  ...e,
550
- compute: (s) => this._runUntracked(() => t(s))
645
+ compute: (r) => this._runUntracked(() => t(r))
551
646
  });
552
- return this._own(() => r.dispose(), this.rootScope), r;
647
+ return this._own(() => s.dispose(), this.rootScope), s;
553
648
  }
554
649
  dispose() {
555
- var c, n;
556
650
  if (this._disposed)
557
651
  return;
558
652
  this._disposed = !0, this._executionRequested = !1, this._signalLifecycle.owner = void 0;
559
- const e = [], t = [...this._owners];
653
+ const e = [];
560
654
  try {
561
- (c = this._frameLoop) == null || c.dispose();
655
+ this._frameLoop?.dispose();
562
656
  } catch (a) {
563
657
  e.push(a);
564
658
  }
565
659
  this._frameLoop = void 0;
566
660
  try {
567
- (n = this._phases) == null || n.dispose();
661
+ this._phases?.dispose();
568
662
  } catch (a) {
569
663
  e.push(a);
570
664
  }
@@ -574,38 +668,39 @@ const v = class v {
574
668
  } catch (a) {
575
669
  e.push(a);
576
670
  }
577
- for (const a of t.reverse())
671
+ const t = this._collectOwners().sort(ie);
672
+ for (const a of t)
578
673
  if (!(a === this.root || a === this.rootScope || a.disposed))
579
674
  try {
580
675
  a.dispose();
581
- } catch (h) {
582
- e.push(h);
676
+ } catch (n) {
677
+ e.push(n);
583
678
  }
584
679
  try {
585
680
  this.rootScope.dispose();
586
681
  } catch (a) {
587
682
  e.push(a);
588
683
  }
589
- const r = `[Raph] Runtime "${this.id}" is disposed.`, s = () => {
590
- throw new A(r);
684
+ const s = `[Raph] Runtime "${this.id}" is disposed.`, r = () => {
685
+ throw new A(s);
591
686
  };
592
687
  try {
593
688
  L(this._reactivity, {
594
- assertRead: s,
595
- assertWrite: s,
596
- throwForeign: s
689
+ assertRead: r,
690
+ assertWrite: r,
691
+ throwForeign: r
597
692
  });
598
693
  } catch (a) {
599
694
  e.push(a);
600
695
  }
601
- this._owners.clear(), this._meta = void 0;
696
+ this._topOwners.clear(), this._ownersReleased = !0, this._meta = void 0;
602
697
  const i = this._pathHandles;
603
698
  if (this._pathHandles = void 0, i !== void 0) {
604
699
  for (const a of i.values())
605
700
  try {
606
701
  a.dispose();
607
- } catch (h) {
608
- e.push(h);
702
+ } catch (n) {
703
+ e.push(n);
609
704
  }
610
705
  i.clear();
611
706
  }
@@ -624,10 +719,10 @@ const v = class v {
624
719
  for (const a of o)
625
720
  try {
626
721
  a();
627
- } catch (h) {
628
- e.push(h);
722
+ } catch (n) {
723
+ e.push(n);
629
724
  }
630
- y(e, `[Raph] Runtime "${this.id}" disposal failed.`);
725
+ m(e, `[Raph] Runtime "${this.id}" disposal failed.`);
631
726
  }
632
727
  /** @internal */
633
728
  _onDisposed(e) {
@@ -637,11 +732,34 @@ const v = class v {
637
732
  });
638
733
  }
639
734
  /** @internal */
640
- _notifyNodeStructure(e, t, r, s) {
735
+ _notifyNodeStructure(e, t, s, r) {
736
+ if (!this._workGraph._hasStructuralDemand(e)) {
737
+ this._touchMutationBoundary();
738
+ return;
739
+ }
641
740
  this._runNodeMutation(() => {
642
- this._workGraph.notifyNode(e, "structure", { structure: t, oldAncestors: r, newAncestors: s });
741
+ this._workGraph.notifyNode(e, "structure", { structure: t, oldAncestors: s, newAncestors: r });
643
742
  });
644
743
  }
744
+ /**
745
+ * Сообщает, может ли structural publication этой node дойти до подписчика;
746
+ * `false` позволяет не строить structure cause и списки ancestors.
747
+ *
748
+ * @internal
749
+ */
750
+ _hasNodeStructureDemand(e) {
751
+ return this._workGraph._hasStructuralDemand(e);
752
+ }
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
+ }
645
763
  /** @internal */
646
764
  _notifyNodeTouch(e, t) {
647
765
  this._runNodeMutation(() => this._workGraph.notifyNode(e, "touch", { metadata: t }));
@@ -658,34 +776,142 @@ const v = class v {
658
776
  _runNodeMutation(e) {
659
777
  return this._runWrite(e);
660
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
+ }
661
791
  /** @internal */
662
792
  _runPhaseTransition(e) {
663
793
  return this._runWrite(e, !1);
664
794
  }
665
- /** @internal */
666
- _beginOwnerDisposal() {
667
- this._ownerDisposalDepth++;
795
+ /**
796
+ * Открывает границу освобождения. `node` передаёт только dispose самой node:
797
+ * Runtime помнит её до парного `_endOwnerDisposal`.
798
+ *
799
+ * @internal
800
+ */
801
+ _beginOwnerDisposal(e) {
802
+ this._disposingNodes[this._ownerDisposalDepth++] = e;
668
803
  }
669
804
  /** @internal */
670
805
  _endOwnerDisposal() {
671
- this._ownerDisposalDepth !== 0 && (this._ownerDisposalDepth--, this._clearTransientCausesIfSettled(), this._disposed || this._requestExecution());
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;
672
868
  }
673
869
  /** @internal */
674
870
  _ownerDisposalActive() {
675
871
  return this._ownerDisposalDepth !== 0;
676
872
  }
677
- /** @internal */
873
+ /**
874
+ * Учитывает нового владельца и возвращает его порядковый номер регистрации.
875
+ * Plain scope сразу входит в набор владельцев вне списков детей; node входит
876
+ * в него сама через `_addTopOwner`, и только если у неё нет parent.
877
+ *
878
+ * @internal
879
+ */
678
880
  _registerOwner(e) {
679
- this._assertAlive(), this._owners.add(e);
881
+ return this._assertAlive(), e._isNode || this._topOwners.add(e), ++this._ownerRegistrations;
680
882
  }
681
- /** @internal */
883
+ /**
884
+ * Снимает владельца с учёта. Plain scope выходит и из набора владельцев вне
885
+ * списков детей; node без parent выходит из него сама через
886
+ * `_removeTopOwner`, а node с parent в нём не состоит.
887
+ *
888
+ * @internal
889
+ */
682
890
  _unregisterOwner(e) {
683
- this._owners.delete(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);
684
910
  }
685
911
  /** @internal */
686
912
  _assertOwnerRuntime(e) {
687
913
  if (this._assertAlive(), e.runtime !== this)
688
- throw new k("[Raph] Owner belongs to another runtime.");
914
+ throw new b("[Raph] Owner belongs to another runtime.");
689
915
  e._assertAlive();
690
916
  }
691
917
  /** @internal */
@@ -747,33 +973,46 @@ const v = class v {
747
973
  this._traceCauseStack.pop();
748
974
  }
749
975
  }
750
- _validatePhaseBinding(e, t, r, s = !1) {
751
- if (typeof t != "function")
976
+ /**
977
+ * Выполняет единственную проверку binding: pipeline доверяет её результату.
978
+ */
979
+ _validatePhaseBinding(e, t, s, r, i = !1) {
980
+ if (typeof s != "function")
752
981
  throw new TypeError("[Raph] Phase callback must be a function.");
753
- const i = e.trim();
754
- this._execution.requirePhase(i);
755
- const o = r.priority ?? 0;
756
- if (!Number.isFinite(o))
982
+ const o = e.resolvePhase(t), a = r.priority ?? 0;
983
+ if (!Number.isFinite(a))
757
984
  throw new TypeError("[Raph] Effect priority must be finite.");
758
- const c = r.initial ?? "scheduled";
759
- if (c !== "scheduled" && c !== "sync" && !(s && c === "none"))
760
- throw new TypeError(`[Raph] Unsupported effect initial mode "${String(c)}".`);
761
- return i;
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;
762
1002
  }
763
1003
  _createDebugSnapshot() {
764
- var r, s, i;
765
- const e = ((r = this._frameLoop) == null ? void 0 : r._debugState()) ?? { running: !1, manual: !1, leases: 0 }, t = [...this._owners].filter((o) => o !== this.rootScope && !(o instanceof g)).map(b);
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);
766
1005
  return Object.freeze({
767
1006
  id: this.id,
768
1007
  disposed: this._disposed,
769
- pending: !this._disposed && (this._executionRequested || (((s = this._phases) == null ? void 0 : s._debugPending()) ?? !1)),
1008
+ pending: !this._disposed && (this._executionRequested || (this._phases?._debugPending() ?? !1)),
770
1009
  batchDepth: this._batchDepth,
771
1010
  kernelBatchDepth: this._kernelBatchDepth,
772
- owners: this._owners.size,
773
- pathHandles: ((i = this._pathHandles) == null ? void 0 : i.size) ?? 0,
774
- rootScope: b(this.rootScope),
1011
+ owners: this._liveOwnerCount(),
1012
+ pathHandles: this._pathHandles?.size ?? 0,
1013
+ rootScope: D(this.rootScope),
775
1014
  scopes: Object.freeze(t),
776
- root: b(this.root),
1015
+ root: D(this.root),
777
1016
  frameLoop: Object.freeze(e),
778
1017
  actionDepth: this._actionDepth,
779
1018
  machines: this._debugController.machineCount,
@@ -782,9 +1021,9 @@ const v = class v {
782
1021
  }
783
1022
  _createDebugTree() {
784
1023
  const e = this._debugController.machineTreeNodesByOwner(), t = [
785
- R(this.rootScope, e),
786
- R(this.root, e),
787
- ...[...this._owners].filter((r) => r !== this.rootScope && r !== this.root && !(r instanceof g)).map((r) => R(r, e))
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))
788
1027
  ];
789
1028
  return Object.freeze({
790
1029
  children: Object.freeze(t),
@@ -794,76 +1033,128 @@ const v = class v {
794
1033
  });
795
1034
  }
796
1035
  _createDebugStats() {
797
- var i, o;
798
- let e = 0, t = 0, r = 0, s = 0;
799
- for (const c of this._owners)
800
- c instanceof g ? e++ : t++, r += c._debugResourceCount(), s += c._debugSourceCount();
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);
1047
+ }
1048
+ }
801
1049
  return Object.freeze({
802
1050
  actors: this._debugController.actorCount,
803
1051
  machines: this._debugController.machineCount,
804
- nodes: e,
805
- owners: this._owners.size,
806
- pathHandles: ((i = this._pathHandles) == null ? void 0 : i.size) ?? 0,
807
- pending: !this._disposed && (this._executionRequested || (((o = this._phases) == null ? void 0 : o._debugPending()) ?? !1)),
808
- resources: r,
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,
809
1058
  scopes: t,
810
- sources: s,
1059
+ sources: s.sources,
811
1060
  traceEvents: this._debugController.traceSize
812
1061
  });
813
1062
  }
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
+ }
814
1091
  _releasePathHandle(e) {
815
1092
  const t = this._pathHandles;
816
- (t == null ? void 0 : t.get(e.path)) === e && (t.delete(e.path), t.size === 0 && (this._pathHandles = void 0));
1093
+ t?.get(e.path) === e && (t.delete(e.path), t.size === 0 && (this._pathHandles = void 0));
817
1094
  }
818
1095
  get _execution() {
819
- return this._assertAlive(), this._phases ?? (this._phases = new H(
1096
+ return this._assertAlive(), this._phases ??= new j(
820
1097
  this.configuration.scheduler,
821
- (e) => this._runUntracked(e),
1098
+ this._reactivity,
822
1099
  (e) => this._workGraph.causeForToken(e),
823
1100
  () => {
824
1101
  const e = this._mutationDepth !== 0 || this._batchDepth !== 0 || this._kernelBatchDepth !== 0 || this._ownerDisposalDepth !== 0 || this._reactivity._isFlushingEffects();
825
- return e && this.configuration.scheduler === w.Sync && (this._executionRequested = !0), e;
1102
+ return e && this.configuration.scheduler === f.Sync && (this._executionRequested = !0), e;
826
1103
  },
827
- (e, t, r) => {
828
- var i, o, c;
829
- let s;
830
- t === "start" ? (s = this._debugController.nextOperationId("phase"), s !== void 0 && (this._phaseTraceOperations ?? (this._phaseTraceOperations = /* @__PURE__ */ new Map())).set(e, s)) : (s = (i = this._phaseTraceOperations) == null ? void 0 : i.get(e), (o = this._phaseTraceOperations) == null || o.delete(e), ((c = this._phaseTraceOperations) == null ? void 0 : c.size) === 0 && (this._phaseTraceOperations = void 0)), this._debugController.record({
831
- ...s === void 0 ? {} : { causeId: s },
832
- ...r === void 0 ? {} : { details: { message: C(r) } },
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) } },
833
1111
  kind: "phase",
834
1112
  name: e,
835
- ...s === void 0 ? {} : { operationId: s },
1113
+ ...r === void 0 ? {} : { operationId: r },
836
1114
  status: t
837
1115
  });
838
1116
  }
839
- ));
1117
+ );
840
1118
  }
841
1119
  get _clock() {
842
- return this._frameLoop ?? (this._frameLoop = new I(() => this._tickFrameLoop()));
1120
+ return this._frameLoop ??= new z(() => this._tickFrameLoop());
843
1121
  }
844
1122
  _tickFrameLoop() {
845
- this._disposed || this._setFrameTick(this._frameTickWritable.peek() + 1);
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();
846
1137
  }
847
- _attachWritableComputed(e, t, r) {
848
- let s = t;
1138
+ _attachWritableComputed(e, t, s) {
1139
+ let r = t;
849
1140
  this._own(() => {
850
- s = void 0;
851
- }, r);
1141
+ r = void 0;
1142
+ }, s);
852
1143
  const i = e;
853
1144
  return i.set = (o) => {
854
- r._assertAlive(), this._assertWriteAllowed(), this._runWrite(() => s(o));
1145
+ s._assertAlive(), this._assertWriteAllowed(), this._runWrite(() => r(o));
855
1146
  }, i;
856
1147
  }
857
1148
  _own(e, t) {
858
1149
  try {
859
1150
  return t._adoptResource(e);
860
- } catch (r) {
1151
+ } catch (s) {
861
1152
  try {
862
1153
  e();
863
- } catch (s) {
864
- throw new AggregateError([r, s], "[Raph] Resource registration and cleanup failed.");
1154
+ } catch (r) {
1155
+ throw new AggregateError([s, r], "[Raph] Resource registration and cleanup failed.");
865
1156
  }
866
- throw r;
1157
+ throw s;
867
1158
  }
868
1159
  }
869
1160
  _runTracked(e, t) {
@@ -873,33 +1164,81 @@ const v = class v {
873
1164
  return this._reactivity.untrackedWithOwner(e);
874
1165
  }
875
1166
  _runWrite(e, t = !0) {
876
- t && this.configuration.scheduler === w.Sync && (this._executionRequested = !0), this._mutationDepth++;
877
- let r, s, i = !1;
1167
+ t && this.configuration.scheduler === f.Sync && (this._executionRequested = !0), this._mutationDepth++;
1168
+ let s, r, i = !1;
878
1169
  try {
879
- r = e();
880
- } catch (c) {
881
- i = !0, s = c;
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;
882
1178
  }
883
- this._mutationDepth--;
884
1179
  const o = this._finishExecutionBoundary();
885
1180
  if (i)
886
- throw o.length !== 0 ? new AggregateError(
887
- [s, ...o],
1181
+ throw o !== void 0 ? new AggregateError(
1182
+ [r, ...o],
888
1183
  "[Raph] Mutation and scheduled phase execution failed."
889
- ) : s;
890
- return y(o, "[Raph] Mutation phase execution failed."), r;
1184
+ ) : r;
1185
+ return o !== void 0 && m(o, "[Raph] Mutation phase execution failed."), s;
1186
+ }
1187
+ /**
1188
+ * Открывает границу записи без closure; повторяет начало `_runWrite`.
1189
+ *
1190
+ * @internal
1191
+ */
1192
+ _enterWrite() {
1193
+ this.configuration.scheduler === f.Sync && (this._executionRequested = !0), this._mutationDepth++;
891
1194
  }
1195
+ /**
1196
+ * Закрывает успешную запись, открытую `_enterWrite`; внешняя граница очищает
1197
+ * transient causes и запускает фазы с теми же ошибками, что и `_runWrite`.
1198
+ *
1199
+ * @internal
1200
+ */
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.");
1206
+ }
1207
+ /**
1208
+ * Закрывает запись после ошибки операции и возвращает ошибку для throw:
1209
+ * исходную либо AggregateError, если упало и закрытие внешней границы.
1210
+ *
1211
+ * @internal
1212
+ */
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
+ );
1221
+ }
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;
1229
+ }
1230
+ /** Закрывает внешнюю границу; массив ошибок создаётся только при первой ошибке. */
892
1231
  _finishExecutionBoundary() {
893
- const e = [];
1232
+ let e;
894
1233
  try {
895
1234
  this._clearTransientCausesIfSettled();
896
1235
  } catch (t) {
897
- e.push(t);
1236
+ e = [t];
898
1237
  }
899
1238
  try {
900
1239
  this._requestExecution();
901
1240
  } catch (t) {
902
- e.push(t);
1241
+ e === void 0 ? e = [t] : e.push(t);
903
1242
  }
904
1243
  return e;
905
1244
  }
@@ -907,8 +1246,7 @@ const v = class v {
907
1246
  this._mutationDepth === 0 && this._batchDepth === 0 && this._kernelBatchDepth === 0 && this._ownerDisposalDepth === 0 && !this._reactivity._isFlushingEffects() && this._workGraph.clearTransientCauses();
908
1247
  }
909
1248
  _requestExecution() {
910
- var e;
911
- this._disposed || this.configuration.scheduler !== w.Sync || this._mutationDepth !== 0 || this._batchDepth !== 0 || this._kernelBatchDepth !== 0 || this._ownerDisposalDepth !== 0 || this._reactivity._isFlushingEffects() || this._executionRequested && (this._executionRequested = !1, (e = this._phases) == null || e.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());
912
1250
  }
913
1251
  _assertTrackedRead() {
914
1252
  this._assertAlive();
@@ -926,16 +1264,16 @@ const v = class v {
926
1264
  this._assertAlive();
927
1265
  const t = this._reactivity.getActiveOwner();
928
1266
  t !== void 0 && t !== this && this._throwCrossRuntime(t);
929
- const r = this._reactivity.getActiveConsumerOwner();
930
- r !== void 0 && this._assertImplicitDependency(e, r), e._assertAlive();
1267
+ const s = this._reactivity.getActiveConsumerOwner();
1268
+ s !== void 0 && this._assertImplicitDependency(e, s), e._assertAlive();
931
1269
  }
932
1270
  _assertImplicitDependency(e, t) {
933
1271
  if (e.runtime !== this || t.runtime !== this)
934
- throw new k("[Raph] Implicit dependency crosses runtime boundaries.");
1272
+ throw new b("[Raph] Implicit dependency crosses runtime boundaries.");
935
1273
  if (!(e === this.rootScope || e === t)) {
936
- if (e instanceof g && t instanceof g) {
937
- for (let r = t.parent; r !== null; r = r.parent)
938
- if (r === e)
1274
+ if (e instanceof v && t instanceof v) {
1275
+ for (let s = t.parent; s !== null; s = s.parent)
1276
+ if (s === e)
939
1277
  return;
940
1278
  }
941
1279
  throw new Error(
@@ -945,10 +1283,10 @@ const v = class v {
945
1283
  }
946
1284
  _assertWriteAllowed() {
947
1285
  if (this._assertAlive(), this.configuration.enforceActions && this._batchDepth === 0)
948
- throw new B("[Raph] Writes are allowed only inside action() or batch().");
1286
+ throw new F("[Raph] Writes are allowed only inside action() or batch().");
949
1287
  }
950
1288
  _throwCrossRuntime(e) {
951
- throw new k(
1289
+ throw new b(
952
1290
  `[Raph] Runtime "${this.id}" cannot be tracked by runtime "${e.id}".`
953
1291
  );
954
1292
  }
@@ -956,24 +1294,39 @@ const v = class v {
956
1294
  if (this._disposed)
957
1295
  throw new A(`[Raph] Runtime "${this.id}" is disposed.`);
958
1296
  }
959
- };
960
- u(v, "_runtimeCounter", 0);
961
- let S = v;
962
- function K(p) {
963
- return p === w.Sync || p === w.Microtask || p === w.AnimationFrame;
964
1297
  }
965
- function J(p, e) {
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) {
966
1319
  const t = Array.isArray(p) ? p : [p];
967
1320
  if (t.length === 0)
968
1321
  throw new TypeError("[RaphMeta] watch requires at least one mask.");
969
1322
  if (e.namespace !== void 0 && !e.namespace.trim())
970
1323
  throw new Error("[RaphMeta] namespace must not be empty.");
971
- for (const r of t)
972
- x.from(r, e)._asMask();
1324
+ for (const s of t)
1325
+ B.from(s, e)._asMask();
973
1326
  }
974
- function C(p) {
1327
+ function x(p) {
975
1328
  return p instanceof Error ? p.message : String(p);
976
1329
  }
977
1330
  export {
978
- S as RaphRuntime
1331
+ T as RaphRuntime
979
1332
  };