@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 +1 @@
1
- "use strict";var u=Object.defineProperty;var n=(i,s,e)=>s in i?u(i,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[s]=e;var r=(i,s,e)=>n(i,typeof s!="symbol"?s+"":s,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("../../reactivity/scope.cjs"),c=require("../errors.cjs"),d=require("./throwDisposalErrors.cjs");class _{constructor(s,e){r(this,"id");r(this,"runtime");r(this,"_resources");r(this,"_disposed",!1);r(this,"_disposing",!1);this.id=s,this.runtime=e,this._resources=new h.ScopeNode(e._getReactivity()),e._registerOwner(this)}get disposed(){return this._disposed}get active(){return!this._disposed&&!this._disposing}get node(){}signal(s){return this._assertAlive(),this.runtime.signal(s,this)}computed(s){return this._assertAlive(),typeof s=="function"?this.runtime.computed(s,this):this.runtime.computed(s,this)}effect(s,e,t){return this._assertAlive(),this.runtime.effect(this,s,e,t)}watch(s,e,t,o){return this._assertAlive(),this.runtime.watch(this,s,e,t,o)}aggregate(s){return this._assertAlive(),this.runtime.aggregate(this,s)}action(s,e){return this._assertAlive(),typeof s=="function"?this.runtime.action(s,this):this.runtime.action(s,e,this)}own(s){return this.active?this._resources._own(s):(s(),a)}dispose(){if(this._disposed)return;this._disposed=!0,this._disposing=!0;const s=!this.runtime._ownerDisposalActive();s&&this.runtime._beginOwnerDisposal();const e=[];try{try{this._resources.dispose()}catch(t){e.push(t)}}finally{this._disposing=!1;try{this.runtime._unregisterOwner(this)}catch(t){e.push(t)}if(s)try{this.runtime._endOwnerDisposal()}catch(t){e.push(t)}}d.throwDisposalErrors(e,`[Raph] Scope "${this.id}" disposal failed.`)}_adoptResource(s){return this._assertAlive(),this._resources._adoptResource(s)}_adoptSource(s){return this._assertAlive(),this._resources._adoptSource(s)}_debugResourceCount(){return this._resources._debugResourceCount()}_debugSourceCount(){return this._resources._debugSourceCount()}_assertAlive(){if(this._disposed||this._disposing)throw new c.RaphDisposedError(`[Raph] Owner "${this.id}" is disposed.`)}}function a(){}exports.RaphScope=_;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("../../reactivity/disposal.cjs"),c=require("../../reactivity/scope.cjs"),p=require("../errors.cjs");let l,u;class n extends c.ScopeOwner{constructor(e,t){super(),this._id=e,this.runtime=t,this._order=t._registerOwner(this)}get id(){return this._id}get node(){}signal(e){return this._assertAlive(),this.runtime.signal(e,this)}computed(e){return this._assertAlive(),typeof e=="function"?this.runtime.computed(e,this):this.runtime.computed(e,this)}selector(e,t){const i=this.runtime;return i._assertOwnerRuntime(this),i._getReactivity().selectorForOwner(e,this,t).select}effect(e,t,i){return this._assertAlive(),this.runtime.effect(this,e,t,i)}bindEffect(e,t,i){this._assertAlive(),this.runtime._effectRegistration(this,e,t,i,!1,!0)}effectGroup(e,t,i,s,r){return this._assertAlive(),this.runtime._effectGroupRegistration(this,e,t,i,s,r)}watch(e,t,i,s){return this._assertAlive(),this.runtime.watch(this,e,t,i,s)}_registerEffect(e,t,i,s,r,h){this._assertAlive(),this.runtime._effectRegistration(this,e,t,i,!1,s,r,h)}_registerWatch(e,t,i,s,r,h){this._assertAlive(),this.runtime._watchRegistration(this,e,t,i,s,!1,r,h)}_registerEffectGroup(e,t,i,s,r){return this._assertAlive(),this.runtime._effectGroupRegistration(this,e,t,i,s,r)}aggregate(e){return this._assertAlive(),this.runtime.aggregate(this,e)}action(e,t){return this._assertAlive(),typeof e=="function"?this.runtime.action(e,this):this.runtime.action(e,t,this)}own(e){return this._disposed||this._disposing?(e(),a):this._ownCleanup(e)}dispose(){o.throwDisposalFailure(u.call(this))}_disposeScopeForOwner(e){try{if(e===l)return u.call(this);e.call(this);return}catch(t){return o.unroutedDisposalFailure(t)}}_disposeWithOutcome(){if(this._disposed)return;this._disposed=!0,this._disposing=!0;const e=this.runtime,t=!e._ownerDisposalActive();t&&e._beginOwnerDisposal();let i;try{const s=this._releaseOwned();s!==void 0&&(i=[o.combineDisposalFailures(s,"ScopeNode disposal failed.")])}finally{this._disposing=!1;try{e._unregisterOwner(this)}catch(s){(i??=[]).push(o.unroutedDisposalFailure(s))}if(t)try{e._endOwnerDisposal()}catch(s){(i??=[]).push(o.unroutedDisposalFailure(s))}}if(i!==void 0)return o.combineDisposalFailures(i,`[Raph] Scope "${this.id}" disposal failed.`)}_ownCompletedCleanup(e){return this._disposed||this._disposing?(o.throwDisposalFailure(e()),a):this._ownCompleted(e)}_adoptResource(e){return this._assertAlive(),this._ownCleanup(e)}_adoptRecord(e){this._assertAlive(),this._ownRecord(e)}_adoptSource(e){return this._assertAlive(),this._ownSourceFinalizer(e.dispose),e.source}_adoptSourceEntry(e){this._assertAlive(),this._ownSourceEntry(e)}_assertAlive(){if(this._disposed||this._disposing)throw new p.RaphDisposedError(`[Raph] Owner "${this.id}" is disposed.`)}}n.prototype._isNode=!1;function a(){}l=n.prototype.dispose;u=n.prototype._disposeWithOutcome;exports.RaphScope=n;
@@ -1,101 +1,236 @@
1
- var h = Object.defineProperty;
2
- var u = (i, s, t) => s in i ? h(i, s, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[s] = t;
3
- var r = (i, s, t) => u(i, typeof s != "symbol" ? s + "" : s, t);
4
- import { ScopeNode as n } from "../../reactivity/scope.js";
5
- import { RaphDisposedError as c } from "../errors.js";
6
- import { throwDisposalErrors as d } from "./throwDisposalErrors.js";
7
- class f {
8
- constructor(s, t) {
9
- r(this, "id");
10
- r(this, "runtime");
11
- r(this, "_resources");
12
- r(this, "_disposed", !1);
13
- r(this, "_disposing", !1);
14
- this.id = s, this.runtime = t, this._resources = new n(t._getReactivity()), t._registerOwner(this);
15
- }
16
- get disposed() {
17
- return this._disposed;
18
- }
19
- get active() {
20
- return !this._disposed && !this._disposing;
1
+ import { throwDisposalFailure as u, unroutedDisposalFailure as n, combineDisposalFailures as p } from "../../reactivity/disposal.js";
2
+ import { ScopeOwner as l } from "../../reactivity/scope.js";
3
+ import { RaphDisposedError as d } from "../errors.js";
4
+ let _, h;
5
+ class a extends l {
6
+ constructor(t, e) {
7
+ super(), this._id = t, this.runtime = e, this._order = e._registerOwner(this);
8
+ }
9
+ /**
10
+ * Возвращает id владельца; plain scope всегда хранит явную строку.
11
+ */
12
+ get id() {
13
+ return this._id;
21
14
  }
22
15
  /** Stable selector for process ordering; plain scopes are not tree nodes. */
23
16
  get node() {
24
17
  }
25
- signal(s) {
26
- return this._assertAlive(), this.runtime.signal(s, this);
18
+ signal(t) {
19
+ return this._assertAlive(), this.runtime.signal(t, this);
20
+ }
21
+ computed(t) {
22
+ return this._assertAlive(), typeof t == "function" ? this.runtime.computed(t, this) : this.runtime.computed(t, this);
23
+ }
24
+ /**
25
+ * Создаёт selector над записываемым signal: функцию `(key) => boolean`,
26
+ * которая отвечает, совпадает ли ключ с текущим значением `source`, и
27
+ * подписывает потребителя только на этот ключ. Запись в `source` будит
28
+ * потребителей прежнего и нового значения, а не всех читателей.
29
+ *
30
+ * Selector принадлежит этому владельцу и живёт до его освобождения; `source`
31
+ * должен принадлежать самому владельцу, его предку или root scope. Читать
32
+ * selector вправе те же потребители, что и signal этого владельца.
33
+ *
34
+ * @typeParam Key — тип ключа и значения `source`.
35
+ */
36
+ selector(t, e) {
37
+ const i = this.runtime;
38
+ return i._assertOwnerRuntime(this), i._getReactivity().selectorForOwner(t, this, e).select;
39
+ }
40
+ effect(t, e, i) {
41
+ return this._assertAlive(), this.runtime.effect(this, t, e, i);
42
+ }
43
+ /**
44
+ * Регистрирует phase effect без task и без disposer. Тело вызывается без
45
+ * аргументов, а binding живёт до освобождения этого владельца: отдельно его
46
+ * остановить нельзя. Зависимости, порядок, `initial`, `priority` и cleanup
47
+ * те же, что у `effect()`.
48
+ *
49
+ * Frozen task такого binding создаётся, только если его запросит `process`
50
+ * своей phase; на регистрацию приходится одна запись binding.
51
+ * Для тела, которому нужна task или отдельная остановка, остаётся `effect()`.
52
+ */
53
+ bindEffect(t, e, i) {
54
+ this._assertAlive(), this.runtime._effectRegistration(this, t, e, i, !1, !0);
55
+ }
56
+ /**
57
+ * Регистрирует группу из `count` phase effects на одном binding: без task и
58
+ * без disposer, как `bindEffect()`. `runSlot(run)` — тело каждого slot: оно
59
+ * получает запуск, где `run[0]` — context группы, а `run[1]` — номер slot.
60
+ * Чтения внутри вызова отслеживаются отдельно для этого slot, поэтому
61
+ * изменение зависимости перезапускает только те slots, которые её читали.
62
+ *
63
+ * Группа — одна phase task и один ресурс владельца. Регистрация ничего не
64
+ * исполняет: каждый slot запускает `start(slot, initial?)` возвращённой
65
+ * группы, и с этого вызова slot ведёт себя как binding, который
66
+ * `bindEffect()` зарегистрировал бы в этом месте. Доставка исполняет
67
+ * запущенные slots, чьи зависимости изменились, в порядке их номеров; сбой
68
+ * одного slot не мешает остальным и сообщается отдельной ошибкой, как сбой
69
+ * отдельного binding. Причины всех slots складываются в `causes` одной task,
70
+ * которую custom `process` получает на всю группу. Cleanup, который вернул
71
+ * slot, выполняется перед его следующим запуском и при освобождении группы.
72
+ *
73
+ * Порядок `priority desc → FIFO` действует между tasks: группа занимает в
74
+ * очереди phase место своего первого изменившегося slot. Внутри task slots
75
+ * исполняются по номерам, а slot, который изменился, пока его группа
76
+ * доставляется, исполняется в этой же доставке, если до него ещё не дошла
77
+ * очередь. Slot, в источник которого записали, пока он ждал запуска в этой
78
+ * доставке, исполняется в ней один раз и читает новое значение; slot, чьи
79
+ * зависимости не изменились, тело не исполняет, даже если причина пришла
80
+ * группе из-за соседнего slot. После доставки, во время которой группе
81
+ * пришла причина, группа доставляется ещё раз с новыми причинами и
82
+ * исполняет только slots, изменившиеся после своего запуска; `cancel()`
83
+ * доставки, во время которой пришла причина, оставляет ждавшие slots
84
+ * запланированными.
85
+ *
86
+ * Группа живёт до освобождения этого владельца: отдельно её остановить
87
+ * нельзя. Владелец освобождает её после ресурсов, зарегистрированных позже,
88
+ * в том числе телами её slots; slots освобождаются в порядке, обратном
89
+ * порядку номеров. Несколько сбоев cleanup при освобождении группы приходят
90
+ * одним `AggregateError` с сообщением `[Raph] Effect group disposal failed.`
91
+ * как один сбой ресурса владельца; единственный сбой бросается как есть.
92
+ *
93
+ * @typeParam Context — значение, которое получает тело каждого slot.
94
+ * @param phase Имя объявленной phase.
95
+ * @param count Число slots: целое от 1 до 4294967293, иначе `RangeError`.
96
+ * @param runSlot Тело slot: получает запуск с `context` и номером slot.
97
+ * @param context Значение, которое группа передаёт телу каждого slot.
98
+ * @param options `priority` task группы, как у `effect()`.
99
+ */
100
+ effectGroup(t, e, i, s, r) {
101
+ return this._assertAlive(), this.runtime._effectGroupRegistration(
102
+ this,
103
+ t,
104
+ e,
105
+ i,
106
+ s,
107
+ r
108
+ );
109
+ }
110
+ watch(t, e, i, s) {
111
+ return this._assertAlive(), this.runtime.watch(this, t, e, i, s);
112
+ }
113
+ /**
114
+ * Внутренняя регистрация renderer без возвращаемого disposer. Failure
115
+ * continuation относится только к завершившемуся execution request.
116
+ * @internal
117
+ */
118
+ _registerEffect(t, e, i, s, r, o) {
119
+ this._assertAlive(), this.runtime._effectRegistration(this, t, e, i, !1, s, r, o);
27
120
  }
28
- computed(s) {
29
- return this._assertAlive(), typeof s == "function" ? this.runtime.computed(s, this) : this.runtime.computed(s, this);
30
- }
31
- effect(s, t, e) {
32
- return this._assertAlive(), this.runtime.effect(this, s, t, e);
33
- }
34
- watch(s, t, e, o) {
35
- return this._assertAlive(), this.runtime.watch(this, s, t, e, o);
36
- }
37
- aggregate(s) {
38
- return this._assertAlive(), this.runtime.aggregate(this, s);
121
+ /** @internal */
122
+ _registerWatch(t, e, i, s, r, o) {
123
+ this._assertAlive(), this.runtime._watchRegistration(this, t, e, i, s, !1, r, o);
124
+ }
125
+ /**
126
+ * Выдаёт внутренний typed handle вместо приведения публичного group handle.
127
+ * Порядок создания и принятия ресурса совпадает с effectGroup().
128
+ * @internal
129
+ */
130
+ _registerEffectGroup(t, e, i, s, r) {
131
+ return this._assertAlive(), this.runtime._effectGroupRegistration(
132
+ this,
133
+ t,
134
+ e,
135
+ i,
136
+ s,
137
+ r
138
+ );
139
+ }
140
+ aggregate(t) {
141
+ return this._assertAlive(), this.runtime.aggregate(this, t);
142
+ }
143
+ action(t, e) {
144
+ return this._assertAlive(), typeof t == "function" ? this.runtime.action(t, this) : this.runtime.action(t, e, this);
145
+ }
146
+ own(t) {
147
+ return this._disposed || this._disposing ? (t(), c) : this._ownCleanup(t);
39
148
  }
40
- action(s, t) {
41
- return this._assertAlive(), typeof s == "function" ? this.runtime.action(s, this) : this.runtime.action(s, t, this);
149
+ dispose() {
150
+ u(h.call(this));
42
151
  }
43
- own(s) {
44
- return this.active ? this._resources._own(s) : (s(), _);
152
+ /** Node's super stage keeps the actual public base-method lookup observable. @internal */
153
+ _disposeScopeForOwner(t) {
154
+ try {
155
+ if (t === _)
156
+ return h.call(this);
157
+ t.call(this);
158
+ return;
159
+ } catch (e) {
160
+ return n(e);
161
+ }
45
162
  }
46
- dispose() {
163
+ /** One explicit framework disposal result; public dispose never leaks it. @internal */
164
+ _disposeWithOutcome() {
47
165
  if (this._disposed)
48
166
  return;
49
167
  this._disposed = !0, this._disposing = !0;
50
- const s = !this.runtime._ownerDisposalActive();
51
- s && this.runtime._beginOwnerDisposal();
52
- const t = [];
168
+ const t = this.runtime, e = !t._ownerDisposalActive();
169
+ e && t._beginOwnerDisposal();
170
+ let i;
53
171
  try {
54
- try {
55
- this._resources.dispose();
56
- } catch (e) {
57
- t.push(e);
58
- }
172
+ const s = this._releaseOwned();
173
+ s !== void 0 && (i = [p(s, "ScopeNode disposal failed.")]);
59
174
  } finally {
60
175
  this._disposing = !1;
61
176
  try {
62
- this.runtime._unregisterOwner(this);
63
- } catch (e) {
64
- t.push(e);
177
+ t._unregisterOwner(this);
178
+ } catch (s) {
179
+ (i ??= []).push(n(s));
65
180
  }
66
- if (s)
181
+ if (e)
67
182
  try {
68
- this.runtime._endOwnerDisposal();
69
- } catch (e) {
70
- t.push(e);
183
+ t._endOwnerDisposal();
184
+ } catch (s) {
185
+ (i ??= []).push(n(s));
71
186
  }
72
187
  }
73
- d(t, `[Raph] Scope "${this.id}" disposal failed.`);
188
+ if (i !== void 0)
189
+ return p(i, `[Raph] Scope "${this.id}" disposal failed.`);
74
190
  }
75
- /** @internal */
76
- _adoptResource(s) {
77
- return this._assertAlive(), this._resources._adoptResource(s);
78
- }
79
- /** @internal */
80
- _adoptSource(s) {
81
- return this._assertAlive(), this._resources._adoptSource(s);
191
+ /** Framework capture registration; ordinary own callback semantics are unchanged. @internal */
192
+ _ownCompletedCleanup(t) {
193
+ return this._disposed || this._disposing ? (u(t()), c) : this._ownCompleted(t);
82
194
  }
83
195
  /** @internal */
84
- _debugResourceCount() {
85
- return this._resources._debugResourceCount();
196
+ _adoptResource(t) {
197
+ return this._assertAlive(), this._ownCleanup(t);
198
+ }
199
+ /**
200
+ * Связывает готовую запись ресурса: запись сама становится элементом списка
201
+ * ресурсов этого владельца, без обёртки и closure, и освобождает себя через
202
+ * унаследованный _releaseRecord() из собственного dispose().
203
+ *
204
+ * @internal
205
+ */
206
+ _adoptRecord(t) {
207
+ this._assertAlive(), this._ownRecord(t);
86
208
  }
87
209
  /** @internal */
88
- _debugSourceCount() {
89
- return this._resources._debugSourceCount();
210
+ _adoptSource(t) {
211
+ return this._assertAlive(), this._ownSourceFinalizer(t.dispose), t.source;
212
+ }
213
+ /**
214
+ * Связывает готовую запись источника: источник сам становится элементом
215
+ * списка источников этого владельца, без обёртки и closure, и освобождает
216
+ * себя через собственный _finalizeSource().
217
+ *
218
+ * @internal
219
+ */
220
+ _adoptSourceEntry(t) {
221
+ this._assertAlive(), this._ownSourceEntry(t);
90
222
  }
91
223
  /** @internal */
92
224
  _assertAlive() {
93
225
  if (this._disposed || this._disposing)
94
- throw new c(`[Raph] Owner "${this.id}" is disposed.`);
226
+ throw new d(`[Raph] Owner "${this.id}" is disposed.`);
95
227
  }
96
228
  }
97
- function _() {
229
+ a.prototype._isNode = !1;
230
+ function c() {
98
231
  }
232
+ _ = a.prototype.dispose;
233
+ h = a.prototype._disposeWithOutcome;
99
234
  export {
100
- f as RaphScope
235
+ a as RaphScope
101
236
  };
@@ -1 +1 @@
1
- "use strict";var a=Object.defineProperty;var r=(n,e,i)=>e in n?a(n,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):n[e]=i;var s=(n,e,i)=>r(n,typeof e!="symbol"?e+"":e,i);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class l{constructor(e){s(this,"_leases",new Map);s(this,"_frameHandle");s(this,"_frameHandleKind");s(this,"_scheduleToken",0);s(this,"_running",!1);s(this,"_manual",!1);this._tick=e}get running(){return this._running}acquire(e){this._leases.set(e,(this._leases.get(e)??0)+1),this._ensureRunning();let i=!0;return{owner:e,release:()=>{if(!i)return;i=!1;const t=this._leases.get(e)??0;t<=1?this._leases.delete(e):this._leases.set(e,t-1),this._reconcile()}}}start(){this._manual=!0,this._ensureRunning()}stop(){this._manual=!1,this._reconcile()}dispose(){this._manual=!1,this._leases.clear(),this._stop()}_debugState(){let e=0;for(const i of this._leases.values())e+=i;return{running:this._running,manual:this._manual,leases:e}}_onFrame(e){if(!(!this._running||e!==this._scheduleToken)){this._frameHandle=void 0,this._frameHandleKind=void 0;try{this._tick()}catch(i){throw this._running=!1,i}this._running&&this._schedule()}}_ensureRunning(){this._running||(this._running=!0,this._schedule())}_schedule(){const e=++this._scheduleToken;if(typeof globalThis.requestAnimationFrame=="function"){this._frameHandleKind="animation-frame",this._frameHandle=globalThis.requestAnimationFrame(()=>this._onFrame(e));return}this._frameHandleKind="timeout",this._frameHandle=setTimeout(()=>this._onFrame(e),16)}_reconcile(){if(this._manual||this._leases.size!==0){this._ensureRunning();return}this._stop()}_stop(){var e;this._running=!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}}exports.RaphFrameLoop=l;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class n{constructor(e){this._tick=e}_leases=new Map;_frameHandle;_frameHandleKind;_scheduleToken=0;_running=!1;_manual=!1;get running(){return this._running}acquire(e){this._leases.set(e,(this._leases.get(e)??0)+1),this._ensureRunning();let i=!0;return{owner:e,release:()=>{if(!i)return;i=!1;const s=this._leases.get(e)??0;s<=1?this._leases.delete(e):this._leases.set(e,s-1),this._reconcile()}}}start(){this._manual=!0,this._ensureRunning()}stop(){this._manual=!1,this._reconcile()}dispose(){this._manual=!1,this._leases.clear(),this._stop()}_debugState(){let e=0;for(const i of this._leases.values())e+=i;return{running:this._running,manual:this._manual,leases:e}}_onFrame(e){if(!(!this._running||e!==this._scheduleToken)){this._frameHandle=void 0,this._frameHandleKind=void 0;try{this._tick()}catch(i){throw this._running=!1,i}this._running&&this._schedule()}}_ensureRunning(){this._running||(this._running=!0,this._schedule())}_schedule(){const e=++this._scheduleToken;if(typeof globalThis.requestAnimationFrame=="function"){this._frameHandleKind="animation-frame",this._frameHandle=globalThis.requestAnimationFrame(()=>this._onFrame(e));return}this._frameHandleKind="timeout",this._frameHandle=setTimeout(()=>this._onFrame(e),16)}_reconcile(){if(this._manual||this._leases.size!==0){this._ensureRunning();return}this._stop()}_stop(){this._running=!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}}exports.RaphFrameLoop=n;
@@ -1,21 +1,18 @@
1
- var a = Object.defineProperty;
2
- var r = (n, e, i) => e in n ? a(n, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : n[e] = i;
3
- var s = (n, e, i) => r(n, typeof e != "symbol" ? e + "" : e, i);
4
- class h {
1
+ class t {
5
2
  /**
6
3
  * Создаёт frame-loop, который запрашивает выполнение runtime pipeline.
7
4
  */
8
5
  constructor(e) {
9
- // Хранят leases и текущую browser/timeout frame registration.
10
- s(this, "_leases", /* @__PURE__ */ new Map());
11
- s(this, "_frameHandle");
12
- s(this, "_frameHandleKind");
13
- s(this, "_scheduleToken", 0);
14
- // Различают фактический loop lifecycle и ручной lease.
15
- s(this, "_running", !1);
16
- s(this, "_manual", !1);
17
6
  this._tick = e;
18
7
  }
8
+ // Хранят leases и текущую browser/timeout frame registration.
9
+ _leases = /* @__PURE__ */ new Map();
10
+ _frameHandle;
11
+ _frameHandleKind;
12
+ _scheduleToken = 0;
13
+ // Различают фактический loop lifecycle и ручной lease.
14
+ _running = !1;
15
+ _manual = !1;
19
16
  /**
20
17
  * Показывает, выполняется ли автоматический frame-loop.
21
18
  */
@@ -34,8 +31,8 @@ class h {
34
31
  if (!i)
35
32
  return;
36
33
  i = !1;
37
- const t = this._leases.get(e) ?? 0;
38
- t <= 1 ? this._leases.delete(e) : this._leases.set(e, t - 1), this._reconcile();
34
+ const s = this._leases.get(e) ?? 0;
35
+ s <= 1 ? this._leases.delete(e) : this._leases.set(e, s - 1), this._reconcile();
39
36
  }
40
37
  };
41
38
  }
@@ -97,10 +94,9 @@ class h {
97
94
  this._stop();
98
95
  }
99
96
  _stop() {
100
- var e;
101
- this._running = !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;
97
+ this._running = !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;
102
98
  }
103
99
  }
104
100
  export {
105
- h as RaphFrameLoop
101
+ t as RaphFrameLoop
106
102
  };
@@ -1 +1 @@
1
- "use strict";var q=Object.defineProperty;var D=(l,e,s)=>e in l?q(l,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):l[e]=s;var d=(l,e,s)=>D(l,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("../errors.cjs"),g=Object.freeze([]),k=Object.freeze({now:0,delta:0,elapsed:0,frame:0}),A=1e4,R=1e4,E=Symbol("RaphPhaseTaskRecord");class x{constructor(e,s,t,i=()=>!1,n){d(this,"_phases",[]);d(this,"_phaseByName",new Map);d(this,"_phaseBindings",new Map);d(this,"_queues",new Map);d(this,"_deferred",new Set);d(this,"_idleWaiters",new Set);d(this,"_taskSequence",0);d(this,"_scheduled",!1);d(this,"_scheduleToken",0);d(this,"_frameHandle");d(this,"_frameHandleKind");d(this,"_configurationLocked",!1);d(this,"_running",!1);d(this,"_disposed",!1);d(this,"_firstFrameAt");d(this,"_lastFrameAt");d(this,"_frameNumber",0);d(this,"_frame",k);this._scheduler=e,this._runUntracked=s,this._resolveCause=t,this._deferSync=i,this._tracePhase=n}get frame(){return this._frame}get phases(){return this._phases.map(e=>e.phase)}definePhases(e){if(this._assertAlive(),this._configurationLocked||this._firstFrameAt!==void 0)throw new Error("[Raph] Cannot redefine phases after phase pipeline execution has started.");const s=new Map,t=[];for(const i of e){const n=i.name.trim();if(!n)throw new Error("[Raph] Phase name must not be empty.");if(s.has(n))throw new Error(`[Raph] Duplicate phase name "${n}".`);if(i.process!==void 0&&typeof i.process!="function")throw new TypeError(`[Raph] Phase "${n}" process must be a function.`);const a=Object.freeze({name:n,...i.process===void 0?{}:{process:i.process}}),r={index:t.length,phase:a};t.push(r),s.set(n,r)}this._assertRetainedPhases(s),this._phases=t,this._phaseByName=s}addPhase(e){this.definePhases([...this.phases,e])}clearPhases(){this.definePhases([])}requirePhase(e){if(this._assertAlive(),!this._phaseByName.has(e))throw new Error(`[Raph] Phase "${e}" is not defined.`)}bindTask(e,s,t,i,n){const a=e.trim();if(this.requirePhase(a),!Number.isFinite(i))throw new TypeError("[Raph] Effect priority must be finite.");this._phaseBindings.set(a,(this._phaseBindings.get(a)??0)+1);const r={},h=this._createTask(r);Object.assign(r,{active:!0,paused:!1,pending:!1,deferred:!1,inDelivery:!1,discardAcknowledged:!1,requested:!1,resolution:"unresolved",deferCount:0,sequence:0,phase:a,priority:i,consumerOwner:s,effect:t,runner:n,task:h,deliveryCauses:g,frame:k});const f={dependencyOwner:s,allowScheduleDuringRun:!0,task:h,notify:o=>{const _=this._resolveCause(o);if(_!==void 0){const c=_.kind==="structure"?_.source:o;this._appendCause(r,_,c)}},schedule:()=>this._queue(r),enqueue:(o,_=o.source,c=!0)=>{this._appendCause(r,o,_),this._queue(r,c)},pause:()=>this._pauseTask(r),resume:()=>this._resumeTask(r),dispose:()=>this._disposeTask(r)};return r.binding=f,f}request(){this._assertAlive(),this._hasQueued()&&this._schedule()}afterFlush(){return this._assertAlive(),!this._running&&!this._scheduled&&!this._hasPending()?Promise.resolve():new Promise((e,s)=>{this._idleWaiters.add({reject:s,resolve:e})})}flush(){var n,a,r;if(this._assertAlive(),this._cancelScheduled(),this._running)return;if(!this._hasQueued()&&this._deferred.size!==0&&this._activateDeferred(),!this._hasQueued()){this._settleIdleWaiters(void 0,!1);return}this._configurationLocked=!0,this._running=!0;const e=[],s=this._nextFrame();let t=0;try{for(;this._hasQueued();){if(++t>A){const h=this._describeQueued();this._cancelAllQueued(!0,e),e.push(new Error(`[Raph] Phase flush exceeded 10000 passes.${h?` Pending: ${h}.`:""}`));break}for(const h of this._phases){if(this._disposed)break;const f=this._takePhase(h.phase.name);if(f.length===0)continue;const o=e.length;(n=this._tracePhase)==null||n.call(this,h.phase.name,"start");let _=0,c=!0,p;for(const u of f){if(u.pending=!1,!u.active||u.consumerOwner.disposed){this._disposeTask(u);continue}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}if(f.length=_,f.length===0)continue;c||f.sort(K);const P=h.phase.process;if(P===void 0)for(const u of f)try{this._runDelivery(u)}catch(m){e.push(m)}else{const u=[];for(const w of f)u.push(w.task);const m=Object.freeze({phase:h.phase.name,frame:s,tasks:Object.freeze(u)});try{this._runUntracked(()=>P(m))}catch(w){e.push(w)}}let y=0;for(const u of f){if(u.resolution==="unresolved"){y++;try{this._deferDelivery(u)}catch(m){u.resolution="cancel",this._acknowledgeDiscard(u,!0,e),e.push(m)}}try{this._finishDelivery(u)}catch(m){u.resolution!=="run"&&this._acknowledgeDiscard(u,!0,e),u.resolution="cancel",u.inDelivery=!1,u.deliveryFirstCauseKey=void 0,u.deliveryExtraCauseKeys=void 0,u.deliveryCauses=g,e.push(m)}}y!==0&&e.push(new v.RaphPhaseProcessError(`[Raph] Phase "${h.phase.name}" left ${y} task(s) unresolved; they were deferred.`)),e.length===o?(a=this._tracePhase)==null||a.call(this,h.phase.name,"end"):(r=this._tracePhase)==null||r.call(this,h.phase.name,"error",e[e.length-1])}}}catch(h){e.push(h),this._cancelAllQueued(!0,e),this._cancelAllDeferred(!0,e)}finally{this._running=!1}try{this._deferred.size!==0&&this._scheduleDeferredTurn()}catch(h){e.push(h)}const i=e.length===1?e[0]:e.length>1?new AggregateError(e,"[Raph] Multiple phase tasks failed."):void 0;if(i!==void 0)throw this._settleIdleWaiters(i,!0),i;this._settleIdleWaiters(void 0,!1)}dispose(){if(this._disposed)return;this._disposed=!0,this._cancelScheduled(),this._cancelAllQueued(!1);const e=[...this._deferred];this._cancelAllDeferred(!1);for(const t of e)t.active=!1;this._phaseBindings.clear(),this._phases=[],this._phaseByName.clear();const s=new v.RaphDisposedError("[Raph] Phase pipeline is disposed.");this._settleIdleWaiters(s,!0)}_debugPending(){return this._scheduled||this._running||this._hasPending()}_describeQueued(){var s;const e=[];for(const t of this._phases){const i=((s=this._queues.get(t.phase.name))==null?void 0:s.filter(a=>a.active&&!a.consumerOwner.disposed))??[];if(i.length===0)continue;const n=i.slice(0,3).map(a=>{var c,p;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}`;return`${f}${a.firstCause?`:${a.firstCause.kind}${_}`:""}`}).join(", ");e.push(`${t.phase.name}=${i.length}${n?` [${n}]`:""}`)}return e.join("; ")}_createTask(e){const s={get phase(){return e.phase},get consumerOwner(){return e.consumerOwner},get effect(){return e.effect},get causes(){return e.deliveryCauses},get frame(){return e.frame},get priority(){return e.priority},get sequence(){return e.sequence},run:()=>this._runDelivery(e),defer:()=>this._deferDelivery(e),cancel:()=>this._cancelDelivery(e)};return Object.defineProperty(s,E,{value:e}),Object.freeze(s)}_beginDelivery(e,s){e.pending=!1,e.inDelivery=!0,e.discardAcknowledged=!1,e.requested=!1,e.resolution="unresolved",e.frame=s;const t=e.firstCause;if(t===void 0){e.deliveryFirstCauseKey=void 0,e.deliveryExtraCauseKeys=void 0,e.deliveryCauses=g;return}const i=e.extraCauses;if(e.deliveryFirstCauseKey=e.firstCauseKey,e.firstCause=void 0,e.firstCauseKey=void 0,e.extraCauses=void 0,i===void 0||i.size===0){e.deliveryExtraCauseKeys=void 0,e.deliveryCauses=Object.freeze([t]);return}e.deliveryExtraCauseKeys=Object.freeze([...i.keys()]),e.deliveryCauses=Object.freeze([t,...i.values()])}_runDelivery(e){if(!e.active||e.paused||e.consumerOwner.disposed){e.resolution="cancel";return}this._assertDelivery(e),e.resolution="run",e.deferCount=0,this._runUntracked(e.runner)}_deferDelivery(e){if(!e.active||e.paused||e.consumerOwner.disposed){e.resolution="cancel";return}if(this._assertDelivery(e),e.resolution="defer",++e.deferCount>R){e.resolution="cancel";const s=[];throw this._acknowledgeDiscard(e,!0,s),s.length!==0?new AggregateError([new v.RaphPhaseProcessError(`[Raph] Phase task in "${e.phase}" exceeded 10000 deferred deliveries.`),...s],"[Raph] Phase task defer limit and recovery failed."):new v.RaphPhaseProcessError(`[Raph] Phase task in "${e.phase}" exceeded 10000 deferred deliveries.`)}}_cancelDelivery(e){if(!e.active||e.consumerOwner.disposed){e.resolution="cancel";return}this._assertDelivery(e);const s=[];if(this._acknowledgeDiscard(e,!1,s),s.length!==0)throw s.length===1?s[0]:new AggregateError(s,"[Raph] Phase task cancellation failed.");e.discardAcknowledged&&(e.requested=C(e)),e.resolution="cancel",e.deferCount=0}_finishDelivery(e){var t;if(!e.inDelivery)return;const s=e.resolution;if(e.inDelivery=!1,!e.active||e.consumerOwner.disposed){e.deliveryFirstCauseKey=void 0,e.deliveryExtraCauseKeys=void 0,e.deliveryCauses=g;return}if(e.paused){s!=="run"&&!(s==="cancel"&&e.discardAcknowledged)&&(this._restoreDeliveryCausesBeforePending(e),e.requested=!0),e.deliveryFirstCauseKey=void 0,e.deliveryExtraCauseKeys=void 0,e.deliveryCauses=g;return}if(s==="defer"&&(this._restoreDeliveryCausesBeforePending(e),e.deferred=!0,this._deferred.add(e)),e.deliveryFirstCauseKey=void 0,e.deliveryExtraCauseKeys=void 0,e.deliveryCauses=g,s!=="defer"&&(e.requested||C(e))){const i=(t=e.binding)==null?void 0:t.rearmPending;i===void 0?this._queue(e):i()}}_appendCause(e,s,t){if(!e.active)return;const i=e.firstCause;if(i===void 0){e.firstCause=s,e.firstCauseKey=t;return}if(e.firstCauseKey===t){e.firstCause=b(i,s);return}const n=e.extraCauses??(e.extraCauses=new Map),a=n.get(t);n.set(t,a===void 0?s:b(a,s))}_queue(e,s=!0){if(!e.active||e.consumerOwner.disposed||this._disposed)return;if(e.paused){e.requested=!0;return}if(e.inDelivery){e.requested=!0;return}if(e.pending){s&&this._schedule();return}if(e.deferred)return;e.discardAcknowledged=!1,e.pending=!0,e.sequence=this._taskSequence++;let t=this._queues.get(e.phase);t===void 0&&(t=[],this._queues.set(e.phase,t)),t.push(e),s&&this._schedule()}_disposeTask(e){var i;if(!e.active)return;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=g,this._deferred.delete(e);const s=this._queues.get(e.phase);if(s!==void 0){const n=s.indexOf(e);n>=0&&s.splice(n,1),s.length===0&&this._queues.delete(e.phase)}const t=(this._phaseBindings.get(e.phase)??1)-1;t===0?this._phaseBindings.delete(e.phase):this._phaseBindings.set(e.phase,t),this._hasPending()||this._cancelScheduled(),this._settleIdleWaiters(void 0,!1)}_pauseTask(e){if(!e.active||e.paused)return;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));const s=this._queues.get(e.phase);if(s!==void 0){const t=s.indexOf(e);t>=0&&s.splice(t,1),s.length===0&&this._queues.delete(e.phase)}this._hasPending()||this._cancelScheduled(),this._settleIdleWaiters(void 0,!1)}_resumeTask(e){!e.active||!e.paused||e.consumerOwner.disposed||(e.paused=!1,(e.requested||C(e))&&(e.requested=!1,this._queue(e)))}_restoreDeliveryCausesBeforePending(e){const s=e.deliveryCauses;if(s.length===0)return;const t=e.firstCause,i=e.firstCauseKey,n=e.extraCauses;e.firstCause=void 0,e.firstCauseKey=void 0,e.extraCauses=void 0,this._appendCause(e,s[0],e.deliveryFirstCauseKey);const a=e.deliveryExtraCauseKeys;for(let r=1;r<s.length;r++)this._appendCause(e,s[r],a[r-1]);if(t!==void 0&&(this._appendCause(e,t,i),n!==void 0))for(const[r,h]of n)this._appendCause(e,h,r)}_takePhase(e){const s=this._queues.get(e);return s===void 0?[]:(this._queues.delete(e),s)}_schedule(){if(this._running||this._scheduled||this._disposed)return;if(this._scheduler==="sync"){if(this._deferSync())return;this.flush();return}this._scheduled=!0;const e=++this._scheduleToken,s=()=>{this._disposed||!this._scheduled||e!==this._scheduleToken||(this._scheduled=!1,this._frameHandle=void 0,this._frameHandleKind=void 0,this.flush())};if(this._scheduler==="microtask"){queueMicrotask(s);return}typeof globalThis.requestAnimationFrame=="function"?(this._frameHandleKind="animation-frame",this._frameHandle=globalThis.requestAnimationFrame(s)):(this._frameHandleKind="timeout",this._frameHandle=setTimeout(s,16))}_scheduleDeferredTurn(){if(this._scheduled||this._disposed)return;this._scheduled=!0;const e=++this._scheduleToken,s=()=>{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))};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)}_cancelScheduled(){var e;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)}_activateDeferred(){const e=[...this._deferred];this._deferred.clear();for(const s of e)s.deferred=!1,this._queue(s,!1)}_nextFrame(){var t;const e=((t=globalThis.performance)==null?void 0:t.now())??Date.now();if(this._firstFrameAt===void 0||this._lastFrameAt===void 0)return this._firstFrameAt=e,this._lastFrameAt=e,this._frame=Object.freeze({now:e,delta:0,elapsed:0,frame:0});this._frameNumber++;const s=Object.freeze({now:e,delta:Math.min(Math.max(e-this._lastFrameAt,0),100),elapsed:Math.max(e-this._firstFrameAt,0),frame:this._frameNumber});return this._lastFrameAt=e,this._frame=s}_assertRetainedPhases(e){for(const s of this._phaseBindings.keys())if(!e.has(s))throw new Error(`[Raph] Cannot remove phase "${s}" while it is still bound.`);for(const s of this._queues.keys())if(!e.has(s))throw new Error(`[Raph] Cannot remove phase "${s}" while it has pending work.`)}_assertDelivery(e){if(!e.active||!e.inDelivery||e.resolution!=="unresolved")throw new v.RaphPhaseProcessError("[Raph] Phase task delivery is already resolved.")}_hasQueued(){for(const e of this._queues.values())if(e.some(s=>s.active&&s.pending))return!0;return!1}_hasPending(){return this._hasQueued()||this._deferred.size!==0}_cancelAllQueued(e,s=[]){const t=new Set;for(const i of this._queues.values())for(const n of i)t.add(n);this._queues.clear();for(const i of t)i.pending=!1,e&&this._acknowledgeDiscard(i,!0,s),this._clearPendingDelivery(i)}_cancelAllDeferred(e,s=[]){const t=[...this._deferred];this._deferred.clear();for(const i of t)i.deferred=!1,e&&this._acknowledgeDiscard(i,!0,s),this._clearPendingDelivery(i)}_acknowledgeDiscard(e,s,t){if(e.discardAcknowledged)return;const i=e.binding,n=i==null?void 0:i.cancelPending;if(n===void 0){e.discardAcknowledged=!0;return}try{if(n()){e.discardAcknowledged=!0;return}if(!s){t.push(new v.RaphPhaseProcessError(`[Raph] Initial effect delivery in "${e.phase}" cannot be cancelled before dependency collection.`));return}const a=i==null?void 0:i.abort;if(a===void 0){t.push(new v.RaphPhaseProcessError(`[Raph] Initial effect delivery in "${e.phase}" could not be aborted safely.`));return}a(),e.discardAcknowledged=!0}catch(a){t.push(a)}}_clearPendingDelivery(e){var s;e.requested=!1,e.firstCause=void 0,e.firstCauseKey=void 0,(s=e.extraCauses)==null||s.clear(),e.extraCauses=void 0}_settleIdleWaiters(e,s){if(!s&&(this._running||this._scheduled||this._hasPending()))return;const t=[...this._idleWaiters];this._idleWaiters.clear();for(const i of t)e===void 0?i.resolve():i.reject(e)}_assertAlive(){if(this._disposed)throw new v.RaphDisposedError("[Raph] Phase pipeline is disposed.")}}function K(l,e){return e.priority-l.priority||l.sequence-e.sequence}function C(l){return l.firstCause!==void 0}function b(l,e){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({node:e.structure.node,oldParent:l.structure.oldParent,oldIndex:l.structure.oldIndex,newParent:e.structure.newParent,newIndex:e.structure.newIndex});return Object.freeze({...e,previous:l.previous,...s===void 0?{}:{events:s},...t===void 0?{}:{structure:t}})}exports.RaphPhasePipeline=x;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("../errors.cjs"),w=require("../ownership/throwDisposalErrors.cjs"),i=require("./RaphPhaseTaskRecord.cjs");class R{constructor(e,t){this.name=e,this.pipeline=t,this.queue=[],this.spare=[],this.bindings=0}}const P=1e4,I=1e4,S=i.TASK_ACTIVE|i.TASK_PAUSED,C=i.TASK_IN_DELIVERY|i.TASK_RESOLUTION;class N{constructor(e,t,s,a=()=>!1,n){this._scheduler=e,this._reactivity=t,this._resolveCause=s,this._deferSync=a,this._tracePhase=n}_phases=[];_phaseByName=new Map;_resolvedInput;_resolvedState;_queuedCount=0;_deferred=new Set;_idleWaiters=new Set;_taskSequence=0;_scheduled=!1;_scheduleToken=0;_frameHandle;_frameHandleKind;_configurationLocked=!1;_running=!1;_idleSlotFlags=-1;_disposed=!1;_firstFrameAt;_lastFrameAt;_frameNumber=0;_frame=i.EMPTY_FRAME;get frame(){return this._frame}get phases(){return this._phases.map(e=>e.phase)}definePhases(e){if(this._assertAlive(),this._configurationLocked||this._firstFrameAt!==void 0)throw new Error("[Raph] Cannot redefine phases after phase pipeline execution has started.");const t=this._phaseByName,s=new Map,a=[];for(const n of e){const r=n.name.trim();if(!r)throw new Error("[Raph] Phase name must not be empty.");if(s.has(r))throw new Error(`[Raph] Duplicate phase name "${r}".`);if(n.process!==void 0&&typeof n.process!="function")throw new TypeError(`[Raph] Phase "${r}" process must be a function.`);const h=Object.freeze({name:r,...n.process===void 0?{}:{process:n.process}}),o={index:a.length,phase:h,state:t.get(r)?.state??new R(r,this)};a.push(o),s.set(r,o)}this._assertRetainedPhases(s),this._phases=a,this._phaseByName=s,this._resolvedInput=void 0,this._resolvedState=void 0}addPhase(e){this.definePhases([...this.phases,e])}clearPhases(){this.definePhases([])}resolvePhase(e){this._assertAlive();const t=this._resolvedState;if(t!==void 0&&e===this._resolvedInput)return t;let s=this._phaseByName.get(e);if(s===void 0){const a=e.trim();if(a!==e&&(s=this._phaseByName.get(a)),s===void 0)throw new Error(`[Raph] Phase "${a}" is not defined.`)}return this._resolvedInput=e,this._resolvedState=s.state}bindTask(e,t,s,a){return e.bindings++,new i.RaphPhaseTaskRecord(e,a,t,s)}bindGroup(e,t,s,a,n,r){const h=new Array(i.GROUP_NODES+n);h[i.GROUP_CONTEXT]=a,h[i.GROUP_CURSOR]=0,e.bindings++;const o=new i.RaphPhaseTaskRecord(e,r,t,s);return o.state=i.TASK_ACTIVE|i.TASK_TASKLESS,o.group=h,o}request(){this._assertAlive(),this._queuedCount!==0&&this._schedule()}afterFlush(){return this._assertAlive(),!this._running&&!this._scheduled&&!this._hasPending()?Promise.resolve():new Promise((e,t)=>{this._idleWaiters.add({reject:t,resolve:e})})}flush(){if(this._assertAlive(),this._cancelScheduled(),this._running)return;if(this._queuedCount===0&&this._deferred.size!==0&&this._activateDeferred(),this._queuedCount===0){this._settleIdleWaiters(void 0,!1);return}this._configurationLocked=!0,this._running=!0;const e=[],t=this._nextFrame();let s=0,a;try{for(;this._queuedCount!==0;){if(++s>P){const r=this._describeQueued();this._cancelAllQueued(!0,e),e.push(new Error(`[Raph] Phase flush exceeded 10000 passes.${r?` Pending: ${r}.`:""}`));break}for(const r of this._phases){if(this._disposed)break;const h=r.state,o=h.queue;if(o.length===0)continue;h.queue=h.spare,h.spare=a=o,this._queuedCount-=o.length;const _=e.length;this._tracePhase?.(r.phase.name,"start");let l=0,c=!0,f;for(const d of o){const p=d.state;if(!(p&i.TASK_ACTIVE)||d.consumerOwner.disposed){d.state=p&~i.TASK_PENDING,this._disposeTask(d);continue}this._beginDelivery(d,t),f!==void 0&&(d.priority>f.priority||d.priority===f.priority&&d.sequence<f.sequence)&&(c=!1),f=d,o[l++]=d}if(o.length=l,o.length===0){a=void 0;continue}c||o.sort(k);const A=r.phase.process;if(A===void 0)for(const d of o)try{this._runDelivery(d,e)}catch(p){e.push(p)}else{const d=[];for(const D of o)d.push(D.task);const p=Object.freeze({phase:r.phase.name,frame:t,tasks:Object.freeze(d)});try{this._reactivity.untrackedWithOwner(()=>A(p))}catch(D){e.push(D)}}let v=0;for(const d of o){if((d.state&i.TASK_RESOLUTION)===i.TASK_UNRESOLVED){v++;try{this._deferDelivery(d)}catch(p){d.state|=i.TASK_CANCEL,this._acknowledgeDiscard(d,!0,e),e.push(p)}}try{this._finishDelivery(d)}catch(p){(d.state&i.TASK_RESOLUTION)!==i.TASK_RUN&&this._acknowledgeDiscard(d,!0,e),d.state=(d.state|i.TASK_CANCEL)&~i.TASK_IN_DELIVERY,T(d),e.push(p)}}o.length=0,a=void 0,v!==0&&e.push(new E.RaphPhaseProcessError(`[Raph] Phase "${r.phase.name}" left ${v} task(s) unresolved; they were deferred.`)),e.length===_?this._tracePhase?.(r.phase.name,"end"):this._tracePhase?.(r.phase.name,"error",e[e.length-1])}}}catch(r){e.push(r),a!==void 0&&(a.length=0),this._cancelAllQueued(!0,e),this._cancelAllDeferred(!0,e)}finally{this._running=!1}try{this._deferred.size!==0&&this._scheduleDeferredTurn()}catch(r){e.push(r)}const n=e.length===1?e[0]:e.length>1?new AggregateError(e,"[Raph] Multiple phase tasks failed."):void 0;if(e.length!==0)throw this._settleIdleWaiters(n,!0),n;this._settleIdleWaiters(void 0,!1)}dispose(){if(this._disposed)return;this._disposed=!0,this._cancelScheduled(),this._cancelAllQueued(!1);const e=[...this._deferred];this._cancelAllDeferred(!1);for(const s of e)s.state&=~i.TASK_ACTIVE;this._phases=[],this._phaseByName.clear(),this._resolvedInput=void 0,this._resolvedState=void 0;const t=new E.RaphDisposedError("[Raph] Phase pipeline is disposed.");this._settleIdleWaiters(t,!0)}_debugPending(){return this._scheduled||this._running||this._hasPending()}_describeQueued(){const e=[];for(const t of this._phases){const s=t.state.queue.filter(n=>(n.state&i.TASK_ACTIVE)!==0&&!n.consumerOwner.disposed);if(s.length===0)continue;const a=s.slice(0,3).map(n=>{const r=n.consumerOwner.node,h=r===void 0?void 0:r.componentId,o=r===void 0?n.consumerOwner.id:`${n.consumerOwner.id}/${r.constructor.name}/${r.type}${typeof h=="string"?`/${h}`:""}`,_=n.firstCause?.sourceOwner?.node,l=_===void 0?"":`<=${_.id}/${_.constructor.name}`;return`${o}${n.firstCause?`:${n.firstCause.kind}${l}`:""}`}).join(", ");e.push(`${t.phase.name}=${s.length}${a?` [${a}]`:""}`)}return e.join("; ")}_beginDelivery(e,t){const s=e.state&-1893|i.TASK_IN_DELIVERY;e.state=e.firstCause===void 0?s:s|i.TASK_CAUSES_DELIVERED,e.facade!==void 0&&(e.frame=t)}_runDelivery(e,t){const s=e.state;if((s&S)!==i.TASK_ACTIVE||e.consumerOwner.disposed){e.state=s|i.TASK_CANCEL;return}(s&C)!==i.TASK_IN_DELIVERY&&g(),e.state=s|i.TASK_RUN;const a=e.detail;a!==void 0&&(a.deferCount=0);const n=this._reactivity,r=e.node;if(r!==void 0){n._beginTaskEffectRun(r)&&(e.state|=i.TASK_EXECUTED,n._runTaskEffectUntracked(r));return}const h=e.group;if(h===void 0){const c=e.watch;c!==void 0&&n.untrackedWithOwner(c.deliver);return}const o=h.length;let _=this._idleSlotFlags,l;for(let c=i.GROUP_NODES;c<o;c++){const f=h[c];if(f===null||f.flags===_)continue;if(!n._beginTaskEffectRun(f)){f.evaluate!==void 0&&(this._idleSlotFlags=_=f.flags);continue}h[i.GROUP_CURSOR]=c-i.GROUP_NODES;try{n._runTaskEffectUntracked(f)}catch(v){t!==void 0?t.push(v):(l??=[]).push(v)}const A=e.state;if(!(A&i.TASK_ACTIVE))break;if(A&i.TASK_PAUSED){c+1<o&&(this._restoreDeliveryCausesBeforePending(e),e.state|=i.TASK_REQUESTED);break}}if(l!==void 0)throw l.length===1?l[0]:new AggregateError(l,"[Raph] Effect group delivery failed.")}_deferDelivery(e){const t=e.state;if((t&S)!==i.TASK_ACTIVE||e.consumerOwner.disposed){e.state=t|i.TASK_CANCEL;return}if((t&C)!==i.TASK_IN_DELIVERY&&g(),e.state=t|i.TASK_DEFER,++e.detailed().deferCount>I){e.state|=i.TASK_CANCEL;const s=[];throw this._acknowledgeDiscard(e,!0,s),s.length!==0?new AggregateError([new E.RaphPhaseProcessError(`[Raph] Phase task in "${e.phase}" exceeded 10000 deferred deliveries.`),...s],"[Raph] Phase task defer limit and recovery failed."):new E.RaphPhaseProcessError(`[Raph] Phase task in "${e.phase}" exceeded 10000 deferred deliveries.`)}}_cancelDelivery(e){const t=e.state;if(!(t&i.TASK_ACTIVE)||e.consumerOwner.disposed){e.state=t|i.TASK_CANCEL;return}(t&C)!==i.TASK_IN_DELIVERY&&g();const s=[];if(this._acknowledgeDiscard(e,!1,s),s.length!==0)throw s.length===1?s[0]:new AggregateError(s,"[Raph] Phase task cancellation failed.");let a=e.state|i.TASK_CANCEL;a&i.TASK_DISCARD_ACKNOWLEDGED&&(a=m(e)?a|i.TASK_REQUESTED:a&~i.TASK_REQUESTED),e.state=a;const n=e.detail;n!==void 0&&(n.deferCount=0)}_finishDelivery(e){const t=e.state;if(!(t&i.TASK_IN_DELIVERY))return;const s=t&i.TASK_RESOLUTION;if(e.state=t&~i.TASK_IN_DELIVERY,!(t&i.TASK_ACTIVE)||e.consumerOwner.disposed){T(e);return}if(t&i.TASK_PAUSED){s!==i.TASK_RUN&&!(s===i.TASK_CANCEL&&(t&i.TASK_DISCARD_ACKNOWLEDGED)!==0)&&(this._restoreDeliveryCausesBeforePending(e),e.state|=i.TASK_REQUESTED),T(e);return}if(s===i.TASK_DEFER){this._restoreDeliveryCausesBeforePending(e),e.state|=i.TASK_DEFERRED,this._deferred.add(e),T(e);return}if(T(e),(e.state&i.TASK_REQUESTED)!==0||e.firstCause!==void 0){const a=e.node;if(a!==void 0)this._reactivity._rearmTaskEffect(a);else{const n=e.group;n!==void 0&&this._rearmGroup(n),this._queue(e)}}}_rearmGroup(e){const t=this._reactivity;for(let s=i.GROUP_NODES;s<e.length;s++){const a=e[s];a!==null&&a.firstDep!==null&&t._beginTaskEffectRun(a)&&t._rearmTaskEffect(a)}}_notifyTask(e,t){const s=this._resolveCause(t);if(s!==void 0){const a=s.kind==="structure"?s.source:t;this._appendCause(e,s,a)}}_appendCause(e,t,s){const a=e.state;if(!(a&i.TASK_ACTIVE))return;a&i.TASK_CAUSES_DELIVERED&&this._splitDeliveredCauses(e);const n=e.firstCause;if(n===void 0){e.firstCause=t,e.firstCauseKey=s;return}if(e.firstCauseKey===s){e.firstCause=K(n,t);return}const r=e.detailed().extraCauses??=new Map,h=r.get(s);r.set(s,h===void 0?t:K(h,t))}_splitDeliveredCauses(e){const t=e.detailed(),s=t.extraCauses;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&=~i.TASK_CAUSES_DELIVERED}_queue(e,t=!0){const s=e.state;if(!(!(s&i.TASK_ACTIVE)||e.consumerOwner.disposed||this._disposed)){if(s&(i.TASK_PAUSED|i.TASK_IN_DELIVERY)){e.state=s|i.TASK_REQUESTED;return}if(s&i.TASK_PENDING){t&&this._schedule();return}s&i.TASK_DEFERRED||(e.state=s&~i.TASK_DISCARD_ACKNOWLEDGED|i.TASK_PENDING,e.sequence=this._taskSequence++,e.phaseState.queue.push(e),this._queuedCount++,t&&this._schedule())}}_disposeTask(e){const t=e.state;if(!(t&i.TASK_ACTIVE))return;const s=t&-270;e.state=t&i.TASK_IN_DELIVERY?s|i.TASK_CANCEL:s,e.firstCause=void 0,e.firstCauseKey=void 0;const a=e.detail;a!==void 0&&(a.extraCauses?.clear(),a.extraCauses=void 0,y(a)),t&i.TASK_DEFERRED&&this._deferred.delete(e),t&i.TASK_PENDING&&this._unqueue(e),e.phaseState.bindings--,this._hasPending()||this._cancelScheduled(),this._settleIdleWaiters(void 0,!1)}_disposeBinding(e){const t=e.group;if(t!==void 0&&this._forgetStoppedSlots(t))return;e.scopeParent!==void 0&&e.consumerOwner._releaseRecord(e);const s=e.node;if(s!==void 0)e.node=void 0,this._reactivity._disposeTaskEffect(s);else{if(t!==void 0){e.group=void 0,this._disposeGroup(e,t);return}const a=e.watch;a!==void 0&&(e.watch=void 0,a.stop(()=>this._releaseWatch(e,a)))}this._disposeTask(e)}_forgetStoppedSlots(e){let t=!1,s=!1;for(let a=i.GROUP_NODES;a<e.length;a++){const n=e[a];n!=null&&(n.evaluate===void 0?(e[a]=null,t=!0):s=!0)}return t&&s}_disposeGroup(e,t){const s=this._reactivity;let a;for(let n=t.length-1;n>=i.GROUP_NODES;n--){const r=t[n];if(r!=null)try{s._disposeTaskEffect(r)}catch(h){(a??=[]).push(h)}}try{this._disposeTask(e)}catch(n){(a??=[]).push(n)}if(a!==void 0)throw a.length===1?a[0]:new AggregateError(a,"[Raph] Effect group disposal failed.")}_releaseWatch(e,t){const s=[],a=t.source;if(t.source=void 0,t.record=void 0,a!==void 0)try{a()}catch(n){s.push(n)}try{this._disposeTask(e)}catch(n){s.push(n)}w.throwDisposalErrors(s,"[Raph] Phase watch disposal failed.")}_pauseTask(e){const t=e.state;if((t&S)!==i.TASK_ACTIVE)return;const s=t&i.TASK_RESOLUTION,a=(t|i.TASK_PAUSED)&-13;e.state=(t&(i.TASK_PENDING|i.TASK_DEFERRED))!==0||(t&i.TASK_IN_DELIVERY)!==0&&s!==i.TASK_RUN&&!(s===i.TASK_CANCEL&&(t&i.TASK_DISCARD_ACKNOWLEDGED)!==0)?a|i.TASK_REQUESTED:a,t&i.TASK_DEFERRED&&this._deferred.delete(e),t&i.TASK_PENDING&&this._unqueue(e),this._hasPending()||this._cancelScheduled(),this._settleIdleWaiters(void 0,!1)}_unqueue(e){const t=e.phaseState.queue,s=t.indexOf(e);s>=0&&(t.splice(s,1),this._queuedCount--)}_resumeTask(e){const t=e.state;(t&S)!==S||e.consumerOwner.disposed||((t&i.TASK_REQUESTED)!==0||m(e)?(e.state=t&-67,this._queue(e)):e.state=t&~i.TASK_PAUSED)}_restoreDeliveryCausesBeforePending(e){e.state&i.TASK_CAUSES_DELIVERED&&this._splitDeliveredCauses(e);const t=e.detail;if(t===void 0)return;const s=t.deliveryFirstCause;if(s===void 0)return;const a=e.firstCause,n=e.firstCauseKey,r=t.extraCauses;e.firstCause=void 0,e.firstCauseKey=void 0,t.extraCauses=void 0,this._appendCause(e,s,t.deliveryFirstCauseKey);const h=t.deliveryExtraCauses;if(h!==void 0)for(const[o,_]of h)this._appendCause(e,_,o);if(a!==void 0&&(this._appendCause(e,a,n),r!==void 0))for(const[o,_]of r)this._appendCause(e,_,o)}_schedule(){if(this._running||this._scheduled||this._disposed)return;if(this._scheduler==="sync"){if(this._deferSync())return;this.flush();return}this._scheduled=!0;const e=++this._scheduleToken,t=()=>{this._disposed||!this._scheduled||e!==this._scheduleToken||(this._scheduled=!1,this._frameHandle=void 0,this._frameHandleKind=void 0,this.flush())};if(this._scheduler==="microtask"){queueMicrotask(t);return}typeof globalThis.requestAnimationFrame=="function"?(this._frameHandleKind="animation-frame",this._frameHandle=globalThis.requestAnimationFrame(t)):(this._frameHandleKind="timeout",this._frameHandle=setTimeout(t,16))}_scheduleDeferredTurn(){if(this._scheduled||this._disposed)return;this._scheduled=!0;const e=++this._scheduleToken,t=()=>{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))};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)}_cancelScheduled(){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)}_activateDeferred(){const e=[...this._deferred];this._deferred.clear();for(const t of e)t.state&=~i.TASK_DEFERRED,this._queue(t,!1)}_nextFrame(){const e=globalThis.performance?.now()??Date.now();if(this._firstFrameAt===void 0||this._lastFrameAt===void 0)return this._firstFrameAt=e,this._lastFrameAt=e,this._frame=Object.freeze({now:e,delta:0,elapsed:0,frame:0});this._frameNumber++;const t=Object.freeze({now:e,delta:Math.min(Math.max(e-this._lastFrameAt,0),100),elapsed:Math.max(e-this._firstFrameAt,0),frame:this._frameNumber});return this._lastFrameAt=e,this._frame=t}_assertRetainedPhases(e){for(const t of this._phases){const s=t.state;if(s.bindings!==0&&!e.has(s.name))throw new Error(`[Raph] Cannot remove phase "${s.name}" while it is still bound.`)}for(const t of this._phases){const s=t.state;if(s.queue.length!==0&&!e.has(s.name))throw new Error(`[Raph] Cannot remove phase "${s.name}" while it has pending work.`)}}_hasPending(){return this._queuedCount!==0||this._deferred.size!==0}_cancelAllQueued(e,t=[]){if(this._queuedCount===0)return;const s=[];for(const a of this._phases){const n=a.state.queue;for(const r of n)s.push(r);n.length=0}this._queuedCount=0;for(const a of s)a.state&=~i.TASK_PENDING,e&&this._acknowledgeDiscard(a,!0,t),this._clearPendingDelivery(a)}_cancelAllDeferred(e,t=[]){const s=[...this._deferred];this._deferred.clear();for(const a of s)a.state&=~i.TASK_DEFERRED,e&&this._acknowledgeDiscard(a,!0,t),this._clearPendingDelivery(a)}_acknowledgeDiscard(e,t,s){const a=e.state;if(a&i.TASK_DISCARD_ACKNOWLEDGED)return;const n=e.node,r=e.group;if(n===void 0&&r===void 0||!(a&i.TASK_ACTIVE)){e.state=a|i.TASK_DISCARD_ACKNOWLEDGED;return}try{if(n!==void 0?(a&i.TASK_EXECUTED)!==0&&this._reactivity._cancelTaskEffect(n):this._cancelGroup(e,r,t)){e.state|=i.TASK_DISCARD_ACKNOWLEDGED;return}if(!t){s.push(new E.RaphPhaseProcessError(`[Raph] Initial effect delivery in "${e.phase}" cannot be cancelled before dependency collection.`));return}e.dispose(),e.state|=i.TASK_DISCARD_ACKNOWLEDGED}catch(h){s.push(h)}}_cancelGroup(e,t,s){const a=this._reactivity;let n=!1;for(let o=i.GROUP_NODES;o<t.length;o++){const _=t[o];_===null||_.firstDep!==null||!a._beginTaskEffectRun(_)||(s?a._disposeTaskEffect(_):(a._requestTaskEffect(_,!1),n=!0))}if(n)return!1;const r=!s&&m(e);let h=!1;for(let o=i.GROUP_NODES;o<t.length;o++){const _=t[o];if(_===null)continue;if(_.firstDep===null){h=h||_.evaluate!==void 0;continue}const l=r&&a._beginTaskEffectRun(_);a._cancelTaskEffect(_)&&(h=!0,l&&a._rearmTaskEffect(_))}return h}_clearPendingDelivery(e){e.state&=~i.TASK_REQUESTED,e.firstCause=void 0,e.firstCauseKey=void 0;const t=e.detail;t!==void 0&&(t.extraCauses?.clear(),t.extraCauses=void 0)}_settleIdleWaiters(e,t){const s=this._idleWaiters;if(s.size===0||!t&&(this._running||this._scheduled||this._hasPending()))return;const a=[...s];s.clear();for(const n of a)t?n.reject(e):n.resolve()}_assertAlive(){if(this._disposed)throw new E.RaphDisposedError("[Raph] Phase pipeline is disposed.")}}function k(u,e){return e.priority-u.priority||u.sequence-e.sequence}function m(u){return u.firstCause!==void 0&&!(u.state&i.TASK_CAUSES_DELIVERED)}function T(u){const e=u.state,t=u.detail;if(e&i.TASK_CAUSES_DELIVERED){u.state=e&~i.TASK_CAUSES_DELIVERED,u.firstCause=void 0,u.firstCauseKey=void 0,t!==void 0&&(t.extraCauses=void 0,t.deliveryCauses=void 0);return}t!==void 0&&t.deliveryFirstCause!==void 0&&y(t)}function y(u){u.deliveryFirstCause=void 0,u.deliveryFirstCauseKey=void 0,u.deliveryExtraCauses=void 0,u.deliveryCauses=void 0}function g(){throw new E.RaphPhaseProcessError("[Raph] Phase task delivery is already resolved.")}function K(u,e){const t=u.events===void 0?e.events:e.events===void 0?u.events:Object.freeze([...u.events,...e.events]),s=u.structure===void 0?e.structure:e.structure===void 0?u.structure:Object.freeze({node:e.structure.node,oldParent:u.structure.oldParent,oldIndex:u.structure.oldIndex,newParent:e.structure.newParent,newIndex:e.structure.newIndex});return Object.freeze({...e,previous:u.previous,...t===void 0?{}:{events:t},...s===void 0?{}:{structure:s}})}exports.RaphPhasePipeline=N;exports.RaphPhaseState=R;