@raphy-js/raph 1.0.1-dev.20 → 1.0.1-dev.26

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 +10 -2
  107. package/dist/core-ugchZNqC.cjs +0 -1
@@ -1,31 +1,53 @@
1
- var u = Object.defineProperty;
2
- var h = (t, e, s) => e in t ? u(t, e, { enumerable: !0, configurable: !0, writable: !0, value: s }) : t[e] = s;
3
- var o = (t, e, s) => h(t, typeof e != "symbol" ? e + "" : e, s);
1
+ import { unroutedDisposalFailure as p, throwDisposalFailure as l, combineDisposalFailures as v } from "./disposal.js";
4
2
  class f {
5
3
  /**
6
- * Связывает владельца с реактивным экземпляром без создания нового графа.
7
- * @param reactivity Экземпляр, в котором создаются owned-ресурсы.
4
+ * Создаёт запись уже связанной с владельцем и предыдущей записью списка.
5
+ * Ссылки владельца и предыдущей записи на неё выставляет вызывающий код.
6
+ */
7
+ constructor(e, s, t) {
8
+ this.scopeParent = e, this.scopePrevious = s, this.scopeNext = void 0, this._cleanup = t;
9
+ }
10
+ /**
11
+ * Однократно выполняет cleanup. Запись выходит из списка владельца до вызова,
12
+ * поэтому ошибочный и вложенный stop не оставляют её в списке.
8
13
  */
14
+ dispose() {
15
+ const e = this._cleanup;
16
+ e !== void 0 && (this._cleanup = void 0, this.scopeParent._releaseRecord(this), e());
17
+ }
18
+ }
19
+ let a;
20
+ class u {
21
+ _cleanup;
9
22
  constructor(e) {
10
- /**
11
- * Первый зарегистрированный ресурс; не является ребёнком execution-дерева.
12
- * @internal
13
- */
14
- o(this, "scopeFirstChild");
15
- /**
16
- * Последний ресурс, с которого начинается освобождение владельца.
17
- * @internal
18
- */
19
- o(this, "scopeLastChild");
20
- // Число активных записей owned-ресурсов; финализаторы источников считаются отдельно.
21
- o(this, "_resourceCount", 0);
22
- // Лениво создаваемое множество финализаторов owned-источников.
23
- o(this, "_sourceFinalizers");
24
- // Окончательное состояние владельца; устанавливается до пользовательских cleanup.
25
- o(this, "_disposed", !1);
26
- // Признак выполняющегося освобождения для проверок lifetime и наследников.
27
- o(this, "_disposing", !1);
28
- this.reactivity = e;
23
+ this._cleanup = e;
24
+ }
25
+ dispose() {
26
+ l(a.call(this));
27
+ }
28
+ _disposeWithOutcome() {
29
+ const e = this._cleanup;
30
+ if (e !== void 0)
31
+ return this._cleanup = void 0, this.scopeParent._releaseRecord(this), e();
32
+ }
33
+ }
34
+ const w = u.prototype.dispose;
35
+ a = u.prototype._disposeWithOutcome;
36
+ class C {
37
+ constructor(e, s) {
38
+ this._previousSource = e, this._finalizer = s;
39
+ }
40
+ /**
41
+ * Вызывает финализатор без receiver, как и при хранении самой функции.
42
+ */
43
+ _finalizeSource() {
44
+ const e = this._finalizer;
45
+ return e();
46
+ }
47
+ }
48
+ class g {
49
+ constructor() {
50
+ this.scopeFirstChild = void 0, this.scopeLastChild = void 0, this._resourceCount = 0, this._lastSource = void 0, this._sourceCount = 0, this._disposed = !1, this._disposing = !1;
29
51
  }
30
52
  /**
31
53
  * Показывает, началось ли окончательное освобождение владельца.
@@ -39,6 +61,121 @@ class f {
39
61
  get active() {
40
62
  return !this._disposed && !this._disposing;
41
63
  }
64
+ /**
65
+ * Возвращает число ещё не освобождённых записей ресурсов.
66
+ * @internal
67
+ */
68
+ _debugResourceCount() {
69
+ return this._resourceCount;
70
+ }
71
+ /**
72
+ * Возвращает число зарегистрированных источников; после начала их
73
+ * финализации владелец источников не числит.
74
+ * @internal
75
+ */
76
+ _debugSourceCount() {
77
+ return this._sourceCount;
78
+ }
79
+ /**
80
+ * Возвращает последний зарегистрированный источник: с него по связям
81
+ * `_previousSource` обходится список источников владельца от нового к
82
+ * старому. С началом финализации владелец источников не числит, и метод
83
+ * возвращает undefined. Обход не должен регистрировать и освобождать
84
+ * источники этого владельца.
85
+ * @internal
86
+ */
87
+ _lastOwnedSource() {
88
+ return this._lastSource;
89
+ }
90
+ /**
91
+ * Вынимает запись ресурса из списка владельца и уменьшает счётчик. Запись
92
+ * вызывает метод из своего dispose() до пользовательского cleanup, иначе
93
+ * освобождение владельца не продвинется по списку. Повторный вызов и запись
94
+ * другого владельца безопасно игнорируются.
95
+ * @internal
96
+ */
97
+ _releaseRecord(e) {
98
+ if (e.scopeParent !== this)
99
+ return;
100
+ const s = e.scopePrevious, t = e.scopeNext;
101
+ s === void 0 ? this.scopeFirstChild = t : s.scopeNext = t, t === void 0 ? this.scopeLastChild = s : t.scopePrevious = s, e.scopeParent = void 0, e.scopePrevious = void 0, e.scopeNext = void 0, --this._resourceCount;
102
+ }
103
+ /**
104
+ * Ставит cleanup в конец списка ресурсов и возвращает его однократный stop.
105
+ * Lifetime не проверяет: это делает вызывающий метод владельца.
106
+ *
107
+ * Stop захватывает только запись, а не владельца: снятая запись теряет ссылку
108
+ * на владельца, поэтому удержанный stop не удерживает ни его, ни соседние
109
+ * записи.
110
+ */
111
+ _ownCleanup(e) {
112
+ const s = this.scopeLastChild, t = new f(this, s, e);
113
+ return s === void 0 ? this.scopeFirstChild = t : s.scopeNext = t, this.scopeLastChild = t, ++this._resourceCount, () => t.dispose();
114
+ }
115
+ /** Registers a framework cleanup; the public stop still exposes only raw failure. */
116
+ _ownCompleted(e) {
117
+ const s = new u(e);
118
+ return this._ownRecord(s), () => s.dispose();
119
+ }
120
+ /**
121
+ * Ставит готовую запись ресурса в конец списка без обёртки и closure: запись
122
+ * сама является элементом списка владельца. Её dispose() обязан сначала
123
+ * вызвать _releaseRecord(), иначе освобождение владельца не продвинется по
124
+ * списку. Предусловие: запись не состоит в другом списке.
125
+ * Lifetime не проверяет: это делает вызывающий метод владельца.
126
+ */
127
+ _ownRecord(e) {
128
+ const s = this.scopeLastChild;
129
+ e.scopeParent = this, e.scopePrevious = s, e.scopeNext = void 0, s === void 0 ? this.scopeFirstChild = e : s.scopeNext = e, this.scopeLastChild = e, ++this._resourceCount;
130
+ }
131
+ /**
132
+ * Ставит функцию-финализатор источника в список источников владельца.
133
+ * Lifetime не проверяет: это делает вызывающий метод владельца.
134
+ */
135
+ _ownSourceFinalizer(e) {
136
+ this._lastSource = new C(this._lastSource, e), ++this._sourceCount;
137
+ }
138
+ /**
139
+ * Ставит готовую запись источника в список источников владельца без обёртки:
140
+ * источник сам является элементом списка и сам освобождает себя через
141
+ * _finalizeSource(). Предусловие: запись не состоит в другом списке.
142
+ * Lifetime не проверяет: это делает вызывающий метод владельца.
143
+ */
144
+ _ownSourceEntry(e) {
145
+ e._previousSource = this._lastSource, this._lastSource = e, ++this._sourceCount;
146
+ }
147
+ /**
148
+ * Освобождает ресурсы в обратном порядке регистрации, затем финализирует
149
+ * источники. Сбой одной записи не останавливает остальные; массив ошибок
150
+ * создаётся только при первой ошибке.
151
+ */
152
+ _releaseOwned() {
153
+ let e, s = this.scopeLastChild;
154
+ for (; s !== void 0; ) {
155
+ try {
156
+ const i = s.dispose;
157
+ if (s instanceof u && i === w) {
158
+ const c = a.call(s);
159
+ c !== void 0 && (e ??= []).push(c);
160
+ } else
161
+ i.call(s);
162
+ } catch (i) {
163
+ (e ??= []).push(p(i));
164
+ }
165
+ s = this.scopeLastChild;
166
+ }
167
+ const t = this._lastSource;
168
+ return t !== void 0 && (this._lastSource = void 0, this._sourceCount = 0, e = S(t, e)), e;
169
+ }
170
+ }
171
+ class A extends g {
172
+ /**
173
+ * Связывает владельца с реактивным экземпляром без создания нового графа.
174
+ * @param reactivity Экземпляр, в котором создаются owned-ресурсы.
175
+ */
176
+ constructor(e) {
177
+ super(), this.reactivity = e;
178
+ }
42
179
  /**
43
180
  * Создаёт owned signal и регистрирует его финализатор.
44
181
  * Все методы возвращённого handle проверяют, что владелец ещё активен.
@@ -49,8 +186,8 @@ class f {
49
186
  return {
50
187
  get: () => (this._assertAlive(), s.get()),
51
188
  peek: () => (this._assertAlive(), s.peek()),
52
- set: (i) => {
53
- this._assertAlive(), s.set(i);
189
+ set: (t) => {
190
+ this._assertAlive(), s.set(t);
54
191
  }
55
192
  };
56
193
  }
@@ -60,19 +197,19 @@ class f {
60
197
  */
61
198
  computed(e) {
62
199
  this._assertAlive();
63
- const s = typeof e == "function" ? e : e.get, i = this._adoptSource(this.reactivity._ownedComputed(s)), r = {
64
- get: () => (this._assertAlive(), i.get()),
65
- peek: () => (this._assertAlive(), i.peek())
200
+ const s = typeof e == "function" ? e : e.get, t = this._adoptSource(this.reactivity._ownedComputed(s)), i = {
201
+ get: () => (this._assertAlive(), t.get()),
202
+ peek: () => (this._assertAlive(), t.peek())
66
203
  };
67
204
  if (typeof e == "function")
68
- return r;
205
+ return i;
69
206
  let c = e.set;
70
207
  this._own(() => {
71
208
  c = void 0;
72
209
  });
73
- const n = r;
74
- return n.set = (a) => {
75
- this._assertAlive(), c(a);
210
+ const n = i;
211
+ return n.set = (r) => {
212
+ this._assertAlive(), c(r);
76
213
  }, n;
77
214
  }
78
215
  /**
@@ -85,30 +222,15 @@ class f {
85
222
  /**
86
223
  * Создаёт watch и регистрирует окончательную остановку у владельца.
87
224
  */
88
- watch(e, s, i) {
89
- return this._assertAlive(), this._adoptResource(this.reactivity.watch(e, s, i));
225
+ watch(e, s, t) {
226
+ return this._assertAlive(), this._adoptResource(this.reactivity.watch(e, s, t));
90
227
  }
91
228
  /**
92
229
  * Принимает произвольный cleanup и возвращает однократный disposer.
93
230
  * Если владелец уже неактивен, выполняет cleanup сразу и возвращает пустой disposer.
94
231
  */
95
232
  own(e) {
96
- return this.active ? this._own(e) : (e(), _);
97
- }
98
- /**
99
- * Возвращает число ещё не освобождённых записей ресурсов.
100
- * @internal
101
- */
102
- _debugResourceCount() {
103
- return this._resourceCount;
104
- }
105
- /**
106
- * Возвращает число зарегистрированных финализаторов источников.
107
- * @internal
108
- */
109
- _debugSourceCount() {
110
- var e;
111
- return ((e = this._sourceFinalizers) == null ? void 0 : e.size) ?? 0;
233
+ return this._disposed || this._disposing ? (e(), P) : this._ownCleanup(e);
112
234
  }
113
235
  /**
114
236
  * Освобождает ресурсы в обратном порядке, затем финализирует источники.
@@ -119,24 +241,18 @@ class f {
119
241
  if (this._disposed)
120
242
  return;
121
243
  this._disposed = !0, this._disposing = !0;
122
- const e = [];
244
+ let e;
123
245
  try {
124
- for (; this.scopeLastChild !== void 0; )
125
- try {
126
- this.scopeLastChild.dispose();
127
- } catch (s) {
128
- e.push(s);
129
- }
130
- this._finalizeSources(e);
246
+ e = this._releaseOwned();
131
247
  } finally {
132
248
  this._disposing = !1;
133
249
  try {
134
250
  this._afterDispose();
135
251
  } catch (s) {
136
- e.push(s);
252
+ (e ??= []).push(p(s));
137
253
  }
138
254
  }
139
- l(e, this._disposalMessage());
255
+ e !== void 0 && l(v(e, this._disposalMessage()));
140
256
  }
141
257
  /**
142
258
  * Регистрирует ресурс только у активного владельца.
@@ -145,18 +261,7 @@ class f {
145
261
  * @internal
146
262
  */
147
263
  _own(e) {
148
- this._assertAlive();
149
- let s = e;
150
- const i = {
151
- scopeParent: void 0,
152
- scopePrevious: void 0,
153
- scopeNext: void 0,
154
- dispose: () => {
155
- const r = s;
156
- r !== void 0 && (s = void 0, d(i), --this._resourceCount, r());
157
- }
158
- };
159
- return p(this, i), ++this._resourceCount, i.dispose;
264
+ return this._assertAlive(), this._ownCleanup(e);
160
265
  }
161
266
  /**
162
267
  * Принимает уже созданный ресурс и не оставляет его без владельца при ошибке регистрации.
@@ -169,8 +274,8 @@ class f {
169
274
  } catch (s) {
170
275
  try {
171
276
  e();
172
- } catch (i) {
173
- throw new AggregateError([s, i], "Resource registration and cleanup failed.");
277
+ } catch (t) {
278
+ throw new AggregateError([s, t], "Resource registration and cleanup failed.");
174
279
  }
175
280
  throw s;
176
281
  }
@@ -186,8 +291,8 @@ class f {
186
291
  } catch (s) {
187
292
  try {
188
293
  e.dispose();
189
- } catch (i) {
190
- throw new AggregateError([s, i], "Source registration and cleanup failed.");
294
+ } catch (t) {
295
+ throw new AggregateError([s, t], "Source registration and cleanup failed.");
191
296
  }
192
297
  throw s;
193
298
  }
@@ -196,10 +301,12 @@ class f {
196
301
  /**
197
302
  * Добавляет финализатор источника. Возвращённый им false означает повторную попытку
198
303
  * после прогресса других финализаторов, а не успешное освобождение.
304
+ * Каждая регистрация — отдельный источник: одинаковые финализаторы владелец
305
+ * не объединяет, и функция, переданная дважды, будет вызвана дважды.
199
306
  * @internal
200
307
  */
201
308
  _ownSource(e) {
202
- this._assertAlive(), this._sourceFinalizers === void 0 && (this._sourceFinalizers = /* @__PURE__ */ new Set()), this._sourceFinalizers.add(e);
309
+ this._assertAlive(), this._ownSourceFinalizer(e);
203
310
  }
204
311
  /**
205
312
  * Запрещает операции после начала освобождения владельца.
@@ -222,53 +329,50 @@ class f {
222
329
  _disposalMessage() {
223
330
  return "ScopeNode disposal failed.";
224
331
  }
225
- /**
226
- * Освобождает источники в обратном порядке регистрации с повторными попытками.
227
- * Если в проходе не было прогресса, прекращает обход, сохраняя существующий контракт.
228
- * Исключение одного финализатора не блокирует остальные.
229
- */
230
- _finalizeSources(e) {
231
- const s = this._sourceFinalizers;
232
- if (this._sourceFinalizers = void 0, s === void 0)
233
- return;
234
- let i = [...s].reverse();
235
- for (s.clear(); i.length > 0; ) {
236
- const r = [];
237
- let c = !1;
238
- for (const n of i)
239
- try {
240
- n() ? c = !0 : r.push(n);
241
- } catch (a) {
242
- e.push(a), c = !0;
243
- }
244
- if (!c)
245
- return;
246
- i = r;
332
+ }
333
+ function S(o, e) {
334
+ let s = e, t = o;
335
+ for (; t !== void 0; ) {
336
+ let i, c, n = !1, r = t;
337
+ for (; r !== void 0; ) {
338
+ const d = r._previousSource;
339
+ let h = !0;
340
+ try {
341
+ r._previousSource = void 0, h = r._finalizeSource();
342
+ } catch (_) {
343
+ (s ??= []).push(p(_));
344
+ }
345
+ h ? n = !0 : (c === void 0 ? i = r : c._previousSource = r, c = r), r = d;
247
346
  }
347
+ if (!n)
348
+ return s;
349
+ t = i;
248
350
  }
351
+ return s;
249
352
  }
250
- function p(t, e) {
251
- const s = t.scopeLastChild;
252
- e.scopeParent = t, e.scopePrevious = s, e.scopeNext = void 0, s === void 0 ? t.scopeFirstChild = e : s.scopeNext = e, t.scopeLastChild = e;
353
+ function N(o, e) {
354
+ const s = o.scopeLastChild;
355
+ e.scopeParent = o, e.scopePrevious = s, e.scopeNext = void 0, s === void 0 ? o.scopeFirstChild = e : s.scopeNext = e, o.scopeLastChild = e;
253
356
  }
254
- function d(t) {
255
- const e = t.scopeParent;
357
+ function F(o) {
358
+ const e = o.scopeParent;
256
359
  if (e === void 0)
257
360
  return;
258
- const s = t.scopePrevious, i = t.scopeNext;
259
- s === void 0 ? e.scopeFirstChild = i : s.scopeNext = i, i === void 0 ? e.scopeLastChild = s : i.scopePrevious = s, t.scopeParent = void 0, t.scopePrevious = void 0, t.scopeNext = void 0;
361
+ const s = o.scopePrevious, t = o.scopeNext;
362
+ s === void 0 ? e.scopeFirstChild = t : s.scopeNext = t, t === void 0 ? e.scopeLastChild = s : t.scopePrevious = s, o.scopeParent = void 0, o.scopePrevious = void 0, o.scopeNext = void 0;
260
363
  }
261
- function l(t, e) {
262
- if (t.length === 1)
263
- throw t[0];
264
- if (t.length > 1)
265
- throw new AggregateError(t, e);
364
+ function m(o, e) {
365
+ if (o.length === 1)
366
+ throw o[0];
367
+ if (o.length > 1)
368
+ throw new AggregateError(o, e);
266
369
  }
267
- function _() {
370
+ function P() {
268
371
  }
269
372
  export {
270
- f as ScopeNode,
271
- p as appendScopeChild,
272
- d as detachScopeChild,
273
- l as throwScopeErrors
373
+ A as ScopeNode,
374
+ g as ScopeOwner,
375
+ N as appendScopeChild,
376
+ F as detachScopeChild,
377
+ m as throwScopeErrors
274
378
  };
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("./scope.cjs");function A(t,e,i,d,v={},f){const s=W(i);let l=!1,u,o,a=!1;function h(){if(a)return;a=!0;const n=o;o=void 0,n!==void 0&&e(n)}return t(()=>{if(a)return;const n=f===void 0?s():f(s),p=!l;if(!p&&m(n,u))return;const b=u;if(u=n,l=!0,p&&!v.immediate)return;const y=o;o=void 0;let c;if(y!==void 0)try{e(y)}catch(r){c=[r]}if(!a)try{const r=w(e(()=>d(n,b)));a?r!==void 0&&e(r):o=r}catch(r){c??(c=[]),c.push(r)}c!==void 0&&g.throwScopeErrors(c,"Watch callback and cleanup failed.")},h)}function W(t){if(Array.isArray(t))return()=>t.map(S);const e=t;return typeof e=="function"?e:()=>e.get()}function S(t){return typeof t=="function"?t():t.get()}function m(t,e){if(!Array.isArray(t)||!Array.isArray(e))return Object.is(t,e);if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!Object.is(t[i],e[i]))return!1;return!0}function w(t){return typeof t=="function"?t:void 0}exports.watchWithReactivity=A;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("./scope.cjs");function A(t,e,i,d,v={},f){const s=W(i);let l=!1,u,o,a=!1;function h(){if(a)return;a=!0;const n=o;o=void 0,n!==void 0&&e(n)}return t(()=>{if(a)return;const n=f===void 0?s():f(s),p=!l;if(!p&&m(n,u))return;const b=u;if(u=n,l=!0,p&&!v.immediate)return;const y=o;o=void 0;let c;if(y!==void 0)try{e(y)}catch(r){c=[r]}if(!a)try{const r=w(e(()=>d(n,b)));a?r!==void 0&&e(r):o=r}catch(r){c??=[],c.push(r)}c!==void 0&&g.throwScopeErrors(c,"Watch callback and cleanup failed.")},h)}function W(t){if(Array.isArray(t))return()=>t.map(S);const e=t;return typeof e=="function"?e:()=>e.get()}function S(t){return typeof t=="function"?t():t.get()}function m(t,e){if(!Array.isArray(t)||!Array.isArray(e))return Object.is(t,e);if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!Object.is(t[i],e[i]))return!1;return!0}function w(t){return typeof t=="function"?t:void 0}exports.watchWithReactivity=A;
@@ -32,7 +32,7 @@ function C(t, e, i, y, h = {}, u) {
32
32
  const r = w(e(() => y(n, A)));
33
33
  a ? r !== void 0 && e(r) : o = r;
34
34
  } catch (r) {
35
- f ?? (f = []), f.push(r);
35
+ f ??= [], f.push(r);
36
36
  }
37
37
  f !== void 0 && m(f, "Watch callback and cleanup failed.");
38
38
  }, v);
@@ -1 +1 @@
1
- "use strict";var C=Object.defineProperty;var E=(p,e,t)=>e in p?C(p,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):p[e]=t;var d=(p,e,t)=>E(p,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("../path/data-path.utils.cjs"),P=require("../path/DataPath.cjs"),W=require("../path/meta/RaphMeta.cjs"),q=require("../path/RaphKernel.cjs"),S=require("../reactivity/reactive-object.cjs"),g=require("./diagnostics/RaphDebug.cjs"),w=require("./errors.cjs"),G=require("./ownership/parentGraph.cjs"),v=require("./ownership/RaphNode.cjs"),k=require("./ownership/RaphScope.cjs"),R=require("./ownership/throwDisposalErrors.cjs"),m=require("./phases/phase.types.cjs"),x=require("./phases/RaphFrameLoop.cjs"),O=require("./phases/RaphPhasePipeline.cjs"),M=require("./reactivity/PathHandle.cjs"),L=require("./reactivity/RaphMetaSource.cjs"),F=require("./reactivity/RaphWorkGraph.cjs"),B=require("./reactivity/RuntimeReactivity.cjs"),N=require("./reactivity/RuntimeWatch.cjs"),b=class b{constructor(e={}){d(this,"mode","runtime");d(this,"configuration");d(this,"rootScope");d(this,"root");d(this,"frameTick");d(this,"_reactivity");d(this,"_signalLifecycle");d(this,"_workGraph");d(this,"_frameTickWritable");d(this,"_setFrameTick");d(this,"_pathHandles");d(this,"_meta");d(this,"_phases");d(this,"_frameLoop");d(this,"_debug");d(this,"_debugController");d(this,"_parentGraph");d(this,"_owners",new Set);d(this,"_batchDepth",0);d(this,"_mutationDepth",0);d(this,"_kernelBatchDepth",0);d(this,"_ownerDisposalDepth",0);d(this,"_actionDepth",0);d(this,"_actionCounter",0);d(this,"_traceCauseStack",[]);d(this,"_phaseTraceOperations");d(this,"_executionRequested",!1);d(this,"_disposed",!1);d(this,"_disposedListeners",new Set);const t=e.id??`runtime-${b._runtimeCounter++}`,r=e.adaptiveDependencyIndex??!1,s=e.enforceActions??!1,i=e.scheduler??m.RaphSchedulerType.Sync;if(!H(i))throw new Error(`[Raph] Unsupported scheduler "${String(i)}".`);const o=e.kernel??new q.RaphKernel({id:`${t}-kernel`});this.configuration=Object.freeze({adaptiveDependencyIndex:r,...e.debug===void 0?{}:{debug:e.debug},id:t,kernel:o,enforceActions:s,scheduler:i}),this._debugController=new g.RaphDebugController(e.debug);const c=`[Raph] Runtime "${t}" is disposed.`;this._signalLifecycle={owner:this,runWrite:u=>this._runWrite(u),assertDependencyAllowed:(u,l)=>{this._assertImplicitDependency(u,l)},...s?{assertWriteAllowed:()=>this._assertWriteAllowed()}:{},throwDisposed:()=>{throw new w.RaphDisposedError(c)},throwCrossRuntime:u=>this._throwCrossRuntime(u)},this._reactivity=new B.RuntimeReactivity(this._signalLifecycle,{adaptiveDependencyIndex:r}),this._workGraph=new F.RaphWorkGraph(this),o._attachRuntime(this),this.rootScope=new k.RaphScope(`${t}:root-scope`,this),this.root=new v.RaphNode(null,{id:`${t}:root`},this),S.configureReactiveObjectPolicy(this._reactivity,{owner:this,assertRead:()=>{this._assertAlive();const u=this._reactivity.getActiveOwner();u!==void 0&&u!==this&&this._throwCrossRuntime(u);const l=this._reactivity.getActiveConsumerOwner();l!==void 0&&this._assertImplicitDependency(this.rootScope,l)},assertWrite:()=>this._assertWriteAllowed(),runWrite:u=>this._runWrite(u),throwForeign:u=>{throw u instanceof b&&this._throwCrossRuntime(u),new w.RaphCrossRuntimeError("[Raph] Reactive object belongs to another reactivity engine.")}});const n=this._workGraph.createProducer(this.rootScope,"frame",{includeRuntime:!1});let a;const h=this._reactivity.signalForOwner(0,this.rootScope,this._workGraph.producerHooks(n),u=>{a=u});this._setFrameTick=u=>this._runWrite(()=>a(u)),this._frameTickWritable=h,this.frameTick=this._workGraph.attachProducer(n,{get:h.get,peek:h.peek})}_getReactivity(){return this._reactivity}_getWorkGraph(){return this._workGraph}get id(){return this.configuration.id}get kernel(){return this.configuration.kernel}get disposed(){return this._disposed}get graph(){return this._parentGraph??(this._parentGraph=G.parentGraph())}get loopEnabled(){var e;return((e=this._frameLoop)==null?void 0:e.running)??!1}get frame(){var e;return((e=this._phases)==null?void 0:e.frame)??{now:0,delta:0,elapsed:0,frame:0}}get phases(){var e;return((e=this._phases)==null?void 0:e.phases)??[]}get meta(){if(this._assertAlive(),this._meta!==void 0)return this._meta;const e=new W.RaphMeta(this.kernel,{assertReadable:()=>this._assertAlive(),assertWritable:()=>this._assertWriteAllowed(),runWrite:(t,r)=>this._runWrite(t,r)});return this._meta=Object.freeze({delete:e.delete.bind(e),get:e.get.bind(e),has:e.has.bind(e),merge:e.merge.bind(e),set:e.set.bind(e)})}getDerivedSnapshot(){return this.kernel.getDerivedSnapshot()}get debug(){return this._debug??(this._debug=Object.freeze({snapshot:()=>this._createDebugSnapshot(),getTree:()=>this._createDebugTree(),stats:()=>this._createDebugStats(),trace:this._debugController.trace,machines:this._debugController.machines}))}signal(e,t=this.rootScope){this._assertOwnerRuntime(t);const r=this._workGraph.createProducer(t),s=this._reactivity.signalForOwner(e,t,this._workGraph.producerHooks(r));return this._workGraph.attachProducer(r,s)}reactive(e){return this._assertAlive(),this._reactivity.reactive(e)}computed(e,t=this.rootScope){this._assertOwnerRuntime(t);const r=this._workGraph.createProducer(t),s=typeof e=="function"?e:e.get,i=this._reactivity.computedForOwner(()=>this._runTracked(t,s),t,this._workGraph.producerHooks(r));if(this._workGraph.setProducerActivation(r,()=>{i.peek()}),typeof e=="function")return this._workGraph.attachProducer(r,i);const o=this._attachWritableComputed(i,e.set,t);return this._workGraph.attachProducer(r,o)}effect(e,t,r,s={}){return this._effectRegistration(e,t,r,s).dispose}_effectRegistration(e,t,r,s={},i=!1){this._assertOwnerRuntime(e);const o=this._validatePhaseBinding(t,r,s),c=this._execution,n=s.initial??"scheduled";let a,h,u=!1;const l=this._reactivity.withEffectBinding(f=>{const _=c.bindTask(o,e,r,s.priority??0,f);return i&&_.pause(),a=_},()=>this._reactivity.effect(()=>this._runTracked(e,()=>{const f=r(a.task);return typeof f=="function"?()=>this._runUntracked(f):f}),()=>{h===void 0?u=!0:h()}));h=this._own(l,e),u&&h(),a.abort=()=>h==null?void 0:h();try{n==="sync"?this.flush():this._requestExecution()}catch(f){try{h()}catch(_){throw new AggregateError([f,_],"[Raph] Phase effect registration and rollback failed.")}throw f}return{dispose:()=>h==null?void 0:h(),pause:()=>a==null?void 0:a.pause(),resume:()=>a==null?void 0:a.resume()}}watch(e,t,r,s,i={}){return this._watchRegistration(e,t,r,s,i).dispose}_watchRegistration(e,t,r,s,i={},o=!1){this._assertOwnerRuntime(e);const c=this._validatePhaseBinding(r,s,i,!0);this._workGraph.assertSubscriptionAllowed(e,t);let n;const a=new N.RuntimeWatch(_=>this._runUntracked(_),()=>s(n.task));n=this._execution.bindTask(c,e,s,i.priority??0,a.deliver),o&&n.pause();let h;try{h=this._workGraph.subscribe(t,i.include,n.enqueue)}catch(_){throw n.dispose(),_}const u=()=>a.stop(()=>{const _=[];try{h()}catch(y){_.push(y)}try{n.dispose()}catch(y){_.push(y)}R.throwDisposalErrors(_,"[Raph] Phase watch disposal failed.")}),l=this._own(u,e),f=i.initial??"scheduled";try{f!=="none"&&n.schedule(),f==="sync"&&this.flush()}catch(_){try{l()}catch(y){throw new AggregateError([_,y],"[Raph] Phase watch registration and rollback failed.")}throw _}return{dispose:l,pause:n.pause,resume:n.resume}}aggregate(e,t){return this._assertOwnerRuntime(e),this._workGraph.createAggregate(e,t)}metaSource(e,t={}){this._assertAlive(),I(e,t);const r=this._workGraph.createProducer(this.rootScope,"path"),s=this._workGraph.producerHooks(r).onDispose,i=L.RaphMetaSource._create(this.rootScope,e,t,()=>this.kernel._watchMeta(i.masks,({events:o})=>this._workGraph.notifyProducerEvents(r,o,!1),i.options,o=>{o&&this._execution.request()}),()=>s(!1));i._bindOwner(this.rootScope._adoptResource(()=>i._disposeOwned()));try{return this._workGraph.setProducerActivation(r,()=>i._activate(),!0),this._workGraph.attachProducer(r,i),i}catch(o){try{i.dispose()}catch(c){throw new AggregateError([o,c],"[Raph] Meta source activation and rollback failed.")}throw o}}path(e,t={}){this._assertAlive();const r=T.parseDataPath(e,t),s=this._pathHandles??(this._pathHandles=new Map),i=s.get(r.canonical);if(i!==void 0)return i;const o=this._workGraph.createProducer(this.rootScope,"path"),c=this._workGraph.producerHooks(o),n=new M.PathHandle(this.kernel,r,t,a=>this._releasePathHandle(a),this._reactivity,()=>this._assertAlive(),()=>this._assertTrackedRead(),this.configuration.enforceActions?()=>this._assertWriteAllowed():void 0,a=>this._runWrite(a),{token:o,onDispose:c.onDispose},({events:a},h)=>this._workGraph.notifyProducerEvents(o,a,!0,h));try{return this._workGraph.setProducerActivation(o,()=>n._activate(),!0),this._workGraph.attachProducer(o,n),s.set(r.canonical,n),n}catch(a){let h,u=!1;try{n.dispose()}catch(l){u=!0,h=l}throw s.size===0&&this._pathHandles===s&&(this._pathHandles=void 0),u?new AggregateError([a,h],"[Raph] Path source activation and rollback failed."):a}}get(e,t){this._assertTrackedRead();const r=e??"";return this._reactivity._isTracking()?this.path(r,t)._getTracked():this.kernel.get(r,t)}peek(e,t){return this._assertAlive(),this.kernel.peek(e??"",t)}has(e,t){return this._assertAlive(),this.kernel.has(e,t)}set(e,t,r){this._assertWriteAllowed(),this._runWrite(()=>this.kernel.set(e,t,r))}merge(e,t,r){this._assertWriteAllowed(),this._runWrite(()=>this.kernel.merge(e,t,r))}delete(e,t){this._assertWriteAllowed(),this._runWrite(()=>this.kernel.delete(e,t))}batch(e){return this._batch(e,!0)}_batchReactive(e){return this._batch(e,!1)}_batch(e,t){this._assertAlive(),this._batchDepth++;let r,s,i=!1;try{r=this._reactivity.batch(()=>t?this.kernel.batch(e):e())}catch(c){i=!0,s=c}this._batchDepth--;const o=this._finishExecutionBoundary();if(i)throw o.length!==0?new AggregateError([s,...o],"[Raph] Batch and scheduled phase execution failed."):s;return R.throwDisposalErrors(o,"[Raph] Batch phase execution failed."),r}action(e,t,r){const s=typeof e=="function"?e:t,i=typeof e=="function"?t instanceof k.RaphScope?t:this.rootScope:r??this.rootScope,o=typeof e=="string"?e:`action#${++this._actionCounter}`;if(this._assertOwnerRuntime(i),typeof s!="function")throw new TypeError("[Raph] Action operation must be a function.");if(!o.trim())throw new Error("[Raph] Action name must not be empty.");return(...c)=>{i._assertAlive();const n=this._debugController.nextOperationId("action"),h=this._traceCauseStack.at(-1)??n;this._debugController.record({...h===void 0?{}:{causeId:h},kind:"action",name:o,...n===void 0?{}:{operationId:n},status:"start"}),h!==void 0&&this._traceCauseStack.push(h),this._actionDepth++;try{const u=this.batch(()=>this._runUntracked(()=>s(...c)));return this._debugController.record({...h===void 0?{}:{causeId:h},kind:"action",name:o,...n===void 0?{}:{operationId:n},status:"end"}),u}catch(u){throw this._debugController.record({...h===void 0?{}:{causeId:h},details:{message:D(u)},kind:"action",name:o,...n===void 0?{}:{operationId:n},status:"error"}),this._debugController.record({...h===void 0?{}:{causeId:h},details:{message:D(u)},kind:"error",name:`action:${o}`,...n===void 0?{}:{operationId:n},status:"error"}),u}finally{this._actionDepth--,h!==void 0&&this._traceCauseStack.pop()}}}untracked(e){return this._assertAlive(),this._runUntracked(e)}scope(e){return this._assertAlive(),new k.RaphScope(e,this)}node(e,t){this._assertAlive();const r=this._runNodeMutation(()=>{const s=e.parent??this.root,i=v.createProvisionalNode(s,e,this);try{const o=t==null?void 0:t(i);return i._assertAlive(),s._assertAlive(),i._setApi(o),i._publishCreation(),i}catch(o){try{i.dispose()}catch(c){throw new AggregateError([o,c],`[Raph] Node "${i.id}" setup and cleanup failed.`)}throw o}});return r._assertAlive(),r}getNode(e){this._assertAlive();const t=[this.root];for(;t.length!==0;){const r=t.pop();if(r.id===e)return r;t.push(...r.children)}}definePhases(e){this._execution.definePhases(e)}addPhase(e){this._execution.addPhase(e)}clearPhases(){var e;this._assertAlive(),(e=this._phases)==null||e.clearPhases()}requestExecution(){var e;this._assertAlive(),(e=this._phases)==null||e.request()}flush(){var e;this._assertAlive(),this._executionRequested=!1,(e=this._phases)==null||e.flush()}afterFlush(){var e;return this._assertAlive(),((e=this._phases)==null?void 0:e.afterFlush())??Promise.resolve()}acquireLoop(e){return this._assertAlive(),this._clock.acquire(e)}startLoop(){this._assertAlive(),this._clock.start()}stopLoop(){var e;(e=this._frameLoop)==null||e.stop()}derive(e){this._assertAlive();const t=e.compute,r=this.kernel.derive({...e,compute:s=>this._runUntracked(()=>t(s))});return this._own(()=>r.dispose(),this.rootScope),r}dispose(){var c,n;if(this._disposed)return;this._disposed=!0,this._executionRequested=!1,this._signalLifecycle.owner=void 0;const e=[],t=[...this._owners];try{(c=this._frameLoop)==null||c.dispose()}catch(a){e.push(a)}this._frameLoop=void 0;try{(n=this._phases)==null||n.dispose()}catch(a){e.push(a)}this._phases=void 0;try{this.root.dispose()}catch(a){e.push(a)}for(const a of t.reverse())if(!(a===this.root||a===this.rootScope||a.disposed))try{a.dispose()}catch(h){e.push(h)}try{this.rootScope.dispose()}catch(a){e.push(a)}const r=`[Raph] Runtime "${this.id}" is disposed.`,s=()=>{throw new w.RaphDisposedError(r)};try{S.disposeReactiveObjectContext(this._reactivity,{assertRead:s,assertWrite:s,throwForeign:s})}catch(a){e.push(a)}this._owners.clear(),this._meta=void 0;const i=this._pathHandles;if(this._pathHandles=void 0,i!==void 0){for(const a of i.values())try{a.dispose()}catch(h){e.push(h)}i.clear()}try{this._workGraph.dispose()}catch(a){e.push(a)}try{this.kernel._detachRuntime(this)}catch(a){e.push(a)}const o=[...this._disposedListeners];this._disposedListeners.clear();for(const a of o)try{a()}catch(h){e.push(h)}R.throwDisposalErrors(e,`[Raph] Runtime "${this.id}" disposal failed.`)}_onDisposed(e){return this._disposed?(e(),()=>{}):(this._disposedListeners.add(e),()=>{this._disposedListeners.delete(e)})}_notifyNodeStructure(e,t,r,s){this._runNodeMutation(()=>{this._workGraph.notifyNode(e,"structure",{structure:t,oldAncestors:r,newAncestors:s})})}_notifyNodeTouch(e,t){this._runNodeMutation(()=>this._workGraph.notifyNode(e,"touch",{metadata:t}))}_assertNodeReparentAllowed(e,t){this._workGraph.assertReparentAllowed(e,t)}_releaseNode(e){this._workGraph.releaseNode(e)}_runNodeMutation(e){return this._runWrite(e)}_runPhaseTransition(e){return this._runWrite(e,!1)}_beginOwnerDisposal(){this._ownerDisposalDepth++}_endOwnerDisposal(){this._ownerDisposalDepth!==0&&(this._ownerDisposalDepth--,this._clearTransientCausesIfSettled(),this._disposed||this._requestExecution())}_ownerDisposalActive(){return this._ownerDisposalDepth!==0}_registerOwner(e){this._assertAlive(),this._owners.add(e)}_unregisterOwner(e){this._owners.delete(e)}_assertOwnerRuntime(e){if(this._assertAlive(),e.runtime!==this)throw new w.RaphCrossRuntimeError("[Raph] Owner belongs to another runtime.");e._assertAlive()}_beginKernelBatch(){this._disposed||this._kernelBatchDepth++}_endKernelBatch(){this._kernelBatchDepth!==0&&(this._kernelBatchDepth--,this._clearTransientCausesIfSettled(),this._disposed||this._requestExecution())}_registerMachineDebug(e){return this._assertAlive(),this._debugController.registerMachine(e)}_hasMachineDebug(e){return this._debugController.hasMachine(e)}_traces(e){return this._debugController.traces(e)}_currentTraceCauseId(){return this._traceCauseStack.at(-1)}_nextTraceOperation(e){return this._debugController.nextOperationId(e)}_hasActiveReactiveContext(){return this._assertAlive(),this._reactivity.hasActiveContext()}_recordTrace(e){this._debugController.record(e)}_runWithTraceCause(e,t){if(e===void 0)return t();this._traceCauseStack.push(e);try{return t()}finally{this._traceCauseStack.pop()}}_validatePhaseBinding(e,t,r,s=!1){if(typeof t!="function")throw new TypeError("[Raph] Phase callback must be a function.");const i=e.trim();this._execution.requirePhase(i);const o=r.priority??0;if(!Number.isFinite(o))throw new TypeError("[Raph] Effect priority must be finite.");const c=r.initial??"scheduled";if(c!=="scheduled"&&c!=="sync"&&!(s&&c==="none"))throw new TypeError(`[Raph] Unsupported effect initial mode "${String(c)}".`);return i}_createDebugSnapshot(){var r,s,i;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 v.RaphNode)).map(g.createOwnerSnapshot);return Object.freeze({id:this.id,disposed:this._disposed,pending:!this._disposed&&(this._executionRequested||(((s=this._phases)==null?void 0:s._debugPending())??!1)),batchDepth:this._batchDepth,kernelBatchDepth:this._kernelBatchDepth,owners:this._owners.size,pathHandles:((i=this._pathHandles)==null?void 0:i.size)??0,rootScope:g.createOwnerSnapshot(this.rootScope),scopes:Object.freeze(t),root:g.createOwnerSnapshot(this.root),frameLoop:Object.freeze(e),actionDepth:this._actionDepth,machines:this._debugController.machineCount,traceEvents:this._debugController.traceSize})}_createDebugTree(){const e=this._debugController.machineTreeNodesByOwner(),t=[g.createOwnerTree(this.rootScope,e),g.createOwnerTree(this.root,e),...[...this._owners].filter(r=>r!==this.rootScope&&r!==this.root&&!(r instanceof v.RaphNode)).map(r=>g.createOwnerTree(r,e))];return Object.freeze({children:Object.freeze(t),disposed:this._disposed,id:this.id,kind:"runtime"})}_createDebugStats(){var i,o;let e=0,t=0,r=0,s=0;for(const c of this._owners)c instanceof v.RaphNode?e++:t++,r+=c._debugResourceCount(),s+=c._debugSourceCount();return Object.freeze({actors:this._debugController.actorCount,machines:this._debugController.machineCount,nodes:e,owners:this._owners.size,pathHandles:((i=this._pathHandles)==null?void 0:i.size)??0,pending:!this._disposed&&(this._executionRequested||(((o=this._phases)==null?void 0:o._debugPending())??!1)),resources:r,scopes:t,sources:s,traceEvents:this._debugController.traceSize})}_releasePathHandle(e){const t=this._pathHandles;(t==null?void 0:t.get(e.path))===e&&(t.delete(e.path),t.size===0&&(this._pathHandles=void 0))}get _execution(){return this._assertAlive(),this._phases??(this._phases=new O.RaphPhasePipeline(this.configuration.scheduler,e=>this._runUntracked(e),e=>this._workGraph.causeForToken(e),()=>{const e=this._mutationDepth!==0||this._batchDepth!==0||this._kernelBatchDepth!==0||this._ownerDisposalDepth!==0||this._reactivity._isFlushingEffects();return e&&this.configuration.scheduler===m.RaphSchedulerType.Sync&&(this._executionRequested=!0),e},(e,t,r)=>{var i,o,c;let s;t==="start"?(s=this._debugController.nextOperationId("phase"),s!==void 0&&(this._phaseTraceOperations??(this._phaseTraceOperations=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({...s===void 0?{}:{causeId:s},...r===void 0?{}:{details:{message:D(r)}},kind:"phase",name:e,...s===void 0?{}:{operationId:s},status:t})}))}get _clock(){return this._frameLoop??(this._frameLoop=new x.RaphFrameLoop(()=>this._tickFrameLoop()))}_tickFrameLoop(){this._disposed||this._setFrameTick(this._frameTickWritable.peek()+1)}_attachWritableComputed(e,t,r){let s=t;this._own(()=>{s=void 0},r);const i=e;return i.set=o=>{r._assertAlive(),this._assertWriteAllowed(),this._runWrite(()=>s(o))},i}_own(e,t){try{return t._adoptResource(e)}catch(r){try{e()}catch(s){throw new AggregateError([r,s],"[Raph] Resource registration and cleanup failed.")}throw r}}_runTracked(e,t){return this._reactivity.runWithOwner(this._signalLifecycle,e,t)}_runUntracked(e){return this._reactivity.untrackedWithOwner(e)}_runWrite(e,t=!0){t&&this.configuration.scheduler===m.RaphSchedulerType.Sync&&(this._executionRequested=!0),this._mutationDepth++;let r,s,i=!1;try{r=e()}catch(c){i=!0,s=c}this._mutationDepth--;const o=this._finishExecutionBoundary();if(i)throw o.length!==0?new AggregateError([s,...o],"[Raph] Mutation and scheduled phase execution failed."):s;return R.throwDisposalErrors(o,"[Raph] Mutation phase execution failed."),r}_finishExecutionBoundary(){const e=[];try{this._clearTransientCausesIfSettled()}catch(t){e.push(t)}try{this._requestExecution()}catch(t){e.push(t)}return e}_clearTransientCausesIfSettled(){this._mutationDepth===0&&this._batchDepth===0&&this._kernelBatchDepth===0&&this._ownerDisposalDepth===0&&!this._reactivity._isFlushingEffects()&&this._workGraph.clearTransientCauses()}_requestExecution(){var e;this._disposed||this.configuration.scheduler!==m.RaphSchedulerType.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())}_assertTrackedRead(){this._assertAlive();const e=this._reactivity.getActiveOwner();e!==void 0&&e!==this&&this._throwCrossRuntime(e);const t=this._reactivity.getActiveConsumerOwner();t!==void 0&&this._assertImplicitDependency(this.rootScope,t)}_assertSourceReadable(e){this._assertAlive();const t=this._reactivity.getActiveOwner();t!==void 0&&t!==this&&this._throwCrossRuntime(t);const r=this._reactivity.getActiveConsumerOwner();r!==void 0&&this._assertImplicitDependency(e,r),e._assertAlive()}_assertImplicitDependency(e,t){if(e.runtime!==this||t.runtime!==this)throw new w.RaphCrossRuntimeError("[Raph] Implicit dependency crosses runtime boundaries.");if(!(e===this.rootScope||e===t)){if(e instanceof v.RaphNode&&t instanceof v.RaphNode){for(let r=t.parent;r!==null;r=r.parent)if(r===e)return}throw new Error(`[Raph] Implicit dependency from "${t.id}" to "${e.id}" is not allowed; use watch().`)}}_assertWriteAllowed(){if(this._assertAlive(),this.configuration.enforceActions&&this._batchDepth===0)throw new w.RaphActionError("[Raph] Writes are allowed only inside action() or batch().")}_throwCrossRuntime(e){throw new w.RaphCrossRuntimeError(`[Raph] Runtime "${this.id}" cannot be tracked by runtime "${e.id}".`)}_assertAlive(){if(this._disposed)throw new w.RaphDisposedError(`[Raph] Runtime "${this.id}" is disposed.`)}};d(b,"_runtimeCounter",0);let A=b;function H(p){return p===m.RaphSchedulerType.Sync||p===m.RaphSchedulerType.Microtask||p===m.RaphSchedulerType.AnimationFrame}function I(p,e){const t=Array.isArray(p)?p:[p];if(t.length===0)throw new TypeError("[RaphMeta] watch requires at least one mask.");if(e.namespace!==void 0&&!e.namespace.trim())throw new Error("[RaphMeta] namespace must not be empty.");for(const r of t)P.DataPath.from(r,e)._asMask()}function D(p){return p instanceof Error?p.message:String(p)}exports.RaphRuntime=A;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("../path/data-path.utils.cjs"),P=require("../path/DataPath.cjs"),N=require("../path/meta/RaphMeta.cjs"),q=require("../path/RaphKernel.cjs"),O=require("../reactivity/reactive-object.cjs"),R=require("./diagnostics/RaphDebug.cjs"),v=require("./errors.cjs"),I=require("./ownership/parentGraph.cjs"),m=require("./ownership/RaphNode.cjs"),E=require("./ownership/RaphScope.cjs"),b=require("./ownership/throwDisposalErrors.cjs"),w=require("./phases/phase.types.cjs"),G=require("./phases/RaphFrameLoop.cjs"),B=require("./phases/RaphPhasePipeline.cjs"),f=require("./phases/RaphPhaseTaskRecord.cjs"),W=require("./phases/RaphPhaseWatch.cjs"),k=require("./reactivity/disposal-sweep.utils.cjs"),M=require("./reactivity/PathHandle.cjs"),L=require("./reactivity/RaphMetaSource.cjs"),F=require("./reactivity/RaphWorkGraph.cjs"),$=require("./reactivity/RuntimeReactivity.cjs"),S=Object.freeze({}),x=2**32-1-f.GROUP_NODES;class A{static _runtimeCounter=0;mode="runtime";configuration;rootScope;root;frameTick;_reactivity;_signalLifecycle;_workGraph;_frameTickSignal;_pathHandles;_meta;_phases;_frameLoop;_debug;_debugController;_parentGraph;_topOwners=new Set;_ownerRegistrations=0;_ownersReleased=!1;_batchDepth=0;_mutationDepth=0;_kernelBatchDepth=0;_ownerDisposalDepth=0;_disposingNodes=[];_ownerDisposals=0;_disposalSweepers;_nextDisposalSweep=Number.POSITIVE_INFINITY;_actionDepth=0;_actionCounter=0;_traceCauseStack=[];_phaseTraceOperations;_executionRequested=!1;_disposed=!1;_disposedListeners=new Set;constructor(e={}){const t=e.id??`runtime-${A._runtimeCounter++}`,s=e.adaptiveDependencyIndex??!1,r=e.enforceActions??!1,i=e.scheduler??w.RaphSchedulerType.Sync;if(!K(i))throw new Error(`[Raph] Unsupported scheduler "${String(i)}".`);const o=e.kernel??new q.RaphKernel({id:`${t}-kernel`});this.configuration=Object.freeze({adaptiveDependencyIndex:s,...e.debug===void 0?{}:{debug:e.debug},id:t,kernel:o,enforceActions:r,scheduler:i}),this._debugController=new R.RaphDebugController(e.debug);const a=`[Raph] Runtime "${t}" is disposed.`;this._signalLifecycle={owner:this,assertDependencyAllowed:(h,u)=>{this._assertImplicitDependency(h,u)},...r?{assertWriteAllowed:()=>this._assertWriteAllowed()}:{},throwDisposed:()=>{throw new v.RaphDisposedError(a)},throwCrossRuntime:h=>this._throwCrossRuntime(h)},this._reactivity=new $.RuntimeReactivity(this._signalLifecycle,{adaptiveDependencyIndex:s}),this._workGraph=new F.RaphWorkGraph(this),o._attachRuntime(this),this.rootScope=new E.RaphScope(`${t}:root-scope`,this),this.root=new m.RaphNode(null,{id:`${t}:root`},this),O.configureReactiveObjectPolicy(this._reactivity,{owner:this,assertRead:()=>{this._assertAlive();const h=this._reactivity.getActiveOwner();h!==void 0&&h!==this&&this._throwCrossRuntime(h);const u=this._reactivity.getActiveConsumerOwner();u!==void 0&&this._assertImplicitDependency(this.rootScope,u)},assertWrite:()=>this._assertWriteAllowed(),runWrite:h=>this._runWrite(h),throwForeign:h=>{throw h instanceof A&&this._throwCrossRuntime(h),new v.RaphCrossRuntimeError("[Raph] Reactive object belongs to another reactivity engine.")}});const n=this._reactivity.signalForOwner(0,this.rootScope,"frame",!1);this._frameTickSignal=n,this.frameTick=this._workGraph.attachProducer(n,{get:()=>n.get(),peek:()=>n.peek()})}_getReactivity(){return this._reactivity}_getWorkGraph(){return this._workGraph}get id(){return this.configuration.id}get kernel(){return this.configuration.kernel}get disposed(){return this._disposed}get graph(){return this._parentGraph??=I.parentGraph()}get loopEnabled(){return this._frameLoop?.running??!1}get frame(){return this._phases?.frame??{now:0,delta:0,elapsed:0,frame:0}}get phases(){return this._phases?.phases??[]}get meta(){if(this._assertAlive(),this._meta!==void 0)return this._meta;const e=new N.RaphMeta(this.kernel,{assertReadable:()=>this._assertAlive(),assertWritable:()=>this._assertWriteAllowed(),runWrite:(t,s)=>this._runWrite(t,s)});return this._meta=Object.freeze({delete:e.delete.bind(e),get:e.get.bind(e),has:e.has.bind(e),merge:e.merge.bind(e),set:e.set.bind(e)})}getDerivedSnapshot(){return this.kernel.getDerivedSnapshot()}get debug(){return this._debug??=Object.freeze({snapshot:()=>this._createDebugSnapshot(),getTree:()=>this._createDebugTree(),stats:()=>this._createDebugStats(),trace:this._debugController.trace,machines:this._debugController.machines})}signal(e,t=this.rootScope){return this._assertOwnerRuntime(t),this._reactivity.signalForOwner(e,t)}reactive(e){return this._assertAlive(),this._reactivity.reactive(e)}computed(e,t=this.rootScope){this._assertOwnerRuntime(t);const s=this._workGraph.createProducer(t),r=typeof e=="function"?e:e.get,i=this._reactivity.computedForOwner(()=>this._runTracked(t,r),t,this._workGraph.producerHooks(s));if(this._workGraph.setProducerActivation(s,()=>{i.peek()}),typeof e=="function")return this._workGraph.attachProducer(s,i);const o=this._attachWritableComputed(i,e.set,t);return this._workGraph.attachProducer(s,o)}effect(e,t,s,r=S){return H(this._effectRegistration(e,t,s,r))}_effectRegistration(e,t,s,r=S,i=!1,o=!1,a,n){this._assertOwnerRuntime(e);const h=this._execution,u=this._validatePhaseBinding(h,t,s,r),c=h.bindTask(u,e,s,r.priority??0);o&&(c.state=f.TASK_ACTIVE|f.TASK_TASKLESS);const d=this._reactivity,_=r.initial==="sync",l=_&&this.configuration.scheduler!==w.RaphSchedulerType.Sync;let y="Effect registration and cleanup failed.",g=!1;try{i&&c.pause();const D=d._allocateTaskEffect(d._phaseBody,c);if(c.node=D,l&&h._queue(c,!1),g=!0,d._requestTaskEffect(D,!l),n?.())return c.dispose(),c;g=!1,y="[Raph] Resource registration and cleanup failed.",(c.state&f.TASK_ACTIVE)!==0&&c.node!==void 0?e._adoptRecord(c):(e._assertAlive(),c.dispose()),y="[Raph] Phase effect registration and rollback failed.",g=!0,_?this.flush():this._requestExecution(),n?.()&&c.dispose()}catch(D){this._rollbackRegistration(c,D,y,g?a:void 0)}return c}_effectGroupRegistration(e,t,s,r,i,o=S,a=!1){this._assertOwnerRuntime(e);const n=this._execution,h=r,u=this._validatePhaseBinding(n,t,h,o);if(!Number.isInteger(s)||s<1)throw new RangeError("[Raph] Effect group slot count must be a positive integer.");if(s>x)throw new RangeError(`[Raph] Effect group slot count must not exceed ${x}.`);const c=n.bindGroup(u,e,h,i,s,o.priority??0);try{a&&c.pause();const d=c.group,_=this._reactivity,l=_._phaseBody,y=f.GROUP_NODES+s;for(let g=f.GROUP_NODES;g<y;g++)d[g]=_._allocateTaskEffect(l,c);e._adoptRecord(c)}catch(d){this._rollbackRegistration(c,d,"[Raph] Resource registration and cleanup failed.")}return c}_startGroupSlot(e,t,s,r){const i=e.group;if(i===void 0){e.consumerOwner._assertAlive();return}const o=t>=0?i[f.GROUP_NODES+t]:void 0;if(o===void 0)throw new RangeError(`[Raph] Effect group has no slot ${String(t)}.`);if(s!=="scheduled"&&s!=="sync")throw new TypeError(`[Raph] Unsupported effect initial mode "${String(s)}".`);if(o===null||o.firstDep!==null)return;const a=e.phaseState.pipeline,n=s==="sync",h=n&&this.configuration.scheduler!==w.RaphSchedulerType.Sync;let u=!1;try{u=!0,this._reactivity._requestTaskEffect(o,!1),h?e.state&f.TASK_PENDING||a._queue(e,!1):e.schedule(),u=!1,e.state&(f.TASK_PENDING|f.TASK_REQUESTED)||e.consumerOwner._assertAlive(),n?a._running?this._executionRequested=!1:(u=!0,this.flush(),u=!1,e.state&f.TASK_ACTIVE||e.consumerOwner._assertAlive()):(u=!0,this._requestExecution())}catch(c){let d=c;try{this._reactivity._disposeTaskEffect(o)}catch(_){d=new AggregateError([c,_],"[Raph] Phase effect registration and rollback failed.")}throw u&&r!==void 0&&r(d),d}}watch(e,t,s,r,i=S){const o=this._watchRegistration(e,t,s,r,i).watch;return o===void 0?U:z(o)}_watchRegistration(e,t,s,r,i=S,o=!1,a,n){this._assertOwnerRuntime(e);const h=this._execution,u=this._validatePhaseBinding(h,s,r,i,!0);this._workGraph.assertSubscriptionAllowed(e,t);const c=h.bindTask(u,e,r,i.priority??0),d=W.createPhaseWatch(l=>this._runUntracked(l),c);c.watch=d,o&&c.pause();try{if(d.source=this._workGraph.subscribe(t,i.include,(l,y,g)=>d.record?.enqueue(l,y,g)),n?.())return c.dispose(),c}catch(l){throw c.dispose(),l}try{e._adoptRecord(c)}catch(l){this._rollbackRegistration(c,l,"[Raph] Resource registration and cleanup failed.")}const _=i.initial??"scheduled";try{_!=="none"&&c.schedule(),_==="sync"&&this.flush(),n?.()&&c.dispose()}catch(l){this._rollbackRegistration(c,l,"[Raph] Phase watch registration and rollback failed.",a)}return c}aggregate(e,t){return this._assertOwnerRuntime(e),this._workGraph.createAggregate(e,t)}metaSource(e,t={}){this._assertAlive(),V(e,t);const s=this._workGraph.createProducer(this.rootScope,"path"),r=this._workGraph.producerHooks(s).onDispose,i=L.RaphMetaSource._create(this.rootScope,e,t,()=>this.kernel._watchMeta(i.masks,({events:o})=>this._workGraph.notifyProducerEvents(s,o,!1),i.options,o=>{o&&this._execution.request()}),()=>r(!1));i._bindOwner(this.rootScope._adoptResource(()=>i._disposeOwned()));try{return this._workGraph.setProducerActivation(s,()=>i._activate(),!0),this._workGraph.attachProducer(s,i),i}catch(o){try{i.dispose()}catch(a){throw new AggregateError([o,a],"[Raph] Meta source activation and rollback failed.")}throw o}}path(e,t={}){this._assertAlive();const s=C.parseDataPath(e,t),r=this._pathHandles??=new Map,i=r.get(s.canonical);if(i!==void 0)return i;const o=this._workGraph.createProducer(this.rootScope,"path"),a=this._workGraph.producerHooks(o),n=new M.PathHandle(this.kernel,s,t,h=>this._releasePathHandle(h),this._reactivity,()=>this._assertAlive(),()=>this._assertTrackedRead(),this.configuration.enforceActions?()=>this._assertWriteAllowed():void 0,h=>this._runWrite(h),{token:o,onDispose:a.onDispose},({events:h},u)=>this._workGraph.notifyProducerEvents(o,h,!0,u));try{return this._workGraph.setProducerActivation(o,()=>n._activate(),!0),this._workGraph.attachProducer(o,n),r.set(s.canonical,n),n}catch(h){let u,c=!1;try{n.dispose()}catch(d){c=!0,u=d}throw r.size===0&&this._pathHandles===r&&(this._pathHandles=void 0),c?new AggregateError([h,u],"[Raph] Path source activation and rollback failed."):h}}get(e,t){this._assertTrackedRead();const s=e??"";return this._reactivity._isTracking()?this.path(s,t)._getTracked():this.kernel.get(s,t)}peek(e,t){return this._assertAlive(),this.kernel.peek(e??"",t)}has(e,t){return this._assertAlive(),this.kernel.has(e,t)}set(e,t,s){this._assertWriteAllowed(),this._runWrite(()=>this.kernel.set(e,t,s))}merge(e,t,s){this._assertWriteAllowed(),this._runWrite(()=>this.kernel.merge(e,t,s))}delete(e,t){this._assertWriteAllowed(),this._runWrite(()=>this.kernel.delete(e,t))}batch(e){return this._batch(e,!0)}_batchReactive(e){return this._batch(e,!1)}_batch(e,t){this._assertAlive(),this._batchDepth++;let s,r,i=!1;try{s=this._reactivity.batch(()=>t?this.kernel.batch(e):e())}catch(o){i=!0,r=o}return this._closeBatch(i,r),s}_closeBatch(e,t){if(this._batchDepth--,this._executionBoundaryOpen()){if(e)throw t;return}const s=this._finishExecutionBoundary();if(e)throw s!==void 0?new AggregateError([t,...s],"[Raph] Batch and scheduled phase execution failed."):t;s!==void 0&&b.throwDisposalErrors(s,"[Raph] Batch phase execution failed.")}_applyBatch(e,t){this._assertAlive();const s=this.kernel,r=s._openSoleRuntimeBatch(this);if(r===void 0)return this._batch(()=>this._runUntracked(()=>e(...t)),!0);const i=this._reactivity;this._batchDepth++,i._startBatch();let o,a,n=!1;try{o=i._applyUntrackedWithOwner(e,t)}catch(h){n=!0,a=h}try{s._closeSoleRuntimeBatch(this,r,n,a)}catch(h){n=!0,a=h}try{i._endBatch()}catch(h){a=n?new AggregateError([a,h],"Batch operation and effect queue processing failed."):h,n=!0}return this._closeBatch(n,a),o}action(e,t,s){const r=typeof e=="function"?e:t,i=typeof e=="function"?t instanceof E.RaphScope?t:this.rootScope:s??this.rootScope,o=typeof e=="string"?e:`action#${++this._actionCounter}`;if(this._assertOwnerRuntime(i),typeof r!="function")throw new TypeError("[Raph] Action operation must be a function.");if(!o.trim())throw new Error("[Raph] Action name must not be empty.");return(...a)=>{i._assertAlive();const n=this._debugController,h=this._traceCauseStack,u=n.nextOperationId("action"),d=(h.length===0?void 0:h[h.length-1])??u;n.traces("action")&&n.record({...d===void 0?{}:{causeId:d},kind:"action",name:o,...u===void 0?{}:{operationId:u},status:"start"}),d!==void 0&&h.push(d),this._actionDepth++;try{const _=this._applyBatch(r,a);return n.traces("action")&&n.record({...d===void 0?{}:{causeId:d},kind:"action",name:o,...u===void 0?{}:{operationId:u},status:"end"}),_}catch(_){throw this._debugController.record({...d===void 0?{}:{causeId:d},details:{message:T(_)},kind:"action",name:o,...u===void 0?{}:{operationId:u},status:"error"}),this._debugController.record({...d===void 0?{}:{causeId:d},details:{message:T(_)},kind:"error",name:`action:${o}`,...u===void 0?{}:{operationId:u},status:"error"}),_}finally{this._actionDepth--,d!==void 0&&h.pop()}}}untracked(e){return this._assertAlive(),this._runUntracked(e)}scope(e){return this._assertAlive(),new E.RaphScope(e,this)}node(e,t){this._assertAlive(),this._enterWrite();let s;try{s=this._createCommittedNode(e,t)}catch(r){throw this._failWrite(r)}return this._exitWrite(),s._assertAlive(),s}_createCommittedNode(e,t){const s=e.parent??this.root,r=m.createProvisionalNode(s,e,this);try{const i=t?.(r);return r._assertAlive(),s._assertAlive(),r._setApi(i),r._publishCreation(),r}catch(i){try{r.dispose()}catch(o){throw new AggregateError([i,o],`[Raph] Node "${r.id}" setup and cleanup failed.`)}throw i}}getNode(e){return this._assertAlive(),this.root._findNode(e)}definePhases(e){this._execution.definePhases(e)}addPhase(e){this._execution.addPhase(e)}clearPhases(){this._assertAlive(),this._phases?.clearPhases()}requestExecution(){this._assertAlive(),this._phases?.request()}flush(){this._assertAlive(),this._executionRequested=!1,this._phases?.flush()}afterFlush(){return this._assertAlive(),this._phases?.afterFlush()??Promise.resolve()}acquireLoop(e){return this._assertAlive(),this._clock.acquire(e)}startLoop(){this._assertAlive(),this._clock.start()}stopLoop(){this._frameLoop?.stop()}derive(e){this._assertAlive();const t=e.compute,s=this.kernel.derive({...e,compute:r=>this._runUntracked(()=>t(r))});return this._own(()=>s.dispose(),this.rootScope),s}dispose(){if(this._disposed)return;this._disposed=!0,this._executionRequested=!1,this._signalLifecycle.owner=void 0;const e=[];try{this._frameLoop?.dispose()}catch(a){e.push(a)}this._frameLoop=void 0;try{this._phases?.dispose()}catch(a){e.push(a)}this._phases=void 0;try{this.root.dispose()}catch(a){e.push(a)}const t=this._collectOwners().sort(j);for(const a of t)if(!(a===this.root||a===this.rootScope||a.disposed))try{a.dispose()}catch(n){e.push(n)}try{this.rootScope.dispose()}catch(a){e.push(a)}const s=`[Raph] Runtime "${this.id}" is disposed.`,r=()=>{throw new v.RaphDisposedError(s)};try{O.disposeReactiveObjectContext(this._reactivity,{assertRead:r,assertWrite:r,throwForeign:r})}catch(a){e.push(a)}this._topOwners.clear(),this._ownersReleased=!0,this._meta=void 0;const i=this._pathHandles;if(this._pathHandles=void 0,i!==void 0){for(const a of i.values())try{a.dispose()}catch(n){e.push(n)}i.clear()}try{this._workGraph.dispose()}catch(a){e.push(a)}try{this.kernel._detachRuntime(this)}catch(a){e.push(a)}const o=[...this._disposedListeners];this._disposedListeners.clear();for(const a of o)try{a()}catch(n){e.push(n)}b.throwDisposalErrors(e,`[Raph] Runtime "${this.id}" disposal failed.`)}_onDisposed(e){return this._disposed?(e(),()=>{}):(this._disposedListeners.add(e),()=>{this._disposedListeners.delete(e)})}_notifyNodeStructure(e,t,s,r){if(!this._workGraph._hasStructuralDemand(e)){this._touchMutationBoundary();return}this._runNodeMutation(()=>{this._workGraph.notifyNode(e,"structure",{structure:t,oldAncestors:s,newAncestors:r})})}_hasNodeStructureDemand(e){return this._workGraph._hasStructuralDemand(e)}_hasNodeSubscribers(){return this._workGraph._hasNodeSubscribers()}_notifyNodeTouch(e,t){this._runNodeMutation(()=>this._workGraph.notifyNode(e,"touch",{metadata:t}))}_assertNodeReparentAllowed(e,t){this._workGraph.assertReparentAllowed(e,t)}_releaseNode(e){this._workGraph.releaseNode(e)}_runNodeMutation(e){return this._runWrite(e)}_touchMutationBoundary(){if(this.configuration.scheduler===w.RaphSchedulerType.Sync&&(this._executionRequested=!0),this._executionBoundaryOpen())return;const e=this._finishExecutionBoundary();e!==void 0&&b.throwDisposalErrors(e,"[Raph] Mutation phase execution failed.")}_runPhaseTransition(e){return this._runWrite(e,!1)}_beginOwnerDisposal(e){this._disposingNodes[this._ownerDisposalDepth++]=e}_endOwnerDisposal(){const e=this._ownerDisposalDepth;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())}_ownerDisposalCount(){return this._ownerDisposals}_addDisposalSweeper(e,t){const s=this._disposalSweepers;if(s===void 0){e._sweepSlot=0,e._sweepDue=t,this._disposalSweepers=[e],this._nextDisposalSweep=t;return}k.enqueueSweeper(s,e,t),this._nextDisposalSweep=s[0]._sweepDue}_removeDisposalSweeper(e){const t=this._disposalSweepers;t===void 0||!k.dequeueSweeper(t,e)||(t.length===0?(this._disposalSweepers=void 0,this._nextDisposalSweep=Number.POSITIVE_INFINITY):this._nextDisposalSweep=t[0]._sweepDue)}_sweepAfterDisposals(){const e=this._disposalSweepers;if(e===void 0)return;const t=this._ownerDisposals;if(e.length===1){const s=e[0],r=s._afterOwnerDisposals(t);r>t?(s._sweepDue=r,this._nextDisposalSweep=r):(s._sweepSlot=-1,this._disposalSweepers=void 0,this._nextDisposalSweep=Number.POSITIVE_INFINITY);return}for(let s=e[0];s._sweepDue<=t;s=e[0]){const r=s._afterOwnerDisposals(t);if(r>t)k.postponeFirstSweeper(e,r);else if(k.dequeueSweeper(e,s),e.length===0){this._disposalSweepers=void 0,this._nextDisposalSweep=Number.POSITIVE_INFINITY;return}}this._nextDisposalSweep=e[0]._sweepDue}_ownerDisposalActive(){return this._ownerDisposalDepth!==0}_registerOwner(e){return this._assertAlive(),e._isNode||this._topOwners.add(e),++this._ownerRegistrations}_unregisterOwner(e){e._isNode||this._topOwners.delete(e),this._ownerDisposals++}_addTopOwner(e){this._topOwners.add(e)}_removeTopOwner(e){this._topOwners.delete(e)}_assertOwnerRuntime(e){if(this._assertAlive(),e.runtime!==this)throw new v.RaphCrossRuntimeError("[Raph] Owner belongs to another runtime.");e._assertAlive()}_beginKernelBatch(){this._disposed||this._kernelBatchDepth++}_endKernelBatch(){this._kernelBatchDepth!==0&&(this._kernelBatchDepth--,this._clearTransientCausesIfSettled(),this._disposed||this._requestExecution())}_registerMachineDebug(e){return this._assertAlive(),this._debugController.registerMachine(e)}_hasMachineDebug(e){return this._debugController.hasMachine(e)}_traces(e){return this._debugController.traces(e)}_currentTraceCauseId(){return this._traceCauseStack.at(-1)}_nextTraceOperation(e){return this._debugController.nextOperationId(e)}_hasActiveReactiveContext(){return this._assertAlive(),this._reactivity.hasActiveContext()}_recordTrace(e){this._debugController.record(e)}_runWithTraceCause(e,t){if(e===void 0)return t();this._traceCauseStack.push(e);try{return t()}finally{this._traceCauseStack.pop()}}_validatePhaseBinding(e,t,s,r,i=!1){if(typeof s!="function")throw new TypeError("[Raph] Phase callback must be a function.");const o=e.resolvePhase(t),a=r.priority??0;if(!Number.isFinite(a))throw new TypeError("[Raph] Effect priority must be finite.");const n=r.initial??"scheduled";if(n!=="scheduled"&&n!=="sync"&&!(i&&n==="none"))throw new TypeError(`[Raph] Unsupported effect initial mode "${String(n)}".`);return o}_rollbackRegistration(e,t,s,r){let i=t;try{e.dispose()}catch(o){i=new AggregateError([t,o],s)}throw r!==void 0&&r(i),i}_createDebugSnapshot(){const e=this._frameLoop?._debugState()??{running:!1,manual:!1,leases:0},t=[...this._topOwners].filter(s=>s!==this.rootScope&&!(s instanceof m.RaphNode)).map(R.createOwnerSnapshot);return Object.freeze({id:this.id,disposed:this._disposed,pending:!this._disposed&&(this._executionRequested||(this._phases?._debugPending()??!1)),batchDepth:this._batchDepth,kernelBatchDepth:this._kernelBatchDepth,owners:this._liveOwnerCount(),pathHandles:this._pathHandles?.size??0,rootScope:R.createOwnerSnapshot(this.rootScope),scopes:Object.freeze(t),root:R.createOwnerSnapshot(this.root),frameLoop:Object.freeze(e),actionDepth:this._actionDepth,machines:this._debugController.machineCount,traceEvents:this._debugController.traceSize})}_createDebugTree(){const e=this._debugController.machineTreeNodesByOwner(),t=[R.createOwnerTree(this.rootScope,e),R.createOwnerTree(this.root,e),...[...this._topOwners].filter(s=>s!==this.rootScope&&s!==this.root&&!(s instanceof m.RaphNode)).map(s=>R.createOwnerTree(s,e))];return Object.freeze({children:Object.freeze(t),disposed:this._disposed,id:this.id,kind:"runtime"})}_createDebugStats(){const e=this._liveOwnerCount();let t=0;const s={resources:0,sources:0};if(!this._ownersReleased){const r=this._topOwners;for(const a of r)a._isNode?a._countSubtree(s):(t++,s.resources+=a._debugResourceCount(),s.sources+=a._debugSourceCount());const i=this._disposingNodes,o=this._ownerDisposalDepth;for(let a=0;a<o;a++){const n=i[a];n===void 0||n._isLinked()||r.has(n)||n._countSubtree(s)}}return Object.freeze({actors:this._debugController.actorCount,machines:this._debugController.machineCount,nodes:e-t,owners:e,pathHandles:this._pathHandles?.size??0,pending:!this._disposed&&(this._executionRequested||(this._phases?._debugPending()??!1)),resources:s.resources,scopes:t,sources:s.sources,traceEvents:this._debugController.traceSize})}_liveOwnerCount(){return this._ownersReleased?0:this._ownerRegistrations-this._ownerDisposals}_collectOwners(){const e=[];if(this._ownersReleased)return e;const t=this._topOwners;for(const i of t)e.push(i),i._isNode&&i._collectDescendants(e);const s=this._disposingNodes,r=this._ownerDisposalDepth;for(let i=0;i<r;i++){const o=s[i];o===void 0||o._isLinked()||t.has(o)||(e.push(o),o._collectDescendants(e))}return e}_releasePathHandle(e){const t=this._pathHandles;t?.get(e.path)===e&&(t.delete(e.path),t.size===0&&(this._pathHandles=void 0))}get _execution(){return this._assertAlive(),this._phases??=new B.RaphPhasePipeline(this.configuration.scheduler,this._reactivity,e=>this._workGraph.causeForToken(e),()=>{const e=this._mutationDepth!==0||this._batchDepth!==0||this._kernelBatchDepth!==0||this._ownerDisposalDepth!==0||this._reactivity._isFlushingEffects();return e&&this.configuration.scheduler===w.RaphSchedulerType.Sync&&(this._executionRequested=!0),e},(e,t,s)=>{if(this._phaseTraceOperations===void 0&&!this._debugController.traces("phase"))return;let r;t==="start"?(r=this._debugController.nextOperationId("phase"),r!==void 0&&(this._phaseTraceOperations??=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({...r===void 0?{}:{causeId:r},...s===void 0?{}:{details:{message:T(s)}},kind:"phase",name:e,...r===void 0?{}:{operationId:r},status:t})})}get _clock(){return this._frameLoop??=new G.RaphFrameLoop(()=>this._tickFrameLoop())}_tickFrameLoop(){this._disposed||this._setFrameTick(this._frameTickSignal.peek()+1)}_setFrameTick(e){this._enterWrite();try{this._frameTickSignal._writeInBoundary(e)}catch(t){throw this._failWrite(t)}this._exitWrite()}_attachWritableComputed(e,t,s){let r=t;this._own(()=>{r=void 0},s);const i=e;return i.set=o=>{s._assertAlive(),this._assertWriteAllowed(),this._runWrite(()=>r(o))},i}_own(e,t){try{return t._adoptResource(e)}catch(s){try{e()}catch(r){throw new AggregateError([s,r],"[Raph] Resource registration and cleanup failed.")}throw s}}_runTracked(e,t){return this._reactivity.runWithOwner(this._signalLifecycle,e,t)}_runUntracked(e){return this._reactivity.untrackedWithOwner(e)}_runWrite(e,t=!0){t&&this.configuration.scheduler===w.RaphSchedulerType.Sync&&(this._executionRequested=!0),this._mutationDepth++;let s,r,i=!1;try{s=e()}catch(a){i=!0,r=a}if(this._mutationDepth--,this._executionBoundaryOpen()){if(i)throw r;return s}const o=this._finishExecutionBoundary();if(i)throw o!==void 0?new AggregateError([r,...o],"[Raph] Mutation and scheduled phase execution failed."):r;return o!==void 0&&b.throwDisposalErrors(o,"[Raph] Mutation phase execution failed."),s}_enterWrite(){this.configuration.scheduler===w.RaphSchedulerType.Sync&&(this._executionRequested=!0),this._mutationDepth++}_exitWrite(){if(this._mutationDepth--,this._executionBoundaryOpen())return;const e=this._finishExecutionBoundary();e!==void 0&&b.throwDisposalErrors(e,"[Raph] Mutation phase execution failed.")}_failWrite(e){if(this._mutationDepth--,this._executionBoundaryOpen())return e;const t=this._finishExecutionBoundary();return t===void 0?e:new AggregateError([e,...t],"[Raph] Mutation and scheduled phase execution failed.")}_executionBoundaryOpen(){return this._mutationDepth!==0||this._batchDepth!==0||this._kernelBatchDepth!==0||this._ownerDisposalDepth!==0}_finishExecutionBoundary(){let e;try{this._clearTransientCausesIfSettled()}catch(t){e=[t]}try{this._requestExecution()}catch(t){e===void 0?e=[t]:e.push(t)}return e}_clearTransientCausesIfSettled(){this._mutationDepth===0&&this._batchDepth===0&&this._kernelBatchDepth===0&&this._ownerDisposalDepth===0&&!this._reactivity._isFlushingEffects()&&this._workGraph.clearTransientCauses()}_requestExecution(){this._disposed||this.configuration.scheduler!==w.RaphSchedulerType.Sync||this._mutationDepth!==0||this._batchDepth!==0||this._kernelBatchDepth!==0||this._ownerDisposalDepth!==0||this._reactivity._isFlushingEffects()||this._executionRequested&&(this._executionRequested=!1,this._phases?.flush())}_assertTrackedRead(){this._assertAlive();const e=this._reactivity.getActiveOwner();e!==void 0&&e!==this&&this._throwCrossRuntime(e);const t=this._reactivity.getActiveConsumerOwner();t!==void 0&&this._assertImplicitDependency(this.rootScope,t)}_assertSourceReadable(e){this._assertAlive();const t=this._reactivity.getActiveOwner();t!==void 0&&t!==this&&this._throwCrossRuntime(t);const s=this._reactivity.getActiveConsumerOwner();s!==void 0&&this._assertImplicitDependency(e,s),e._assertAlive()}_assertImplicitDependency(e,t){if(e.runtime!==this||t.runtime!==this)throw new v.RaphCrossRuntimeError("[Raph] Implicit dependency crosses runtime boundaries.");if(!(e===this.rootScope||e===t)){if(e instanceof m.RaphNode&&t instanceof m.RaphNode){for(let s=t.parent;s!==null;s=s.parent)if(s===e)return}throw new Error(`[Raph] Implicit dependency from "${t.id}" to "${e.id}" is not allowed; use watch().`)}}_assertWriteAllowed(){if(this._assertAlive(),this.configuration.enforceActions&&this._batchDepth===0)throw new v.RaphActionError("[Raph] Writes are allowed only inside action() or batch().")}_throwCrossRuntime(e){throw new v.RaphCrossRuntimeError(`[Raph] Runtime "${this.id}" cannot be tracked by runtime "${e.id}".`)}_assertAlive(){if(this._disposed)throw new v.RaphDisposedError(`[Raph] Runtime "${this.id}" is disposed.`)}}function H(p){let e=p;return()=>{const t=e;t!==void 0&&(e=void 0,t.dispose())}}function z(p){return()=>{p.record?.dispose()}}function U(){}function j(p,e){return e._order-p._order}function K(p){return p===w.RaphSchedulerType.Sync||p===w.RaphSchedulerType.Microtask||p===w.RaphSchedulerType.AnimationFrame}function V(p,e){const t=Array.isArray(p)?p:[p];if(t.length===0)throw new TypeError("[RaphMeta] watch requires at least one mask.");if(e.namespace!==void 0&&!e.namespace.trim())throw new Error("[RaphMeta] namespace must not be empty.");for(const s of t)P.DataPath.from(s,e)._asMask()}function T(p){return p instanceof Error?p.message:String(p)}exports.RaphRuntime=A;