@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,30 +1,45 @@
1
- var D = Object.defineProperty;
2
- var A = (l, e, s) => e in l ? D(l, e, { enumerable: !0, configurable: !0, writable: !0, value: s }) : l[e] = s;
3
- var d = (l, e, s) => A(l, typeof e != "symbol" ? e + "" : e, s);
4
- import { RaphPhaseProcessError as g, RaphDisposedError as P } from "../errors.js";
5
- const m = Object.freeze([]), q = Object.freeze({ now: 0, delta: 0, elapsed: 0, frame: 0 }), x = 1e4, K = 1e4, O = Symbol("RaphPhaseTaskRecord");
6
- class R {
7
- constructor(e, s, t, i = () => !1, n) {
8
- d(this, "_phases", []);
9
- d(this, "_phaseByName", /* @__PURE__ */ new Map());
10
- d(this, "_phaseBindings", /* @__PURE__ */ new Map());
11
- d(this, "_queues", /* @__PURE__ */ new Map());
12
- d(this, "_deferred", /* @__PURE__ */ new Set());
13
- d(this, "_idleWaiters", /* @__PURE__ */ new Set());
14
- d(this, "_taskSequence", 0);
15
- d(this, "_scheduled", !1);
16
- d(this, "_scheduleToken", 0);
17
- d(this, "_frameHandle");
18
- d(this, "_frameHandleKind");
19
- d(this, "_configurationLocked", !1);
20
- d(this, "_running", !1);
21
- d(this, "_disposed", !1);
22
- d(this, "_firstFrameAt");
23
- d(this, "_lastFrameAt");
24
- d(this, "_frameNumber", 0);
25
- d(this, "_frame", q);
26
- this._scheduler = e, this._runUntracked = s, this._resolveCause = t, this._deferSync = i, this._tracePhase = n;
1
+ import { RaphPhaseProcessError as R, RaphDisposedError as I } from "../errors.js";
2
+ import { throwDisposalErrors as z } from "../ownership/throwDisposalErrors.js";
3
+ import { EMPTY_FRAME as B, RaphPhaseTaskRecord as $, GROUP_NODES as y, GROUP_CONTEXT as M, GROUP_CURSOR as N, TASK_ACTIVE as f, TASK_TASKLESS as G, TASK_PENDING as w, TASK_RESOLUTION as b, TASK_UNRESOLVED as j, TASK_CANCEL as m, TASK_RUN as q, TASK_IN_DELIVERY as p, TASK_CAUSES_DELIVERED as k, TASK_EXECUTED as H, TASK_PAUSED as A, TASK_REQUESTED as g, TASK_DEFER as W, TASK_DISCARD_ACKNOWLEDGED as C, TASK_DEFERRED as E } from "./RaphPhaseTaskRecord.js";
4
+ class Q {
5
+ constructor(e, t) {
6
+ this.name = e, this.pipeline = t, this.queue = [], this.spare = [], this.bindings = 0;
27
7
  }
8
+ }
9
+ const V = 1e4, X = 1e4, P = f | A, x = p | b;
10
+ class te {
11
+ constructor(e, t, s, i = () => !1, a) {
12
+ this._scheduler = e, this._reactivity = t, this._resolveCause = s, this._deferSync = i, this._tracePhase = a;
13
+ }
14
+ _phases = [];
15
+ _phaseByName = /* @__PURE__ */ new Map();
16
+ // Последнее разрешённое имя phase в том виде, в каком его передал вызывающий.
17
+ _resolvedInput;
18
+ _resolvedState;
19
+ // Число записей во всех живых очередях.
20
+ _queuedCount = 0;
21
+ _deferred = /* @__PURE__ */ new Set();
22
+ _idleWaiters = /* @__PURE__ */ new Set();
23
+ _taskSequence = 0;
24
+ _scheduled = !1;
25
+ _scheduleToken = 0;
26
+ _frameHandle;
27
+ _frameHandleKind;
28
+ _configurationLocked = !1;
29
+ /**
30
+ * Flush исполняется сейчас: новая работа попадёт в его следующий проход.
31
+ *
32
+ * @internal
33
+ */
34
+ _running = !1;
35
+ // Значение flags записи slot, которая не запланирована: slot с таким же
36
+ // значением доставка группы пропускает, не обращаясь к engine.
37
+ _idleSlotFlags = -1;
38
+ _disposed = !1;
39
+ _firstFrameAt;
40
+ _lastFrameAt;
41
+ _frameNumber = 0;
42
+ _frame = B;
28
43
  get frame() {
29
44
  return this._frame;
30
45
  }
@@ -34,22 +49,26 @@ class R {
34
49
  definePhases(e) {
35
50
  if (this._assertAlive(), this._configurationLocked || this._firstFrameAt !== void 0)
36
51
  throw new Error("[Raph] Cannot redefine phases after phase pipeline execution has started.");
37
- const s = /* @__PURE__ */ new Map(), t = [];
38
- for (const i of e) {
39
- const n = i.name.trim();
52
+ const t = this._phaseByName, s = /* @__PURE__ */ new Map(), i = [];
53
+ for (const a of e) {
54
+ const n = a.name.trim();
40
55
  if (!n)
41
56
  throw new Error("[Raph] Phase name must not be empty.");
42
57
  if (s.has(n))
43
58
  throw new Error(`[Raph] Duplicate phase name "${n}".`);
44
- if (i.process !== void 0 && typeof i.process != "function")
59
+ if (a.process !== void 0 && typeof a.process != "function")
45
60
  throw new TypeError(`[Raph] Phase "${n}" process must be a function.`);
46
- const a = Object.freeze({
61
+ const o = Object.freeze({
47
62
  name: n,
48
- ...i.process === void 0 ? {} : { process: i.process }
49
- }), r = { index: t.length, phase: a };
50
- t.push(r), s.set(n, r);
63
+ ...a.process === void 0 ? {} : { process: a.process }
64
+ }), r = {
65
+ index: i.length,
66
+ phase: o,
67
+ state: t.get(n)?.state ?? new Q(n, this)
68
+ };
69
+ i.push(r), s.set(n, r);
51
70
  }
52
- this._assertRetainedPhases(s), this._phases = t, this._phaseByName = s;
71
+ this._assertRetainedPhases(s), this._phases = i, this._phaseByName = s, this._resolvedInput = void 0, this._resolvedState = void 0;
53
72
  }
54
73
  addPhase(e) {
55
74
  this.definePhases([...this.phases, e]);
@@ -57,164 +76,160 @@ class R {
57
76
  clearPhases() {
58
77
  this.definePhases([]);
59
78
  }
60
- requirePhase(e) {
61
- if (this._assertAlive(), !this._phaseByName.has(e))
62
- throw new Error(`[Raph] Phase "${e}" is not defined.`);
63
- }
64
- bindTask(e, s, t, i, n) {
65
- const a = e.trim();
66
- if (this.requirePhase(a), !Number.isFinite(i))
67
- throw new TypeError("[Raph] Effect priority must be finite.");
68
- this._phaseBindings.set(a, (this._phaseBindings.get(a) ?? 0) + 1);
69
- const r = {}, h = this._createTask(r);
70
- Object.assign(r, {
71
- active: !0,
72
- paused: !1,
73
- pending: !1,
74
- deferred: !1,
75
- inDelivery: !1,
76
- discardAcknowledged: !1,
77
- requested: !1,
78
- resolution: "unresolved",
79
- deferCount: 0,
80
- sequence: 0,
81
- phase: a,
82
- priority: i,
83
- consumerOwner: s,
84
- effect: t,
85
- runner: n,
86
- task: h,
87
- deliveryCauses: m,
88
- frame: q
89
- });
90
- const f = {
91
- dependencyOwner: s,
92
- allowScheduleDuringRun: !0,
93
- task: h,
94
- notify: (o) => {
95
- const _ = this._resolveCause(o);
96
- if (_ !== void 0) {
97
- const c = _.kind === "structure" ? _.source : o;
98
- this._appendCause(r, _, c);
99
- }
100
- },
101
- schedule: () => this._queue(r),
102
- enqueue: (o, _ = o.source, c = !0) => {
103
- this._appendCause(r, o, _), this._queue(r, c);
104
- },
105
- pause: () => this._pauseTask(r),
106
- resume: () => this._resumeTask(r),
107
- dispose: () => this._disposeTask(r)
108
- };
109
- return r.binding = f, f;
79
+ /**
80
+ * Находит состояние объявленной phase по имени, которое передал вызывающий.
81
+ * Подряд идущие bindings одной phase попадают в кэш из одной записи; точное
82
+ * имя находится без `trim()`, и только имя с пробелами по краям нормализуется.
83
+ */
84
+ resolvePhase(e) {
85
+ this._assertAlive();
86
+ const t = this._resolvedState;
87
+ if (t !== void 0 && e === this._resolvedInput)
88
+ return t;
89
+ let s = this._phaseByName.get(e);
90
+ if (s === void 0) {
91
+ const i = e.trim();
92
+ if (i !== e && (s = this._phaseByName.get(i)), s === void 0)
93
+ throw new Error(`[Raph] Phase "${i}" is not defined.`);
94
+ }
95
+ return this._resolvedInput = e, this._resolvedState = s.state;
96
+ }
97
+ /**
98
+ * Создаёт постоянную запись одного binding. Вызывающий уже разрешил phase
99
+ * и проверил priority, поэтому горячий путь регистрации проверяет их один раз.
100
+ * Запись ничего не выполняет, пока вызывающий не подключит engine effect
101
+ * (`node`) или watch lifecycle (`watch`).
102
+ */
103
+ bindTask(e, t, s, i) {
104
+ return e.bindings++, new $(e, i, t, s);
105
+ }
106
+ /**
107
+ * Создаёт постоянную запись группы из `count` slots: одна запись binding и
108
+ * её состояние с местом под запись графа каждого slot. Вызывающий уже
109
+ * разрешил phase и проверил priority и `count`; записи графа он подключает
110
+ * сам через _allocateTaskEffect() и кладёт в состояние по порядку slots.
111
+ * Slot ничего не исполняет, пока его запись не запланирована.
112
+ *
113
+ * `runSlot` занимает место callback записи: его показывает `task.effect`
114
+ * группы, а вызывает только общее тело записей engine — с состоянием
115
+ * группы, где лежат её context и номер slot. Поэтому запись группы несёт
116
+ * `TASK_TASKLESS`: вместо task тело получает поле `group`.
117
+ */
118
+ bindGroup(e, t, s, i, a, n) {
119
+ const o = new Array(y + a);
120
+ o[M] = i, o[N] = 0, e.bindings++;
121
+ const r = new $(e, n, t, s);
122
+ return r.state = f | G, r.group = o, r;
110
123
  }
111
124
  request() {
112
- this._assertAlive(), this._hasQueued() && this._schedule();
125
+ this._assertAlive(), this._queuedCount !== 0 && this._schedule();
113
126
  }
114
127
  afterFlush() {
115
- return this._assertAlive(), !this._running && !this._scheduled && !this._hasPending() ? Promise.resolve() : new Promise((e, s) => {
116
- this._idleWaiters.add({ reject: s, resolve: e });
128
+ return this._assertAlive(), !this._running && !this._scheduled && !this._hasPending() ? Promise.resolve() : new Promise((e, t) => {
129
+ this._idleWaiters.add({ reject: t, resolve: e });
117
130
  });
118
131
  }
119
132
  flush() {
120
- var n, a, r;
121
133
  if (this._assertAlive(), this._cancelScheduled(), this._running)
122
134
  return;
123
- if (!this._hasQueued() && this._deferred.size !== 0 && this._activateDeferred(), !this._hasQueued()) {
135
+ if (this._queuedCount === 0 && this._deferred.size !== 0 && this._activateDeferred(), this._queuedCount === 0) {
124
136
  this._settleIdleWaiters(void 0, !1);
125
137
  return;
126
138
  }
127
139
  this._configurationLocked = !0, this._running = !0;
128
- const e = [], s = this._nextFrame();
129
- let t = 0;
140
+ const e = [], t = this._nextFrame();
141
+ let s = 0, i;
130
142
  try {
131
- for (; this._hasQueued(); ) {
132
- if (++t > x) {
133
- const h = this._describeQueued();
134
- this._cancelAllQueued(!0, e), e.push(new Error(`[Raph] Phase flush exceeded 10000 passes.${h ? ` Pending: ${h}.` : ""}`));
143
+ for (; this._queuedCount !== 0; ) {
144
+ if (++s > V) {
145
+ const n = this._describeQueued();
146
+ this._cancelAllQueued(!0, e), e.push(new Error(`[Raph] Phase flush exceeded 10000 passes.${n ? ` Pending: ${n}.` : ""}`));
135
147
  break;
136
148
  }
137
- for (const h of this._phases) {
149
+ for (const n of this._phases) {
138
150
  if (this._disposed)
139
151
  break;
140
- const f = this._takePhase(h.phase.name);
141
- if (f.length === 0)
152
+ const o = n.state, r = o.queue;
153
+ if (r.length === 0)
142
154
  continue;
143
- const o = e.length;
144
- (n = this._tracePhase) == null || n.call(this, h.phase.name, "start");
145
- let _ = 0, c = !0, p;
146
- for (const u of f) {
147
- if (u.pending = !1, !u.active || u.consumerOwner.disposed) {
148
- this._disposeTask(u);
155
+ o.queue = o.spare, o.spare = i = r, this._queuedCount -= r.length;
156
+ const d = e.length;
157
+ this._tracePhase?.(n.phase.name, "start");
158
+ let l = 0, _ = !0, c;
159
+ for (const u of r) {
160
+ const v = u.state;
161
+ if (!(v & f) || u.consumerOwner.disposed) {
162
+ u.state = v & ~w, this._disposeTask(u);
149
163
  continue;
150
164
  }
151
- this._beginDelivery(u, s), p !== void 0 && (u.priority > p.priority || u.priority === p.priority && u.sequence < p.sequence) && (c = !1), p = u, f[_++] = u;
165
+ this._beginDelivery(u, t), c !== void 0 && (u.priority > c.priority || u.priority === c.priority && u.sequence < c.sequence) && (_ = !1), c = u, r[l++] = u;
152
166
  }
153
- if (f.length = _, f.length === 0)
167
+ if (r.length = l, r.length === 0) {
168
+ i = void 0;
154
169
  continue;
155
- c || f.sort(T);
156
- const k = h.phase.process;
157
- if (k === void 0)
158
- for (const u of f)
170
+ }
171
+ _ || r.sort(Y);
172
+ const D = n.phase.process;
173
+ if (D === void 0)
174
+ for (const u of r)
159
175
  try {
160
- this._runDelivery(u);
176
+ this._runDelivery(u, e);
161
177
  } catch (v) {
162
178
  e.push(v);
163
179
  }
164
180
  else {
165
181
  const u = [];
166
- for (const w of f)
167
- u.push(w.task);
182
+ for (const K of r)
183
+ u.push(K.task);
168
184
  const v = Object.freeze({
169
- phase: h.phase.name,
170
- frame: s,
185
+ phase: n.phase.name,
186
+ frame: t,
171
187
  tasks: Object.freeze(u)
172
188
  });
173
189
  try {
174
- this._runUntracked(() => k(v));
175
- } catch (w) {
176
- e.push(w);
190
+ this._reactivity.untrackedWithOwner(() => D(v));
191
+ } catch (K) {
192
+ e.push(K);
177
193
  }
178
194
  }
179
- let y = 0;
180
- for (const u of f) {
181
- if (u.resolution === "unresolved") {
182
- y++;
195
+ let T = 0;
196
+ for (const u of r) {
197
+ if ((u.state & b) === j) {
198
+ T++;
183
199
  try {
184
200
  this._deferDelivery(u);
185
201
  } catch (v) {
186
- u.resolution = "cancel", this._acknowledgeDiscard(u, !0, e), e.push(v);
202
+ u.state |= m, this._acknowledgeDiscard(u, !0, e), e.push(v);
187
203
  }
188
204
  }
189
205
  try {
190
206
  this._finishDelivery(u);
191
207
  } catch (v) {
192
- u.resolution !== "run" && this._acknowledgeDiscard(u, !0, e), u.resolution = "cancel", u.inDelivery = !1, u.deliveryFirstCauseKey = void 0, u.deliveryExtraCauseKeys = void 0, u.deliveryCauses = m, e.push(v);
208
+ (u.state & b) !== q && this._acknowledgeDiscard(u, !0, e), u.state = (u.state | m) & ~p, S(u), e.push(v);
193
209
  }
194
210
  }
195
- y !== 0 && e.push(new g(
196
- `[Raph] Phase "${h.phase.name}" left ${y} task(s) unresolved; they were deferred.`
197
- )), e.length === o ? (a = this._tracePhase) == null || a.call(this, h.phase.name, "end") : (r = this._tracePhase) == null || r.call(
198
- this,
199
- h.phase.name,
211
+ r.length = 0, i = void 0, T !== 0 && e.push(new R(
212
+ `[Raph] Phase "${n.phase.name}" left ${T} task(s) unresolved; they were deferred.`
213
+ )), e.length === d ? this._tracePhase?.(n.phase.name, "end") : this._tracePhase?.(
214
+ n.phase.name,
200
215
  "error",
201
216
  e[e.length - 1]
202
217
  );
203
218
  }
204
219
  }
205
- } catch (h) {
206
- e.push(h), this._cancelAllQueued(!0, e), this._cancelAllDeferred(!0, e);
220
+ } catch (n) {
221
+ e.push(n), i !== void 0 && (i.length = 0), this._cancelAllQueued(!0, e), this._cancelAllDeferred(!0, e);
207
222
  } finally {
208
223
  this._running = !1;
209
224
  }
210
225
  try {
211
226
  this._deferred.size !== 0 && this._scheduleDeferredTurn();
212
- } catch (h) {
213
- e.push(h);
227
+ } catch (n) {
228
+ e.push(n);
214
229
  }
215
- const i = e.length === 1 ? e[0] : e.length > 1 ? new AggregateError(e, "[Raph] Multiple phase tasks failed.") : void 0;
216
- if (i !== void 0)
217
- throw this._settleIdleWaiters(i, !0), i;
230
+ const a = e.length === 1 ? e[0] : e.length > 1 ? new AggregateError(e, "[Raph] Multiple phase tasks failed.") : void 0;
231
+ if (e.length !== 0)
232
+ throw this._settleIdleWaiters(a, !0), a;
218
233
  this._settleIdleWaiters(void 0, !1);
219
234
  }
220
235
  dispose() {
@@ -223,207 +238,396 @@ class R {
223
238
  this._disposed = !0, this._cancelScheduled(), this._cancelAllQueued(!1);
224
239
  const e = [...this._deferred];
225
240
  this._cancelAllDeferred(!1);
226
- for (const t of e)
227
- t.active = !1;
228
- this._phaseBindings.clear(), this._phases = [], this._phaseByName.clear();
229
- const s = new P("[Raph] Phase pipeline is disposed.");
230
- this._settleIdleWaiters(s, !0);
241
+ for (const s of e)
242
+ s.state &= ~f;
243
+ this._phases = [], this._phaseByName.clear(), this._resolvedInput = void 0, this._resolvedState = void 0;
244
+ const t = new I("[Raph] Phase pipeline is disposed.");
245
+ this._settleIdleWaiters(t, !0);
231
246
  }
232
247
  _debugPending() {
233
248
  return this._scheduled || this._running || this._hasPending();
234
249
  }
235
250
  _describeQueued() {
236
- var s;
237
251
  const e = [];
238
252
  for (const t of this._phases) {
239
- const i = ((s = this._queues.get(t.phase.name)) == null ? void 0 : s.filter((a) => a.active && !a.consumerOwner.disposed)) ?? [];
240
- if (i.length === 0)
253
+ const s = t.state.queue.filter(
254
+ (a) => (a.state & f) !== 0 && !a.consumerOwner.disposed
255
+ );
256
+ if (s.length === 0)
241
257
  continue;
242
- const n = i.slice(0, 3).map((a) => {
243
- var c, p;
244
- const r = a.consumerOwner.node, h = r === void 0 ? void 0 : r.componentId, f = r === void 0 ? a.consumerOwner.id : `${a.consumerOwner.id}/${r.constructor.name}/${r.type}${typeof h == "string" ? `/${h}` : ""}`, o = (p = (c = a.firstCause) == null ? void 0 : c.sourceOwner) == null ? void 0 : p.node, _ = o === void 0 ? "" : `<=${o.id}/${o.constructor.name}`;
245
- return `${f}${a.firstCause ? `:${a.firstCause.kind}${_}` : ""}`;
258
+ const i = s.slice(0, 3).map((a) => {
259
+ const n = a.consumerOwner.node, o = n === void 0 ? void 0 : n.componentId, r = n === void 0 ? a.consumerOwner.id : `${a.consumerOwner.id}/${n.constructor.name}/${n.type}${typeof o == "string" ? `/${o}` : ""}`, d = a.firstCause?.sourceOwner?.node, l = d === void 0 ? "" : `<=${d.id}/${d.constructor.name}`;
260
+ return `${r}${a.firstCause ? `:${a.firstCause.kind}${l}` : ""}`;
246
261
  }).join(", ");
247
- e.push(`${t.phase.name}=${i.length}${n ? ` [${n}]` : ""}`);
262
+ e.push(`${t.phase.name}=${s.length}${i ? ` [${i}]` : ""}`);
248
263
  }
249
264
  return e.join("; ");
250
265
  }
251
- _createTask(e) {
252
- const s = {
253
- get phase() {
254
- return e.phase;
255
- },
256
- get consumerOwner() {
257
- return e.consumerOwner;
258
- },
259
- get effect() {
260
- return e.effect;
261
- },
262
- get causes() {
263
- return e.deliveryCauses;
264
- },
265
- get frame() {
266
- return e.frame;
267
- },
268
- get priority() {
269
- return e.priority;
270
- },
271
- get sequence() {
272
- return e.sequence;
273
- },
274
- run: () => this._runDelivery(e),
275
- defer: () => this._deferDelivery(e),
276
- cancel: () => this._cancelDelivery(e)
277
- };
278
- return Object.defineProperty(s, O, { value: e }), Object.freeze(s);
279
- }
280
- _beginDelivery(e, s) {
281
- e.pending = !1, e.inDelivery = !0, e.discardAcknowledged = !1, e.requested = !1, e.resolution = "unresolved", e.frame = s;
282
- const t = e.firstCause;
283
- if (t === void 0) {
284
- e.deliveryFirstCauseKey = void 0, e.deliveryExtraCauseKeys = void 0, e.deliveryCauses = m;
266
+ /**
267
+ * Открывает доставку одной записью `state`. Накопленные причины остаются на
268
+ * своих местах и становятся причинами доставки под TASK_CAUSES_DELIVERED:
269
+ * ничего не копируется, а массив для `task.causes` строится, только если его
270
+ * прочитают. Frame доставки получает только запись с facade: без facade его
271
+ * нечем прочитать, а запись ссылки на новый frame в каждую доставленную
272
+ * запись стоит write barrier.
273
+ *
274
+ * Запись попадает сюда только из живой очереди, а в ней нет записей с
275
+ * открытой доставкой, поэтому причин прошлой доставки здесь не бывает.
276
+ */
277
+ _beginDelivery(e, t) {
278
+ const s = e.state & -1893 | p;
279
+ e.state = e.firstCause === void 0 ? s : s | k, e.facade !== void 0 && (e.frame = t);
280
+ }
281
+ /**
282
+ * Исполняет открытую доставку binding. `failures` передаёт default runner:
283
+ * группа складывает туда сбой каждого slot отдельно. Без него сбои slots
284
+ * бросаются вызывающему — `task.run()` внутри `process` — после прохода: один
285
+ * как есть, несколько одним AggregateError.
286
+ *
287
+ * @internal
288
+ */
289
+ _runDelivery(e, t) {
290
+ const s = e.state;
291
+ if ((s & P) !== f || e.consumerOwner.disposed) {
292
+ e.state = s | m;
285
293
  return;
286
294
  }
287
- const i = e.extraCauses;
288
- if (e.deliveryFirstCauseKey = e.firstCauseKey, e.firstCause = void 0, e.firstCauseKey = void 0, e.extraCauses = void 0, i === void 0 || i.size === 0) {
289
- e.deliveryExtraCauseKeys = void 0, e.deliveryCauses = Object.freeze([t]);
295
+ (s & x) !== p && O(), e.state = s | q;
296
+ const i = e.detail;
297
+ i !== void 0 && (i.deferCount = 0);
298
+ const a = this._reactivity, n = e.node;
299
+ if (n !== void 0) {
300
+ a._beginTaskEffectRun(n) && (e.state |= H, a._runTaskEffectUntracked(n));
290
301
  return;
291
302
  }
292
- e.deliveryExtraCauseKeys = Object.freeze([...i.keys()]), e.deliveryCauses = Object.freeze([t, ...i.values()]);
293
- }
294
- _runDelivery(e) {
295
- if (!e.active || e.paused || e.consumerOwner.disposed) {
296
- e.resolution = "cancel";
303
+ const o = e.group;
304
+ if (o === void 0) {
305
+ const _ = e.watch;
306
+ _ !== void 0 && a.untrackedWithOwner(_.deliver);
297
307
  return;
298
308
  }
299
- this._assertDelivery(e), e.resolution = "run", e.deferCount = 0, this._runUntracked(e.runner);
309
+ const r = o.length;
310
+ let d = this._idleSlotFlags, l;
311
+ for (let _ = y; _ < r; _++) {
312
+ const c = o[_];
313
+ if (c === null || c.flags === d)
314
+ continue;
315
+ if (!a._beginTaskEffectRun(c)) {
316
+ c.evaluate !== void 0 && (this._idleSlotFlags = d = c.flags);
317
+ continue;
318
+ }
319
+ o[N] = _ - y;
320
+ try {
321
+ a._runTaskEffectUntracked(c);
322
+ } catch (T) {
323
+ t !== void 0 ? t.push(T) : (l ??= []).push(T);
324
+ }
325
+ const D = e.state;
326
+ if (!(D & f))
327
+ break;
328
+ if (D & A) {
329
+ _ + 1 < r && (this._restoreDeliveryCausesBeforePending(e), e.state |= g);
330
+ break;
331
+ }
332
+ }
333
+ if (l !== void 0)
334
+ throw l.length === 1 ? l[0] : new AggregateError(l, "[Raph] Effect group delivery failed.");
300
335
  }
336
+ /** @internal */
301
337
  _deferDelivery(e) {
302
- if (!e.active || e.paused || e.consumerOwner.disposed) {
303
- e.resolution = "cancel";
338
+ const t = e.state;
339
+ if ((t & P) !== f || e.consumerOwner.disposed) {
340
+ e.state = t | m;
304
341
  return;
305
342
  }
306
- if (this._assertDelivery(e), e.resolution = "defer", ++e.deferCount > K) {
307
- e.resolution = "cancel";
343
+ if ((t & x) !== p && O(), e.state = t | W, ++e.detailed().deferCount > X) {
344
+ e.state |= m;
308
345
  const s = [];
309
346
  throw this._acknowledgeDiscard(e, !0, s), s.length !== 0 ? new AggregateError(
310
- [new g(
347
+ [new R(
311
348
  `[Raph] Phase task in "${e.phase}" exceeded 10000 deferred deliveries.`
312
349
  ), ...s],
313
350
  "[Raph] Phase task defer limit and recovery failed."
314
- ) : new g(
351
+ ) : new R(
315
352
  `[Raph] Phase task in "${e.phase}" exceeded 10000 deferred deliveries.`
316
353
  );
317
354
  }
318
355
  }
356
+ /** @internal */
319
357
  _cancelDelivery(e) {
320
- if (!e.active || e.consumerOwner.disposed) {
321
- e.resolution = "cancel";
358
+ const t = e.state;
359
+ if (!(t & f) || e.consumerOwner.disposed) {
360
+ e.state = t | m;
322
361
  return;
323
362
  }
324
- this._assertDelivery(e);
363
+ (t & x) !== p && O();
325
364
  const s = [];
326
365
  if (this._acknowledgeDiscard(e, !1, s), s.length !== 0)
327
366
  throw s.length === 1 ? s[0] : new AggregateError(s, "[Raph] Phase task cancellation failed.");
328
- e.discardAcknowledged && (e.requested = C(e)), e.resolution = "cancel", e.deferCount = 0;
367
+ let i = e.state | m;
368
+ i & C && (i = F(e) ? i | g : i & ~g), e.state = i;
369
+ const a = e.detail;
370
+ a !== void 0 && (a.deferCount = 0);
329
371
  }
330
372
  _finishDelivery(e) {
331
- var t;
332
- if (!e.inDelivery)
373
+ const t = e.state;
374
+ if (!(t & p))
333
375
  return;
334
- const s = e.resolution;
335
- if (e.inDelivery = !1, !e.active || e.consumerOwner.disposed) {
336
- e.deliveryFirstCauseKey = void 0, e.deliveryExtraCauseKeys = void 0, e.deliveryCauses = m;
376
+ const s = t & b;
377
+ if (e.state = t & ~p, !(t & f) || e.consumerOwner.disposed) {
378
+ S(e);
337
379
  return;
338
380
  }
339
- if (e.paused) {
340
- s !== "run" && !(s === "cancel" && e.discardAcknowledged) && (this._restoreDeliveryCausesBeforePending(e), e.requested = !0), e.deliveryFirstCauseKey = void 0, e.deliveryExtraCauseKeys = void 0, e.deliveryCauses = m;
381
+ if (t & A) {
382
+ s !== q && !(s === m && (t & C) !== 0) && (this._restoreDeliveryCausesBeforePending(e), e.state |= g), S(e);
341
383
  return;
342
384
  }
343
- if (s === "defer" && (this._restoreDeliveryCausesBeforePending(e), e.deferred = !0, this._deferred.add(e)), e.deliveryFirstCauseKey = void 0, e.deliveryExtraCauseKeys = void 0, e.deliveryCauses = m, s !== "defer" && (e.requested || C(e))) {
344
- const i = (t = e.binding) == null ? void 0 : t.rearmPending;
345
- i === void 0 ? this._queue(e) : i();
385
+ if (s === W) {
386
+ this._restoreDeliveryCausesBeforePending(e), e.state |= E, this._deferred.add(e), S(e);
387
+ return;
388
+ }
389
+ if (S(e), (e.state & g) !== 0 || e.firstCause !== void 0) {
390
+ const i = e.node;
391
+ if (i !== void 0)
392
+ this._reactivity._rearmTaskEffect(i);
393
+ else {
394
+ const a = e.group;
395
+ a !== void 0 && this._rearmGroup(a), this._queue(e);
396
+ }
346
397
  }
347
398
  }
348
- _appendCause(e, s, t) {
349
- if (!e.active)
350
- return;
351
- const i = e.firstCause;
352
- if (i === void 0) {
353
- e.firstCause = s, e.firstCauseKey = t;
354
- return;
399
+ /**
400
+ * Делает исполняемыми slots группы, которые остались запланированными после
401
+ * доставки: slot, изменивший собственную зависимость, и slot, чью зависимость
402
+ * изменили после его запуска. Slot, который не запланирован, не трогается:
403
+ * он уже прочитал актуальные значения и в следующей доставке не исполняется.
404
+ * Запись, сделанную до запуска slot в той же доставке, slot читает в ней же:
405
+ * прямую запись engine переводит в обязательный запуск, отложенную находит
406
+ * проверка зависимостей. Отдельный binding после такой записи исполняется
407
+ * ещё раз следующим проходом; slot повторно не исполняется.
408
+ *
409
+ * Запись без зависимостей пропускается. Запланированной она бывает в двух
410
+ * случаях: slot запущен во время доставки и ждёт первого запуска — тогда она
411
+ * исполняема с момента создания; либо повторно запущен slot, который уже
412
+ * исполнился и ничего не прочитал, — тогда исполнять его нечем.
413
+ */
414
+ _rearmGroup(e) {
415
+ const t = this._reactivity;
416
+ for (let s = y; s < e.length; s++) {
417
+ const i = e[s];
418
+ i !== null && i.firstDep !== null && t._beginTaskEffectRun(i) && t._rearmTaskEffect(i);
355
419
  }
356
- if (e.firstCauseKey === t) {
357
- e.firstCause = b(i, s);
358
- return;
420
+ }
421
+ /** @internal */
422
+ _notifyTask(e, t) {
423
+ const s = this._resolveCause(t);
424
+ if (s !== void 0) {
425
+ const i = s.kind === "structure" ? s.source : t;
426
+ this._appendCause(e, s, i);
359
427
  }
360
- const n = e.extraCauses ?? (e.extraCauses = /* @__PURE__ */ new Map()), a = n.get(t);
361
- n.set(t, a === void 0 ? s : b(a, s));
362
428
  }
363
- _queue(e, s = !0) {
364
- if (!e.active || e.consumerOwner.disposed || this._disposed)
429
+ /** @internal */
430
+ _appendCause(e, t, s) {
431
+ const i = e.state;
432
+ if (!(i & f))
365
433
  return;
366
- if (e.paused) {
367
- e.requested = !0;
434
+ i & k && this._splitDeliveredCauses(e);
435
+ const a = e.firstCause;
436
+ if (a === void 0) {
437
+ e.firstCause = t, e.firstCauseKey = s;
368
438
  return;
369
439
  }
370
- if (e.inDelivery) {
371
- e.requested = !0;
440
+ if (e.firstCauseKey === s) {
441
+ e.firstCause = U(a, t);
372
442
  return;
373
443
  }
374
- if (e.pending) {
375
- s && this._schedule();
376
- return;
444
+ const n = e.detailed().extraCauses ??= /* @__PURE__ */ new Map(), o = n.get(s);
445
+ n.set(s, o === void 0 ? t : U(o, t));
446
+ }
447
+ /**
448
+ * Переносит причины открытой доставки с места ожидающих в detail, без
449
+ * копирования, и освобождает это место. После вызова запись хранит оба
450
+ * набора раздельно: ожидающие причины — в своих полях, причины доставки — в
451
+ * detail. Массив, уже построенный для `task.causes`, остаётся тем же.
452
+ */
453
+ _splitDeliveredCauses(e) {
454
+ const t = e.detailed(), s = t.extraCauses;
455
+ t.deliveryFirstCause = e.firstCause, t.deliveryFirstCauseKey = e.firstCauseKey, t.deliveryExtraCauses = s === void 0 || s.size === 0 ? void 0 : s, t.extraCauses = void 0, e.firstCause = void 0, e.firstCauseKey = void 0, e.state &= ~k;
456
+ }
457
+ /** @internal */
458
+ _queue(e, t = !0) {
459
+ const s = e.state;
460
+ if (!(!(s & f) || e.consumerOwner.disposed || this._disposed)) {
461
+ if (s & (A | p)) {
462
+ e.state = s | g;
463
+ return;
464
+ }
465
+ if (s & w) {
466
+ t && this._schedule();
467
+ return;
468
+ }
469
+ s & E || (e.state = s & ~C | w, e.sequence = this._taskSequence++, e.phaseState.queue.push(e), this._queuedCount++, t && this._schedule());
377
470
  }
378
- if (e.deferred)
379
- return;
380
- e.discardAcknowledged = !1, e.pending = !0, e.sequence = this._taskSequence++;
381
- let t = this._queues.get(e.phase);
382
- t === void 0 && (t = [], this._queues.set(e.phase, t)), t.push(e), s && this._schedule();
383
471
  }
472
+ /** @internal */
384
473
  _disposeTask(e) {
385
- var i;
386
- if (!e.active)
474
+ const t = e.state;
475
+ if (!(t & f))
387
476
  return;
388
- e.active = !1, e.binding !== void 0 && (delete e.binding.cancelPending, delete e.binding.rearmPending, delete e.binding.abort, delete e.binding), e.pending = !1, e.deferred = !1, e.inDelivery && (e.resolution = "cancel"), e.firstCause = void 0, e.firstCauseKey = void 0, (i = e.extraCauses) == null || i.clear(), e.extraCauses = void 0, e.deliveryFirstCauseKey = void 0, e.deliveryExtraCauseKeys = void 0, e.deliveryCauses = m, this._deferred.delete(e);
389
- const s = this._queues.get(e.phase);
390
- if (s !== void 0) {
391
- const n = s.indexOf(e);
392
- n >= 0 && s.splice(n, 1), s.length === 0 && this._queues.delete(e.phase);
477
+ const s = t & -270;
478
+ e.state = t & p ? s | m : s, e.firstCause = void 0, e.firstCauseKey = void 0;
479
+ const i = e.detail;
480
+ i !== void 0 && (i.extraCauses?.clear(), i.extraCauses = void 0, L(i)), t & E && this._deferred.delete(e), t & w && this._unqueue(e), e.phaseState.bindings--, this._hasPending() || this._cancelScheduled(), this._settleIdleWaiters(void 0, !1);
481
+ }
482
+ /**
483
+ * Полностью освобождает один binding; каждый шаг идемпотентен, поэтому
484
+ * владелец, engine и пользователь могут прийти сюда в любом порядке и
485
+ * повторно войти в метод.
486
+ *
487
+ * @internal
488
+ */
489
+ _disposeBinding(e) {
490
+ const t = e.group;
491
+ if (t !== void 0 && this._forgetStoppedSlots(t))
492
+ return;
493
+ e.scopeParent !== void 0 && e.consumerOwner._releaseRecord(e);
494
+ const s = e.node;
495
+ if (s !== void 0)
496
+ e.node = void 0, this._reactivity._disposeTaskEffect(s);
497
+ else {
498
+ if (t !== void 0) {
499
+ e.group = void 0, this._disposeGroup(e, t);
500
+ return;
501
+ }
502
+ const i = e.watch;
503
+ i !== void 0 && (e.watch = void 0, i.stop(() => this._releaseWatch(e, i)));
504
+ }
505
+ this._disposeTask(e);
506
+ }
507
+ /**
508
+ * Убирает из состояния группы slots, записи графа которых уже остановлены, и
509
+ * сообщает, остались ли при этом живые slots.
510
+ *
511
+ * Запись одного slot останавливается отдельно от группы в трёх случаях: упал
512
+ * cleanup перед повторным запуском slot; перезапускается или останавливается
513
+ * effect, внутри тела которого группа зарегистрирована; провалился запуск
514
+ * slot через `start()`. Engine сообщает о каждой такой остановке через task
515
+ * hook, общий для всех slots, и запись в этот момент уже остановлена. Группа
516
+ * тогда теряет только этот slot, как owner потерял бы один из отдельных
517
+ * bindings; запись binding освобождается, когда остановлен последний slot.
518
+ *
519
+ * Вызов владельца или effect scope остановленных записей не находит: место
520
+ * остановленного slot уже занято `null`.
521
+ *
522
+ * @returns true, если вызов был сообщением engine и живые slots остались.
523
+ */
524
+ _forgetStoppedSlots(e) {
525
+ let t = !1, s = !1;
526
+ for (let i = y; i < e.length; i++) {
527
+ const a = e[i];
528
+ a != null && (a.evaluate === void 0 ? (e[i] = null, t = !0) : s = !0);
393
529
  }
394
- const t = (this._phaseBindings.get(e.phase) ?? 1) - 1;
395
- t === 0 ? this._phaseBindings.delete(e.phase) : this._phaseBindings.set(e.phase, t), this._hasPending() || this._cancelScheduled(), this._settleIdleWaiters(void 0, !1);
530
+ return t && s;
531
+ }
532
+ /**
533
+ * Останавливает записи графа всех slots группы в порядке, обратном порядку
534
+ * slots: так владелец освобождал бы отдельные bindings. Сбой cleanup одного
535
+ * slot не мешает остановить остальные.
536
+ *
537
+ * Группа — один ресурс, поэтому порядок и вид ошибки не зависят от того, кто
538
+ * её освобождает. Effect scope отдельные bindings освободил бы в порядке
539
+ * регистрации и сложил бы их сбои в собственный список; группу он
540
+ * освобождает в обратном порядке slots и получает несколько сбоев одним
541
+ * AggregateError. Владелец получает тот же AggregateError как один сбой
542
+ * ресурса вместо отдельных сбоев bindings.
543
+ *
544
+ * Остановка первой же записи повторно входит в _disposeBinding() через task
545
+ * hook engine: вложенный вызов уже не находит состояния группы и освобождает
546
+ * состояние pipeline до cleanup slots. Группа без живых slots освобождает
547
+ * его здесь.
548
+ */
549
+ _disposeGroup(e, t) {
550
+ const s = this._reactivity;
551
+ let i;
552
+ for (let a = t.length - 1; a >= y; a--) {
553
+ const n = t[a];
554
+ if (n != null)
555
+ try {
556
+ s._disposeTaskEffect(n);
557
+ } catch (o) {
558
+ (i ??= []).push(o);
559
+ }
560
+ }
561
+ try {
562
+ this._disposeTask(e);
563
+ } catch (a) {
564
+ (i ??= []).push(a);
565
+ }
566
+ if (i !== void 0)
567
+ throw i.length === 1 ? i[0] : new AggregateError(i, "[Raph] Effect group disposal failed.");
568
+ }
569
+ /**
570
+ * Освобождает подписку и состояние pipeline остановленного watch.
571
+ */
572
+ _releaseWatch(e, t) {
573
+ const s = [], i = t.source;
574
+ if (t.source = void 0, t.record = void 0, i !== void 0)
575
+ try {
576
+ i();
577
+ } catch (a) {
578
+ s.push(a);
579
+ }
580
+ try {
581
+ this._disposeTask(e);
582
+ } catch (a) {
583
+ s.push(a);
584
+ }
585
+ z(s, "[Raph] Phase watch disposal failed.");
396
586
  }
587
+ /** @internal */
397
588
  _pauseTask(e) {
398
- if (!e.active || e.paused)
589
+ const t = e.state;
590
+ if ((t & P) !== f)
399
591
  return;
400
- e.paused = !0, e.requested = e.requested || e.pending || e.deferred || e.inDelivery && e.resolution !== "run" && !(e.resolution === "cancel" && e.discardAcknowledged), e.pending = !1, e.deferred && (e.deferred = !1, this._deferred.delete(e));
401
- const s = this._queues.get(e.phase);
402
- if (s !== void 0) {
403
- const t = s.indexOf(e);
404
- t >= 0 && s.splice(t, 1), s.length === 0 && this._queues.delete(e.phase);
405
- }
406
- this._hasPending() || this._cancelScheduled(), this._settleIdleWaiters(void 0, !1);
407
- }
592
+ const s = t & b, i = (t | A) & -13;
593
+ e.state = (t & (w | E)) !== 0 || (t & p) !== 0 && s !== q && !(s === m && (t & C) !== 0) ? i | g : i, t & E && this._deferred.delete(e), t & w && this._unqueue(e), this._hasPending() || this._cancelScheduled(), this._settleIdleWaiters(void 0, !1);
594
+ }
595
+ /**
596
+ * Убирает ожидающую запись из живой очереди её phase. Запись, которую flush
597
+ * уже забрал на разбор, в живой очереди не находится и счётчик не меняет.
598
+ */
599
+ _unqueue(e) {
600
+ const t = e.phaseState.queue, s = t.indexOf(e);
601
+ s >= 0 && (t.splice(s, 1), this._queuedCount--);
602
+ }
603
+ /** @internal */
408
604
  _resumeTask(e) {
409
- !e.active || !e.paused || e.consumerOwner.disposed || (e.paused = !1, (e.requested || C(e)) && (e.requested = !1, this._queue(e)));
410
- }
605
+ const t = e.state;
606
+ (t & P) !== P || e.consumerOwner.disposed || ((t & g) !== 0 || F(e) ? (e.state = t & -67, this._queue(e)) : e.state = t & ~A);
607
+ }
608
+ /**
609
+ * Возвращает причины открытой доставки в ожидающие, впереди причин, которые
610
+ * пришли после её открытия; причины одного source сливаются. Причины доставки
611
+ * при этом остаются причинами доставки до её конца, поэтому сначала они
612
+ * отделяются от ожидающих.
613
+ */
411
614
  _restoreDeliveryCausesBeforePending(e) {
412
- const s = e.deliveryCauses;
413
- if (s.length === 0)
615
+ e.state & k && this._splitDeliveredCauses(e);
616
+ const t = e.detail;
617
+ if (t === void 0)
618
+ return;
619
+ const s = t.deliveryFirstCause;
620
+ if (s === void 0)
414
621
  return;
415
- const t = e.firstCause, i = e.firstCauseKey, n = e.extraCauses;
416
- e.firstCause = void 0, e.firstCauseKey = void 0, e.extraCauses = void 0, this._appendCause(e, s[0], e.deliveryFirstCauseKey);
417
- const a = e.deliveryExtraCauseKeys;
418
- for (let r = 1; r < s.length; r++)
419
- this._appendCause(e, s[r], a[r - 1]);
420
- if (t !== void 0 && (this._appendCause(e, t, i), n !== void 0))
421
- for (const [r, h] of n)
422
- this._appendCause(e, h, r);
423
- }
424
- _takePhase(e) {
425
- const s = this._queues.get(e);
426
- return s === void 0 ? [] : (this._queues.delete(e), s);
622
+ const i = e.firstCause, a = e.firstCauseKey, n = t.extraCauses;
623
+ e.firstCause = void 0, e.firstCauseKey = void 0, t.extraCauses = void 0, this._appendCause(e, s, t.deliveryFirstCauseKey);
624
+ const o = t.deliveryExtraCauses;
625
+ if (o !== void 0)
626
+ for (const [r, d] of o)
627
+ this._appendCause(e, d, r);
628
+ if (i !== void 0 && (this._appendCause(e, i, a), n !== void 0))
629
+ for (const [r, d] of n)
630
+ this._appendCause(e, d, r);
427
631
  }
428
632
  _schedule() {
429
633
  if (this._running || this._scheduled || this._disposed)
@@ -435,153 +639,210 @@ class R {
435
639
  return;
436
640
  }
437
641
  this._scheduled = !0;
438
- const e = ++this._scheduleToken, s = () => {
642
+ const e = ++this._scheduleToken, t = () => {
439
643
  this._disposed || !this._scheduled || e !== this._scheduleToken || (this._scheduled = !1, this._frameHandle = void 0, this._frameHandleKind = void 0, this.flush());
440
644
  };
441
645
  if (this._scheduler === "microtask") {
442
- queueMicrotask(s);
646
+ queueMicrotask(t);
443
647
  return;
444
648
  }
445
- typeof globalThis.requestAnimationFrame == "function" ? (this._frameHandleKind = "animation-frame", this._frameHandle = globalThis.requestAnimationFrame(s)) : (this._frameHandleKind = "timeout", this._frameHandle = setTimeout(s, 16));
649
+ typeof globalThis.requestAnimationFrame == "function" ? (this._frameHandleKind = "animation-frame", this._frameHandle = globalThis.requestAnimationFrame(t)) : (this._frameHandleKind = "timeout", this._frameHandle = setTimeout(t, 16));
446
650
  }
447
651
  _scheduleDeferredTurn() {
448
652
  if (this._scheduled || this._disposed)
449
653
  return;
450
654
  this._scheduled = !0;
451
- const e = ++this._scheduleToken, s = () => {
452
- this._disposed || !this._scheduled || e !== this._scheduleToken || (this._scheduled = !1, this._frameHandle = void 0, this._frameHandleKind = void 0, this._activateDeferred(), this._hasQueued() ? this.flush() : this._settleIdleWaiters(void 0, !1));
655
+ const e = ++this._scheduleToken, t = () => {
656
+ this._disposed || !this._scheduled || e !== this._scheduleToken || (this._scheduled = !1, this._frameHandle = void 0, this._frameHandleKind = void 0, this._activateDeferred(), this._queuedCount !== 0 ? this.flush() : this._settleIdleWaiters(void 0, !1));
453
657
  };
454
- this._scheduler === "animationFrame" ? typeof globalThis.requestAnimationFrame == "function" ? (this._frameHandleKind = "animation-frame", this._frameHandle = globalThis.requestAnimationFrame(s)) : (this._frameHandleKind = "timeout", this._frameHandle = setTimeout(s, 16)) : queueMicrotask(s);
658
+ this._scheduler === "animationFrame" ? typeof globalThis.requestAnimationFrame == "function" ? (this._frameHandleKind = "animation-frame", this._frameHandle = globalThis.requestAnimationFrame(t)) : (this._frameHandleKind = "timeout", this._frameHandle = setTimeout(t, 16)) : queueMicrotask(t);
455
659
  }
456
660
  _cancelScheduled() {
457
- var e;
458
- this._scheduled && (this._scheduled = !1, this._scheduleToken++, this._frameHandleKind === "animation-frame" && this._frameHandle !== void 0 ? (e = globalThis.cancelAnimationFrame) == null || e.call(globalThis, this._frameHandle) : this._frameHandleKind === "timeout" && this._frameHandle !== void 0 && clearTimeout(this._frameHandle), this._frameHandle = void 0, this._frameHandleKind = void 0);
661
+ this._scheduled && (this._scheduled = !1, this._scheduleToken++, this._frameHandleKind === "animation-frame" && this._frameHandle !== void 0 ? globalThis.cancelAnimationFrame?.(this._frameHandle) : this._frameHandleKind === "timeout" && this._frameHandle !== void 0 && clearTimeout(this._frameHandle), this._frameHandle = void 0, this._frameHandleKind = void 0);
459
662
  }
460
663
  _activateDeferred() {
461
664
  const e = [...this._deferred];
462
665
  this._deferred.clear();
463
- for (const s of e)
464
- s.deferred = !1, this._queue(s, !1);
666
+ for (const t of e)
667
+ t.state &= ~E, this._queue(t, !1);
465
668
  }
466
669
  _nextFrame() {
467
- var t;
468
- const e = ((t = globalThis.performance) == null ? void 0 : t.now()) ?? Date.now();
670
+ const e = globalThis.performance?.now() ?? Date.now();
469
671
  if (this._firstFrameAt === void 0 || this._lastFrameAt === void 0)
470
672
  return this._firstFrameAt = e, this._lastFrameAt = e, this._frame = Object.freeze({ now: e, delta: 0, elapsed: 0, frame: 0 });
471
673
  this._frameNumber++;
472
- const s = Object.freeze({
674
+ const t = Object.freeze({
473
675
  now: e,
474
676
  delta: Math.min(Math.max(e - this._lastFrameAt, 0), 100),
475
677
  elapsed: Math.max(e - this._firstFrameAt, 0),
476
678
  frame: this._frameNumber
477
679
  });
478
- return this._lastFrameAt = e, this._frame = s;
680
+ return this._lastFrameAt = e, this._frame = t;
479
681
  }
480
682
  _assertRetainedPhases(e) {
481
- for (const s of this._phaseBindings.keys())
482
- if (!e.has(s))
483
- throw new Error(`[Raph] Cannot remove phase "${s}" while it is still bound.`);
484
- for (const s of this._queues.keys())
485
- if (!e.has(s))
486
- throw new Error(`[Raph] Cannot remove phase "${s}" while it has pending work.`);
487
- }
488
- _assertDelivery(e) {
489
- if (!e.active || !e.inDelivery || e.resolution !== "unresolved")
490
- throw new g("[Raph] Phase task delivery is already resolved.");
491
- }
492
- _hasQueued() {
493
- for (const e of this._queues.values())
494
- if (e.some((s) => s.active && s.pending))
495
- return !0;
496
- return !1;
683
+ for (const t of this._phases) {
684
+ const s = t.state;
685
+ if (s.bindings !== 0 && !e.has(s.name))
686
+ throw new Error(`[Raph] Cannot remove phase "${s.name}" while it is still bound.`);
687
+ }
688
+ for (const t of this._phases) {
689
+ const s = t.state;
690
+ if (s.queue.length !== 0 && !e.has(s.name))
691
+ throw new Error(`[Raph] Cannot remove phase "${s.name}" while it has pending work.`);
692
+ }
497
693
  }
498
694
  _hasPending() {
499
- return this._hasQueued() || this._deferred.size !== 0;
500
- }
501
- _cancelAllQueued(e, s = []) {
502
- const t = /* @__PURE__ */ new Set();
503
- for (const i of this._queues.values())
504
- for (const n of i)
505
- t.add(n);
506
- this._queues.clear();
507
- for (const i of t)
508
- i.pending = !1, e && this._acknowledgeDiscard(i, !0, s), this._clearPendingDelivery(i);
509
- }
510
- _cancelAllDeferred(e, s = []) {
511
- const t = [...this._deferred];
695
+ return this._queuedCount !== 0 || this._deferred.size !== 0;
696
+ }
697
+ _cancelAllQueued(e, t = []) {
698
+ if (this._queuedCount === 0)
699
+ return;
700
+ const s = [];
701
+ for (const i of this._phases) {
702
+ const a = i.state.queue;
703
+ for (const n of a)
704
+ s.push(n);
705
+ a.length = 0;
706
+ }
707
+ this._queuedCount = 0;
708
+ for (const i of s)
709
+ i.state &= ~w, e && this._acknowledgeDiscard(i, !0, t), this._clearPendingDelivery(i);
710
+ }
711
+ _cancelAllDeferred(e, t = []) {
712
+ const s = [...this._deferred];
512
713
  this._deferred.clear();
513
- for (const i of t)
514
- i.deferred = !1, e && this._acknowledgeDiscard(i, !0, s), this._clearPendingDelivery(i);
714
+ for (const i of s)
715
+ i.state &= ~E, e && this._acknowledgeDiscard(i, !0, t), this._clearPendingDelivery(i);
515
716
  }
516
- _acknowledgeDiscard(e, s, t) {
517
- if (e.discardAcknowledged)
717
+ _acknowledgeDiscard(e, t, s) {
718
+ const i = e.state;
719
+ if (i & C)
518
720
  return;
519
- const i = e.binding, n = i == null ? void 0 : i.cancelPending;
520
- if (n === void 0) {
521
- e.discardAcknowledged = !0;
721
+ const a = e.node, n = e.group;
722
+ if (a === void 0 && n === void 0 || !(i & f)) {
723
+ e.state = i | C;
522
724
  return;
523
725
  }
524
726
  try {
525
- if (n()) {
526
- e.discardAcknowledged = !0;
727
+ if (a !== void 0 ? (i & H) !== 0 && this._reactivity._cancelTaskEffect(a) : this._cancelGroup(e, n, t)) {
728
+ e.state |= C;
527
729
  return;
528
730
  }
529
- if (!s) {
530
- t.push(new g(
731
+ if (!t) {
732
+ s.push(new R(
531
733
  `[Raph] Initial effect delivery in "${e.phase}" cannot be cancelled before dependency collection.`
532
734
  ));
533
735
  return;
534
736
  }
535
- const a = i == null ? void 0 : i.abort;
536
- if (a === void 0) {
537
- t.push(new g(
538
- `[Raph] Initial effect delivery in "${e.phase}" could not be aborted safely.`
539
- ));
540
- return;
737
+ e.dispose(), e.state |= C;
738
+ } catch (o) {
739
+ s.push(o);
740
+ }
741
+ }
742
+ /**
743
+ * Гасит ожидающую доставку slots группы.
744
+ *
745
+ * Slot, чей первый запуск ещё впереди, погасить нельзя: он не собрал
746
+ * зависимости, и после отмены его ничто не разбудит. Такой slot узнаётся по
747
+ * запланированной записи без единой зависимости: запись, которая уже
748
+ * исполнялась и ничего не прочитала, больше не планируется. Обычная отмена
749
+ * тогда не трогает ни один slot и возвращает false; fatal discard
750
+ * останавливает такие slots окончательно и гасит остальные.
751
+ *
752
+ * Обычная отмена отказывается только от того, что доставка знала при
753
+ * открытии. Причина, пришедшая группе после открытия доставки, означает
754
+ * запись, которую запланированный slot ещё не прочитал. Гашение снимает с
755
+ * записи slot и отметку планирования, и требование запуска, которое engine
756
+ * поставил при прямой записи, поэтому slots, ждавшие запуска, после гашения
757
+ * снова требуют его, как отдельный binding, отменённый при новой причине.
758
+ * Группа тогда доставляется ещё раз с новыми причинами. Fatal discard гасит
759
+ * всё.
760
+ *
761
+ * @returns false, если доставку нельзя отменить либо живых slots не осталось.
762
+ */
763
+ _cancelGroup(e, t, s) {
764
+ const i = this._reactivity;
765
+ let a = !1;
766
+ for (let r = y; r < t.length; r++) {
767
+ const d = t[r];
768
+ d === null || d.firstDep !== null || !i._beginTaskEffectRun(d) || (s ? i._disposeTaskEffect(d) : (i._requestTaskEffect(d, !1), a = !0));
769
+ }
770
+ if (a)
771
+ return !1;
772
+ const n = !s && F(e);
773
+ let o = !1;
774
+ for (let r = y; r < t.length; r++) {
775
+ const d = t[r];
776
+ if (d === null)
777
+ continue;
778
+ if (d.firstDep === null) {
779
+ o = o || d.evaluate !== void 0;
780
+ continue;
541
781
  }
542
- a(), e.discardAcknowledged = !0;
543
- } catch (a) {
544
- t.push(a);
782
+ const l = n && i._beginTaskEffectRun(d);
783
+ i._cancelTaskEffect(d) && (o = !0, l && i._rearmTaskEffect(d));
545
784
  }
785
+ return o;
546
786
  }
787
+ /**
788
+ * Сбрасывает ожидающую работу записи, снятой с очереди либо из отложенных.
789
+ * Такая запись не находится в доставке, поэтому её причины ожидающие.
790
+ */
547
791
  _clearPendingDelivery(e) {
548
- var s;
549
- e.requested = !1, e.firstCause = void 0, e.firstCauseKey = void 0, (s = e.extraCauses) == null || s.clear(), e.extraCauses = void 0;
792
+ e.state &= ~g, e.firstCause = void 0, e.firstCauseKey = void 0;
793
+ const t = e.detail;
794
+ t !== void 0 && (t.extraCauses?.clear(), t.extraCauses = void 0);
550
795
  }
551
- _settleIdleWaiters(e, s) {
552
- if (!s && (this._running || this._scheduled || this._hasPending()))
796
+ _settleIdleWaiters(e, t) {
797
+ const s = this._idleWaiters;
798
+ if (s.size === 0 || !t && (this._running || this._scheduled || this._hasPending()))
553
799
  return;
554
- const t = [...this._idleWaiters];
555
- this._idleWaiters.clear();
556
- for (const i of t)
557
- e === void 0 ? i.resolve() : i.reject(e);
800
+ const i = [...s];
801
+ s.clear();
802
+ for (const a of i)
803
+ t ? a.reject(e) : a.resolve();
558
804
  }
559
805
  _assertAlive() {
560
806
  if (this._disposed)
561
- throw new P("[Raph] Phase pipeline is disposed.");
807
+ throw new I("[Raph] Phase pipeline is disposed.");
808
+ }
809
+ }
810
+ function Y(h, e) {
811
+ return e.priority - h.priority || h.sequence - e.sequence;
812
+ }
813
+ function F(h) {
814
+ return h.firstCause !== void 0 && !(h.state & k);
815
+ }
816
+ function S(h) {
817
+ const e = h.state, t = h.detail;
818
+ if (e & k) {
819
+ h.state = e & ~k, h.firstCause = void 0, h.firstCauseKey = void 0, t !== void 0 && (t.extraCauses = void 0, t.deliveryCauses = void 0);
820
+ return;
562
821
  }
822
+ t !== void 0 && t.deliveryFirstCause !== void 0 && L(t);
563
823
  }
564
- function T(l, e) {
565
- return e.priority - l.priority || l.sequence - e.sequence;
824
+ function L(h) {
825
+ h.deliveryFirstCause = void 0, h.deliveryFirstCauseKey = void 0, h.deliveryExtraCauses = void 0, h.deliveryCauses = void 0;
566
826
  }
567
- function C(l) {
568
- return l.firstCause !== void 0;
827
+ function O() {
828
+ throw new R("[Raph] Phase task delivery is already resolved.");
569
829
  }
570
- function b(l, e) {
571
- const s = l.events === void 0 ? e.events : e.events === void 0 ? l.events : Object.freeze([...l.events, ...e.events]), t = l.structure === void 0 ? e.structure : e.structure === void 0 ? l.structure : Object.freeze({
830
+ function U(h, e) {
831
+ const t = h.events === void 0 ? e.events : e.events === void 0 ? h.events : Object.freeze([...h.events, ...e.events]), s = h.structure === void 0 ? e.structure : e.structure === void 0 ? h.structure : Object.freeze({
572
832
  node: e.structure.node,
573
- oldParent: l.structure.oldParent,
574
- oldIndex: l.structure.oldIndex,
833
+ oldParent: h.structure.oldParent,
834
+ oldIndex: h.structure.oldIndex,
575
835
  newParent: e.structure.newParent,
576
836
  newIndex: e.structure.newIndex
577
837
  });
578
838
  return Object.freeze({
579
839
  ...e,
580
- previous: l.previous,
581
- ...s === void 0 ? {} : { events: s },
582
- ...t === void 0 ? {} : { structure: t }
840
+ previous: h.previous,
841
+ ...t === void 0 ? {} : { events: t },
842
+ ...s === void 0 ? {} : { structure: s }
583
843
  });
584
844
  }
585
845
  export {
586
- R as RaphPhasePipeline
846
+ te as RaphPhasePipeline,
847
+ Q as RaphPhaseState
587
848
  };