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

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 (127) hide show
  1. package/README.md +100 -0
  2. package/dist/api/Raph.d.ts +15 -15
  3. package/dist/api/RaphFacadeSession.d.ts +4 -4
  4. package/dist/api/RaphReactivityInstance.d.ts +4 -4
  5. package/dist/api/types.d.ts +11 -11
  6. package/dist/compact.cjs +1 -0
  7. package/dist/compact.js +4 -0
  8. package/dist/debug/reactivity/engine-core.cjs +1 -0
  9. package/dist/debug/reactivity/engine-core.js +1760 -0
  10. package/dist/debug/reactivity/engine.cjs +1 -1
  11. package/dist/debug/reactivity/engine.js +25 -1689
  12. package/dist/debug/reactivity/reactive-object.cjs +1 -1
  13. package/dist/debug/reactivity/reactive-object.js +604 -167
  14. package/dist/debug/runtime/RaphCompactExecutionRuntime.cjs +1 -0
  15. package/dist/debug/runtime/RaphCompactExecutionRuntime.js +9 -0
  16. package/dist/debug/runtime/RaphExecutionRuntime.cjs +1 -0
  17. package/dist/debug/runtime/RaphExecutionRuntime.js +11 -0
  18. package/dist/debug/runtime/RaphRuntime.cjs +1 -1
  19. package/dist/debug/runtime/RaphRuntime.js +115 -1176
  20. package/dist/debug/runtime/RaphRuntimeBase.cjs +1 -0
  21. package/dist/debug/runtime/RaphRuntimeBase.js +941 -0
  22. package/dist/debug/runtime/diagnostics/RaphDebug.cjs +1 -1
  23. package/dist/debug/runtime/diagnostics/RaphDebug.js +72 -66
  24. package/dist/debug/runtime/ownership/RaphNode.cjs +1 -1
  25. package/dist/debug/runtime/ownership/RaphNode.js +11 -0
  26. package/dist/debug/runtime/ownership/RaphScope.cjs +1 -1
  27. package/dist/debug/runtime/ownership/RaphScope.js +12 -12
  28. package/dist/debug/runtime/phases/RaphPhasePipeline.cjs +1 -1
  29. package/dist/debug/runtime/phases/RaphPhasePipeline.js +361 -242
  30. package/dist/debug/runtime/phases/RaphPhaseTaskRecord.cjs +1 -1
  31. package/dist/debug/runtime/phases/RaphPhaseTaskRecord.js +23 -22
  32. package/dist/debug/runtime/reactivity/RaphSelector.cjs +1 -1
  33. package/dist/debug/runtime/reactivity/RaphSelector.js +111 -90
  34. package/dist/debug/runtime/reactivity/RuntimeObjectSupport.cjs +1 -0
  35. package/dist/debug/runtime/reactivity/RuntimeObjectSupport.js +11 -0
  36. package/dist/debug/runtime/reactivity/RuntimeReactivity.cjs +1 -1
  37. package/dist/debug/runtime/reactivity/RuntimeReactivity.js +118 -103
  38. package/dist/debug/runtime/reactivity/RuntimeSelectorSupport.cjs +1 -0
  39. package/dist/debug/runtime/reactivity/RuntimeSelectorSupport.js +12 -0
  40. package/dist/entrypoints/compact.d.ts +2 -0
  41. package/dist/entrypoints/execution.d.ts +2 -0
  42. package/dist/entrypoints/machine-testing.d.ts +2 -2
  43. package/dist/entrypoints/machine.d.ts +5 -5
  44. package/dist/entrypoints/observable.d.ts +4 -0
  45. package/dist/entrypoints/path.d.ts +14 -14
  46. package/dist/entrypoints/reactivity.d.ts +1 -1
  47. package/dist/entrypoints/runtime.d.ts +19 -18
  48. package/dist/execution.cjs +1 -0
  49. package/dist/execution.js +4 -0
  50. package/dist/index.cjs +1 -1
  51. package/dist/index.js +23 -21
  52. package/dist/machine/compiler.d.ts +1 -1
  53. package/dist/machine/core.d.ts +2 -2
  54. package/dist/machine/persistence.d.ts +1 -1
  55. package/dist/machine/runtime.d.ts +3 -3
  56. package/dist/machine/testing.d.ts +1 -1
  57. package/dist/machine/types.d.ts +3 -3
  58. package/dist/main.d.ts +19 -19
  59. package/dist/observable/buffer.d.ts +6 -0
  60. package/dist/observable/class-admin.d.ts +63 -0
  61. package/dist/observable/class-plan.d.ts +46 -0
  62. package/dist/observable/classes.d.ts +10 -0
  63. package/dist/observable/context.d.ts +73 -0
  64. package/dist/observable/native.d.ts +2 -0
  65. package/dist/observable/observable.d.ts +13 -0
  66. package/dist/observable/types.d.ts +60 -0
  67. package/dist/observable.cjs +1 -0
  68. package/dist/observable.js +1187 -0
  69. package/dist/path/DataPath.d.ts +2 -2
  70. package/dist/path/PathRouter.d.ts +1 -1
  71. package/dist/path/RaphKernel.d.ts +6 -6
  72. package/dist/path/data-path.types.d.ts +1 -1
  73. package/dist/path/data-path.utils.d.ts +2 -2
  74. package/dist/path/derived/DerivedRegistry.d.ts +3 -3
  75. package/dist/path/derived/RaphDerivedHandle.d.ts +3 -3
  76. package/dist/path/derived/derived-collection.types.d.ts +1 -1
  77. package/dist/path/derived/derived-collection.utils.d.ts +3 -3
  78. package/dist/path/derived/derived-strategy.utils.d.ts +1 -1
  79. package/dist/path/meta/MetaController.d.ts +5 -5
  80. package/dist/path/meta/RaphMeta.d.ts +3 -3
  81. package/dist/path/meta/RaphMetaStore.d.ts +1 -1
  82. package/dist/path/meta/meta.types.d.ts +2 -2
  83. package/dist/path/path.types.d.ts +2 -2
  84. package/dist/path/pathSegmentKey.d.ts +1 -1
  85. package/dist/path/storage/AdapterPathStore.d.ts +2 -2
  86. package/dist/path/storage/DefaultDataAdapter.d.ts +2 -2
  87. package/dist/path/storage/PathEventHub.d.ts +1 -1
  88. package/dist/path/storage/PathStore.d.ts +2 -2
  89. package/dist/path/storage/data-adapter.types.d.ts +1 -1
  90. package/dist/raph.cjs +1 -1
  91. package/dist/raph.js +23 -21
  92. package/dist/reactivity/engine-core.d.ts +600 -0
  93. package/dist/reactivity/engine.d.ts +6 -550
  94. package/dist/reactivity/reactive-object.d.ts +143 -2
  95. package/dist/reactivity/scope.d.ts +7 -6
  96. package/dist/reactivity/types.d.ts +9 -12
  97. package/dist/reactivity/watch.d.ts +1 -1
  98. package/dist/runtime/RaphCompactExecutionRuntime.d.ts +7 -0
  99. package/dist/runtime/RaphExecutionRuntime.d.ts +6 -0
  100. package/dist/runtime/RaphRuntime.d.ts +19 -403
  101. package/dist/runtime/RaphRuntimeBase.d.ts +194 -0
  102. package/dist/runtime/diagnostics/RaphDebug.d.ts +8 -5
  103. package/dist/runtime/errors.d.ts +1 -1
  104. package/dist/runtime/ownership/RaphEffectScope.d.ts +13 -12
  105. package/dist/runtime/ownership/RaphNode.d.ts +28 -21
  106. package/dist/runtime/ownership/RaphScope.d.ts +32 -19
  107. package/dist/runtime/ownership/parent-graph.types.d.ts +1 -1
  108. package/dist/runtime/ownership/parentGraph.d.ts +2 -2
  109. package/dist/runtime/phases/RaphFrameLoop.d.ts +1 -1
  110. package/dist/runtime/phases/RaphPhasePipeline.d.ts +80 -29
  111. package/dist/runtime/phases/RaphPhaseTaskRecord.d.ts +21 -21
  112. package/dist/runtime/phases/RaphPhaseWatch.d.ts +3 -3
  113. package/dist/runtime/phases/orderPhaseTasks.d.ts +4 -2
  114. package/dist/runtime/phases/phase.types.d.ts +36 -35
  115. package/dist/runtime/reactivity/PathHandle.d.ts +5 -5
  116. package/dist/runtime/reactivity/RaphMetaSource.d.ts +7 -7
  117. package/dist/runtime/reactivity/RaphSelector.d.ts +27 -6
  118. package/dist/runtime/reactivity/RaphWorkGraph.d.ts +40 -39
  119. package/dist/runtime/reactivity/RuntimeObjectSupport.d.ts +9 -0
  120. package/dist/runtime/reactivity/RuntimeReactivity.d.ts +27 -19
  121. package/dist/runtime/reactivity/RuntimeSelectorSupport.d.ts +10 -0
  122. package/dist/runtime/reactivity/RuntimeWatch.d.ts +1 -1
  123. package/dist/runtime/reactivity/disposal-sweep.utils.d.ts +1 -1
  124. package/dist/runtime/reactivity/runtime-reactivity.types.d.ts +3 -3
  125. package/dist/runtime.cjs +1 -1
  126. package/dist/runtime.js +13 -11
  127. package/package.json +22 -62
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("../ownership/RaphNode.cjs"),_=Object.freeze(["action","machine","error"]),f=1024;class l{_capacity=f;_context="none";_guards="failed";_include=new Set(_);_enabled=!1;_events;_eventStart=0;_eventSize=0;_sequence=0;_operationSequence=0;_machines;trace;machines;constructor(e){const s=e?.trace;s!==void 0&&s!==!1&&(this._applyOptions(s),this._enabled=!0,this._ensureBuffer()),this.trace=Object.freeze({clear:()=>this.clear(),read:t=>this.read(t),start:t=>this.start(t),status:()=>this.status(),stop:()=>this.stop()}),this.machines=Object.freeze({list:()=>this.listMachines(),snapshot:t=>this.machineSnapshot(t)})}start(e){e!==void 0&&this._applyOptions(e),this._enabled=!0,this._ensureBuffer()}stop(){this._enabled=!1}clear(){this._events?.fill(void 0),this._eventStart=0,this._eventSize=0}read(e={}){const s=e.since??-1,t=e.limit??Number.POSITIVE_INFINITY;if(!Number.isFinite(t)&&t!==Number.POSITIVE_INFINITY)throw new TypeError("[Raph] Trace limit must be a positive integer.");if(t!==Number.POSITIVE_INFINITY&&(!Number.isInteger(t)||t<0))throw new TypeError("[Raph] Trace limit must be a positive integer.");const a=this._events;if(a===void 0||this._eventSize===0||t===0)return Object.freeze([]);const n=[];for(let r=0;r<this._eventSize;r++){const d=a[(this._eventStart+r)%this._capacity];if(!(d===void 0||d.sequence<=s)&&(n.push(d),n.length>=t))break}return Object.freeze(n)}status(){return Object.freeze({capacity:this._capacity,context:this._context,enabled:this._enabled,guards:this._guards,include:Object.freeze([...this._include]),size:this._eventSize})}nextOperationId(e){if(!(!this._enabled||!this._include.has(e)))return++this._operationSequence}traces(e){return this._enabled&&this._include.has(e)}record(e){if(!this._enabled||!this._include.has(e.kind)||e.guard!==void 0&&(this._guards==="none"||this._guards==="failed"&&e.guard!=="failed"))return;const s=Object.freeze({...e.causeId===void 0?{}:{causeId:e.causeId},...e.context===void 0||this._context==="none"?{}:{contextKeys:Object.freeze(Object.keys(e.context))},...e.details===void 0?{}:{details:Object.freeze({...e.details})},...e.guard===void 0?{}:{guard:e.guard},...e.operationId===void 0?{}:{operationId:e.operationId},...e.status===void 0?{}:{status:e.status},kind:e.kind,name:e.name,sequence:++this._sequence,timestamp:Date.now()}),t=this._ensureBuffer();if(this._eventSize<this._capacity){t[(this._eventStart+this._eventSize++)%this._capacity]=s;return}t[this._eventStart]=s,this._eventStart=(this._eventStart+1)%this._capacity}registerMachine(e){const s=this._machines??=new Map;if(s.has(e.id))throw new Error(`[Raph] Machine diagnostic id "${e.id}" is already registered.`);return s.set(e.id,e),()=>{s.get(e.id)===e&&s.delete(e.id),s.size===0&&this._machines===s&&(this._machines=void 0)}}hasMachine(e){return this._machines?.has(e)??!1}listMachines(){const e=[];for(const s of this._machines?.values()??[]){const t=s.snapshot();e.push(Object.freeze({active:t.active,id:t.id,modelId:t.modelId,ownerId:t.ownerId,...t.parentId===void 0?{}:{parentId:t.parentId},revision:t.revision,status:t.status}))}return Object.freeze(e)}machineSnapshot(e){return this._machines?.get(e)?.snapshot()}get machineCount(){return this._machines?.size??0}get traceSize(){return this._eventSize}get actorCount(){let e=0;for(const s of this._machines?.values()??[])e+=s.snapshot().actors.length;return e}machineTreeNodesByOwner(){const e=[...this._machines?.values()??[]],s=new Map(e.map(n=>[n.id,n])),t=new Map;for(const n of e){if(n.parentId===void 0||!s.has(n.parentId))continue;const r=t.get(n.parentId)??[];r.push(n),t.set(n.parentId,r)}const a=new Map;for(const n of e){if(n.parentId!==void 0&&s.has(n.parentId))continue;const r=a.get(n.ownerId)??[];r.push(u(n,t,!1)),a.set(n.ownerId,r)}return new Map([...a].map(([n,r])=>[n,Object.freeze(r)]))}_applyOptions(e){if(e.capacity!==void 0){if(!Number.isInteger(e.capacity)||e.capacity<=0)throw new TypeError("[Raph] Trace capacity must be a positive integer.");e.capacity!==this._capacity&&(this._capacity=e.capacity,this._events=void 0,this._eventStart=0,this._eventSize=0)}if(e.context!==void 0){if(e.context!=="none"&&e.context!=="keys")throw new TypeError('[Raph] Trace context must be "none" or "keys".');this._context=e.context}if(e.guards!==void 0){if(e.guards!=="none"&&e.guards!=="failed"&&e.guards!=="all")throw new TypeError('[Raph] Trace guards must be "none", "failed" or "all".');this._guards=e.guards}if(e.include!==void 0){const s=new Set;for(const t of e.include){if(t!=="action"&&t!=="machine"&&t!=="phase"&&t!=="error")throw new TypeError(`[Raph] Unsupported trace kind "${String(t)}".`);s.add(t)}this._include=s}}_ensureBuffer(){return this._events??=new Array(this._capacity)}}function h(i){const e=i instanceof c.RaphNode?i.children.map(h):[];return Object.freeze({children:Object.freeze(e),disposed:i.disposed,id:i.id,kind:i instanceof c.RaphNode?"node":"scope",resources:i._debugResourceCount(),sources:i._debugSourceCount()})}function o(i,e=new Map){const s=i instanceof c.RaphNode?i.children.map(a=>o(a,e)):[],t=i._debugResourceCount();return t!==0&&s.push(Object.freeze({children:Object.freeze([]),count:t,id:`${i.id}:resources`,kind:"resource"})),s.push(...e.get(i.id)??[]),Object.freeze({children:Object.freeze(s),disposed:i.disposed,id:i.id,kind:i instanceof c.RaphNode?"node":"scope"})}function u(i,e,s){const t=i.snapshot();return Object.freeze({children:Object.freeze((e.get(i.id)??[]).map(a=>u(a,e,!0))),id:t.id,kind:s?"actor":"machine",status:t.status})}exports.RaphDebugController=l;exports.createOwnerSnapshot=h;exports.createOwnerTree=o;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("../ownership/RaphNode.cjs"),_=Object.freeze(["action","machine","error"]),f=1024;class l{constructor(e,i,t){this._onTraceChange=t,this._traceTarget=i===void 0?void 0:new WeakRef(i);const r=e?.trace;r!==void 0&&r!==!1&&(this._applyOptions(r),this._enabled=!0,this._ensureBuffer()),this.trace=Object.freeze({clear:()=>this.clear(),read:s=>this.read(s),start:s=>this.start(s),status:()=>this.status(),stop:()=>this.stop()}),this.machines=Object.freeze({list:()=>this.listMachines(),snapshot:s=>this.machineSnapshot(s)})}_capacity=f;_context="none";_guards="failed";_include=new Set(_);_enabled=!1;_events;_eventStart=0;_eventSize=0;_sequence=0;_operationSequence=0;_machines;_traceTarget;trace;machines;start(e){e!==void 0&&this._applyOptions(e),this._enabled=!0,this._ensureBuffer(),this._notifyTraceChange()}stop(){this._enabled=!1,this._notifyTraceChange()}_notifyTraceChange(){const e=this._traceTarget?.deref();e!==void 0&&this._onTraceChange?.call(e)}clear(){this._events?.fill(void 0),this._eventStart=0,this._eventSize=0}read(e={}){const i=e.since??-1,t=e.limit??Number.POSITIVE_INFINITY;if(!Number.isFinite(t)&&t!==Number.POSITIVE_INFINITY)throw new TypeError("[Raph] Trace limit must be a positive integer.");if(t!==Number.POSITIVE_INFINITY&&(!Number.isInteger(t)||t<0))throw new TypeError("[Raph] Trace limit must be a positive integer.");const r=this._events;if(r===void 0||this._eventSize===0||t===0)return Object.freeze([]);const s=[];for(let a=0;a<this._eventSize;a++){const d=r[(this._eventStart+a)%this._capacity];if(!(d===void 0||d.sequence<=i)&&(s.push(d),s.length>=t))break}return Object.freeze(s)}status(){return Object.freeze({capacity:this._capacity,context:this._context,enabled:this._enabled,guards:this._guards,include:Object.freeze([...this._include]),size:this._eventSize})}nextOperationId(e){if(!(!this._enabled||!this._include.has(e)))return++this._operationSequence}traces(e){return this._enabled&&this._include.has(e)}record(e){if(!this._enabled||!this._include.has(e.kind)||e.guard!==void 0&&(this._guards==="none"||this._guards==="failed"&&e.guard!=="failed"))return;const i=Object.freeze({...e.causeId===void 0?{}:{causeId:e.causeId},...e.context===void 0||this._context==="none"?{}:{contextKeys:Object.freeze(Object.keys(e.context))},...e.details===void 0?{}:{details:Object.freeze({...e.details})},...e.guard===void 0?{}:{guard:e.guard},...e.operationId===void 0?{}:{operationId:e.operationId},...e.status===void 0?{}:{status:e.status},kind:e.kind,name:e.name,sequence:++this._sequence,timestamp:Date.now()}),t=this._ensureBuffer();if(this._eventSize<this._capacity){t[(this._eventStart+this._eventSize++)%this._capacity]=i;return}t[this._eventStart]=i,this._eventStart=(this._eventStart+1)%this._capacity}registerMachine(e){const i=this._machines??=new Map;if(i.has(e.id))throw new Error(`[Raph] Machine diagnostic id "${e.id}" is already registered.`);return i.set(e.id,e),()=>{i.get(e.id)===e&&i.delete(e.id),i.size===0&&this._machines===i&&(this._machines=void 0)}}hasMachine(e){return this._machines?.has(e)??!1}listMachines(){const e=[];for(const i of this._machines?.values()??[]){const t=i.snapshot();e.push(Object.freeze({active:t.active,id:t.id,modelId:t.modelId,ownerId:t.ownerId,...t.parentId===void 0?{}:{parentId:t.parentId},revision:t.revision,status:t.status}))}return Object.freeze(e)}machineSnapshot(e){return this._machines?.get(e)?.snapshot()}get machineCount(){return this._machines?.size??0}get traceSize(){return this._eventSize}get actorCount(){let e=0;for(const i of this._machines?.values()??[])e+=i.snapshot().actors.length;return e}machineTreeNodesByOwner(){const e=[...this._machines?.values()??[]],i=new Map(e.map(s=>[s.id,s])),t=new Map;for(const s of e){if(s.parentId===void 0||!i.has(s.parentId))continue;const a=t.get(s.parentId)??[];a.push(s),t.set(s.parentId,a)}const r=new Map;for(const s of e){if(s.parentId!==void 0&&i.has(s.parentId))continue;const a=r.get(s.ownerId)??[];a.push(u(s,t,!1)),r.set(s.ownerId,a)}return new Map([...r].map(([s,a])=>[s,Object.freeze(a)]))}_applyOptions(e){if(e.capacity!==void 0){if(!Number.isInteger(e.capacity)||e.capacity<=0)throw new TypeError("[Raph] Trace capacity must be a positive integer.");e.capacity!==this._capacity&&(this._capacity=e.capacity,this._events=void 0,this._eventStart=0,this._eventSize=0)}if(e.context!==void 0){if(e.context!=="none"&&e.context!=="keys")throw new TypeError('[Raph] Trace context must be "none" or "keys".');this._context=e.context}if(e.guards!==void 0){if(e.guards!=="none"&&e.guards!=="failed"&&e.guards!=="all")throw new TypeError('[Raph] Trace guards must be "none", "failed" or "all".');this._guards=e.guards}if(e.include!==void 0){const i=new Set;for(const t of e.include){if(t!=="action"&&t!=="machine"&&t!=="phase"&&t!=="error")throw new TypeError(`[Raph] Unsupported trace kind "${String(t)}".`);i.add(t)}this._include=i}}_ensureBuffer(){return this._events??=new Array(this._capacity)}}function h(n){const e=n instanceof c.RaphNode?n.children.map(h):[];return Object.freeze({children:Object.freeze(e),disposed:n.disposed,id:n.id,kind:n instanceof c.RaphNode?"node":"scope",resources:n._debugResourceCount(),sources:n._debugSourceCount()})}function o(n,e=new Map){const i=n instanceof c.RaphNode?n.children.map(r=>o(r,e)):[],t=n._debugResourceCount();return t!==0&&i.push(Object.freeze({children:Object.freeze([]),count:t,id:`${n.id}:resources`,kind:"resource"})),i.push(...e.get(n.id)??[]),Object.freeze({children:Object.freeze(i),disposed:n.disposed,id:n.id,kind:n instanceof c.RaphNode?"node":"scope"})}function u(n,e,i){const t=n.snapshot();return Object.freeze({children:Object.freeze((e.get(n.id)??[]).map(r=>u(r,e,!0))),id:t.id,kind:i?"actor":"machine",status:t.status})}exports.RaphDebugController=l;exports.createOwnerSnapshot=h;exports.createOwnerTree=o;
@@ -5,6 +5,23 @@ const o = Object.freeze([
5
5
  "error"
6
6
  ]), u = 1024;
7
7
  class p {
8
+ /**
9
+ * Создаёт controller; ring buffer появляется только при включённом trace.
10
+ */
11
+ constructor(e, i, t) {
12
+ this._onTraceChange = t, this._traceTarget = i === void 0 ? void 0 : new WeakRef(i);
13
+ const a = e?.trace;
14
+ a !== void 0 && a !== !1 && (this._applyOptions(a), this._enabled = !0, this._ensureBuffer()), this.trace = Object.freeze({
15
+ clear: () => this.clear(),
16
+ read: (s) => this.read(s),
17
+ start: (s) => this.start(s),
18
+ status: () => this.status(),
19
+ stop: () => this.stop()
20
+ }), this.machines = Object.freeze({
21
+ list: () => this.listMachines(),
22
+ snapshot: (s) => this.machineSnapshot(s)
23
+ });
24
+ }
8
25
  _capacity = u;
9
26
  _context = "none";
10
27
  _guards = "failed";
@@ -16,24 +33,9 @@ class p {
16
33
  _sequence = 0;
17
34
  _operationSequence = 0;
18
35
  _machines;
36
+ _traceTarget;
19
37
  trace;
20
38
  machines;
21
- /**
22
- * Создаёт controller; ring buffer появляется только при включённом trace.
23
- */
24
- constructor(e) {
25
- const s = e?.trace;
26
- s !== void 0 && s !== !1 && (this._applyOptions(s), this._enabled = !0, this._ensureBuffer()), this.trace = Object.freeze({
27
- clear: () => this.clear(),
28
- read: (t) => this.read(t),
29
- start: (t) => this.start(t),
30
- status: () => this.status(),
31
- stop: () => this.stop()
32
- }), this.machines = Object.freeze({
33
- list: () => this.listMachines(),
34
- snapshot: (t) => this.machineSnapshot(t)
35
- });
36
- }
37
39
  // ---------------------------------------------
38
40
  // PUBLIC API
39
41
  // ---------------------------------------------
@@ -41,13 +43,17 @@ class p {
41
43
  * Включает trace с текущими или явно переданными настройками.
42
44
  */
43
45
  start(e) {
44
- e !== void 0 && this._applyOptions(e), this._enabled = !0, this._ensureBuffer();
46
+ e !== void 0 && this._applyOptions(e), this._enabled = !0, this._ensureBuffer(), this._notifyTraceChange();
45
47
  }
46
48
  /**
47
49
  * Останавливает запись, сохраняя уже накопленные events.
48
50
  */
49
51
  stop() {
50
- this._enabled = !1;
52
+ this._enabled = !1, this._notifyTraceChange();
53
+ }
54
+ _notifyTraceChange() {
55
+ const e = this._traceTarget?.deref();
56
+ e !== void 0 && this._onTraceChange?.call(e);
51
57
  }
52
58
  /**
53
59
  * Удаляет все накопленные events, не меняя status trace.
@@ -59,7 +65,7 @@ class p {
59
65
  * Формирует immutable chronological copy ring buffer.
60
66
  */
61
67
  read(e = {}) {
62
- const s = e.since ?? -1, t = e.limit ?? Number.POSITIVE_INFINITY;
68
+ const i = e.since ?? -1, t = e.limit ?? Number.POSITIVE_INFINITY;
63
69
  if (!Number.isFinite(t) && t !== Number.POSITIVE_INFINITY)
64
70
  throw new TypeError("[Raph] Trace limit must be a positive integer.");
65
71
  if (t !== Number.POSITIVE_INFINITY && (!Number.isInteger(t) || t < 0))
@@ -67,13 +73,13 @@ class p {
67
73
  const a = this._events;
68
74
  if (a === void 0 || this._eventSize === 0 || t === 0)
69
75
  return Object.freeze([]);
70
- const n = [];
76
+ const s = [];
71
77
  for (let r = 0; r < this._eventSize; r++) {
72
78
  const d = a[(this._eventStart + r) % this._capacity];
73
- if (!(d === void 0 || d.sequence <= s) && (n.push(d), n.length >= t))
79
+ if (!(d === void 0 || d.sequence <= i) && (s.push(d), s.length >= t))
74
80
  break;
75
81
  }
76
- return Object.freeze(n);
82
+ return Object.freeze(s);
77
83
  }
78
84
  /**
79
85
  * Возвращает текущую конфигурацию и заполнение buffer.
@@ -111,7 +117,7 @@ class p {
111
117
  record(e) {
112
118
  if (!this._enabled || !this._include.has(e.kind) || e.guard !== void 0 && (this._guards === "none" || this._guards === "failed" && e.guard !== "failed"))
113
119
  return;
114
- const s = Object.freeze({
120
+ const i = Object.freeze({
115
121
  ...e.causeId === void 0 ? {} : { causeId: e.causeId },
116
122
  ...e.context === void 0 || this._context === "none" ? {} : { contextKeys: Object.freeze(Object.keys(e.context)) },
117
123
  ...e.details === void 0 ? {} : { details: Object.freeze({ ...e.details }) },
@@ -124,21 +130,21 @@ class p {
124
130
  timestamp: Date.now()
125
131
  }), t = this._ensureBuffer();
126
132
  if (this._eventSize < this._capacity) {
127
- t[(this._eventStart + this._eventSize++) % this._capacity] = s;
133
+ t[(this._eventStart + this._eventSize++) % this._capacity] = i;
128
134
  return;
129
135
  }
130
- t[this._eventStart] = s, this._eventStart = (this._eventStart + 1) % this._capacity;
136
+ t[this._eventStart] = i, this._eventStart = (this._eventStart + 1) % this._capacity;
131
137
  }
132
138
  /**
133
139
  * Регистрирует read-only machine projection без импорта machine engine в Runtime.
134
140
  * @internal
135
141
  */
136
142
  registerMachine(e) {
137
- const s = this._machines ??= /* @__PURE__ */ new Map();
138
- if (s.has(e.id))
143
+ const i = this._machines ??= /* @__PURE__ */ new Map();
144
+ if (i.has(e.id))
139
145
  throw new Error(`[Raph] Machine diagnostic id "${e.id}" is already registered.`);
140
- return s.set(e.id, e), () => {
141
- s.get(e.id) === e && s.delete(e.id), s.size === 0 && this._machines === s && (this._machines = void 0);
146
+ return i.set(e.id, e), () => {
147
+ i.get(e.id) === e && i.delete(e.id), i.size === 0 && this._machines === i && (this._machines = void 0);
142
148
  };
143
149
  }
144
150
  /**
@@ -154,8 +160,8 @@ class p {
154
160
  */
155
161
  listMachines() {
156
162
  const e = [];
157
- for (const s of this._machines?.values() ?? []) {
158
- const t = s.snapshot();
163
+ for (const i of this._machines?.values() ?? []) {
164
+ const t = i.snapshot();
159
165
  e.push(Object.freeze({
160
166
  active: t.active,
161
167
  id: t.id,
@@ -191,27 +197,27 @@ class p {
191
197
  /** Возвращает число child actors по уже готовым snapshots. @internal */
192
198
  get actorCount() {
193
199
  let e = 0;
194
- for (const s of this._machines?.values() ?? [])
195
- e += s.snapshot().actors.length;
200
+ for (const i of this._machines?.values() ?? [])
201
+ e += i.snapshot().actors.length;
196
202
  return e;
197
203
  }
198
204
  /** Группирует machine/actor ветви по фактическому lifecycle owner. @internal */
199
205
  machineTreeNodesByOwner() {
200
- const e = [...this._machines?.values() ?? []], s = new Map(e.map((n) => [n.id, n])), t = /* @__PURE__ */ new Map();
201
- for (const n of e) {
202
- if (n.parentId === void 0 || !s.has(n.parentId))
206
+ const e = [...this._machines?.values() ?? []], i = new Map(e.map((s) => [s.id, s])), t = /* @__PURE__ */ new Map();
207
+ for (const s of e) {
208
+ if (s.parentId === void 0 || !i.has(s.parentId))
203
209
  continue;
204
- const r = t.get(n.parentId) ?? [];
205
- r.push(n), t.set(n.parentId, r);
210
+ const r = t.get(s.parentId) ?? [];
211
+ r.push(s), t.set(s.parentId, r);
206
212
  }
207
213
  const a = /* @__PURE__ */ new Map();
208
- for (const n of e) {
209
- if (n.parentId !== void 0 && s.has(n.parentId))
214
+ for (const s of e) {
215
+ if (s.parentId !== void 0 && i.has(s.parentId))
210
216
  continue;
211
- const r = a.get(n.ownerId) ?? [];
212
- r.push(h(n, t, !1)), a.set(n.ownerId, r);
217
+ const r = a.get(s.ownerId) ?? [];
218
+ r.push(h(s, t, !1)), a.set(s.ownerId, r);
213
219
  }
214
- return new Map([...a].map(([n, r]) => [n, Object.freeze(r)]));
220
+ return new Map([...a].map(([s, r]) => [s, Object.freeze(r)]));
215
221
  }
216
222
  // ---------------------------------------------
217
223
  // PRIVATE
@@ -233,50 +239,50 @@ class p {
233
239
  this._guards = e.guards;
234
240
  }
235
241
  if (e.include !== void 0) {
236
- const s = /* @__PURE__ */ new Set();
242
+ const i = /* @__PURE__ */ new Set();
237
243
  for (const t of e.include) {
238
244
  if (t !== "action" && t !== "machine" && t !== "phase" && t !== "error")
239
245
  throw new TypeError(`[Raph] Unsupported trace kind "${String(t)}".`);
240
- s.add(t);
246
+ i.add(t);
241
247
  }
242
- this._include = s;
248
+ this._include = i;
243
249
  }
244
250
  }
245
251
  _ensureBuffer() {
246
252
  return this._events ??= new Array(this._capacity);
247
253
  }
248
254
  }
249
- function f(i) {
250
- const e = i instanceof c ? i.children.map(f) : [];
255
+ function f(n) {
256
+ const e = n instanceof c ? n.children.map(f) : [];
251
257
  return Object.freeze({
252
258
  children: Object.freeze(e),
253
- disposed: i.disposed,
254
- id: i.id,
255
- kind: i instanceof c ? "node" : "scope",
256
- resources: i._debugResourceCount(),
257
- sources: i._debugSourceCount()
259
+ disposed: n.disposed,
260
+ id: n.id,
261
+ kind: n instanceof c ? "node" : "scope",
262
+ resources: n._debugResourceCount(),
263
+ sources: n._debugSourceCount()
258
264
  });
259
265
  }
260
- function _(i, e = /* @__PURE__ */ new Map()) {
261
- const s = i instanceof c ? i.children.map((a) => _(a, e)) : [], t = i._debugResourceCount();
262
- return t !== 0 && s.push(Object.freeze({
266
+ function _(n, e = /* @__PURE__ */ new Map()) {
267
+ const i = n instanceof c ? n.children.map((a) => _(a, e)) : [], t = n._debugResourceCount();
268
+ return t !== 0 && i.push(Object.freeze({
263
269
  children: Object.freeze([]),
264
270
  count: t,
265
- id: `${i.id}:resources`,
271
+ id: `${n.id}:resources`,
266
272
  kind: "resource"
267
- })), s.push(...e.get(i.id) ?? []), Object.freeze({
268
- children: Object.freeze(s),
269
- disposed: i.disposed,
270
- id: i.id,
271
- kind: i instanceof c ? "node" : "scope"
273
+ })), i.push(...e.get(n.id) ?? []), Object.freeze({
274
+ children: Object.freeze(i),
275
+ disposed: n.disposed,
276
+ id: n.id,
277
+ kind: n instanceof c ? "node" : "scope"
272
278
  });
273
279
  }
274
- function h(i, e, s) {
275
- const t = i.snapshot();
280
+ function h(n, e, i) {
281
+ const t = n.snapshot();
276
282
  return Object.freeze({
277
- children: Object.freeze((e.get(i.id) ?? []).map((a) => h(a, e, !0))),
283
+ children: Object.freeze((e.get(n.id) ?? []).map((a) => h(a, e, !0))),
278
284
  id: t.id,
279
- kind: s ? "actor" : "machine",
285
+ kind: i ? "actor" : "machine",
280
286
  status: t.status
281
287
  });
282
288
  }
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("../../reactivity/disposal.cjs"),b=require("../errors.cjs"),S=require("../reactivity/RaphWorkGraph.cjs"),w=require("./RaphScope.cjs");let x=0;const C=Symbol("RaphProvisionalNode"),A=Object.freeze({}),O="[Raph] Child order must contain every direct child exactly once.",p="[Raph] Child order can contain only direct children of the node.";let f,c;class u extends w.RaphScope{#i;constructor(i,t={},e,r){const s=e??(i instanceof u?i.runtime:i??void 0);if(s===void 0)throw new Error("[RaphNode] A root node requires an explicit runtime.");const n=i instanceof u?i:i?.root??null;if(n!==null&&n.runtime!==s)throw new b.RaphCrossRuntimeError("[Raph] Parent belongs to another runtime.");const l=t.priority??0,h=t.id,a=t.meta,y=a===void 0?void 0:{...a},g=t.type??"default";n?._assertAlive(),v(l),super(h??x++,s);const m=r===C;if(this.priority=l,this._parent=n,this._prevSibling=null,this._nextSibling=null,this._firstChild=null,this._lastChild=null,this._childCount=0,this._childArray=void 0,this._published=n===null||!m&&n._published,this.#i=A,new.target!==u&&Object.defineProperty(this,"api",{configurable:!0,enumerable:!0,value:this.#i,writable:!0}),this._meta=y,this.type=g,this._subtreeIdentity=void 0,n!==null){if(n._appendChild(this),!this._published)return;s._hasNodeStructureDemand(this)?s._notifyNodeStructure(this,{node:this,newIndex:n._childCount-1,newParent:n},[],d(this)):s._touchMutationBoundary(),this._assertAlive()}else s._addTopOwner(this)}get id(){const i=this._id;return typeof i=="string"?i:this._id=`node-${i}`}get meta(){return this._meta??={}}set meta(i){this._meta=i}get api(){return this.#i}get _subtreeSourceIdentity(){return this._subtreeIdentity??=Object.freeze({})}get node(){return this}get parent(){return this._parent}get children(){return this._childArray??this._materializeChildren()}addChild(i){if(this._assertAlive(),i._assertAlive(),i.runtime!==this.runtime)throw new b.RaphCrossRuntimeError("[Raph] Child belongs to another runtime.");if(this===i)throw new Error("[Raph] A node cannot become its own ancestor.");if(!i._published||!this._published)throw new Error("[Raph] A provisional node cannot be reparented before setup commits.");for(let t=this;t!==null;t=t.parent)if(t===i)throw new Error("[Raph] A node cannot become its own ancestor.");return i.parent===this?!0:this.runtime._runNodeMutation(()=>{const t=this.runtime;t._assertNodeReparentAllowed(i,this);const e=i._parent;if(!t._hasNodeStructureDemand(i))return e!==null&&i._unlinkFrom(e,-1),i._parent=this,this._appendChild(i),e===null&&t._removeTopOwner(i),!0;const r=d(i),s=e===null?-1:i._indexIn(e);e!==null&&i._unlinkFrom(e,s),i._parent=this;const n=this._childCount;return this._appendChild(i),e===null&&t._removeTopOwner(i),t._notifyNodeStructure(i,{node:i,...e===null?{}:{oldParent:e},...s<0?{}:{oldIndex:s},newParent:this,newIndex:n},r,d(i)),!0})}reorderChildren(i){this._assertAlive(),this._applyChildOrder(i)||this._rejectChildOrder(i)}moveChild(i,t){if(this._assertAlive(),i._assertAlive(),t!==null&&t._assertAlive(),i._parent!==this||t!==null&&t._parent!==this)throw new Error(p);const e=this.runtime;if(i===t||i._nextSibling===t){e._touchMutationBoundary();return}const r=e._hasNodeSubscribers()?this._indexChildren():void 0;if(this._relinkBefore(i,t),r!==void 0){this._publishChildOrder(r);return}this._childArray=void 0,e._touchMutationBoundary()}_swapChildren(i,t){if(this._assertAlive(),i._assertAlive(),t._assertAlive(),i._parent!==this||t._parent!==this)throw new Error(p);const e=this.runtime;if(i===t){e._touchMutationBoundary();return}const r=e._hasNodeSubscribers()?this._indexChildren():void 0,s=i._nextSibling,n=t._nextSibling;if(s===t?this._relinkBefore(t,i):n===i?this._relinkBefore(i,t):(this._relinkBefore(i,n),this._relinkBefore(t,s)),r!==void 0){this._publishChildOrder(r);return}this._childArray=void 0,e._touchMutationBoundary()}_disposeChildren(i,t=0,e=i===void 0?0:i.length){let r=i;if(r===void 0&&(r=this._childArray??this._collectChildren(),e=r.length),t>=e)return;const s=this._childArray;s!==void 0&&(s===r||this._firstChild===r[t].node)&&(this._childArray=void 0);const n=this.runtime;let l;n._beginOwnerDisposal();for(let h=t;h<e;h++)try{r[h].node.dispose()}catch(a){(l??=[]).push(a)}try{n._endOwnerDisposal()}catch(h){(l??=[]).push(h)}return l}options(i){this._assertAlive(),i.meta!==void 0&&(this._meta={...i.meta}),i.priority!==void 0&&(v(i.priority),this.priority=i.priority),i.type!==void 0&&(this.type=i.type),this.touch(Object.freeze({options:Object.freeze({...i})}))}touch(i){this._assertAlive(),this.runtime._runNodeMutation(()=>this.runtime._notifyNodeTouch(this,i))}remove(){this.dispose()}dispose(){o.throwDisposalFailure(c.call(this))}_disposeForOwner(){try{const i=this.dispose;if(i===f)return c.call(this);i.call(this);return}catch(i){return o.unroutedDisposalFailure(i)}}_disposeWithOutcome(){if(this._disposed||this._disposing)return;this._disposing=!0;const i=this.runtime;i._beginOwnerDisposal(this);let t;try{if(this._firstChild!==null){const r=this._takeChildSnapshot();for(let s=0;s<r.length;s++){const n=r[s];try{const l=n.dispose;if(l===f){const h=c.call(n);h!==void 0&&(t??=[]).push(h)}else l.call(n)}catch(l){(t??=[]).push(o.unroutedDisposalFailure(l))}}this._resetChildList(r)}const e=this._parent;if(this._published&&i._hasNodeStructureDemand(this)){const r=d(this),s=e===null?-1:this._indexIn(e);e!==null&&(this._unlinkFrom(e,s),this._parent=null);try{i._notifyNodeStructure(this,{node:this,...e===null?{}:{oldParent:e},...s<0?{}:{oldIndex:s}},r,[])}catch(n){(t??=[]).push(o.unroutedDisposalFailure(n))}}else if(e!==null&&(this._unlinkFrom(e,-1),this._parent=null),this._published)try{i._touchMutationBoundary()}catch(r){(t??=[]).push(o.unroutedDisposalFailure(r))}try{const r=super._disposeScopeForOwner(super.dispose);r!==void 0&&(t??=[]).push(r)}catch(r){(t??=[]).push(o.unroutedDisposalFailure(r))}e===null&&i._removeTopOwner(this),this._published=!1;try{i._releaseNode(this)}catch(r){(t??=[]).push(o.unroutedDisposalFailure(r))}}finally{try{i._endOwnerDisposal()}catch(e){(t??=[]).push(o.unroutedDisposalFailure(e))}}if(t!==void 0)return o.combineDisposalFailures(t,`[Raph] Node "${this.id}" disposal failed.`)}_setApi(i){this.#i=typeof i=="object"&&i!==null&&!(i instanceof S.RaphProducer)?Object.freeze(i):i,Object.hasOwn(this,"api")&&Object.defineProperty(this,"api",{configurable:!1,enumerable:!0,value:this.#i,writable:!1})}_publishCreation(){if(this._published)return;const i=this._parent;if(!(i===null||!i._published)){this._published=!0;try{const t=this.runtime;t._hasNodeStructureDemand(this)?t._notifyNodeStructure(this,{node:this,newIndex:this._indexIn(i),newParent:i},[],d(this)):t._touchMutationBoundary();for(let e=this._firstChild;e!==null;e=e._nextSibling)e._publishCreation()}catch(t){throw this._published=!1,t}}}_isPublished(){return this._published}_isLinked(){const i=this._parent;return i!==null&&(this._prevSibling!==null||i._firstChild===this)}_collectDescendants(i){let t=this;for(;;){let e=t._firstChild;for(;e===null;){if(t===this)return;e=t._nextSibling,e===null&&(t=t._parent)}t=e,i.push(t)}}_countSubtree(i){let t=this;for(;;){i.resources+=t._debugResourceCount(),i.sources+=t._debugSourceCount();let e=t._firstChild;for(;e===null;){if(t===this)return;e=t._nextSibling,e===null&&(t=t._parent)}t=e}}_findNode(i){let t=this;for(;;){if(t.id===i)return t;let e=t._lastChild;for(;e===null;){if(t===this)return;e=t._prevSibling,e===null&&(t=t._parent)}t=e}}_applyChildOrder(i){const t=i.length;if(t!==this._childCount)return!1;const e=[];for(let l=0;l<t;l++)e.push(i[l]);if(t!==this._childCount)return!1;const r=this.runtime,s=r._hasNodeSubscribers()?this._indexChildren():void 0;if(!this._relinkChildren(e))return!1;const n=this._childArray;if(n!==void 0&&n!==i)for(let l=0;l<t;l++)n[l]=e[l];return s===void 0?r._touchMutationBoundary():this._notifyChildOrder(e,s),!0}_relinkChildren(i){for(let n=this._firstChild;n!==null;n=n._nextSibling)n._prevSibling=this;const t=i.length;let e=null,r=0;try{for(;r<t;r++){const n=i[r];if(n?._parent!==this||n._prevSibling!==this||n._disposing)break;n._prevSibling=e,e=n}}finally{if(r!==t){let n=null;for(let l=this._firstChild;l!==null;l=l._nextSibling)l._prevSibling=n,n=l}}if(r!==t)return!1;let s=null;for(let n=e;n!==null;n=n._prevSibling)n._nextSibling=s,s=n;return this._firstChild=s,this._lastChild=e,!0}_rejectChildOrder(i){if(i.length===this._childCount&&new Set(i).size===i.length){for(const t of i)if(t._assertAlive(),t._parent!==this)throw new Error(p)}throw new Error(O)}_indexChildren(){const i=new Map;let t=0;for(let e=this._firstChild;e!==null;e=e._nextSibling)i.set(e,t++);return i}_publishChildOrder(i){let t=this._childArray;if(t===void 0)t=this._materializeChildren();else{let e=0;for(let r=this._firstChild;r!==null;r=r._nextSibling)t[e++]=r}this._notifyChildOrder(t,i)}_notifyChildOrder(i,t){const e=this.runtime;e._runNodeMutation(()=>{for(let r=0;r<i.length;r++){const s=i[r],n=t.get(s);if(n===r)continue;const l=d(s);e._notifyNodeStructure(s,{node:s,oldParent:this,newParent:this,oldIndex:n,newIndex:r},l,l)}})}_relinkBefore(i,t){const e=i._prevSibling,r=i._nextSibling;e===null?this._firstChild=r:e._nextSibling=r,r===null?this._lastChild=e:r._prevSibling=e;const s=t===null?this._lastChild:t._prevSibling;i._prevSibling=s,i._nextSibling=t,s===null?this._firstChild=i:s._nextSibling=i,t===null?this._lastChild=i:t._prevSibling=i}_materializeChildren(){return this._childArray=this._collectChildren()}_collectChildren(){const i=[];for(let t=this._firstChild;t!==null;t=t._nextSibling)i.push(t);return i}_clearChildArray(){const i=this._childArray;i!==void 0&&(i.length=0,this._childArray=void 0)}_appendChild(i){const t=this._lastChild;i._prevSibling=t,t===null?this._firstChild=i:t._nextSibling=i,this._lastChild=i,this._childCount++;const e=this._childArray;e!==void 0&&e.push(i)}_indexIn(i){return this._prevSibling===null?i._firstChild===this?0:-1:i._lastChild===this?i._childCount-1:(i._childArray??i._materializeChildren()).indexOf(this)}_unlinkFrom(i,t){const e=this._prevSibling,r=this._nextSibling;if(e===null){if(i._firstChild!==this)return;i._firstChild=r}else e._nextSibling=r,this._prevSibling=null;r===null?i._lastChild=e:(r._prevSibling=e,this._nextSibling=null),i._childCount--;const s=i._childArray;if(s!==void 0)if(r===null)s.pop();else if(t<0&&!i._disposing&&!this.runtime._hasNodeSubscribers())i._childArray=void 0;else if(e===null)s.shift();else{const n=t>=0?t:s.indexOf(this);n>=0?s.splice(n,1):i._childArray=void 0}}_takeChildSnapshot(){const i=this._childArray;return i===void 0?this._collectChildren():(this._childArray=void 0,i)}_resetChildList(i){i.length=0,this._clearChildArray();let t=this._firstChild;for(;t!==null;){const e=t._nextSibling;t._prevSibling=null,t._nextSibling=null,t=e}this._firstChild=null,this._lastChild=null,this._childCount=0}}function N(_,i,t){return new u(_,i,t,C)}u.prototype._isNode=!0;function d(_){const i=[];for(let t=_;t!==null;t=t.parent)i.push(t);return i}function v(_){if(!Number.isFinite(_))throw new TypeError("[Raph] Node priority must be finite.")}f=u.prototype.dispose;c=u.prototype._disposeWithOutcome;exports.RaphNode=u;exports.createProvisionalNode=N;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("../../reactivity/disposal.cjs"),b=require("../errors.cjs"),S=require("../reactivity/RaphWorkGraph.cjs"),w=require("./RaphScope.cjs");let x=0;const C=Symbol("RaphProvisionalNode"),A=Object.freeze({}),O="[Raph] Child order must contain every direct child exactly once.",p="[Raph] Child order can contain only direct children of the node.";let f,c;class u extends w.RaphScope{#i;constructor(i,t={},e,r){const s=e??(i instanceof u?i.runtime:i??void 0);if(s===void 0)throw new Error("[RaphNode] A root node requires an explicit runtime.");const n=i instanceof u?i:i?.root??null;if(n!==null&&n.runtime!==s)throw new b.RaphCrossRuntimeError("[Raph] Parent belongs to another runtime.");const l=t.priority??0,h=t.id,a=t.meta,y=a===void 0?void 0:{...a},g=t.type??"default";n?._assertAlive(),v(l),super(h??x++,s);const m=r===C;if(this.priority=l,this._parent=n,this._prevSibling=null,this._nextSibling=null,this._firstChild=null,this._lastChild=null,this._childCount=0,this._childArray=void 0,this._published=n===null||!m&&n._published,this.#i=A,new.target!==u&&Object.defineProperty(this,"api",{configurable:!0,enumerable:!0,value:this.#i,writable:!0}),this._meta=y,this.type=g,this._subtreeIdentity=void 0,n!==null){if(n._appendChild(this),!this._published)return;s._hasNodeStructureDemand(this)?s._notifyNodeStructure(this,{node:this,newIndex:n._childCount-1,newParent:n},[],d(this)):s._touchMutationBoundary(),this._assertAlive()}else s._addTopOwner(this)}get id(){const i=this._id;return typeof i=="string"?i:this._id=`node-${i}`}get meta(){return this._meta??={}}set meta(i){this._meta=i}get api(){return this.#i}get _subtreeSourceIdentity(){return this._subtreeIdentity??=Object.freeze({})}get node(){return this}get parent(){return this._parent}_hasAncestor(i){for(let t=this._parent;t!==null;t=t._parent)if(t===i)return!0;return!1}get children(){return this._childArray??this._materializeChildren()}addChild(i){if(this._assertAlive(),i._assertAlive(),i.runtime!==this.runtime)throw new b.RaphCrossRuntimeError("[Raph] Child belongs to another runtime.");if(this===i)throw new Error("[Raph] A node cannot become its own ancestor.");if(!i._published||!this._published)throw new Error("[Raph] A provisional node cannot be reparented before setup commits.");for(let t=this;t!==null;t=t.parent)if(t===i)throw new Error("[Raph] A node cannot become its own ancestor.");return i.parent===this?!0:this.runtime._runNodeMutation(()=>{const t=this.runtime;t._assertNodeReparentAllowed(i,this);const e=i._parent;if(!t._hasNodeStructureDemand(i))return e!==null&&i._unlinkFrom(e,-1),i._parent=this,this._appendChild(i),e===null&&t._removeTopOwner(i),!0;const r=d(i),s=e===null?-1:i._indexIn(e);e!==null&&i._unlinkFrom(e,s),i._parent=this;const n=this._childCount;return this._appendChild(i),e===null&&t._removeTopOwner(i),t._notifyNodeStructure(i,{node:i,...e===null?{}:{oldParent:e},...s<0?{}:{oldIndex:s},newParent:this,newIndex:n},r,d(i)),!0})}reorderChildren(i){this._assertAlive(),this._applyChildOrder(i)||this._rejectChildOrder(i)}moveChild(i,t){if(this._assertAlive(),i._assertAlive(),t!==null&&t._assertAlive(),i._parent!==this||t!==null&&t._parent!==this)throw new Error(p);const e=this.runtime;if(i===t||i._nextSibling===t){e._touchMutationBoundary();return}const r=e._hasNodeSubscribers()?this._indexChildren():void 0;if(this._relinkBefore(i,t),r!==void 0){this._publishChildOrder(r);return}this._childArray=void 0,e._touchMutationBoundary()}_swapChildren(i,t){if(this._assertAlive(),i._assertAlive(),t._assertAlive(),i._parent!==this||t._parent!==this)throw new Error(p);const e=this.runtime;if(i===t){e._touchMutationBoundary();return}const r=e._hasNodeSubscribers()?this._indexChildren():void 0,s=i._nextSibling,n=t._nextSibling;if(s===t?this._relinkBefore(t,i):n===i?this._relinkBefore(i,t):(this._relinkBefore(i,n),this._relinkBefore(t,s)),r!==void 0){this._publishChildOrder(r);return}this._childArray=void 0,e._touchMutationBoundary()}_disposeChildren(i,t=0,e=i===void 0?0:i.length){let r=i;if(r===void 0&&(r=this._childArray??this._collectChildren(),e=r.length),t>=e)return;const s=this._childArray;s!==void 0&&(s===r||this._firstChild===r[t].node)&&(this._childArray=void 0);const n=this.runtime;let l;n._beginOwnerDisposal();for(let h=t;h<e;h++)try{r[h].node.dispose()}catch(a){(l??=[]).push(a)}try{n._endOwnerDisposal()}catch(h){(l??=[]).push(h)}return l}options(i){this._assertAlive(),i.meta!==void 0&&(this._meta={...i.meta}),i.priority!==void 0&&(v(i.priority),this.priority=i.priority),i.type!==void 0&&(this.type=i.type),this.touch(Object.freeze({options:Object.freeze({...i})}))}touch(i){this._assertAlive(),this.runtime._runNodeMutation(()=>this.runtime._notifyNodeTouch(this,i))}remove(){this.dispose()}dispose(){o.throwDisposalFailure(c.call(this))}_disposeForOwner(){try{const i=this.dispose;if(i===f)return c.call(this);i.call(this);return}catch(i){return o.unroutedDisposalFailure(i)}}_disposeWithOutcome(){if(this._disposed||this._disposing)return;this._disposing=!0;const i=this.runtime;i._beginOwnerDisposal(this);let t;try{if(this._firstChild!==null){const r=this._takeChildSnapshot();for(let s=0;s<r.length;s++){const n=r[s];try{const l=n.dispose;if(l===f){const h=c.call(n);h!==void 0&&(t??=[]).push(h)}else l.call(n)}catch(l){(t??=[]).push(o.unroutedDisposalFailure(l))}}this._resetChildList(r)}const e=this._parent;if(this._published&&i._hasNodeStructureDemand(this)){const r=d(this),s=e===null?-1:this._indexIn(e);e!==null&&(this._unlinkFrom(e,s),this._parent=null);try{i._notifyNodeStructure(this,{node:this,...e===null?{}:{oldParent:e},...s<0?{}:{oldIndex:s}},r,[])}catch(n){(t??=[]).push(o.unroutedDisposalFailure(n))}}else if(e!==null&&(this._unlinkFrom(e,-1),this._parent=null),this._published)try{i._touchMutationBoundary()}catch(r){(t??=[]).push(o.unroutedDisposalFailure(r))}try{const r=super._disposeScopeForOwner(super.dispose);r!==void 0&&(t??=[]).push(r)}catch(r){(t??=[]).push(o.unroutedDisposalFailure(r))}e===null&&i._removeTopOwner(this),this._published=!1;try{i._releaseNode(this)}catch(r){(t??=[]).push(o.unroutedDisposalFailure(r))}}finally{try{i._endOwnerDisposal()}catch(e){(t??=[]).push(o.unroutedDisposalFailure(e))}}if(t!==void 0)return o.combineDisposalFailures(t,`[Raph] Node "${this.id}" disposal failed.`)}_setApi(i){this.#i=typeof i=="object"&&i!==null&&!(i instanceof S.RaphProducer)?Object.freeze(i):i,Object.hasOwn(this,"api")&&Object.defineProperty(this,"api",{configurable:!1,enumerable:!0,value:this.#i,writable:!1})}_publishCreation(){if(this._published)return;const i=this._parent;if(!(i===null||!i._published)){this._published=!0;try{const t=this.runtime;t._hasNodeStructureDemand(this)?t._notifyNodeStructure(this,{node:this,newIndex:this._indexIn(i),newParent:i},[],d(this)):t._touchMutationBoundary();for(let e=this._firstChild;e!==null;e=e._nextSibling)e._publishCreation()}catch(t){throw this._published=!1,t}}}_isPublished(){return this._published}_isLinked(){const i=this._parent;return i!==null&&(this._prevSibling!==null||i._firstChild===this)}_collectDescendants(i){let t=this;for(;;){let e=t._firstChild;for(;e===null;){if(t===this)return;e=t._nextSibling,e===null&&(t=t._parent)}t=e,i.push(t)}}_countSubtree(i){let t=this;for(;;){i.resources+=t._debugResourceCount(),i.sources+=t._debugSourceCount();let e=t._firstChild;for(;e===null;){if(t===this)return;e=t._nextSibling,e===null&&(t=t._parent)}t=e}}_findNode(i){let t=this;for(;;){if(t.id===i)return t;let e=t._lastChild;for(;e===null;){if(t===this)return;e=t._prevSibling,e===null&&(t=t._parent)}t=e}}_applyChildOrder(i){const t=i.length;if(t!==this._childCount)return!1;const e=[];for(let l=0;l<t;l++)e.push(i[l]);if(t!==this._childCount)return!1;const r=this.runtime,s=r._hasNodeSubscribers()?this._indexChildren():void 0;if(!this._relinkChildren(e))return!1;const n=this._childArray;if(n!==void 0&&n!==i)for(let l=0;l<t;l++)n[l]=e[l];return s===void 0?r._touchMutationBoundary():this._notifyChildOrder(e,s),!0}_relinkChildren(i){for(let n=this._firstChild;n!==null;n=n._nextSibling)n._prevSibling=this;const t=i.length;let e=null,r=0;try{for(;r<t;r++){const n=i[r];if(n?._parent!==this||n._prevSibling!==this||n._disposing)break;n._prevSibling=e,e=n}}finally{if(r!==t){let n=null;for(let l=this._firstChild;l!==null;l=l._nextSibling)l._prevSibling=n,n=l}}if(r!==t)return!1;let s=null;for(let n=e;n!==null;n=n._prevSibling)n._nextSibling=s,s=n;return this._firstChild=s,this._lastChild=e,!0}_rejectChildOrder(i){if(i.length===this._childCount&&new Set(i).size===i.length){for(const t of i)if(t._assertAlive(),t._parent!==this)throw new Error(p)}throw new Error(O)}_indexChildren(){const i=new Map;let t=0;for(let e=this._firstChild;e!==null;e=e._nextSibling)i.set(e,t++);return i}_publishChildOrder(i){let t=this._childArray;if(t===void 0)t=this._materializeChildren();else{let e=0;for(let r=this._firstChild;r!==null;r=r._nextSibling)t[e++]=r}this._notifyChildOrder(t,i)}_notifyChildOrder(i,t){const e=this.runtime;e._runNodeMutation(()=>{for(let r=0;r<i.length;r++){const s=i[r],n=t.get(s);if(n===r)continue;const l=d(s);e._notifyNodeStructure(s,{node:s,oldParent:this,newParent:this,oldIndex:n,newIndex:r},l,l)}})}_relinkBefore(i,t){const e=i._prevSibling,r=i._nextSibling;e===null?this._firstChild=r:e._nextSibling=r,r===null?this._lastChild=e:r._prevSibling=e;const s=t===null?this._lastChild:t._prevSibling;i._prevSibling=s,i._nextSibling=t,s===null?this._firstChild=i:s._nextSibling=i,t===null?this._lastChild=i:t._prevSibling=i}_materializeChildren(){return this._childArray=this._collectChildren()}_collectChildren(){const i=[];for(let t=this._firstChild;t!==null;t=t._nextSibling)i.push(t);return i}_clearChildArray(){const i=this._childArray;i!==void 0&&(i.length=0,this._childArray=void 0)}_appendChild(i){const t=this._lastChild;i._prevSibling=t,t===null?this._firstChild=i:t._nextSibling=i,this._lastChild=i,this._childCount++;const e=this._childArray;e!==void 0&&e.push(i)}_indexIn(i){return this._prevSibling===null?i._firstChild===this?0:-1:i._lastChild===this?i._childCount-1:(i._childArray??i._materializeChildren()).indexOf(this)}_unlinkFrom(i,t){const e=this._prevSibling,r=this._nextSibling;if(e===null){if(i._firstChild!==this)return;i._firstChild=r}else e._nextSibling=r,this._prevSibling=null;r===null?i._lastChild=e:(r._prevSibling=e,this._nextSibling=null),i._childCount--;const s=i._childArray;if(s!==void 0)if(r===null)s.pop();else if(t<0&&!i._disposing&&!this.runtime._hasNodeSubscribers())i._childArray=void 0;else if(e===null)s.shift();else{const n=t>=0?t:s.indexOf(this);n>=0?s.splice(n,1):i._childArray=void 0}}_takeChildSnapshot(){const i=this._childArray;return i===void 0?this._collectChildren():(this._childArray=void 0,i)}_resetChildList(i){i.length=0,this._clearChildArray();let t=this._firstChild;for(;t!==null;){const e=t._nextSibling;t._prevSibling=null,t._nextSibling=null,t=e}this._firstChild=null,this._lastChild=null,this._childCount=0}}function N(_,i,t){return new u(_,i,t,C)}u.prototype._isNode=!0;function d(_){const i=[];for(let t=_;t!==null;t=t.parent)i.push(t);return i}function v(_){if(!Number.isFinite(_))throw new TypeError("[Raph] Node priority must be finite.")}f=u.prototype.dispose;c=u.prototype._disposeWithOutcome;exports.RaphNode=u;exports.createProvisionalNode=N;
@@ -68,6 +68,17 @@ class o extends A {
68
68
  get parent() {
69
69
  return this._parent;
70
70
  }
71
+ /**
72
+ * Сообщает, является ли `owner` строгим предком узла: тот же обход, что по
73
+ * `parent`, но по полям, без вызова getter на каждом шаге.
74
+ * @internal
75
+ */
76
+ _hasAncestor(i) {
77
+ for (let t = this._parent; t !== null; t = t._parent)
78
+ if (t === i)
79
+ return !0;
80
+ return !1;
81
+ }
71
82
  /**
72
83
  * Возвращает прямых детей в их порядке. Массив действителен до следующей
73
84
  * структурной mutation этой node; после неё порядок даёт новое чтение.
@@ -1 +1 @@
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
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("../../reactivity/disposal.cjs"),d=require("../../reactivity/scope.cjs"),l=require("../errors.cjs");let p,u;class n extends d.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._disposed||this._disposing)&&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===p)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._disposed||this._disposing)&&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 l.RaphDisposedError(`[Raph] Owner "${this.id}" is disposed.`)}}n.prototype._isNode=!1;function a(){}p=n.prototype.dispose;u=n.prototype._disposeWithOutcome;exports.RaphScope=n;
@@ -1,8 +1,8 @@
1
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 {
2
+ import { ScopeOwner as c } from "../../reactivity/scope.js";
3
+ import { RaphDisposedError as l } from "../errors.js";
4
+ let d, h;
5
+ class a extends c {
6
6
  constructor(t, e) {
7
7
  super(), this._id = t, this.runtime = e, this._order = e._registerOwner(this);
8
8
  }
@@ -116,7 +116,7 @@ class a extends l {
116
116
  * @internal
117
117
  */
118
118
  _registerEffect(t, e, i, s, r, o) {
119
- this._assertAlive(), this.runtime._effectRegistration(this, t, e, i, !1, s, r, o);
119
+ (this._disposed || this._disposing) && this._assertAlive(), this.runtime._effectRegistration(this, t, e, i, !1, s, r, o);
120
120
  }
121
121
  /** @internal */
122
122
  _registerWatch(t, e, i, s, r, o) {
@@ -144,7 +144,7 @@ class a extends l {
144
144
  return this._assertAlive(), typeof t == "function" ? this.runtime.action(t, this) : this.runtime.action(t, e, this);
145
145
  }
146
146
  own(t) {
147
- return this._disposed || this._disposing ? (t(), c) : this._ownCleanup(t);
147
+ return this._disposed || this._disposing ? (t(), _) : this._ownCleanup(t);
148
148
  }
149
149
  dispose() {
150
150
  u(h.call(this));
@@ -152,7 +152,7 @@ class a extends l {
152
152
  /** Node's super stage keeps the actual public base-method lookup observable. @internal */
153
153
  _disposeScopeForOwner(t) {
154
154
  try {
155
- if (t === _)
155
+ if (t === d)
156
156
  return h.call(this);
157
157
  t.call(this);
158
158
  return;
@@ -190,7 +190,7 @@ class a extends l {
190
190
  }
191
191
  /** Framework capture registration; ordinary own callback semantics are unchanged. @internal */
192
192
  _ownCompletedCleanup(t) {
193
- return this._disposed || this._disposing ? (u(t()), c) : this._ownCompleted(t);
193
+ return this._disposed || this._disposing ? (u(t()), _) : this._ownCompleted(t);
194
194
  }
195
195
  /** @internal */
196
196
  _adoptResource(t) {
@@ -204,7 +204,7 @@ class a extends l {
204
204
  * @internal
205
205
  */
206
206
  _adoptRecord(t) {
207
- this._assertAlive(), this._ownRecord(t);
207
+ (this._disposed || this._disposing) && this._assertAlive(), this._ownRecord(t);
208
208
  }
209
209
  /** @internal */
210
210
  _adoptSource(t) {
@@ -223,13 +223,13 @@ class a extends l {
223
223
  /** @internal */
224
224
  _assertAlive() {
225
225
  if (this._disposed || this._disposing)
226
- throw new d(`[Raph] Owner "${this.id}" is disposed.`);
226
+ throw new l(`[Raph] Owner "${this.id}" is disposed.`);
227
227
  }
228
228
  }
229
229
  a.prototype._isNode = !1;
230
- function c() {
230
+ function _() {
231
231
  }
232
- _ = a.prototype.dispose;
232
+ d = a.prototype.dispose;
233
233
  h = a.prototype._disposeWithOutcome;
234
234
  export {
235
235
  a as RaphScope
@@ -1 +1 @@
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;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("../errors.cjs"),O=require("../ownership/throwDisposalErrors.cjs"),s=require("./RaphPhaseTaskRecord.cjs");class w{constructor(e,t){this.name=e,this.pipeline=t,this.first=void 0,this.queue=[],this.spare=[],this.bindings=0}}const F=1e4,b=1e4,I=s.TASK_PENDING|s.TASK_DISCARD_ACKNOWLEDGED|s.TASK_REQUESTED|s.TASK_RESOLUTION|s.TASK_CAUSES_DELIVERED,C=s.TASK_ACTIVE|s.TASK_PAUSED,R=s.TASK_IN_DELIVERY|s.TASK_RESOLUTION;class L{constructor(e,t,i,a=()=>!1,n){this._scheduler=e,this._reactivity=t,this._resolveCause=i,this._deferSync=a,this._tracePhase=n;const r=globalThis.performance;this._now=r===void 0?Date.now:r.now.bind(r)}_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=Number.NaN;_lastFrameAt=Number.NaN;_frameNumber=-1;_frame=s.EMPTY_FRAME;_publicFrames=!1;_frameStale=!1;_unmeasuredFrame;_firstReadFrame;_readPublicFrame=this._exposeCurrentFrame;_now;_setPhaseTrace(e){this._tracePhase=e}get frame(){return this._readPublicFrame()}_readCurrentFrame(){return this._frame}_exposeCurrentFrame(){return this._exposeFrame(this._frame)}_frameForDelivery(){return this._frame}_exposeFrame(e){return this._publicFrames||(this._frameStale&&(this._unmeasuredFrame=this._frame,this._materializeFrame(),this._firstReadFrame=this._frame),this._publicFrames=!0,Object.freeze(this._frame),this._readPublicFrame=this._readCurrentFrame),e===this._unmeasuredFrame?this._firstReadFrame:e===this._frame?e:Object.freeze(e)}get phases(){return this._phases.map(e=>e.phase)}definePhases(e){if(this._assertAlive(),this._configurationLocked||this._frameNumber!==-1)throw new Error("[Raph] Cannot redefine phases after phase pipeline execution has started.");const t=this._phaseByName,i=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(i.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 o=Object.freeze({name:r,...n.process===void 0?{}:{process:n.process}}),_={index:a.length,phase:o,state:t.get(r)?.state??new w(r,this)};a.push(_),i.set(r,_)}this._assertRetainedPhases(i),this._phases=a,this._phaseByName=i,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 i=this._phaseByName.get(e);if(i===void 0){const a=e.trim();if(a!==e&&(i=this._phaseByName.get(a)),i===void 0)throw new Error(`[Raph] Phase "${a}" is not defined.`)}return this._resolvedInput=e,this._resolvedState=i.state}bindTask(e,t,i,a){return e.bindings++,new s.RaphPhaseTaskRecord(e,a,t,i)}bindGroup(e,t,i,a,n,r){const o=new Array(s.GROUP_NODES+n);o[s.GROUP_CONTEXT]=a,o[s.GROUP_CURSOR]=0,e.bindings++;const _=new s.RaphPhaseTaskRecord(e,r,t,i);return _.state=s.TASK_ACTIVE|s.TASK_TASKLESS,_.group=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._scheduled&&this._cancelScheduled(),!this._running){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,this._drain(this._publicFrames?this._nextFrame():this._skipFrame())}}_canDeliverFirst(e){return!(this._scheduler!=="sync"||this._running||this._scheduled||this._disposed||this._queuedCount!==0||this._deferred.size!==0||(e.state&(s.TASK_PAUSED|s.TASK_IN_DELIVERY|s.TASK_PENDING|s.TASK_DEFERRED))!==0||!(e.state&s.TASK_ACTIVE)||e.consumerOwner.disposed||this._deferSync())}_deliverFirst(e){e.state=e.state&~s.TASK_DISCARD_ACKNOWLEDGED|s.TASK_PENDING,e.sequence=this._taskSequence++,e.phaseState.first=e,this._queuedCount++,this._configurationLocked=!0,this._running=!0,this._drain(this._publicFrames?this._nextFrame():this._skipFrame())}_drain(e){let t,i=0,a;try{for(;this._queuedCount!==0;){if(++i>F){const r=this._describeQueued();this._cancelAllQueued(!0,t??=[]),t.push(new Error(`[Raph] Phase flush exceeded 10000 passes.${r?` Pending: ${r}.`:""}`));break}const n=this._phases;for(let r=0;r<n.length;r++){const o=n[r];if(this._disposed)break;const _=o.state,l=_.first;if(l===void 0)continue;const d=_.queue;_.first=void 0;const E=d.length===0&&o.phase.process===void 0;E||(_.queue=_.spare,_.spare=a=d),this._queuedCount-=d.length+1;const p=t?.length??0;if(this._tracePhase?.(o.phase.name,"start"),E){const u=l,h=u.state;if(!(h&s.TASK_ACTIVE)||u.consumerOwner._disposed){u.state=h&~s.TASK_PENDING,this._disposeTask(u),a=void 0;continue}const c=h&~I|s.TASK_IN_DELIVERY;u.state=u.firstCause===void 0?c:c|s.TASK_CAUSES_DELIVERED,u.facade!==void 0&&(u.frame=e);try{u.group!==void 0&&(t??=[]),this._runDelivery(u,t)}catch(A){(t??=[]).push(A)}try{this._finishDelivery(u)}catch(A){(u.state&s.TASK_RESOLUTION)!==s.TASK_RUN&&this._acknowledgeDiscard(u,!0,t??=[]),u.state=(u.state|s.TASK_CANCEL)&~s.TASK_IN_DELIVERY,v(u),t??=[],t.push(A)}a=void 0,(t?.length??0)===p?this._tracePhase?.(o.phase.name,"end"):this._tracePhase?.(o.phase.name,"error",t[t.length-1]);continue}d.unshift(l),t??=[];let T=0,m=!0,D;for(let u=0;u<d.length;u++){const h=d[u],c=h.state;if(!(c&s.TASK_ACTIVE)||h.consumerOwner._disposed){h.state=c&~s.TASK_PENDING,this._disposeTask(h);continue}const A=c&~I|s.TASK_IN_DELIVERY;h.state=h.firstCause===void 0?A:A|s.TASK_CAUSES_DELIVERED,h.facade!==void 0&&(h.frame=e),D!==void 0&&(h.priority>D.priority||h.priority===D.priority&&h.sequence<D.sequence)&&(m=!1),D=h,d[T++]=h}if(d.length=T,d.length===0){a=void 0;continue}m||d.sort(U);const y=o.phase.process;if(y===void 0)for(let u=0;u<d.length;u++)try{this._runDelivery(d[u],t)}catch(h){t.push(h)}else{const u=[];for(let c=0;c<d.length;c++)u.push(d[c].task);const h=Object.freeze({phase:o.phase.name,frame:this.frame,tasks:Object.freeze(u)});try{this._reactivity.untrackedWithOwner(()=>y(h))}catch(c){t.push(c)}}let K=0;for(let u=0;u<d.length;u++){const h=d[u];if((h.state&s.TASK_RESOLUTION)===s.TASK_UNRESOLVED){K++;try{this._deferDelivery(h)}catch(c){h.state|=s.TASK_CANCEL,this._acknowledgeDiscard(h,!0,t),t.push(c)}}try{this._finishDelivery(h)}catch(c){(h.state&s.TASK_RESOLUTION)!==s.TASK_RUN&&this._acknowledgeDiscard(h,!0,t),h.state=(h.state|s.TASK_CANCEL)&~s.TASK_IN_DELIVERY,v(h),t.push(c)}}d.length=0,a=void 0,K!==0&&t.push(new S.RaphPhaseProcessError(`[Raph] Phase "${o.phase.name}" left ${K} task(s) unresolved; they were deferred.`)),t.length===p?this._tracePhase?.(o.phase.name,"end"):this._tracePhase?.(o.phase.name,"error",t[t.length-1])}}}catch(n){(t??=[]).push(n),a!==void 0&&(a.length=0),this._cancelAllQueued(!0,t),this._cancelAllDeferred(!0,t)}finally{this._running=!1}try{this._deferred.size!==0&&this._scheduleDeferredTurn()}catch(n){(t??=[]).push(n)}if(t!==void 0&&t.length!==0){const n=t.length===1?t[0]:new AggregateError(t,"[Raph] Multiple phase tasks failed.");throw this._settleIdleWaiters(n,!0),n}this._idleWaiters.size!==0&&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 i of e)i.state&=~s.TASK_ACTIVE;this._phases=[],this._phaseByName.clear(),this._resolvedInput=void 0,this._resolvedState=void 0;const t=new S.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 i=t.state.first,a=(i===void 0?[]:[i,...t.state.queue]).filter(r=>(r.state&s.TASK_ACTIVE)!==0&&!r.consumerOwner.disposed);if(a.length===0)continue;const n=a.slice(0,3).map(r=>{const o=r.consumerOwner.node,_=o===void 0?void 0:o.componentId,l=o===void 0?r.consumerOwner.id:`${r.consumerOwner.id}/${o.constructor.name}/${o.type}${typeof _=="string"?`/${_}`:""}`,d=r.firstCause?.sourceOwner?.node,E=d===void 0?"":`<=${d.id}/${d.constructor.name}`;return`${l}${r.firstCause?`:${r.firstCause.kind}${E}`:""}`}).join(", ");e.push(`${t.phase.name}=${a.length}${n?` [${n}]`:""}`)}return e.join("; ")}_runDelivery(e,t){const i=e.state;if((i&C)!==s.TASK_ACTIVE||e.consumerOwner._disposed){e.state=i|s.TASK_CANCEL;return}(i&R)!==s.TASK_IN_DELIVERY&&P(),e.state=i|s.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|=s.TASK_EXECUTED,n._runTaskEffectUntracked(r));return}const o=e.group;if(o===void 0){const E=e.watch;E!==void 0&&n.untrackedWithOwner(E.deliver);return}const _=o.length;let l=this._idleSlotFlags,d;for(let E=s.GROUP_NODES;E<_;E++){const p=o[E];if(p===null||p.flags===l)continue;if(!n._beginTaskEffectRun(p)){p.evaluate!==void 0&&(this._idleSlotFlags=l=p.flags);continue}o[s.GROUP_CURSOR]=E-s.GROUP_NODES;try{n._runTaskEffectUntracked(p)}catch(m){t!==void 0?t.push(m):(d??=[]).push(m)}const T=e.state;if(!(T&s.TASK_ACTIVE))break;if(T&s.TASK_PAUSED){E+1<_&&(this._restoreDeliveryCausesBeforePending(e),e.state|=s.TASK_REQUESTED);break}}if(d!==void 0)throw d.length===1?d[0]:new AggregateError(d,"[Raph] Effect group delivery failed.")}_deferDelivery(e){const t=e.state;if((t&C)!==s.TASK_ACTIVE||e.consumerOwner.disposed){e.state=t|s.TASK_CANCEL;return}if((t&R)!==s.TASK_IN_DELIVERY&&P(),e.state=t|s.TASK_DEFER,++e.detailed().deferCount>b){e.state|=s.TASK_CANCEL;const i=[];throw this._acknowledgeDiscard(e,!0,i),i.length!==0?new AggregateError([new S.RaphPhaseProcessError(`[Raph] Phase task in "${e.phase}" exceeded 10000 deferred deliveries.`),...i],"[Raph] Phase task defer limit and recovery failed."):new S.RaphPhaseProcessError(`[Raph] Phase task in "${e.phase}" exceeded 10000 deferred deliveries.`)}}_cancelDelivery(e){const t=e.state;if(!(t&s.TASK_ACTIVE)||e.consumerOwner.disposed){e.state=t|s.TASK_CANCEL;return}(t&R)!==s.TASK_IN_DELIVERY&&P();const i=[];if(this._acknowledgeDiscard(e,!1,i),i.length!==0)throw i.length===1?i[0]:new AggregateError(i,"[Raph] Phase task cancellation failed.");let a=e.state|s.TASK_CANCEL;a&s.TASK_DISCARD_ACKNOWLEDGED&&(a=g(e)?a|s.TASK_REQUESTED:a&~s.TASK_REQUESTED),e.state=a;const n=e.detail;n!==void 0&&(n.deferCount=0)}_finishDelivery(e){const t=e.state;if(!(t&s.TASK_IN_DELIVERY))return;const i=t&s.TASK_RESOLUTION;if(e.state=t&~s.TASK_IN_DELIVERY,!(t&s.TASK_ACTIVE)||e.consumerOwner._disposed){v(e);return}if(t&s.TASK_PAUSED){i!==s.TASK_RUN&&!(i===s.TASK_CANCEL&&(t&s.TASK_DISCARD_ACKNOWLEDGED)!==0)&&(this._restoreDeliveryCausesBeforePending(e),e.state|=s.TASK_REQUESTED),v(e);return}if(i===s.TASK_DEFER){this._restoreDeliveryCausesBeforePending(e),e.state|=s.TASK_DEFERRED,this._deferred.add(e),v(e);return}if(((e.state&s.TASK_CAUSES_DELIVERED)!==0||e.detail!==void 0)&&v(e),(e.state&s.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 i=s.GROUP_NODES;i<e.length;i++){const a=e[i];a!==null&&a.firstDep!==null&&t._beginTaskEffectRun(a)&&t._rearmTaskEffect(a)}}_notifyTask(e,t){const i=this._resolveCause(t);if(i!==void 0){const a=i.kind==="structure"?i.source:t;this._appendCause(e,i,a)}}_appendCause(e,t,i){const a=e.state;if(!(a&s.TASK_ACTIVE))return;a&s.TASK_CAUSES_DELIVERED&&this._splitDeliveredCauses(e);const n=e.firstCause;if(n===void 0){e.firstCause=t,e.firstCauseKey=i;return}if(e.firstCauseKey===i){e.firstCause=N(n,t);return}const r=e.detailed().extraCauses??=new Map,o=r.get(i);r.set(i,o===void 0?t:N(o,t))}_splitDeliveredCauses(e){const t=e.detailed(),i=t.extraCauses;t.deliveryFirstCause=e.firstCause,t.deliveryFirstCauseKey=e.firstCauseKey,t.deliveryExtraCauses=i===void 0||i.size===0?void 0:i,t.extraCauses=void 0,e.firstCause=void 0,e.firstCauseKey=void 0,e.state&=~s.TASK_CAUSES_DELIVERED}_queue(e,t=!0){const i=e.state;if(!(i&s.TASK_ACTIVE)||e.consumerOwner._disposed||this._disposed)return;if(i&(s.TASK_PAUSED|s.TASK_IN_DELIVERY)){e.state=i|s.TASK_REQUESTED;return}if(i&s.TASK_PENDING){t&&this._schedule();return}if(i&s.TASK_DEFERRED)return;e.state=i&~s.TASK_DISCARD_ACKNOWLEDGED|s.TASK_PENDING,e.sequence=this._taskSequence++;const a=e.phaseState;a.first===void 0?a.first=e:a.queue.push(e),this._queuedCount++,t&&this._schedule()}_disposeTask(e){const t=e.state;if(!(t&s.TASK_ACTIVE))return;const i=t&-270;e.state=t&s.TASK_IN_DELIVERY?i|s.TASK_CANCEL:i,e.firstCause=void 0,e.firstCauseKey=void 0;const a=e.detail;a!==void 0&&(a.extraCauses?.clear(),a.extraCauses=void 0,k(a)),t&s.TASK_DEFERRED&&this._deferred.delete(e),t&s.TASK_PENDING&&this._unqueue(e),e.phaseState.bindings--,this._scheduled&&this._queuedCount===0&&this._deferred.size===0&&this._cancelScheduled(),this._idleWaiters.size!==0&&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 i=e.node;if(i!==void 0)e.node=void 0,this._reactivity._disposeTaskEffect(i);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,this._stopPhaseWatch(e,a))}e.state&s.TASK_ACTIVE&&this._disposeTask(e)}_stopPhaseWatch(e,t){t.stop(()=>this._releaseWatch(e,t))}_forgetStoppedSlots(e){let t=!1,i=!1;for(let a=s.GROUP_NODES;a<e.length;a++){const n=e[a];n!=null&&(n.evaluate===void 0?(e[a]=null,t=!0):i=!0)}return t&&i}_disposeGroup(e,t){const i=this._reactivity;let a;for(let n=t.length-1;n>=s.GROUP_NODES;n--){const r=t[n];if(r!=null)try{i._disposeTaskEffect(r)}catch(o){(a??=[]).push(o)}}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 i=[],a=t.source;if(t.source=void 0,t.record=void 0,a!==void 0)try{a()}catch(n){i.push(n)}try{this._disposeTask(e)}catch(n){i.push(n)}O.throwDisposalErrors(i,"[Raph] Phase watch disposal failed.")}_pauseTask(e){const t=e.state;if((t&C)!==s.TASK_ACTIVE)return;const i=t&s.TASK_RESOLUTION,a=(t|s.TASK_PAUSED)&-13;e.state=(t&(s.TASK_PENDING|s.TASK_DEFERRED))!==0||(t&s.TASK_IN_DELIVERY)!==0&&i!==s.TASK_RUN&&!(i===s.TASK_CANCEL&&(t&s.TASK_DISCARD_ACKNOWLEDGED)!==0)?a|s.TASK_REQUESTED:a,t&s.TASK_DEFERRED&&this._deferred.delete(e),t&s.TASK_PENDING&&this._unqueue(e),this._hasPending()||this._cancelScheduled(),this._settleIdleWaiters(void 0,!1)}_unqueue(e){const t=e.phaseState,i=t.queue;if(t.first===e){t.first=i.shift(),this._queuedCount--;return}const a=i.indexOf(e);a>=0&&(i.splice(a,1),this._queuedCount--)}_resumeTask(e){const t=e.state;(t&C)!==C||e.consumerOwner.disposed||((t&s.TASK_REQUESTED)!==0||g(e)?(e.state=t&-67,this._queue(e)):e.state=t&~s.TASK_PAUSED)}_restoreDeliveryCausesBeforePending(e){e.state&s.TASK_CAUSES_DELIVERED&&this._splitDeliveredCauses(e);const t=e.detail;if(t===void 0)return;const i=t.deliveryFirstCause;if(i===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,i,t.deliveryFirstCauseKey);const o=t.deliveryExtraCauses;if(o!==void 0)for(const[_,l]of o)this._appendCause(e,l,_);if(a!==void 0&&(this._appendCause(e,a,n),r!==void 0))for(const[_,l]of r)this._appendCause(e,l,_)}_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&=~s.TASK_DEFERRED,this._queue(t,!1)}_skipFrame(){return this._frameNumber++,this._frameStale=!0,this._frame}_materializeFrame(){const e=this._now();this._frameStale=!1,this._firstFrameAt=e,this._lastFrameAt=e,this._frame={now:e,delta:0,elapsed:0,frame:this._frameNumber}}_nextFrame(){this._frameStale=!1;const e=this._now();if(this._frameNumber===-1){this._firstFrameAt=e,this._lastFrameAt=e,this._frameNumber=0;const i={now:e,delta:0,elapsed:0,frame:0};return this._frame=this._publicFrames?Object.freeze(i):i}this._frameNumber++;const t={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=this._publicFrames?Object.freeze(t):t}_assertRetainedPhases(e){for(const t of this._phases){const i=t.state;if(i.bindings!==0&&!e.has(i.name))throw new Error(`[Raph] Cannot remove phase "${i.name}" while it is still bound.`)}for(const t of this._phases){const i=t.state;if(i.first!==void 0&&!e.has(i.name))throw new Error(`[Raph] Cannot remove phase "${i.name}" while it has pending work.`)}}_hasPending(){return this._queuedCount!==0||this._deferred.size!==0}_hasPendingWork(){return this._queuedCount!==0||this._deferred.size!==0||this._scheduled||this._idleWaiters.size!==0}_cancelAllQueued(e,t=[]){if(this._queuedCount===0)return;const i=[];for(const a of this._phases){const n=a.state;n.first!==void 0&&(i.push(n.first),n.first=void 0);const r=n.queue;for(const o of r)i.push(o);r.length=0}this._queuedCount=0;for(const a of i)a.state&=~s.TASK_PENDING,e&&this._acknowledgeDiscard(a,!0,t),this._clearPendingDelivery(a)}_cancelAllDeferred(e,t=[]){const i=[...this._deferred];this._deferred.clear();for(const a of i)a.state&=~s.TASK_DEFERRED,e&&this._acknowledgeDiscard(a,!0,t),this._clearPendingDelivery(a)}_acknowledgeDiscard(e,t,i){const a=e.state;if(a&s.TASK_DISCARD_ACKNOWLEDGED)return;const n=e.node,r=e.group;if(n===void 0&&r===void 0||!(a&s.TASK_ACTIVE)){e.state=a|s.TASK_DISCARD_ACKNOWLEDGED;return}try{if(n!==void 0?(a&s.TASK_EXECUTED)!==0&&this._reactivity._cancelTaskEffect(n):this._cancelGroup(e,r,t)){e.state|=s.TASK_DISCARD_ACKNOWLEDGED;return}if(!t){i.push(new S.RaphPhaseProcessError(`[Raph] Initial effect delivery in "${e.phase}" cannot be cancelled before dependency collection.`));return}e.dispose(),e.state|=s.TASK_DISCARD_ACKNOWLEDGED}catch(o){i.push(o)}}_cancelGroup(e,t,i){const a=this._reactivity;let n=!1;for(let _=s.GROUP_NODES;_<t.length;_++){const l=t[_];l===null||l.firstDep!==null||!a._beginTaskEffectRun(l)||(i?a._disposeTaskEffect(l):(a._requestTaskEffect(l,!1),n=!0))}if(n)return!1;const r=!i&&g(e);let o=!1;for(let _=s.GROUP_NODES;_<t.length;_++){const l=t[_];if(l===null)continue;if(l.firstDep===null){o=o||l.evaluate!==void 0;continue}const d=r&&a._beginTaskEffectRun(l);a._cancelTaskEffect(l)&&(o=!0,d&&a._rearmTaskEffect(l))}return o}_clearPendingDelivery(e){e.state&=~s.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 i=this._idleWaiters;if(i.size===0||!t&&(this._running||this._scheduled||this._hasPending()))return;const a=[...i];i.clear();for(const n of a)t?n.reject(e):n.resolve()}_assertAlive(){if(this._disposed)throw new S.RaphDisposedError("[Raph] Phase pipeline is disposed.")}}function U(f,e){return e.priority-f.priority||f.sequence-e.sequence}function g(f){return f.firstCause!==void 0&&!(f.state&s.TASK_CAUSES_DELIVERED)}function v(f){const e=f.state,t=f.detail;if(e&s.TASK_CAUSES_DELIVERED){f.state=e&~s.TASK_CAUSES_DELIVERED,f.firstCause=void 0,f.firstCauseKey=void 0,t!==void 0&&(t.extraCauses=void 0,t.deliveryCauses=void 0);return}t!==void 0&&t.deliveryFirstCause!==void 0&&k(t)}function k(f){f.deliveryFirstCause=void 0,f.deliveryFirstCauseKey=void 0,f.deliveryExtraCauses=void 0,f.deliveryCauses=void 0}function P(){throw new S.RaphPhaseProcessError("[Raph] Phase task delivery is already resolved.")}function N(f,e){const t=f.events===void 0?e.events:e.events===void 0?f.events:Object.freeze([...f.events,...e.events]),i=f.structure===void 0?e.structure:e.structure===void 0?f.structure:Object.freeze({node:e.structure.node,oldParent:f.structure.oldParent,oldIndex:f.structure.oldIndex,newParent:e.structure.newParent,newIndex:e.structure.newIndex});return Object.freeze({...e,previous:f.previous,...t===void 0?{}:{events:t},...i===void 0?{}:{structure:i}})}exports.RaphPhasePipeline=L;exports.RaphPhaseState=w;