@graphrefly/ts 0.0.0

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 (210) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapters/index.cjs +9015 -0
  3. package/dist/adapters/index.cjs.map +1 -0
  4. package/dist/adapters/index.d.cts +678 -0
  5. package/dist/adapters/index.d.ts +678 -0
  6. package/dist/adapters/index.js +2894 -0
  7. package/dist/adapters/index.js.map +1 -0
  8. package/dist/adapters/observe-storage.cjs +260 -0
  9. package/dist/adapters/observe-storage.cjs.map +1 -0
  10. package/dist/adapters/observe-storage.d.cts +77 -0
  11. package/dist/adapters/observe-storage.d.ts +77 -0
  12. package/dist/adapters/observe-storage.js +161 -0
  13. package/dist/adapters/observe-storage.js.map +1 -0
  14. package/dist/append-log-DisvEReb.d.cts +189 -0
  15. package/dist/append-log-DzKMmjxx.d.ts +189 -0
  16. package/dist/chunk-2ILL7HQI.js +1189 -0
  17. package/dist/chunk-2ILL7HQI.js.map +1 -0
  18. package/dist/chunk-4VLAQHZI.js +330 -0
  19. package/dist/chunk-4VLAQHZI.js.map +1 -0
  20. package/dist/chunk-6PHB5CJS.js +229 -0
  21. package/dist/chunk-6PHB5CJS.js.map +1 -0
  22. package/dist/chunk-COHO25CZ.js +2449 -0
  23. package/dist/chunk-COHO25CZ.js.map +1 -0
  24. package/dist/chunk-D6BG7U6A.js +161 -0
  25. package/dist/chunk-D6BG7U6A.js.map +1 -0
  26. package/dist/chunk-DJC4CHLQ.js +818 -0
  27. package/dist/chunk-DJC4CHLQ.js.map +1 -0
  28. package/dist/chunk-DK554R7P.js +67 -0
  29. package/dist/chunk-DK554R7P.js.map +1 -0
  30. package/dist/chunk-DKP56CSW.js +322 -0
  31. package/dist/chunk-DKP56CSW.js.map +1 -0
  32. package/dist/chunk-G4M3NHRJ.js +688 -0
  33. package/dist/chunk-G4M3NHRJ.js.map +1 -0
  34. package/dist/chunk-GAJW5I5P.js +1 -0
  35. package/dist/chunk-GAJW5I5P.js.map +1 -0
  36. package/dist/chunk-GDL26N2T.js +282 -0
  37. package/dist/chunk-GDL26N2T.js.map +1 -0
  38. package/dist/chunk-GTPCOEOZ.js +741 -0
  39. package/dist/chunk-GTPCOEOZ.js.map +1 -0
  40. package/dist/chunk-H2HTHFVN.js +1 -0
  41. package/dist/chunk-H2HTHFVN.js.map +1 -0
  42. package/dist/chunk-HDRL4VQQ.js +218 -0
  43. package/dist/chunk-HDRL4VQQ.js.map +1 -0
  44. package/dist/chunk-I3IHOHCJ.js +2267 -0
  45. package/dist/chunk-I3IHOHCJ.js.map +1 -0
  46. package/dist/chunk-JIMUDQN3.js +965 -0
  47. package/dist/chunk-JIMUDQN3.js.map +1 -0
  48. package/dist/chunk-JR4IKCR2.js +462 -0
  49. package/dist/chunk-JR4IKCR2.js.map +1 -0
  50. package/dist/chunk-K3FXTC3I.js +165 -0
  51. package/dist/chunk-K3FXTC3I.js.map +1 -0
  52. package/dist/chunk-OOEN33FB.js +65 -0
  53. package/dist/chunk-OOEN33FB.js.map +1 -0
  54. package/dist/chunk-PKVBHGBM.js +554 -0
  55. package/dist/chunk-PKVBHGBM.js.map +1 -0
  56. package/dist/chunk-RIIOUTGM.js +1857 -0
  57. package/dist/chunk-RIIOUTGM.js.map +1 -0
  58. package/dist/chunk-SCRFRCGR.js +33 -0
  59. package/dist/chunk-SCRFRCGR.js.map +1 -0
  60. package/dist/chunk-SWTLEQL6.js +53 -0
  61. package/dist/chunk-SWTLEQL6.js.map +1 -0
  62. package/dist/chunk-SZAETNNA.js +1 -0
  63. package/dist/chunk-SZAETNNA.js.map +1 -0
  64. package/dist/chunk-TEW47IVR.js +49 -0
  65. package/dist/chunk-TEW47IVR.js.map +1 -0
  66. package/dist/chunk-Y3ZLRGHC.js +1482 -0
  67. package/dist/chunk-Y3ZLRGHC.js.map +1 -0
  68. package/dist/chunk-Z2ANQ6JW.js +149 -0
  69. package/dist/chunk-Z2ANQ6JW.js.map +1 -0
  70. package/dist/codec-BB7p8fJc.d.cts +38 -0
  71. package/dist/codec-BB7p8fJc.d.ts +38 -0
  72. package/dist/composition/index.cjs +2505 -0
  73. package/dist/composition/index.cjs.map +1 -0
  74. package/dist/composition/index.d.cts +95 -0
  75. package/dist/composition/index.d.ts +95 -0
  76. package/dist/composition/index.js +19 -0
  77. package/dist/composition/index.js.map +1 -0
  78. package/dist/core/index.cjs +2475 -0
  79. package/dist/core/index.cjs.map +1 -0
  80. package/dist/core/index.d.cts +25 -0
  81. package/dist/core/index.d.ts +25 -0
  82. package/dist/core/index.js +74 -0
  83. package/dist/core/index.js.map +1 -0
  84. package/dist/cqrs/index.cjs +595 -0
  85. package/dist/cqrs/index.cjs.map +1 -0
  86. package/dist/cqrs/index.d.cts +200 -0
  87. package/dist/cqrs/index.d.ts +200 -0
  88. package/dist/cqrs/index.js +557 -0
  89. package/dist/cqrs/index.js.map +1 -0
  90. package/dist/data-structures/index.cjs +4277 -0
  91. package/dist/data-structures/index.cjs.map +1 -0
  92. package/dist/data-structures/index.d.cts +22 -0
  93. package/dist/data-structures/index.d.ts +22 -0
  94. package/dist/data-structures/index.js +31 -0
  95. package/dist/data-structures/index.js.map +1 -0
  96. package/dist/describe-BZb7AS2y.d.ts +57 -0
  97. package/dist/describe-Ciu8SUnN.d.cts +57 -0
  98. package/dist/graph/index.cjs +7832 -0
  99. package/dist/graph/index.cjs.map +1 -0
  100. package/dist/graph/index.d.cts +251 -0
  101. package/dist/graph/index.d.ts +251 -0
  102. package/dist/graph/index.js +131 -0
  103. package/dist/graph/index.js.map +1 -0
  104. package/dist/graph-DfdF9zy4.d.ts +666 -0
  105. package/dist/graph-s23RbbFO.d.cts +666 -0
  106. package/dist/index-CAEmLCYF.d.cts +166 -0
  107. package/dist/index-SnzZu3x7.d.ts +166 -0
  108. package/dist/index.cjs +15409 -0
  109. package/dist/index.cjs.map +1 -0
  110. package/dist/index.d.cts +23 -0
  111. package/dist/index.d.ts +23 -0
  112. package/dist/index.js +582 -0
  113. package/dist/index.js.map +1 -0
  114. package/dist/messages-BZqrGGm1.d.cts +55 -0
  115. package/dist/messages-BZqrGGm1.d.ts +55 -0
  116. package/dist/messaging/index.cjs +818 -0
  117. package/dist/messaging/index.cjs.map +1 -0
  118. package/dist/messaging/index.d.cts +235 -0
  119. package/dist/messaging/index.d.ts +235 -0
  120. package/dist/messaging/index.js +767 -0
  121. package/dist/messaging/index.js.map +1 -0
  122. package/dist/observe-event-log-0SVsx7JG.d.cts +88 -0
  123. package/dist/observe-event-log-Dnm76owp.d.ts +88 -0
  124. package/dist/operators/index.cjs +3774 -0
  125. package/dist/operators/index.cjs.map +1 -0
  126. package/dist/operators/index.d.cts +308 -0
  127. package/dist/operators/index.d.ts +308 -0
  128. package/dist/operators/index.js +112 -0
  129. package/dist/operators/index.js.map +1 -0
  130. package/dist/orchestration/index.cjs +3541 -0
  131. package/dist/orchestration/index.cjs.map +1 -0
  132. package/dist/orchestration/index.d.cts +302 -0
  133. package/dist/orchestration/index.d.ts +302 -0
  134. package/dist/orchestration/index.js +1004 -0
  135. package/dist/orchestration/index.js.map +1 -0
  136. package/dist/patterns/index.cjs +1045 -0
  137. package/dist/patterns/index.cjs.map +1 -0
  138. package/dist/patterns/index.d.cts +39 -0
  139. package/dist/patterns/index.d.ts +39 -0
  140. package/dist/patterns/index.js +33 -0
  141. package/dist/patterns/index.js.map +1 -0
  142. package/dist/reactive-collection-BxBqtIOE.d.cts +344 -0
  143. package/dist/reactive-collection-Cb1II1Fi.d.ts +344 -0
  144. package/dist/reactive-collection-storage-BNiEc-Gd.d.ts +217 -0
  145. package/dist/reactive-collection-storage-D-KmjE0J.d.cts +217 -0
  146. package/dist/reactive-map-BcB4KsQR.d.ts +256 -0
  147. package/dist/reactive-map-D-g3dv8I.d.cts +256 -0
  148. package/dist/read-through-B1CYPfq_.d.cts +82 -0
  149. package/dist/read-through-DwyJhGs1.d.ts +82 -0
  150. package/dist/render/index.cjs +250 -0
  151. package/dist/render/index.cjs.map +1 -0
  152. package/dist/render/index.d.cts +58 -0
  153. package/dist/render/index.d.ts +58 -0
  154. package/dist/render/index.js +20 -0
  155. package/dist/render/index.js.map +1 -0
  156. package/dist/resilience-Dig3Q7n0.d.cts +45 -0
  157. package/dist/resilience-Dig3Q7n0.d.ts +45 -0
  158. package/dist/semantic-memory-graph-BYoIlP35.d.cts +356 -0
  159. package/dist/semantic-memory-graph-CxyXLms3.d.ts +356 -0
  160. package/dist/solutions/index.cjs +3249 -0
  161. package/dist/solutions/index.cjs.map +1 -0
  162. package/dist/solutions/index.d.cts +520 -0
  163. package/dist/solutions/index.d.ts +520 -0
  164. package/dist/solutions/index.js +31 -0
  165. package/dist/solutions/index.js.map +1 -0
  166. package/dist/sources/browser.cjs +3095 -0
  167. package/dist/sources/browser.cjs.map +1 -0
  168. package/dist/sources/browser.d.cts +39 -0
  169. package/dist/sources/browser.d.ts +39 -0
  170. package/dist/sources/browser.js +137 -0
  171. package/dist/sources/browser.js.map +1 -0
  172. package/dist/sources/index.cjs +3021 -0
  173. package/dist/sources/index.cjs.map +1 -0
  174. package/dist/sources/index.d.cts +7 -0
  175. package/dist/sources/index.d.ts +7 -0
  176. package/dist/sources/index.js +63 -0
  177. package/dist/sources/index.js.map +1 -0
  178. package/dist/sources/node.cjs +675 -0
  179. package/dist/sources/node.cjs.map +1 -0
  180. package/dist/sources/node.d.cts +109 -0
  181. package/dist/sources/node.d.ts +109 -0
  182. package/dist/sources/node.js +639 -0
  183. package/dist/sources/node.js.map +1 -0
  184. package/dist/storage/browser.cjs +777 -0
  185. package/dist/storage/browser.cjs.map +1 -0
  186. package/dist/storage/browser.d.cts +40 -0
  187. package/dist/storage/browser.d.ts +40 -0
  188. package/dist/storage/browser.js +275 -0
  189. package/dist/storage/browser.js.map +1 -0
  190. package/dist/storage/index.cjs +1989 -0
  191. package/dist/storage/index.cjs.map +1 -0
  192. package/dist/storage/index.d.cts +92 -0
  193. package/dist/storage/index.d.ts +92 -0
  194. package/dist/storage/index.js +161 -0
  195. package/dist/storage/index.js.map +1 -0
  196. package/dist/storage/node.cjs +898 -0
  197. package/dist/storage/node.cjs.map +1 -0
  198. package/dist/storage/node.d.cts +66 -0
  199. package/dist/storage/node.d.ts +66 -0
  200. package/dist/storage/node.js +402 -0
  201. package/dist/storage/node.js.map +1 -0
  202. package/dist/testing/index.cjs +95 -0
  203. package/dist/testing/index.cjs.map +1 -0
  204. package/dist/testing/index.d.cts +20 -0
  205. package/dist/testing/index.d.ts +20 -0
  206. package/dist/testing/index.js +8 -0
  207. package/dist/testing/index.js.map +1 -0
  208. package/dist/types-bNMSWKqF.d.cts +732 -0
  209. package/dist/types-h12mNYbq.d.ts +732 -0
  210. package/package.json +250 -0
@@ -0,0 +1,2505 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/composition/index.ts
21
+ var composition_exports = {};
22
+ __export(composition_exports, {
23
+ pipe: () => pipe,
24
+ stratify: () => stratify,
25
+ stratifyBranch: () => stratifyBranch,
26
+ topologyDiff: () => topologyDiff
27
+ });
28
+ module.exports = __toCommonJS(composition_exports);
29
+
30
+ // src/protocol/messages.ts
31
+ var SENTINEL = void 0;
32
+ function isInvalidErrorPayload(v) {
33
+ return v === SENTINEL || typeof v === "boolean";
34
+ }
35
+ function errorPayload(reason, fallback = "error without a valid payload") {
36
+ return isInvalidErrorPayload(reason) ? new Error(fallback) : reason;
37
+ }
38
+ var TIER_START = 0;
39
+ var TIER_CONTROL = 1;
40
+ var TIER_NOTIFICATION = 2;
41
+ var TIER_VALUE = 3;
42
+ var TIER_SETTLE = 4;
43
+ var TIER_TERMINAL = 5;
44
+ var TIER_TEARDOWN = 6;
45
+ var TIER = {
46
+ START: TIER_START,
47
+ PAUSE: TIER_CONTROL,
48
+ RESUME: TIER_CONTROL,
49
+ DIRTY: TIER_NOTIFICATION,
50
+ DATA: TIER_VALUE,
51
+ RESOLVED: TIER_VALUE,
52
+ INVALIDATE: TIER_SETTLE,
53
+ COMPLETE: TIER_TERMINAL,
54
+ ERROR: TIER_TERMINAL,
55
+ TEARDOWN: TIER_TEARDOWN
56
+ };
57
+ function messageTier(t) {
58
+ return TIER[t];
59
+ }
60
+ function isDeferredTier(t) {
61
+ return TIER[t] >= TIER_VALUE;
62
+ }
63
+ function isValueTier(t) {
64
+ return TIER[t] === TIER_VALUE;
65
+ }
66
+ function isPauseBufferedTier(t) {
67
+ const tier = TIER[t];
68
+ return tier === TIER_VALUE || tier === TIER_SETTLE;
69
+ }
70
+ function isTerminal(t) {
71
+ return TIER[t] === TIER_TERMINAL;
72
+ }
73
+ function isUpAllowed(t) {
74
+ const tier = TIER[t];
75
+ return tier !== TIER_VALUE && tier !== TIER_TERMINAL;
76
+ }
77
+
78
+ // src/ctx/types.ts
79
+ var CTX_DEP_CACHE = /* @__PURE__ */ Symbol("graphrefly.ctx.depCache");
80
+ var CTX_NODE_BINDING = /* @__PURE__ */ Symbol("graphrefly.ctx.nodeBinding");
81
+ function isTerminalNone(t) {
82
+ return t === false || t === void 0;
83
+ }
84
+ function isTerminalComplete(t) {
85
+ return t === true;
86
+ }
87
+ function isTerminalError(t) {
88
+ return !isTerminalNone(t) && !isTerminalComplete(t);
89
+ }
90
+ function terminalErrorValue(t) {
91
+ return isTerminalError(t) ? t : void 0;
92
+ }
93
+ function depWaves(ctx, depIndex) {
94
+ return ctx.waveData[depIndex] ?? [];
95
+ }
96
+ function depBatch(ctx, depIndex) {
97
+ const waves = depWaves(ctx, depIndex);
98
+ if (waves.length === 0) return null;
99
+ const flattened = waves.flat().filter((v) => v !== SENTINEL);
100
+ return flattened.length === 0 ? [] : flattened;
101
+ }
102
+ function depLatest(ctx, depIndex) {
103
+ return ctx[CTX_DEP_CACHE]?.latest[depIndex];
104
+ }
105
+ function depTerminal(ctx, depIndex) {
106
+ const t = ctx.terminal[depIndex];
107
+ return t === void 0 ? false : t;
108
+ }
109
+
110
+ // src/batch/boundary.ts
111
+ var depth = 0;
112
+ var pendingCores = [];
113
+ var pendingHead = 0;
114
+ function enterWave() {
115
+ depth++;
116
+ }
117
+ function exitWave() {
118
+ depth--;
119
+ if (depth === 0 && pendingHead < pendingCores.length) drain();
120
+ }
121
+ function deferRewire(core, apply, options = {}) {
122
+ core.enqueueBoundaryTask({ apply, batchToken: options.batchToken, isReady: options.isReady });
123
+ pendingCores.push(core);
124
+ }
125
+ function scheduleBoundaryDrain(core) {
126
+ for (let i = 0; i < core.boundaryTaskCount(); i++) pendingCores.push(core);
127
+ if (depth === 0 && pendingHead < pendingCores.length) drain();
128
+ }
129
+ function drain() {
130
+ let escaped = null;
131
+ while (pendingHead < pendingCores.length) {
132
+ const core = pendingCores[pendingHead++];
133
+ const task = core.shiftBoundaryTask();
134
+ if (task === void 0) continue;
135
+ if (task.batchToken !== void 0) {
136
+ const committed = task.batchToken.committed === true;
137
+ if (!committed) continue;
138
+ }
139
+ if (task.isReady !== void 0 && !task.isReady()) {
140
+ core.unshiftBoundaryTask(task);
141
+ continue;
142
+ }
143
+ depth++;
144
+ try {
145
+ task.apply();
146
+ } catch (e) {
147
+ if (escaped === null) escaped = { e };
148
+ } finally {
149
+ depth--;
150
+ }
151
+ }
152
+ pendingCores.length = 0;
153
+ pendingHead = 0;
154
+ if (escaped !== null) throw escaped.e;
155
+ }
156
+
157
+ // src/batch/batch.ts
158
+ var active = null;
159
+ var boundaryOwner = null;
160
+ function currentBatch() {
161
+ return active !== null;
162
+ }
163
+ function currentBoundaryBatchToken() {
164
+ return active ?? boundaryOwner ?? void 0;
165
+ }
166
+ function deferToBatch(target, tier3Wave) {
167
+ if (active === null) return false;
168
+ if (!active.deferred.has(target)) active.order.push(target);
169
+ active.deferred.set(target, tier3Wave);
170
+ return true;
171
+ }
172
+ function deferAfterBatchForTarget(target, fn) {
173
+ if (active === null || !active.deferred.has(target)) return false;
174
+ const owner = active;
175
+ target.__deferBoundary(() => {
176
+ if (owner.committed) fn();
177
+ }, owner);
178
+ return true;
179
+ }
180
+
181
+ // src/dispatcher/index.ts
182
+ var PoolTable = class {
183
+ constructor(kind) {
184
+ this.kind = kind;
185
+ }
186
+ fns = [];
187
+ free = [];
188
+ register(fn) {
189
+ const reused = this.free.pop();
190
+ if (reused !== void 0) {
191
+ this.fns[reused] = fn;
192
+ return reused;
193
+ }
194
+ const id = this.fns.length;
195
+ this.fns.push(fn);
196
+ return id;
197
+ }
198
+ unregister(handleId) {
199
+ if (this.fns[handleId] === void 0) return;
200
+ this.fns[handleId] = void 0;
201
+ this.free.push(handleId);
202
+ }
203
+ invoke(handleId, ctx) {
204
+ this.fns[handleId](ctx);
205
+ }
206
+ };
207
+ var statKey = (h) => `${h.poolId}:${h.handleId}`;
208
+ var Dispatcher = class {
209
+ pools = [];
210
+ syncPoolId;
211
+ asyncPoolId;
212
+ // opt-in profile recorder (default OFF → zero overhead, F-PERF).
213
+ _recording = false;
214
+ _stats = /* @__PURE__ */ new Map();
215
+ _totalInvokes = 0;
216
+ constructor() {
217
+ this.syncPoolId = this.addPool(new PoolTable("sync"));
218
+ this.asyncPoolId = this.addPool(new PoolTable("async"));
219
+ }
220
+ /** Turn the profile recorder on/off (D39). Off = zero overhead on invoke. */
221
+ setRecording(on) {
222
+ this._recording = on;
223
+ }
224
+ /** Reset accumulated profiling counters. */
225
+ clearStats() {
226
+ this._stats.clear();
227
+ this._totalInvokes = 0;
228
+ }
229
+ /** Read a handle's accumulated counters (undefined if it never ran while recording). */
230
+ statFor(handle) {
231
+ return this._stats.get(statKey(handle));
232
+ }
233
+ /** Total fn invocations recorded across the dispatcher. */
234
+ get totalInvokes() {
235
+ return this._totalInvokes;
236
+ }
237
+ addPool(pool) {
238
+ const id = this.pools.length;
239
+ this.pools.push(pool);
240
+ return id;
241
+ }
242
+ /** Register a fn in a pool, returning its Handle. Default pool = sync (R-sync-core). */
243
+ register(fn, pool = "sync") {
244
+ const poolId = pool === "sync" ? this.syncPoolId : pool === "async" ? this.asyncPoolId : pool;
245
+ const handleId = this.pools[poolId].register(fn);
246
+ return { poolId, handleId };
247
+ }
248
+ /**
249
+ * Release a handle (B15): frees the pool slot (closure GC'd, id reusable) and drops any
250
+ * accumulated profile stat so a reused id never inherits the previous tenant's counters.
251
+ * Called on rewire fn-swap (node._rewire) — the old handle is dropped before the node
252
+ * adopts the new one. Idempotent. NOT called on deactivate (a node's handle survives
253
+ * activate↔deactivate and is reused on reactivation; only a rewire swaps it).
254
+ */
255
+ unregister(handle) {
256
+ this.pools[handle.poolId].unregister(handle.handleId);
257
+ this._stats.delete(statKey(handle));
258
+ }
259
+ /** Uniform sync-void invoke (R-sync-core / R-dispatch-all). */
260
+ invoke(handle, ctx) {
261
+ if (!this._recording) {
262
+ this.pools[handle.poolId].invoke(handle.handleId, ctx);
263
+ return;
264
+ }
265
+ this._totalInvokes++;
266
+ const t0 = performance.now();
267
+ try {
268
+ this.pools[handle.poolId].invoke(handle.handleId, ctx);
269
+ } finally {
270
+ const dur = (performance.now() - t0) * 1e6;
271
+ const key = statKey(handle);
272
+ const s = this._stats.get(key) ?? {
273
+ invokes: 0,
274
+ totalDurationNs: 0,
275
+ lastDurationNs: 0
276
+ };
277
+ s.invokes++;
278
+ s.lastDurationNs = dur;
279
+ s.totalDurationNs += dur;
280
+ this._stats.set(key, s);
281
+ }
282
+ }
283
+ poolKind(poolId) {
284
+ return this.pools[poolId].kind;
285
+ }
286
+ };
287
+ var defaultDispatcher = new Dispatcher();
288
+
289
+ // src/graph/environment.ts
290
+ var EnvironmentDrivers = class _EnvironmentDrivers {
291
+ process;
292
+ http;
293
+ sse;
294
+ websocket;
295
+ webhook;
296
+ constructor(init = {}) {
297
+ this.process = init.process;
298
+ this.http = init.http;
299
+ this.sse = init.sse;
300
+ this.websocket = init.websocket;
301
+ this.webhook = init.webhook;
302
+ Object.freeze(this);
303
+ }
304
+ static empty() {
305
+ return EMPTY_ENVIRONMENT;
306
+ }
307
+ withProcess(driver) {
308
+ return new _EnvironmentDrivers({ ...this, process: driver });
309
+ }
310
+ withHttp(driver) {
311
+ return new _EnvironmentDrivers({ ...this, http: driver });
312
+ }
313
+ withSse(driver) {
314
+ return new _EnvironmentDrivers({ ...this, sse: driver });
315
+ }
316
+ withWebSocket(driver) {
317
+ return new _EnvironmentDrivers({ ...this, websocket: driver });
318
+ }
319
+ withWebhook(driver) {
320
+ return new _EnvironmentDrivers({ ...this, webhook: driver });
321
+ }
322
+ processDriver() {
323
+ return this.process;
324
+ }
325
+ httpDriver() {
326
+ return this.http;
327
+ }
328
+ sseDriver() {
329
+ return this.sse;
330
+ }
331
+ webSocketDriver() {
332
+ return this.websocket;
333
+ }
334
+ webhookDriver() {
335
+ return this.webhook;
336
+ }
337
+ };
338
+ var EMPTY_ENVIRONMENT = new EnvironmentDrivers();
339
+
340
+ // src/node/core.ts
341
+ var NodeCore = class {
342
+ nextId = 0;
343
+ slots = [];
344
+ values = [];
345
+ waves = [];
346
+ controls = [];
347
+ lifecycles = [];
348
+ depStates = [];
349
+ privateStates = [];
350
+ hooks = [];
351
+ syncCtxs = [];
352
+ versionStates = [];
353
+ boundary = { queue: [], head: 0 };
354
+ createSlot(slot, state) {
355
+ const id = this.nextId++;
356
+ const full = { ...slot, id };
357
+ this.slots[id] = full;
358
+ this.depStates[id] = state.dep;
359
+ this.lifecycles[id] = state.lifecycle;
360
+ this.values[id] = state.value;
361
+ this.waves[id] = state.wave;
362
+ this.controls[id] = state.control;
363
+ this.privateStates[id] = state.privateState;
364
+ this.hooks[id] = state.hooks;
365
+ this.syncCtxs[id] = state.syncCtx;
366
+ this.versionStates[id] = state.version;
367
+ return { id, slot: full };
368
+ }
369
+ get(id) {
370
+ const slot = this.slots[id];
371
+ if (slot === void 0) throw new Error("NodeCore: unknown node slot");
372
+ return slot;
373
+ }
374
+ getValue(id) {
375
+ const value = this.values[id];
376
+ if (value === void 0) throw new Error("NodeCore: unknown node value state");
377
+ return value;
378
+ }
379
+ getWave(id) {
380
+ const wave = this.waves[id];
381
+ if (wave === void 0) throw new Error("NodeCore: unknown node wave state");
382
+ return wave;
383
+ }
384
+ getControl(id) {
385
+ const control = this.controls[id];
386
+ if (control === void 0) throw new Error("NodeCore: unknown node control state");
387
+ return control;
388
+ }
389
+ getLifecycle(id) {
390
+ const lifecycle = this.lifecycles[id];
391
+ if (lifecycle === void 0) throw new Error("NodeCore: unknown node lifecycle state");
392
+ return lifecycle;
393
+ }
394
+ getDep(id) {
395
+ const dep = this.depStates[id];
396
+ if (dep === void 0) throw new Error("NodeCore: unknown node dep state");
397
+ return dep;
398
+ }
399
+ getPrivateState(id) {
400
+ const state = this.privateStates[id];
401
+ if (state === void 0) throw new Error("NodeCore: unknown node private state");
402
+ return state;
403
+ }
404
+ getHooks(id) {
405
+ const hooks = this.hooks[id];
406
+ if (hooks === void 0) throw new Error("NodeCore: unknown node cleanup hooks");
407
+ return hooks;
408
+ }
409
+ getSyncCtx(id) {
410
+ const state = this.syncCtxs[id];
411
+ if (state === void 0) throw new Error("NodeCore: unknown node ctx state");
412
+ return state;
413
+ }
414
+ getVersion(id) {
415
+ const state = this.versionStates[id];
416
+ if (state === void 0) throw new Error("NodeCore: unknown node version state");
417
+ return state;
418
+ }
419
+ /** @internal D122: release graph-owned ephemeral node runtime state from core retention. */
420
+ releaseSlot(id) {
421
+ this.slots[id] = void 0;
422
+ this.depStates[id] = void 0;
423
+ this.lifecycles[id] = void 0;
424
+ this.values[id] = void 0;
425
+ this.waves[id] = void 0;
426
+ this.controls[id] = void 0;
427
+ this.privateStates[id] = void 0;
428
+ this.hooks[id] = void 0;
429
+ this.syncCtxs[id] = void 0;
430
+ this.versionStates[id] = void 0;
431
+ }
432
+ /** @internal B49: graph-local deferred-boundary queue (rewireNext/upNext/batch-after-commit). */
433
+ enqueueBoundaryTask(task) {
434
+ this.boundary.queue.push(task);
435
+ }
436
+ /** @internal */
437
+ hasBoundaryTasks() {
438
+ return this.boundary.head < this.boundary.queue.length;
439
+ }
440
+ /** @internal */
441
+ boundaryTaskCount() {
442
+ return this.boundary.queue.length - this.boundary.head;
443
+ }
444
+ /** @internal */
445
+ shiftBoundaryTask() {
446
+ if (!this.hasBoundaryTasks()) {
447
+ this.boundary.queue = [];
448
+ this.boundary.head = 0;
449
+ return void 0;
450
+ }
451
+ const task = this.boundary.queue[this.boundary.head++];
452
+ if (!this.hasBoundaryTasks()) {
453
+ this.boundary.queue = [];
454
+ this.boundary.head = 0;
455
+ }
456
+ return task;
457
+ }
458
+ /** @internal Put a not-yet-ready task back at this core's FIFO head. */
459
+ unshiftBoundaryTask(task) {
460
+ const remaining = this.boundary.queue.slice(this.boundary.head);
461
+ this.boundary.queue = [task, ...remaining];
462
+ this.boundary.head = 0;
463
+ }
464
+ /** @internal D110: discard all pending tasks caused by an uncommitted batch. */
465
+ dropBoundaryTasksForBatch(batchToken) {
466
+ const remaining = this.boundary.queue.slice(this.boundary.head).filter((task) => task.batchToken !== batchToken);
467
+ this.boundary.queue = remaining;
468
+ this.boundary.head = 0;
469
+ }
470
+ };
471
+ function makeDepBookkeeping(depCount) {
472
+ return {
473
+ batch: new Array(depCount).fill(null),
474
+ waveData: Array.from({ length: depCount }, () => []),
475
+ waveTokens: new Array(depCount).fill(void 0),
476
+ prev: new Array(depCount).fill(SENTINEL),
477
+ hasData: new Array(depCount).fill(false),
478
+ dirty: new Array(depCount).fill(false),
479
+ tier: new Array(depCount).fill(0),
480
+ terminal: new Array(depCount).fill(void 0),
481
+ terminalInput: new Array(depCount).fill(void 0),
482
+ unsubs: [],
483
+ idxBoxes: []
484
+ };
485
+ }
486
+
487
+ // src/json/codec.ts
488
+ var JS_MIN_NORMAL_NUMBER = 2 ** -1022;
489
+ function assertStableJsonNumber(value, path) {
490
+ if (!Number.isFinite(value)) {
491
+ throw new TypeError(`stableJsonString: non-finite number at ${path}`);
492
+ }
493
+ }
494
+ function assertStrictJsonNumber(value, path) {
495
+ assertStableJsonNumber(value, path);
496
+ if (Object.is(value, -0)) {
497
+ throw new TypeError(`stableJsonString: non-canonical number at ${path}`);
498
+ }
499
+ const abs = Math.abs(value);
500
+ if (abs > 0 && abs < JS_MIN_NORMAL_NUMBER) {
501
+ throw new TypeError(`stableJsonString: subnormal number at ${path}`);
502
+ }
503
+ if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
504
+ throw new TypeError(`stableJsonString: integer outside safe range at ${path}`);
505
+ }
506
+ }
507
+ function sortedJsonValue(value, seen = /* @__PURE__ */ new Set(), path = "$", strictNumbers = false) {
508
+ if (value === null) return null;
509
+ if (typeof value === "string" || typeof value === "boolean") return value;
510
+ if (typeof value === "number") {
511
+ if (strictNumbers) assertStrictJsonNumber(value, path);
512
+ else assertStableJsonNumber(value, path);
513
+ return value;
514
+ }
515
+ if (typeof value !== "object") {
516
+ throw new TypeError(`stableJsonString: value at ${path} is not JSON-encodable`);
517
+ }
518
+ if (seen.has(value)) throw new TypeError(`stableJsonString: circular reference at ${path}`);
519
+ const proto = Object.getPrototypeOf(value);
520
+ if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
521
+ throw new TypeError(`stableJsonString: non-plain object at ${path}`);
522
+ }
523
+ seen.add(value);
524
+ try {
525
+ if (Array.isArray(value)) {
526
+ if (Object.getOwnPropertySymbols(value).length > 0) {
527
+ throw new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);
528
+ }
529
+ for (const key of Object.getOwnPropertyNames(value)) {
530
+ const isIndex = /^(0|[1-9]\d*)$/.test(key) && Number.isSafeInteger(Number(key)) && Number(key) < value.length;
531
+ if (key !== "length" && !isIndex) {
532
+ throw new TypeError(`stableJsonString: non-index array property at ${path}.${key}`);
533
+ }
534
+ }
535
+ const out2 = [];
536
+ for (let i = 0; i < value.length; i += 1) {
537
+ if (!(i in value)) {
538
+ throw new TypeError(`stableJsonString: sparse array hole at ${path}[${i}]`);
539
+ }
540
+ out2.push(sortedJsonValue(value[i], seen, `${path}[${i}]`, strictNumbers));
541
+ }
542
+ return out2;
543
+ }
544
+ if (Object.getOwnPropertySymbols(value).length > 0) {
545
+ throw new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);
546
+ }
547
+ const out = /* @__PURE__ */ Object.create(null);
548
+ for (const key of Object.keys(value).sort()) {
549
+ out[key] = sortedJsonValue(
550
+ value[key],
551
+ seen,
552
+ `${path}.${key}`,
553
+ strictNumbers
554
+ );
555
+ }
556
+ return out;
557
+ } finally {
558
+ seen.delete(value);
559
+ }
560
+ }
561
+ function stableJsonString(value) {
562
+ return JSON.stringify(sortedJsonValue(value));
563
+ }
564
+ function strictStableJsonString(value) {
565
+ return JSON.stringify(sortedJsonValue(value, /* @__PURE__ */ new Set(), "$", true));
566
+ }
567
+ function jsonCodecFor() {
568
+ const encoder = new TextEncoder();
569
+ const decoder = new TextDecoder();
570
+ return {
571
+ encode(value) {
572
+ return encoder.encode(stableJsonString(value));
573
+ },
574
+ decode(bytes) {
575
+ return JSON.parse(decoder.decode(bytes));
576
+ }
577
+ };
578
+ }
579
+ var jsonCodec = jsonCodecFor();
580
+ function bytesEqual(a, b) {
581
+ if (a.byteLength !== b.byteLength) return false;
582
+ for (let i = 0; i < a.byteLength; i += 1) {
583
+ if (a[i] !== b[i]) return false;
584
+ }
585
+ return true;
586
+ }
587
+ function hasUnpairedSurrogate(value) {
588
+ for (let i = 0; i < value.length; i += 1) {
589
+ const code = value.charCodeAt(i);
590
+ if (code >= 55296 && code <= 56319) {
591
+ const next = value.charCodeAt(i + 1);
592
+ if (next >= 56320 && next <= 57343) {
593
+ i += 1;
594
+ continue;
595
+ }
596
+ return true;
597
+ }
598
+ if (code >= 56320 && code <= 57343) return true;
599
+ }
600
+ return false;
601
+ }
602
+ function assertNoUnpairedSurrogates(value, seen = /* @__PURE__ */ new Set(), path = "$") {
603
+ if (typeof value === "string") {
604
+ if (hasUnpairedSurrogate(value)) {
605
+ throw new TypeError(`strictJsonCodec: unpaired surrogate at ${path}`);
606
+ }
607
+ return;
608
+ }
609
+ if (value === null || typeof value !== "object") return;
610
+ if (seen.has(value)) return;
611
+ seen.add(value);
612
+ try {
613
+ if (Array.isArray(value)) {
614
+ for (let i = 0; i < value.length; i += 1) {
615
+ assertNoUnpairedSurrogates(value[i], seen, `${path}[${i}]`);
616
+ }
617
+ return;
618
+ }
619
+ for (const key of Object.keys(value)) {
620
+ if (hasUnpairedSurrogate(key)) {
621
+ throw new TypeError(`strictJsonCodec: unpaired surrogate at ${path}.${key}`);
622
+ }
623
+ assertNoUnpairedSurrogates(value[key], seen, `${path}.${key}`);
624
+ }
625
+ } finally {
626
+ seen.delete(value);
627
+ }
628
+ }
629
+ function assertNoDuplicateJsonObjectKeys(text) {
630
+ let index = 0;
631
+ function fail(message) {
632
+ throw new TypeError(`strictJsonCodec: ${message}`);
633
+ }
634
+ function skipWhitespace() {
635
+ while (/\s/.test(text[index] ?? "")) index += 1;
636
+ }
637
+ function readJsonString() {
638
+ const start = index;
639
+ index += 1;
640
+ while (index < text.length) {
641
+ const ch = text[index];
642
+ if (ch === '"') {
643
+ index += 1;
644
+ try {
645
+ return JSON.parse(text.slice(start, index));
646
+ } catch {
647
+ fail("malformed JSON string");
648
+ }
649
+ }
650
+ if (ch === "\\") {
651
+ index += 2;
652
+ continue;
653
+ }
654
+ index += 1;
655
+ }
656
+ fail("unterminated JSON string");
657
+ }
658
+ function consumeLiteral(literal) {
659
+ if (text.slice(index, index + literal.length) !== literal) {
660
+ fail(`malformed JSON near byte ${index}`);
661
+ }
662
+ index += literal.length;
663
+ }
664
+ function consumeNumber() {
665
+ const match = /^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/.exec(text.slice(index));
666
+ if (!match) fail(`malformed JSON number near byte ${index}`);
667
+ index += match[0].length;
668
+ }
669
+ function parseValue(path) {
670
+ skipWhitespace();
671
+ const ch = text[index];
672
+ if (ch === "{") {
673
+ parseObject(path);
674
+ return;
675
+ }
676
+ if (ch === "[") {
677
+ parseArray(path);
678
+ return;
679
+ }
680
+ if (ch === '"') {
681
+ readJsonString();
682
+ return;
683
+ }
684
+ if (ch === "t") {
685
+ consumeLiteral("true");
686
+ return;
687
+ }
688
+ if (ch === "f") {
689
+ consumeLiteral("false");
690
+ return;
691
+ }
692
+ if (ch === "n") {
693
+ consumeLiteral("null");
694
+ return;
695
+ }
696
+ if (ch === "-" || ch !== void 0 && ch >= "0" && ch <= "9") {
697
+ consumeNumber();
698
+ return;
699
+ }
700
+ fail(`malformed JSON near byte ${index}`);
701
+ }
702
+ function parseObject(path) {
703
+ const keys = /* @__PURE__ */ new Set();
704
+ index += 1;
705
+ skipWhitespace();
706
+ if (text[index] === "}") {
707
+ index += 1;
708
+ return;
709
+ }
710
+ while (index < text.length) {
711
+ skipWhitespace();
712
+ if (text[index] !== '"') fail(`expected object key near byte ${index}`);
713
+ const key = readJsonString();
714
+ if (keys.has(key)) {
715
+ throw new TypeError(
716
+ `strictJsonCodec: duplicate object key ${JSON.stringify(key)} at ${path}`
717
+ );
718
+ }
719
+ keys.add(key);
720
+ skipWhitespace();
721
+ if (text[index] !== ":") fail(`expected ':' after object key near byte ${index}`);
722
+ index += 1;
723
+ parseValue(`${path}.${key}`);
724
+ skipWhitespace();
725
+ if (text[index] === ",") {
726
+ index += 1;
727
+ continue;
728
+ }
729
+ if (text[index] === "}") {
730
+ index += 1;
731
+ return;
732
+ }
733
+ fail(`expected ',' or '}' near byte ${index}`);
734
+ }
735
+ fail("unterminated JSON object");
736
+ }
737
+ function parseArray(path) {
738
+ index += 1;
739
+ skipWhitespace();
740
+ if (text[index] === "]") {
741
+ index += 1;
742
+ return;
743
+ }
744
+ let item = 0;
745
+ while (index < text.length) {
746
+ parseValue(`${path}[${item}]`);
747
+ item += 1;
748
+ skipWhitespace();
749
+ if (text[index] === ",") {
750
+ index += 1;
751
+ continue;
752
+ }
753
+ if (text[index] === "]") {
754
+ index += 1;
755
+ return;
756
+ }
757
+ fail(`expected ',' or ']' near byte ${index}`);
758
+ }
759
+ fail("unterminated JSON array");
760
+ }
761
+ parseValue("$");
762
+ skipWhitespace();
763
+ if (index !== text.length) fail(`trailing JSON token near byte ${index}`);
764
+ }
765
+ function strictJsonCodecFor() {
766
+ const encoder = new TextEncoder();
767
+ const decoder = new TextDecoder("utf-8", { fatal: true });
768
+ return {
769
+ encode(value) {
770
+ assertNoUnpairedSurrogates(value);
771
+ return encoder.encode(strictStableJsonString(value));
772
+ },
773
+ decode(bytes) {
774
+ const text = decoder.decode(bytes);
775
+ assertNoDuplicateJsonObjectKeys(text);
776
+ const decoded = JSON.parse(text);
777
+ assertNoUnpairedSurrogates(decoded);
778
+ const canonical = encoder.encode(strictStableJsonString(decoded));
779
+ if (!bytesEqual(bytes, canonical)) {
780
+ throw new TypeError("strictJsonCodec: bytes are not canonical stable JSON");
781
+ }
782
+ return decoded;
783
+ }
784
+ };
785
+ }
786
+ var strictJsonCodec = strictJsonCodecFor();
787
+ function strictCanonicalJsonBytes(value) {
788
+ return strictJsonCodec.encode(value);
789
+ }
790
+
791
+ // src/node/versioning.ts
792
+ var ABSENT_V1_SEED = Object.freeze({
793
+ "@graphrefly/node-version": "v1-absent"
794
+ });
795
+ function fnv1a64(input) {
796
+ let hash = 0xcbf29ce484222325n;
797
+ const prime = 0x100000001b3n;
798
+ for (const byte of input) {
799
+ hash ^= BigInt(byte);
800
+ hash = BigInt.asUintN(64, hash * prime);
801
+ }
802
+ return hash.toString(16).padStart(16, "0");
803
+ }
804
+ function defaultNodeVersionHash(bytes) {
805
+ return `fnv1a64:${fnv1a64(bytes)}`;
806
+ }
807
+ function computeV1Cid(policy, value) {
808
+ return policy.hash(strictCanonicalJsonBytes(value));
809
+ }
810
+ function assertNodeVersionDataCompatible(policy, value) {
811
+ if (!policy.enabled || policy.level === 0) return;
812
+ strictCanonicalJsonBytes(value);
813
+ }
814
+ function snapshotNodeVersionData(policy, value) {
815
+ if (!policy.enabled || policy.level === 0) return value;
816
+ const bytes = strictCanonicalJsonBytes(value);
817
+ return strictJsonCodec.decode(bytes);
818
+ }
819
+ function resolveNodeVersioningPolicy(policy) {
820
+ if (policy === false) return { enabled: false };
821
+ if (policy === void 0 || policy === 0) return { enabled: true, level: 0 };
822
+ if (policy === 1) return { enabled: true, level: 1, hash: defaultNodeVersionHash };
823
+ if (typeof policy === "object" && policy !== null) {
824
+ if (policy.level === 0) return { enabled: true, level: 0 };
825
+ if (policy.level === 1) {
826
+ return { enabled: true, level: 1, hash: policy.hash ?? defaultNodeVersionHash };
827
+ }
828
+ }
829
+ throw new Error("node: versioning level must be 0 or 1; V2/V3 are not locked yet (D109)");
830
+ }
831
+ function createNodeVersion(policy, initialValue = ABSENT_V1_SEED) {
832
+ if (!policy.enabled) return void 0;
833
+ if (policy.level === 0) return Object.freeze({ level: 0, counter: 0 });
834
+ return Object.freeze({
835
+ level: 1,
836
+ counter: 0,
837
+ cid: computeV1Cid(policy, initialValue),
838
+ prev: null
839
+ });
840
+ }
841
+ function advanceNodeVersion(current, policy, value) {
842
+ if (!policy.enabled) return void 0;
843
+ if (current === void 0) return createNodeVersion(policy, value);
844
+ if (policy.level === 0) {
845
+ return Object.freeze({ level: 0, counter: current.counter + 1 });
846
+ }
847
+ const previous = current.level === 1 ? current.cid : null;
848
+ return Object.freeze({
849
+ level: 1,
850
+ counter: current.counter + 1,
851
+ cid: computeV1Cid(policy, value),
852
+ prev: previous
853
+ });
854
+ }
855
+ function cloneNodeVersion(version) {
856
+ if (version === void 0) return void 0;
857
+ if (version.level === 0) return Object.freeze({ level: 0, counter: version.counter });
858
+ return Object.freeze({
859
+ level: 1,
860
+ counter: version.counter,
861
+ cid: version.cid,
862
+ prev: version.prev
863
+ });
864
+ }
865
+ function restoredV1Cid(policy, hasData, cache) {
866
+ return computeV1Cid(policy, hasData ? cache : ABSENT_V1_SEED);
867
+ }
868
+
869
+ // src/node/node.ts
870
+ var constructingCore;
871
+ var constructingEnvironment;
872
+ var ownerTokens = /* @__PURE__ */ new WeakMap();
873
+ var topologyDepsChangedObservers = /* @__PURE__ */ new WeakMap();
874
+ var checkpointReaders = /* @__PURE__ */ new WeakMap();
875
+ var restoreWriters = /* @__PURE__ */ new WeakMap();
876
+ var runtimeReleasers = /* @__PURE__ */ new WeakMap();
877
+ var runtimeQuiescenceReaders = /* @__PURE__ */ new WeakMap();
878
+ var subscriberCountReaders = /* @__PURE__ */ new WeakMap();
879
+ var activationReaders = /* @__PURE__ */ new WeakMap();
880
+ var releasedNodes = /* @__PURE__ */ new WeakSet();
881
+ function withNodeCore(core, create) {
882
+ const prev = constructingCore;
883
+ constructingCore = core;
884
+ try {
885
+ return create();
886
+ } finally {
887
+ constructingCore = prev;
888
+ }
889
+ }
890
+ function withEnvironmentDrivers(environment, create) {
891
+ const prev = constructingEnvironment;
892
+ constructingEnvironment = environment;
893
+ try {
894
+ return create();
895
+ } finally {
896
+ constructingEnvironment = prev;
897
+ }
898
+ }
899
+ function getNodeOwner(n) {
900
+ return ownerTokens.get(n);
901
+ }
902
+ function notifyTopologyDepsChanged(node, prevDeps, deps) {
903
+ topologyDepsChangedObservers.get(node)?.(node, prevDeps, deps);
904
+ }
905
+ function terminalView(t) {
906
+ return t === void 0 ? false : t;
907
+ }
908
+ function validateDownPayloads(msgs) {
909
+ for (const m of msgs) {
910
+ if (m[0] === "DATA" && m[1] === void 0) {
911
+ throw new Error("down: DATA requires a non-SENTINEL payload (R-data-payload)");
912
+ }
913
+ if (m[0] === "ERROR" && isInvalidErrorPayload(m[1])) {
914
+ throw new Error("down: ERROR requires a non-SENTINEL, non-boolean payload (R-data-payload)");
915
+ }
916
+ }
917
+ }
918
+ var Node = class {
919
+ _core;
920
+ _id;
921
+ _slot;
922
+ _dep;
923
+ _value;
924
+ _wave;
925
+ _control;
926
+ _lifecycle;
927
+ _privateState;
928
+ _hooks;
929
+ _syncCtxState;
930
+ _version;
931
+ _restoredActivationPending = false;
932
+ _released = false;
933
+ get _syncCtx() {
934
+ return this._syncCtxState.value;
935
+ }
936
+ set _syncCtx(ctx) {
937
+ this._syncCtxState.value = ctx;
938
+ }
939
+ constructor(deps, handleOrFn, opts = {}) {
940
+ const core = constructingCore;
941
+ constructingCore = void 0;
942
+ const dispatcher = opts.dispatcher ?? defaultDispatcher;
943
+ const environment = constructingEnvironment ?? EnvironmentDrivers.empty();
944
+ constructingEnvironment = void 0;
945
+ const pool = opts.pool ?? "sync";
946
+ const pausable = opts.pausable ?? true;
947
+ const pullLock = opts.pullId;
948
+ const pull = opts.pullId !== void 0;
949
+ if (pull && pausable === false)
950
+ throw new Error(
951
+ "node: pullId is incompatible with pausable:false \u2014 a pull node is demanded via RESUME, which pausable:false ignores (R-pull / R-pause-modes / D55,D59)"
952
+ );
953
+ let handle;
954
+ if (handleOrFn === null) handle = null;
955
+ else if (typeof handleOrFn === "function") handle = dispatcher.register(handleOrFn, pool);
956
+ else handle = handleOrFn;
957
+ const n = deps.length;
958
+ const dep = makeDepBookkeeping(n);
959
+ const versioning = resolveNodeVersioningPolicy(opts.versioning);
960
+ const value = {
961
+ cache: SENTINEL,
962
+ hasData: false,
963
+ status: "sentinel",
964
+ terminal: void 0,
965
+ hasTorndown: false,
966
+ replayRing: []
967
+ };
968
+ if (opts.initial !== void 0) {
969
+ value.cache = opts.initial;
970
+ value.hasData = true;
971
+ value.status = "settled";
972
+ }
973
+ const pauseLockset = /* @__PURE__ */ new Set();
974
+ if (pull) pauseLockset.add(pullLock);
975
+ this._core = core ?? new NodeCore();
976
+ const created = this._core.createSlot(
977
+ {
978
+ deps,
979
+ handle,
980
+ pool,
981
+ dispatcher,
982
+ environment,
983
+ partial: opts.partial ?? false,
984
+ terminalAsRealInput: opts.terminalAsRealInput ?? false,
985
+ completeWhenDepsComplete: opts.completeWhenDepsComplete ?? true,
986
+ errorWhenDepsError: opts.errorWhenDepsError ?? true,
987
+ resubscribable: opts.resubscribable ?? false,
988
+ resetOnTeardown: opts.resetOnTeardown ?? false,
989
+ pausable,
990
+ pull,
991
+ pullLock,
992
+ replayN: opts.replayBuffer ?? 0,
993
+ dynamic: opts.dynamic ?? false,
994
+ name: opts.name,
995
+ factory: opts.factory
996
+ },
997
+ {
998
+ dep,
999
+ lifecycle: { subscribers: /* @__PURE__ */ new Set(), activated: false },
1000
+ value,
1001
+ wave: {
1002
+ pending: 0,
1003
+ hasCalledFnOnce: false,
1004
+ emittedDirtyThisWave: false,
1005
+ emittedSettleThisWave: false,
1006
+ insideRunWave: false,
1007
+ inDepMutation: false,
1008
+ rewireRunPending: false,
1009
+ batchDirtyOwed: false
1010
+ },
1011
+ control: {
1012
+ pauseLockset,
1013
+ pausedDepWaveOccurred: false,
1014
+ pauseBuffer: [],
1015
+ demandOwed: false,
1016
+ inDeliverDemand: false
1017
+ },
1018
+ privateState: { value: SENTINEL, persist: false },
1019
+ hooks: { onDeactivation: [], onInvalidate: [] },
1020
+ syncCtx: { value: null },
1021
+ version: {
1022
+ policy: versioning,
1023
+ value: createNodeVersion(
1024
+ versioning,
1025
+ opts.initial !== void 0 ? opts.initial : void 0
1026
+ )
1027
+ }
1028
+ }
1029
+ );
1030
+ this._id = created.id;
1031
+ this._slot = this._core.get(this._id);
1032
+ this._dep = this._core.getDep(this._id);
1033
+ this._value = this._core.getValue(this._id);
1034
+ this._wave = this._core.getWave(this._id);
1035
+ this._control = this._core.getControl(this._id);
1036
+ this._lifecycle = this._core.getLifecycle(this._id);
1037
+ this._privateState = this._core.getPrivateState(this._id);
1038
+ this._hooks = this._core.getHooks(this._id);
1039
+ this._syncCtxState = this._core.getSyncCtx(this._id);
1040
+ this._version = this._core.getVersion(this._id);
1041
+ checkpointReaders.set(this, () => ({
1042
+ cache: this._value.cache,
1043
+ hasData: this._value.hasData,
1044
+ terminal: this._value.terminal,
1045
+ activated: this._lifecycle.activated,
1046
+ hasCalledFnOnce: this._wave.hasCalledFnOnce,
1047
+ ctxState: {
1048
+ value: this._privateState.value,
1049
+ persist: this._privateState.persist
1050
+ },
1051
+ version: cloneNodeVersion(this._version.value),
1052
+ handle: this._slot.handle
1053
+ }));
1054
+ restoreWriters.set(this, (state) => {
1055
+ this._assertNotReleased("restoreGraph");
1056
+ this._value.cache = state.cache;
1057
+ this._value.hasData = state.hasData;
1058
+ this._value.status = state.status;
1059
+ this._value.terminal = state.terminal;
1060
+ this._value.hasTorndown = false;
1061
+ this._value.replayRing = [];
1062
+ this._wave.hasCalledFnOnce = state.hasCalledFnOnce;
1063
+ this._wave.emittedDirtyThisWave = false;
1064
+ this._wave.emittedSettleThisWave = false;
1065
+ this._wave.pending = 0;
1066
+ this._wave.insideRunWave = false;
1067
+ this._wave.inDepMutation = false;
1068
+ this._wave.rewireRunPending = false;
1069
+ this._wave.batchDirtyOwed = false;
1070
+ this._control.pauseBuffer = [];
1071
+ this._control.pausedDepWaveOccurred = false;
1072
+ this._control.demandOwed = false;
1073
+ this._control.inDeliverDemand = false;
1074
+ this._control.pauseLockset.clear();
1075
+ if (this._slot.pull) this._control.pauseLockset.add(this._slot.pullLock);
1076
+ this._privateState.value = state.ctxState.value;
1077
+ this._privateState.persist = state.ctxState.persist;
1078
+ if (state.version === false) {
1079
+ this._version.policy = { enabled: false };
1080
+ this._version.value = void 0;
1081
+ } else if (state.version.level === 0) {
1082
+ this._version.policy = { enabled: true, level: 0 };
1083
+ this._version.value = cloneNodeVersion(state.version);
1084
+ } else {
1085
+ if (!this._version.policy.enabled || this._version.policy.level !== 1) {
1086
+ throw new Error(
1087
+ `restoreGraph: checkpoint node version level ${state.version.level} requires matching node versioning policy`
1088
+ );
1089
+ }
1090
+ if (!state.hasData && state.version.counter > 0) {
1091
+ throw new Error(
1092
+ "restoreGraph: checkpoint node version cid cannot be verified without current DATA under V1 versioning (D109)"
1093
+ );
1094
+ }
1095
+ const expectedCid = restoredV1Cid(this._version.policy, state.hasData, state.cache);
1096
+ if (expectedCid !== state.version.cid) {
1097
+ throw new Error(
1098
+ "restoreGraph: checkpoint node version cid does not match the selected node versioning hash policy (D109)"
1099
+ );
1100
+ }
1101
+ this._version.value = cloneNodeVersion(state.version);
1102
+ }
1103
+ this._syncCtx = null;
1104
+ this._resetDepState();
1105
+ this._lifecycle.activated = false;
1106
+ this._lifecycle.subscribers.clear();
1107
+ this._restoredActivationPending = true;
1108
+ });
1109
+ runtimeReleasers.set(this, () => this._releaseRuntime());
1110
+ runtimeQuiescenceReaders.set(this, () => this._isRuntimeQuiescentForRelease());
1111
+ subscriberCountReaders.set(this, () => this._subscriberCount());
1112
+ activationReaders.set(this, () => this._lifecycle.activated);
1113
+ }
1114
+ /** R-pull (D55): true while a pull node is quiet (holds its own pullId/demand lock). */
1115
+ _isPullQuiet() {
1116
+ return this._slot.pull && this._control.pauseLockset.has(this._slot.pullLock);
1117
+ }
1118
+ /**
1119
+ * R-pull (D55/D59): this pull node's pullId (pure data, like {@link cache}/{@link handle} — never
1120
+ * triggers computation). A consumer demands one delivery by cone-routing a RESUME of it (no node
1121
+ * reference): `ctx.up([["RESUME", pullId]])` (immediate; loops back → D37 for a self-read dep) or
1122
+ * `ctx.upNext([["RESUME", pullId]])` (boundary-deferred self-demand, R-up-routing/R-rewire-deferred).
1123
+ * Undefined for a non-pull node. The author writes the pullId verbatim, so this getter is mainly
1124
+ * for inspection/describe; routing matches by the pullId value carried in the RESUME, by identity.
1125
+ */
1126
+ get pullId() {
1127
+ return this._slot.pullLock;
1128
+ }
1129
+ get cache() {
1130
+ return this._value.cache;
1131
+ }
1132
+ get status() {
1133
+ return this._value.status;
1134
+ }
1135
+ get version() {
1136
+ return cloneNodeVersion(this._version.value);
1137
+ }
1138
+ get name() {
1139
+ return this._slot.name;
1140
+ }
1141
+ /** R-describe/D51: real factory name for a standalone graph-less node (a runtime *Map inner). */
1142
+ get factory() {
1143
+ return this._slot.factory;
1144
+ }
1145
+ /**
1146
+ * The node's CURRENT/LIVE deps (R-describe / R-edges-derived / D51) — readonly view of the
1147
+ * live `_deps`, which a rewire (C-8 / C-11) mutates. The graph's describe() reads this (NOT a
1148
+ * construction-time snapshot) so every edge corresponds to a real current subscription (D3).
1149
+ * Inspection-only, like cache/status; never triggers computation.
1150
+ */
1151
+ get deps() {
1152
+ return this._slot.deps;
1153
+ }
1154
+ /**
1155
+ * The fn handle (pure data `(poolId, handleId)`, D7) or null for state/passthrough
1156
+ * nodes. Inspection-only (L1.6 handle is referenceable/inspectable) — lets the graph
1157
+ * layer key a dispatcher-backed profile recorder WITHOUT putting counters on the node
1158
+ * (R-node-thin / D39).
1159
+ */
1160
+ get handle() {
1161
+ return this._slot.handle;
1162
+ }
1163
+ /** R-push-subscribe: a new sink receives START, then cached DATA (or DIRTY if dirty). */
1164
+ subscribe(sink) {
1165
+ this._assertNotReleased("subscribe");
1166
+ enterWave();
1167
+ try {
1168
+ if (this._value.terminal !== void 0) {
1169
+ if (this._slot.resubscribable) {
1170
+ this._restoredActivationPending = false;
1171
+ this._resetLifecycle();
1172
+ } else
1173
+ throw new Error(
1174
+ "subscribe: node is non-resubscribable and has terminated; the stream is permanently over (R-terminal / R2.2.7.b)"
1175
+ );
1176
+ }
1177
+ this._lifecycle.subscribers.add(sink);
1178
+ sink(["START"]);
1179
+ if (this._slot.replayN > 0 && this._value.replayRing.length > 0) {
1180
+ for (const v of this._value.replayRing) sink(["DATA", v]);
1181
+ } else if (this._value.hasData && !this._slot.pull) {
1182
+ sink(["DATA", this._value.cache]);
1183
+ } else if (this._value.status === "dirty" && !this._slot.pull) {
1184
+ sink(["DIRTY"]);
1185
+ }
1186
+ if (!this._lifecycle.activated) this._activate();
1187
+ return () => {
1188
+ if (!this._lifecycle.subscribers.delete(sink)) return;
1189
+ if (this._lifecycle.subscribers.size === 0) this._deactivate();
1190
+ };
1191
+ } finally {
1192
+ exitWave();
1193
+ }
1194
+ }
1195
+ /** External emission toward sinks (state-node push, or async late-emit). One call = one wave. */
1196
+ down(msgs) {
1197
+ this._assertNotReleased("down");
1198
+ enterWave();
1199
+ try {
1200
+ this._down(msgs);
1201
+ } finally {
1202
+ exitWave();
1203
+ }
1204
+ }
1205
+ /**
1206
+ * Emit upstream toward deps — control tiers only (R-ctx-up). `towardDep` (a dep index) routes up
1207
+ * ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.
1208
+ */
1209
+ up(msgs, towardDep) {
1210
+ this._assertNotReleased("up");
1211
+ enterWave();
1212
+ try {
1213
+ this._up(msgs, towardDep);
1214
+ } finally {
1215
+ exitWave();
1216
+ }
1217
+ }
1218
+ // ── deferred self-rewire (R-rewire-deferred / D47): ctx.rewireNext drain support ──
1219
+ /**
1220
+ * Enqueue a deferred self-rewire op (issued from this node's fn via `ctx.rewireNext`).
1221
+ * Applied at the committed wave boundary (boundary.ts drain), never in place — the in-fn
1222
+ * immediate path (`subscribeDep`/`replaceDeps`/`unsubscribeDep`) still throws mid-run (D37/R-reentrancy).
1223
+ */
1224
+ _requestRewireNext(op) {
1225
+ deferRewire(this._core, () => this._applyRewireNext(op), {
1226
+ batchToken: currentBoundaryBatchToken(),
1227
+ isReady: () => !this._hasBoundaryPauseLock()
1228
+ });
1229
+ }
1230
+ /**
1231
+ * Enqueue a deferred up-going control wave (R-up-routing / R-pull / D59): at the committed wave
1232
+ * boundary, route `msgs` up from THIS node (broadcast, or up the single `towardDep` edge). The
1233
+ * deferred form of `ctx.up` — the SELF-demand path: a consumer issues `ctx.upNext([[RESUME,
1234
+ * pullId]])` to demand a dep it ALSO reads; the demand applies at the boundary (not mid-fn), so
1235
+ * the pull node's delivery loops back as a FRESH wave rather than re-entering the consumer (D37 /
1236
+ * R-reentrancy). Rides the same R-rewire-deferred (D47) drain as ctx.rewireNext.
1237
+ */
1238
+ _requestUpNext(msgs, towardDep) {
1239
+ deferRewire(
1240
+ this._core,
1241
+ () => {
1242
+ if (!this._released) this._up(msgs, towardDep);
1243
+ },
1244
+ {
1245
+ batchToken: currentBoundaryBatchToken(),
1246
+ isReady: () => !this._hasBoundaryPauseLock()
1247
+ }
1248
+ );
1249
+ }
1250
+ /** Apply one queued self-rewire at the boundary (drain thunk). */
1251
+ _applyRewireNext(op) {
1252
+ if (this._released) return;
1253
+ try {
1254
+ if (op.kind === "add") {
1255
+ const next = this._slot.deps.includes(op.dep) ? [...this._slot.deps] : [...this._slot.deps, op.dep];
1256
+ this._rewire(next, op.fn, { allowTerminalOwner: true });
1257
+ } else if (op.kind === "remove") {
1258
+ this._rewire(
1259
+ this._slot.deps.filter((d) => d !== op.dep),
1260
+ op.fn,
1261
+ { allowTerminalOwner: true }
1262
+ );
1263
+ } else {
1264
+ this._rewire(this._dedupDeps(op.deps), op.fn, { allowTerminalOwner: true });
1265
+ }
1266
+ } catch (e) {
1267
+ this._down([["ERROR", errorPayload(e, "rewireNext op failed")]]);
1268
+ }
1269
+ }
1270
+ // ── rewire (R-rewire / D42): intra-graph runtime topology mutation ──
1271
+ /**
1272
+ * Replace this node's deps atomically (surgical, Option-C). Requires an explicit
1273
+ * `fn` (SD-1 fn-deps pairing — user fns read dep input positionally). Kept deps
1274
+ * keep their subscription + per-dep state; only removed deps unsubscribe and only
1275
+ * added deps fresh-subscribe (push-on-subscribe for an added cached dep). The
1276
+ * first-run gate and cache are PRESERVED (R-rewire Q2/Q7). Intra-graph only (D22).
1277
+ */
1278
+ replaceDeps(newDeps, fn) {
1279
+ this._assertNotReleased("replaceDeps");
1280
+ this._rewire(this._dedupDeps(newDeps), fn);
1281
+ }
1282
+ /** Subscribe to one dep (special case of replaceDeps); returns its index. fn required (SD-1). */
1283
+ subscribeDep(depNode, fn) {
1284
+ this._assertNotReleased("subscribeDep");
1285
+ const next = this._slot.deps.includes(depNode) ? [...this._slot.deps] : [...this._slot.deps, depNode];
1286
+ const deferred = this._rewire(next, fn);
1287
+ return deferred ? next.indexOf(depNode) : this._slot.deps.indexOf(depNode);
1288
+ }
1289
+ /** Unsubscribe from one dep (special case of replaceDeps); idempotent if absent (fn swap still applies). */
1290
+ unsubscribeDep(depNode, fn) {
1291
+ this._assertNotReleased("unsubscribeDep");
1292
+ this._rewire(
1293
+ this._slot.deps.filter((d) => d !== depNode),
1294
+ fn
1295
+ );
1296
+ }
1297
+ _dedupDeps(deps) {
1298
+ const seen = /* @__PURE__ */ new Set();
1299
+ const out = [];
1300
+ for (const d of deps)
1301
+ if (!seen.has(d)) {
1302
+ seen.add(d);
1303
+ out.push(d);
1304
+ }
1305
+ return out;
1306
+ }
1307
+ /** Is `target` reachable upstream from `from` (following deps)? Cycle-prevention DFS. */
1308
+ _reachableUpstream(from, target) {
1309
+ const seen = /* @__PURE__ */ new Set();
1310
+ const stack = [from];
1311
+ while (stack.length > 0) {
1312
+ const n = stack.pop();
1313
+ if (n === void 0) continue;
1314
+ if (n === target) return true;
1315
+ if (seen.has(n)) continue;
1316
+ seen.add(n);
1317
+ for (const d of n._slot.deps) stack.push(d);
1318
+ }
1319
+ return false;
1320
+ }
1321
+ _assertRewireDepOwner(dep) {
1322
+ const selfOwner = getNodeOwner(this);
1323
+ const depOwner = getNodeOwner(dep);
1324
+ if (selfOwner !== void 0 && depOwner !== void 0 && selfOwner !== depOwner) {
1325
+ throw new Error(
1326
+ "rewire: dep belongs to a different graph; cross-graph deps require a wire bridge (D22 / R-graph-domain)"
1327
+ );
1328
+ }
1329
+ }
1330
+ _rewire(newDeps, fn, opts = {}) {
1331
+ if (this._value.terminal !== void 0 && !opts.allowTerminalOwner)
1332
+ throw new Error(
1333
+ "rewire: node is terminal (completed/errored) \u2014 cannot rewire (R-rewire / D42)"
1334
+ );
1335
+ if (this._wave.insideRunWave)
1336
+ throw new Error(
1337
+ "rewire: mid-fn topology mutation \u2014 a fn mutating its own deps mid-wave is the feedback cycle (R-rewire / D37)"
1338
+ );
1339
+ if (this._wave.inDepMutation)
1340
+ throw new Error(
1341
+ "rewire: reentrant dep mutation \u2014 another replaceDeps/subscribeDep/unsubscribeDep is in flight (R-rewire)"
1342
+ );
1343
+ if (newDeps.includes(this))
1344
+ throw new Error("rewire: self-dependency rejected (R-rewire / D42)");
1345
+ const oldDeps = this._slot.deps;
1346
+ const added = newDeps.filter((d) => !oldDeps.includes(d));
1347
+ for (const d of added) {
1348
+ if (this._reachableUpstream(d, this))
1349
+ throw new Error(
1350
+ "rewire: would create a cycle \u2014 dep already transitively depends on this node (R-rewire / D42)"
1351
+ );
1352
+ if (d._value.terminal !== void 0 && !d._slot.resubscribable)
1353
+ throw new Error(
1354
+ "rewire: cannot add a non-resubscribable terminal dep \u2014 would wedge (R-rewire / D42)"
1355
+ );
1356
+ this._assertRewireDepOwner(d);
1357
+ }
1358
+ if (deferAfterBatchForTarget(this, () => {
1359
+ this._rewire(newDeps, fn, { ...opts, allowTerminalOwner: true });
1360
+ })) {
1361
+ return true;
1362
+ }
1363
+ if (!this._lifecycle.activated) this._restoredActivationPending = false;
1364
+ this._wave.inDepMutation = true;
1365
+ this._wave.rewireRunPending = false;
1366
+ let zeroDepUnDirty = false;
1367
+ try {
1368
+ const oldHandle = this._slot.handle;
1369
+ this._slot.handle = this._slot.dispatcher.register(fn, this._slot.pool);
1370
+ if (oldHandle !== null) this._slot.dispatcher.unregister(oldHandle);
1371
+ const removed = oldDeps.filter((d) => !newDeps.includes(d));
1372
+ let removedDirtyContributor = false;
1373
+ for (const d of removed) {
1374
+ const oldIdx = oldDeps.indexOf(d);
1375
+ if (this._dep.dirty[oldIdx]) {
1376
+ removedDirtyContributor = true;
1377
+ this._wave.pending--;
1378
+ }
1379
+ if (this._lifecycle.activated) {
1380
+ const box = this._dep.idxBoxes[oldIdx];
1381
+ if (box) box.v = -1;
1382
+ const unsub = this._dep.unsubs[oldIdx];
1383
+ if (unsub) unsub();
1384
+ }
1385
+ }
1386
+ const n = newDeps.length;
1387
+ const newBatch = new Array(n).fill(null);
1388
+ const newPrev = new Array(n).fill(SENTINEL);
1389
+ const newHasData = new Array(n).fill(false);
1390
+ const newDirty = new Array(n).fill(false);
1391
+ const newTier = new Array(n).fill(0);
1392
+ const newTerminal = new Array(n).fill(void 0);
1393
+ const newTerminalInput = new Array(n).fill(void 0);
1394
+ const newUnsubs = new Array(n);
1395
+ const newBoxes = new Array(n);
1396
+ for (let j = 0; j < n; j++) {
1397
+ const oldIdx = oldDeps.indexOf(newDeps[j]);
1398
+ if (oldIdx !== -1) {
1399
+ newBatch[j] = this._dep.batch[oldIdx];
1400
+ newPrev[j] = this._dep.prev[oldIdx];
1401
+ newHasData[j] = this._dep.hasData[oldIdx];
1402
+ newDirty[j] = this._dep.dirty[oldIdx];
1403
+ newTier[j] = this._dep.tier[oldIdx];
1404
+ newTerminal[j] = this._dep.terminal[oldIdx];
1405
+ newUnsubs[j] = this._dep.unsubs[oldIdx];
1406
+ const box = this._dep.idxBoxes[oldIdx];
1407
+ if (box) box.v = j;
1408
+ newBoxes[j] = box;
1409
+ }
1410
+ }
1411
+ this._slot.deps = newDeps;
1412
+ this._dep.batch = newBatch;
1413
+ this._dep.prev = newPrev;
1414
+ this._dep.hasData = newHasData;
1415
+ this._dep.dirty = newDirty;
1416
+ this._dep.tier = newTier;
1417
+ this._dep.terminal = newTerminal;
1418
+ this._dep.terminalInput = newTerminalInput;
1419
+ this._dep.unsubs = newUnsubs;
1420
+ this._dep.idxBoxes = newBoxes;
1421
+ this._dep.waveData = newDeps.map(() => []);
1422
+ this._dep.waveTokens = new Array(newDeps.length).fill(void 0);
1423
+ this._syncCtx = null;
1424
+ if (this._lifecycle.activated) {
1425
+ for (const d of added) this._subscribeDepAt(d);
1426
+ }
1427
+ notifyTopologyDepsChanged(this, oldDeps, newDeps);
1428
+ if (removedDirtyContributor && this._wave.pending === 0 && this._value.status === "dirty") {
1429
+ if (newDeps.length > 0) this._wave.rewireRunPending = true;
1430
+ else zeroDepUnDirty = true;
1431
+ }
1432
+ } finally {
1433
+ this._wave.inDepMutation = false;
1434
+ }
1435
+ if (this._wave.rewireRunPending) {
1436
+ this._wave.rewireRunPending = false;
1437
+ this._settleRewire();
1438
+ } else if (zeroDepUnDirty) {
1439
+ if (this._wave.emittedDirtyThisWave) this._down([["RESOLVED"]]);
1440
+ else this._value.status = this._value.hasData ? "settled" : "sentinel";
1441
+ }
1442
+ return false;
1443
+ }
1444
+ // ── activation / deactivation (lazy; R-rom-ram) ──
1445
+ _activate() {
1446
+ this._lifecycle.activated = true;
1447
+ const seedRestoredDeps = this._restoredActivationPending;
1448
+ this._restoredActivationPending = false;
1449
+ if (this._slot.pull) this._control.pauseLockset.add(this._slot.pullLock);
1450
+ this._dep.unsubs = new Array(this._slot.deps.length);
1451
+ this._dep.idxBoxes = new Array(this._slot.deps.length);
1452
+ for (const dep of this._slot.deps)
1453
+ this._subscribeDepAt(dep, { seedRestored: seedRestoredDeps });
1454
+ if (this._slot.deps.length === 0 && this._slot.handle !== null && !this._wave.hasCalledFnOnce) {
1455
+ this._runWave();
1456
+ }
1457
+ }
1458
+ /**
1459
+ * Subscribe to a dep. The dispatch callback reads the dep's CURRENT index from a
1460
+ * mutable box (O(1)); a surgical rewire that reorders kept deps just updates the box
1461
+ * (R-rewire Option-C / D42) — no re-subscribe, no per-message indexOf scan. A removed
1462
+ * dep's box is set to -1 so any stale in-flight callback drops (drain).
1463
+ */
1464
+ _subscribeDepAt(depNode, opts = {}) {
1465
+ const idx0 = this._slot.deps.indexOf(depNode);
1466
+ const box = { v: idx0 };
1467
+ let ignoreInitialPush = opts.seedRestored === true;
1468
+ if (ignoreInitialPush && idx0 !== -1) {
1469
+ this._seedRestoredDepAt(idx0, depNode);
1470
+ if (depNode._value.terminal !== void 0 && !depNode._slot.resubscribable) {
1471
+ this._dep.unsubs[idx0] = () => {
1472
+ };
1473
+ this._dep.idxBoxes[idx0] = box;
1474
+ return;
1475
+ }
1476
+ }
1477
+ const unsub = depNode.subscribe((msg, delivery) => {
1478
+ if (ignoreInitialPush && delivery === void 0) return;
1479
+ if (ignoreInitialPush) ignoreInitialPush = false;
1480
+ if (box.v === -1) return;
1481
+ this._receiveFromDep(box.v, msg, delivery);
1482
+ });
1483
+ if (ignoreInitialPush && idx0 !== -1 && box.v !== -1) this._seedRestoredDepAt(idx0, depNode);
1484
+ ignoreInitialPush = false;
1485
+ if (idx0 !== -1) {
1486
+ this._dep.unsubs[idx0] = unsub;
1487
+ this._dep.idxBoxes[idx0] = box;
1488
+ }
1489
+ }
1490
+ _seedRestoredDepAt(idx, depNode) {
1491
+ const seedData = depNode._value.hasData && !depNode._slot.pull;
1492
+ this._dep.batch[idx] = null;
1493
+ this._dep.waveData[idx] = [];
1494
+ this._dep.waveTokens[idx] = void 0;
1495
+ this._dep.prev[idx] = seedData ? depNode._value.cache : SENTINEL;
1496
+ this._dep.hasData[idx] = seedData;
1497
+ this._dep.dirty[idx] = false;
1498
+ this._dep.tier[idx] = seedData ? 3 : 0;
1499
+ this._dep.terminal[idx] = depNode._value.terminal;
1500
+ this._dep.terminalInput[idx] = void 0;
1501
+ }
1502
+ _deactivate() {
1503
+ this._lifecycle.activated = false;
1504
+ for (const u of this._dep.unsubs) if (u) u();
1505
+ this._dep.unsubs = [];
1506
+ this._dep.idxBoxes = [];
1507
+ for (const fn of this._hooks.onDeactivation) fn();
1508
+ this._hooks.onDeactivation = [];
1509
+ this._hooks.onInvalidate = [];
1510
+ const isCompute = this._slot.handle !== null || this._slot.deps.length > 0;
1511
+ if (isCompute) {
1512
+ this._value.cache = SENTINEL;
1513
+ this._value.hasData = false;
1514
+ this._value.status = "sentinel";
1515
+ }
1516
+ this._resetDepState();
1517
+ this._wave.hasCalledFnOnce = false;
1518
+ this._control.pauseLockset.clear();
1519
+ this._control.pauseBuffer = [];
1520
+ this._control.pausedDepWaveOccurred = false;
1521
+ this._control.demandOwed = false;
1522
+ this._value.replayRing = [];
1523
+ if (!this._privateState.persist) this._privateState.value = SENTINEL;
1524
+ }
1525
+ _assertNotReleased(op) {
1526
+ if (this._released)
1527
+ throw new Error(`${op}: node has been released from its graph lifecycle (D122)`);
1528
+ }
1529
+ _subscriberCount() {
1530
+ return this._lifecycle.subscribers.size;
1531
+ }
1532
+ _isRuntimeQuiescentForRelease() {
1533
+ const allowedPullQuietLock = this._slot.pull && this._control.pauseLockset.size === 1 && this._control.pauseLockset.has(this._slot.pullLock);
1534
+ return !this._released && this._value.status !== "dirty" && this._value.status !== "pending" && this._wave.pending === 0 && !this._wave.insideRunWave && !this._wave.inDepMutation && !this._wave.rewireRunPending && !this._wave.batchDirtyOwed && this._dep.dirty.every((dirty) => !dirty) && this._control.pauseBuffer.length === 0 && !this._control.pausedDepWaveOccurred && !this._control.demandOwed && !this._control.inDeliverDemand && (this._control.pauseLockset.size === 0 || allowedPullQuietLock);
1535
+ }
1536
+ _releaseRuntime() {
1537
+ if (this._released) return;
1538
+ this._released = true;
1539
+ releasedNodes.add(this);
1540
+ let releaseError;
1541
+ const recordReleaseError = (error) => {
1542
+ if (releaseError === void 0) releaseError = error;
1543
+ };
1544
+ this._lifecycle.activated = false;
1545
+ for (const u of this._dep.unsubs) {
1546
+ try {
1547
+ u();
1548
+ } catch (error) {
1549
+ recordReleaseError(error);
1550
+ }
1551
+ }
1552
+ for (const fn of this._hooks.onDeactivation) {
1553
+ try {
1554
+ fn();
1555
+ } catch (error) {
1556
+ recordReleaseError(error);
1557
+ }
1558
+ }
1559
+ this._dep.unsubs = [];
1560
+ this._dep.idxBoxes = [];
1561
+ this._lifecycle.subscribers.clear();
1562
+ if (this._slot.handle !== null) {
1563
+ this._slot.dispatcher.unregister(this._slot.handle);
1564
+ this._slot.handle = null;
1565
+ }
1566
+ this._slot.deps = [];
1567
+ this._dep.batch = [];
1568
+ this._dep.waveData = [];
1569
+ this._dep.waveTokens = [];
1570
+ this._dep.prev = [];
1571
+ this._dep.hasData = [];
1572
+ this._dep.dirty = [];
1573
+ this._dep.tier = [];
1574
+ this._dep.terminal = [];
1575
+ this._dep.terminalInput = [];
1576
+ this._value.cache = SENTINEL;
1577
+ this._value.hasData = false;
1578
+ this._value.status = "sentinel";
1579
+ this._value.terminal = void 0;
1580
+ this._value.replayRing = [];
1581
+ this._privateState.value = SENTINEL;
1582
+ this._privateState.persist = false;
1583
+ this._syncCtx = null;
1584
+ this._resetDepState();
1585
+ this._hooks.onDeactivation = [];
1586
+ this._hooks.onInvalidate = [];
1587
+ this._control.pauseLockset.clear();
1588
+ this._control.pauseBuffer = [];
1589
+ this._control.pausedDepWaveOccurred = false;
1590
+ this._control.demandOwed = false;
1591
+ this._restoredActivationPending = false;
1592
+ checkpointReaders.delete(this);
1593
+ restoreWriters.delete(this);
1594
+ runtimeReleasers.delete(this);
1595
+ runtimeQuiescenceReaders.delete(this);
1596
+ subscriberCountReaders.delete(this);
1597
+ activationReaders.delete(this);
1598
+ ownerTokens.delete(this);
1599
+ topologyDepsChangedObservers.delete(this);
1600
+ this._core.releaseSlot(this._id);
1601
+ if (releaseError !== void 0) throw releaseError;
1602
+ }
1603
+ _resetDepState() {
1604
+ const n = this._slot.deps.length;
1605
+ for (let i = 0; i < n; i++) {
1606
+ this._dep.batch[i] = null;
1607
+ this._dep.waveData[i] = [];
1608
+ this._dep.waveTokens[i] = void 0;
1609
+ this._dep.prev[i] = SENTINEL;
1610
+ this._dep.hasData[i] = false;
1611
+ this._dep.dirty[i] = false;
1612
+ this._dep.tier[i] = 0;
1613
+ this._dep.terminal[i] = void 0;
1614
+ this._dep.terminalInput[i] = void 0;
1615
+ }
1616
+ this._wave.pending = 0;
1617
+ this._wave.emittedDirtyThisWave = false;
1618
+ }
1619
+ // ── upstream wave receive (two-phase + diamond) ──
1620
+ _recordDepProjection(idx, delivery) {
1621
+ const token = delivery?.wave ?? {};
1622
+ if (this._dep.waveTokens[idx] !== token) {
1623
+ this._dep.waveData[idx].push([]);
1624
+ this._dep.waveTokens[idx] = token;
1625
+ }
1626
+ return this._dep.waveData[idx][this._dep.waveData[idx].length - 1];
1627
+ }
1628
+ _depProjectionHasData(idx) {
1629
+ const projection = this._dep.waveData[idx][this._dep.waveData[idx].length - 1];
1630
+ return projection?.some((v) => v !== SENTINEL) ?? false;
1631
+ }
1632
+ _receiveFromDep(idx, msg, delivery) {
1633
+ if (this._released) return;
1634
+ const t = msg[0];
1635
+ if (t === "START") return;
1636
+ const isLastInDeliveredWave = delivery?.last ?? true;
1637
+ if (this._value.terminal !== void 0) {
1638
+ if (t === "TEARDOWN") this._down([["TEARDOWN"]]);
1639
+ return;
1640
+ }
1641
+ if (t === "INVALIDATE") {
1642
+ const projection = this._recordDepProjection(idx, delivery);
1643
+ projection.push(SENTINEL);
1644
+ if (projection.some((v) => v !== SENTINEL) && isLastInDeliveredWave) this._maybeRun();
1645
+ this._dep.prev[idx] = SENTINEL;
1646
+ this._dep.hasData[idx] = false;
1647
+ this._dep.batch[idx] = null;
1648
+ if (this._dep.dirty[idx]) {
1649
+ this._dep.dirty[idx] = false;
1650
+ this._wave.pending--;
1651
+ }
1652
+ if (this._control.pausedDepWaveOccurred && this._dep.batch.every((b) => b === null)) {
1653
+ this._control.pausedDepWaveOccurred = false;
1654
+ }
1655
+ const hadData = this._value.hasData;
1656
+ this._invalidate();
1657
+ if (this._wave.pending === 0 && this._wave.emittedDirtyThisWave) {
1658
+ if (!hadData) this._down([["RESOLVED"]]);
1659
+ else this._wave.emittedDirtyThisWave = false;
1660
+ }
1661
+ this._fireOwedDemandIfReady();
1662
+ return;
1663
+ }
1664
+ if (isTerminal(t)) {
1665
+ const isError = t === "ERROR";
1666
+ const errPayload = isError ? msg[1] : void 0;
1667
+ this._dep.terminal[idx] = isError ? errPayload : true;
1668
+ this._dep.terminalInput[idx] = isError ? errPayload : true;
1669
+ this._releaseDepDirty(idx);
1670
+ const ranValueBeforeTerminal = this._depProjectionHasData(idx) && isLastInDeliveredWave;
1671
+ if (ranValueBeforeTerminal) this._maybeRun();
1672
+ if (isError && this._slot.errorWhenDepsError) {
1673
+ this._down([["ERROR", errPayload]]);
1674
+ } else if (this._slot.terminalAsRealInput) {
1675
+ if (ranValueBeforeTerminal) {
1676
+ this._fireOwedDemandIfReady();
1677
+ return;
1678
+ }
1679
+ this._maybeRun();
1680
+ } else if (this._slot.completeWhenDepsComplete && this._allDepsTerminal()) {
1681
+ this._down([["COMPLETE"]]);
1682
+ } else {
1683
+ this._settleAfterAbsorbedTerminal();
1684
+ }
1685
+ this._fireOwedDemandIfReady();
1686
+ return;
1687
+ }
1688
+ if (t === "TEARDOWN") {
1689
+ this._down([["TEARDOWN"]]);
1690
+ return;
1691
+ }
1692
+ if (t === "DIRTY") {
1693
+ if (!this._dep.dirty[idx]) {
1694
+ this._dep.dirty[idx] = true;
1695
+ this._wave.pending++;
1696
+ this._dep.tier[idx] = 2;
1697
+ this._markDirty();
1698
+ }
1699
+ return;
1700
+ }
1701
+ if (t === "DATA") {
1702
+ const v = msg[1];
1703
+ this._recordDepProjection(idx, delivery).push(v);
1704
+ const b = this._dep.batch[idx];
1705
+ if (b === null) this._dep.batch[idx] = [v];
1706
+ else b.push(v);
1707
+ this._dep.prev[idx] = v;
1708
+ this._dep.hasData[idx] = true;
1709
+ this._dep.tier[idx] = 3;
1710
+ if (this._dep.dirty[idx]) {
1711
+ this._dep.dirty[idx] = false;
1712
+ this._wave.pending--;
1713
+ }
1714
+ if (isLastInDeliveredWave) this._maybeRun();
1715
+ this._fireOwedDemandIfReady();
1716
+ return;
1717
+ }
1718
+ if (t === "RESOLVED") {
1719
+ this._recordDepProjection(idx, delivery);
1720
+ this._dep.tier[idx] = 3;
1721
+ if (this._dep.dirty[idx]) {
1722
+ this._dep.dirty[idx] = false;
1723
+ this._wave.pending--;
1724
+ }
1725
+ if (isLastInDeliveredWave) this._maybeRun();
1726
+ this._fireOwedDemandIfReady();
1727
+ return;
1728
+ }
1729
+ }
1730
+ /**
1731
+ * R-terminal-settles-dirty (B35): release a dep's outstanding in-wave DIRTY contribution.
1732
+ * A settle-class event for that dep (DATA/RESOLVED inline above, INVALIDATE, and now
1733
+ * COMPLETE/ERROR) clears its dirty flag + decrements _pending. No-op if the dep already
1734
+ * settled this wave (DATA/RESOLVED ran first) — so the normal DATA-then-COMPLETE flow is
1735
+ * unaffected. This makes the exactly-one-settle invariant a single, shared step.
1736
+ */
1737
+ _releaseDepDirty(idx) {
1738
+ if (this._dep.dirty[idx]) {
1739
+ this._dep.dirty[idx] = false;
1740
+ this._wave.pending--;
1741
+ }
1742
+ }
1743
+ /**
1744
+ * R-terminal-settles-dirty (B35): settle a node whose dirtied dep was released by an ABSORBED
1745
+ * terminal that is NOT a real input (a plain derived/effect — the common default-node case when
1746
+ * one of several deps completes while others stay live). Runs only when the release drained
1747
+ * _pending while the node still owes a downstream settle (it broadcast DIRTY this wave):
1748
+ * - if some OTHER dep delivered real DATA this wave (a value occurred) → recompute (→ DATA);
1749
+ * - else the terminal's signalled change did not materialise (no value) → one undirty RESOLVED
1750
+ * (R-resolved-undirty), keeping the cache (a terminal, unlike INVALIDATE, leaves the value).
1751
+ * A terminalAsRealInput node instead recomputes unconditionally (its fn reads the terminal).
1752
+ */
1753
+ _settleAfterAbsorbedTerminal() {
1754
+ if (this._wave.pending !== 0 || !this._wave.emittedDirtyThisWave) return;
1755
+ const sawData = this._dep.batch.some((b) => b !== null && b.length > 0);
1756
+ if (sawData) this._maybeRun();
1757
+ if (this._wave.emittedDirtyThisWave) this._down([["RESOLVED"]]);
1758
+ }
1759
+ _markDirty() {
1760
+ this._value.status = "dirty";
1761
+ if (this._isPullQuiet()) return;
1762
+ if (!this._wave.emittedDirtyThisWave) {
1763
+ this._wave.emittedDirtyThisWave = true;
1764
+ this._emitToSubs(["DIRTY"]);
1765
+ }
1766
+ }
1767
+ _maybeRun() {
1768
+ if (this._wave.inDepMutation) {
1769
+ this._wave.rewireRunPending = true;
1770
+ return;
1771
+ }
1772
+ if (this._slot.pausable === true && this._isPaused()) {
1773
+ this._control.pausedDepWaveOccurred = true;
1774
+ return;
1775
+ }
1776
+ this._tryRun();
1777
+ }
1778
+ /**
1779
+ * R-rewire atomic settle (after a rewire that warrants a recompute): emit a proper
1780
+ * two-phase DIRTY→DATA wave (R-dirty-before-data — a rewire-triggered settle is a wave),
1781
+ * once, with every added dep already wired. Mirrors _maybeRun/_tryRun's pause + gate +
1782
+ * pending guards, then injects the phase-1 DIRTY the added dep's [START,DATA] handshake
1783
+ * did not carry.
1784
+ */
1785
+ _settleRewire() {
1786
+ if (this._slot.pausable === true && this._isPaused()) {
1787
+ this._control.pausedDepWaveOccurred = true;
1788
+ return;
1789
+ }
1790
+ if (this._wave.pending > 0) return;
1791
+ if (this._slot.handle === null) {
1792
+ this._passthroughEmit();
1793
+ return;
1794
+ }
1795
+ if (!this._wave.hasCalledFnOnce && !(this._slot.partial || this._allDepsSettled())) return;
1796
+ this._markDirty();
1797
+ this._runWave();
1798
+ }
1799
+ _tryRun() {
1800
+ if (this._wave.pending > 0) return;
1801
+ if (this._slot.handle === null) {
1802
+ this._passthroughEmit();
1803
+ return;
1804
+ }
1805
+ if (!this._wave.hasCalledFnOnce) {
1806
+ if (this._slot.partial || this._allDepsSettled()) this._runWave();
1807
+ return;
1808
+ }
1809
+ this._runWave();
1810
+ }
1811
+ _allDepsSettled() {
1812
+ for (let i = 0; i < this._slot.deps.length; i++) {
1813
+ if (this._dep.hasData[i]) continue;
1814
+ if (this._slot.terminalAsRealInput && this._dep.terminal[i] !== void 0) continue;
1815
+ return false;
1816
+ }
1817
+ return true;
1818
+ }
1819
+ _passthroughEmit() {
1820
+ const b = this._dep.batch[0];
1821
+ if (b !== null && b.length > 0) {
1822
+ this._down([["DATA", b[b.length - 1]]]);
1823
+ } else if (this._wave.emittedDirtyThisWave) {
1824
+ this._down([["RESOLVED"]]);
1825
+ }
1826
+ this._dep.batch[0] = null;
1827
+ this._wave.emittedDirtyThisWave = false;
1828
+ }
1829
+ _runWave() {
1830
+ if (this._wave.insideRunWave)
1831
+ throw new Error(
1832
+ "synchronous feedback cycle: node fn re-entered its own wave (R-reentrancy / D37)"
1833
+ );
1834
+ this._wave.hasCalledFnOnce = true;
1835
+ this._hooks.onInvalidate = [];
1836
+ this._hooks.onDeactivation = [];
1837
+ const ctx = this._buildCtx();
1838
+ const wasDirty = this._wave.emittedDirtyThisWave;
1839
+ this._wave.emittedSettleThisWave = false;
1840
+ this._wave.insideRunWave = true;
1841
+ try {
1842
+ this._slot.dispatcher.invoke(this._slot.handle, ctx);
1843
+ } finally {
1844
+ this._wave.insideRunWave = false;
1845
+ }
1846
+ if (wasDirty && !this._wave.emittedSettleThisWave && this._value.terminal === void 0 && !this._isAsyncPool()) {
1847
+ this._down([["RESOLVED"]]);
1848
+ }
1849
+ for (let i = 0; i < this._dep.batch.length; i++) {
1850
+ this._dep.batch[i] = null;
1851
+ this._dep.waveData[i] = [];
1852
+ this._dep.waveTokens[i] = void 0;
1853
+ this._dep.terminalInput[i] = void 0;
1854
+ }
1855
+ this._wave.emittedDirtyThisWave = false;
1856
+ }
1857
+ // ── ctx construction (L3-Q5: sync = node-stable reused ctx; async = per-invocation) ──
1858
+ _buildCtx() {
1859
+ const kind = this._slot.handle ? this._slot.dispatcher.poolKind(this._slot.handle.poolId) : "sync";
1860
+ if (kind === "sync") {
1861
+ if (this._syncCtx === null) this._syncCtx = this._makeCtx();
1862
+ this._refreshCtx(this._syncCtx);
1863
+ return this._syncCtx;
1864
+ }
1865
+ return this._makeCtx({
1866
+ waveData: this._dep.waveData.map((waves) => waves.map((w) => [...w])),
1867
+ terminal: this._dep.terminalInput.map(terminalView),
1868
+ latest: [...this._dep.prev]
1869
+ });
1870
+ }
1871
+ _makeCtx(snapshot) {
1872
+ const ctx = {
1873
+ // Wave-owner boundary (D47): a SYNC fn's emit nests under the public entry that drove
1874
+ // it (cheap inc/dec, no early drain); an ASYNC-pool fn re-enters here from its stashed
1875
+ // ctx at depth 0, so this is the boundary that drains any rewireNext it issued.
1876
+ up: (msgs, towardDep) => {
1877
+ if (this._released) return;
1878
+ enterWave();
1879
+ try {
1880
+ this._up(msgs, towardDep);
1881
+ } finally {
1882
+ exitWave();
1883
+ }
1884
+ },
1885
+ down: (msgs) => {
1886
+ if (this._released) return;
1887
+ enterWave();
1888
+ try {
1889
+ this._down(msgs);
1890
+ } finally {
1891
+ exitWave();
1892
+ }
1893
+ },
1894
+ waveData: snapshot?.waveData ?? this._dep.waveData,
1895
+ terminal: snapshot?.terminal ?? this._dep.terminalInput.map(terminalView),
1896
+ state: this._makeState(),
1897
+ onDeactivation: (fn) => {
1898
+ if (this._released) return;
1899
+ this._hooks.onDeactivation.push(fn);
1900
+ },
1901
+ onInvalidate: (fn) => {
1902
+ if (this._released) return;
1903
+ this._hooks.onInvalidate.push(fn);
1904
+ },
1905
+ environment: () => this._slot.environment,
1906
+ // R-rewire-deferred (D47): defer a self-dep-set mutation to the committed boundary.
1907
+ rewireNext: {
1908
+ subscribeDep: (dep, fn) => this._requestRewireNext({ kind: "add", dep, fn }),
1909
+ unsubscribeDep: (dep, fn) => this._requestRewireNext({ kind: "remove", dep, fn }),
1910
+ replaceDeps: (deps, fn) => this._requestRewireNext({ kind: "set", deps, fn })
1911
+ },
1912
+ // R-up-routing / R-pull (D59): deferred up — route a control wave (e.g. a RESUME pull
1913
+ // DEMAND) up the declared cone at the committed boundary. The SELF-demand path: an
1914
+ // immediate ctx.up whose delivery loops back re-enters this fn (D37 / R-reentrancy).
1915
+ upNext: (msgs, towardDep) => this._requestUpNext(msgs, towardDep),
1916
+ [CTX_DEP_CACHE]: { latest: snapshot?.latest ?? this._dep.prev },
1917
+ [CTX_NODE_BINDING]: {
1918
+ dispatcher: this._slot.dispatcher,
1919
+ create: (factory) => withEnvironmentDrivers(this._slot.environment, () => withNodeCore(this._core, factory))
1920
+ }
1921
+ };
1922
+ if (this._slot.dynamic) {
1923
+ ctx.track = (i) => ctx[CTX_DEP_CACHE]?.latest[i];
1924
+ }
1925
+ return ctx;
1926
+ }
1927
+ _refreshCtx(ctx) {
1928
+ ctx.waveData = this._dep.waveData;
1929
+ ctx.terminal = this._dep.terminalInput.map(terminalView);
1930
+ ctx[CTX_DEP_CACHE] = { latest: this._dep.prev };
1931
+ }
1932
+ _makeState() {
1933
+ return {
1934
+ get: () => this._privateState.value,
1935
+ set: (v) => {
1936
+ this._privateState.value = v;
1937
+ },
1938
+ persist: (on = true) => {
1939
+ this._privateState.persist = on;
1940
+ }
1941
+ };
1942
+ }
1943
+ // ── downstream emission pipeline (the unified waist) ──
1944
+ _down(msgs) {
1945
+ if (this._released) return;
1946
+ validateDownPayloads(msgs);
1947
+ const deliveryWave = {};
1948
+ const assertVersionDataCompatible = (wave) => {
1949
+ for (const m of wave) {
1950
+ if (m[0] === "DATA") assertNodeVersionDataCompatible(this._version.policy, m[1]);
1951
+ }
1952
+ };
1953
+ const snapshotVersionData = (wave) => wave.map(
1954
+ (m) => m[0] === "DATA" ? ["DATA", snapshotNodeVersionData(this._version.policy, m[1])] : m
1955
+ );
1956
+ assertVersionDataCompatible(msgs);
1957
+ if (this._value.terminal !== void 0) {
1958
+ if (!msgs.some((m) => m[0] === "TEARDOWN")) return;
1959
+ this._value.hasTorndown = true;
1960
+ if (this._slot.resetOnTeardown) {
1961
+ this._value.cache = SENTINEL;
1962
+ this._value.hasData = false;
1963
+ }
1964
+ this._emitToSubs(["TEARDOWN"], { wave: deliveryWave, last: true });
1965
+ return;
1966
+ }
1967
+ let sorted = [...msgs].sort((a, b) => messageTier(a[0]) - messageTier(b[0]));
1968
+ const firstInvalidate = sorted.findIndex((m) => m[0] === "INVALIDATE");
1969
+ if (firstInvalidate !== -1) {
1970
+ sorted = sorted.filter((m, i) => m[0] !== "INVALIDATE" || i === firstInvalidate);
1971
+ }
1972
+ const hasTeardown = sorted.some((m) => m[0] === "TEARDOWN");
1973
+ const hasTerminal = sorted.some((m) => m[0] === "COMPLETE" || m[0] === "ERROR");
1974
+ if (hasTeardown && !hasTerminal && this._value.terminal === void 0 && !this._value.hasTorndown) {
1975
+ sorted = [["COMPLETE"], ...sorted];
1976
+ }
1977
+ if (!this._wave.insideRunWave && currentBatch()) {
1978
+ const deferred = snapshotVersionData(sorted.filter((m) => isDeferredTier(m[0])));
1979
+ if (deferred.length > 0) {
1980
+ if (!this._wave.emittedDirtyThisWave) {
1981
+ this._wave.emittedDirtyThisWave = true;
1982
+ this._value.status = "dirty";
1983
+ this._emitToSubs(["DIRTY"], { wave: deliveryWave, last: false });
1984
+ }
1985
+ this._wave.batchDirtyOwed = true;
1986
+ deferToBatch(this, deferred);
1987
+ return;
1988
+ }
1989
+ }
1990
+ if (this._shouldBufferOnPause()) {
1991
+ const buffered = snapshotVersionData(sorted.filter((m) => isPauseBufferedTier(m[0])));
1992
+ if (buffered.length > 0) {
1993
+ this._wave.emittedSettleThisWave = true;
1994
+ this._control.pauseBuffer.push(buffered);
1995
+ }
1996
+ sorted = sorted.filter((m) => !isPauseBufferedTier(m[0]));
1997
+ if (sorted.length === 0) return;
1998
+ }
1999
+ let dataCount = 0;
2000
+ let hasTier3 = false;
2001
+ let hasResolved = false;
2002
+ for (const m of sorted) {
2003
+ if (m[0] === "DATA") dataCount++;
2004
+ if (m[0] === "RESOLVED") hasResolved = true;
2005
+ if (isValueTier(m[0])) hasTier3 = true;
2006
+ }
2007
+ if (dataCount >= 1 && hasResolved) {
2008
+ throw new Error(
2009
+ "down: a wave cannot mix DATA and RESOLVED (tier-3 exclusivity, R-resolved-undirty)"
2010
+ );
2011
+ }
2012
+ const plannedVersions = new Array(sorted.length);
2013
+ if (dataCount > 0) {
2014
+ let plannedVersion = this._version.value;
2015
+ for (let i = 0; i < sorted.length; i++) {
2016
+ const m = sorted[i];
2017
+ if (m[0] !== "DATA") continue;
2018
+ plannedVersion = advanceNodeVersion(plannedVersion, this._version.policy, m[1]);
2019
+ plannedVersions[i] = plannedVersion;
2020
+ }
2021
+ }
2022
+ if (hasTier3 && !this._wave.insideRunWave && !this._wave.emittedDirtyThisWave) {
2023
+ this._wave.emittedDirtyThisWave = true;
2024
+ this._value.status = "dirty";
2025
+ this._emitToSubs(["DIRTY"], { wave: deliveryWave, last: false });
2026
+ }
2027
+ for (let i = 0; i < sorted.length; i++) {
2028
+ const m = sorted[i];
2029
+ const delivery = { wave: deliveryWave, last: i === sorted.length - 1 };
2030
+ if (isDeferredTier(m[0])) this._wave.emittedSettleThisWave = true;
2031
+ if (m[0] === "DIRTY") {
2032
+ if (!this._wave.emittedDirtyThisWave) {
2033
+ this._wave.emittedDirtyThisWave = true;
2034
+ this._value.status = "dirty";
2035
+ this._emitToSubs(["DIRTY"], delivery);
2036
+ }
2037
+ continue;
2038
+ }
2039
+ if (m[0] === "DATA") {
2040
+ const v = m[1];
2041
+ this._value.cache = v;
2042
+ this._value.hasData = true;
2043
+ this._value.status = "settled";
2044
+ this._version.value = plannedVersions[i];
2045
+ if (this._slot.replayN > 0) {
2046
+ this._value.replayRing.push(v);
2047
+ if (this._value.replayRing.length > this._slot.replayN) this._value.replayRing.shift();
2048
+ }
2049
+ this._emitToSubs(["DATA", v], delivery);
2050
+ continue;
2051
+ }
2052
+ if (m[0] === "RESOLVED") {
2053
+ this._value.status = this._value.hasData ? "resolved" : "sentinel";
2054
+ this._emitToSubs(["RESOLVED"], delivery);
2055
+ continue;
2056
+ }
2057
+ if (m[0] === "INVALIDATE") {
2058
+ this._invalidate(delivery);
2059
+ continue;
2060
+ }
2061
+ if (m[0] === "COMPLETE") {
2062
+ if (this._value.terminal !== void 0) continue;
2063
+ this._value.terminal = true;
2064
+ this._control.pauseBuffer = [];
2065
+ this._value.status = "completed";
2066
+ this._emitToSubs(["COMPLETE"], delivery);
2067
+ continue;
2068
+ }
2069
+ if (m[0] === "ERROR") {
2070
+ if (this._value.terminal !== void 0) continue;
2071
+ this._value.terminal = m[1];
2072
+ this._control.pauseBuffer = [];
2073
+ this._value.status = "errored";
2074
+ this._emitToSubs(["ERROR", m[1]], delivery);
2075
+ continue;
2076
+ }
2077
+ if (m[0] === "TEARDOWN") {
2078
+ this._value.hasTorndown = true;
2079
+ if (this._slot.resetOnTeardown) {
2080
+ this._value.cache = SENTINEL;
2081
+ this._value.hasData = false;
2082
+ }
2083
+ this._emitToSubs(["TEARDOWN"], delivery);
2084
+ }
2085
+ }
2086
+ if (!this._wave.insideRunWave) this._wave.emittedDirtyThisWave = false;
2087
+ }
2088
+ _up(msgs, towardDep, route) {
2089
+ if (this._released) return;
2090
+ const routeState = route ?? { demandFired: /* @__PURE__ */ new Map() };
2091
+ for (const m of msgs) {
2092
+ if (!isUpAllowed(m[0])) {
2093
+ throw new Error(
2094
+ `ctx.up: ${m[0]} is down-only (tier ${messageTier(m[0])}); up carries control tiers only (R-ctx-up)`
2095
+ );
2096
+ }
2097
+ }
2098
+ for (const m of msgs) {
2099
+ if (m[0] === "PAUSE") {
2100
+ this._pauseAcquire(m[1]);
2101
+ } else if (m[0] === "RESUME") {
2102
+ if (this._slot.pull && m[1] === this._slot.pullLock) {
2103
+ if (!this._markDemandRouted(m[1], routeState)) this._onDemand();
2104
+ } else if (this._control.pauseLockset.has(m[1])) {
2105
+ this._pauseRelease(m[1]);
2106
+ } else {
2107
+ this._forwardUp(m, towardDep, routeState);
2108
+ }
2109
+ } else if (this._slot.deps.length === 0) {
2110
+ if (m[0] === "INVALIDATE") this._down([["INVALIDATE"]]);
2111
+ } else {
2112
+ this._forwardUp(m, towardDep, routeState);
2113
+ }
2114
+ }
2115
+ }
2116
+ _markDemandRouted(lockId, route) {
2117
+ let holders = route.demandFired.get(lockId);
2118
+ if (holders === void 0) {
2119
+ holders = /* @__PURE__ */ new Set();
2120
+ route.demandFired.set(lockId, holders);
2121
+ }
2122
+ if (holders.has(this)) return true;
2123
+ holders.add(this);
2124
+ return false;
2125
+ }
2126
+ /**
2127
+ * Forward one up-going control message toward deps (R-up-routing): up the single declared edge
2128
+ * `towardDep` (directed — prunes other branches; only meaningful on the issuer's FIRST hop) or
2129
+ * broadcast up ALL deps. A depless source has no deps → the message DROPS here (the terminus —
2130
+ * e.g. a cone-routed RESUME whose pullId no node up this cone holds, R-up-at-source). Recursive
2131
+ * forwarding carries the same per-wave route state and no `towardDep` → broadcast beyond the
2132
+ * first hop.
2133
+ */
2134
+ _forwardUp(m, towardDep, route) {
2135
+ if (this._slot.deps.length === 0) return;
2136
+ if (towardDep !== void 0) {
2137
+ const d = this._slot.deps[towardDep];
2138
+ if (d !== void 0) d._up([m], void 0, route);
2139
+ } else {
2140
+ for (const dep of this._slot.deps) dep._up([m], void 0, route);
2141
+ }
2142
+ }
2143
+ // ── PAUSE/RESUME lockset (R-pause-lockset) + modes (R-pause-modes) ──
2144
+ _isPaused() {
2145
+ return this._control.pauseLockset.size > 0;
2146
+ }
2147
+ _hasBoundaryPauseLock() {
2148
+ if (this._slot.pausable === false) return false;
2149
+ let locks = this._control.pauseLockset.size;
2150
+ if (this._slot.pull && this._control.pauseLockset.has(this._slot.pullLock)) locks--;
2151
+ return locks > 0;
2152
+ }
2153
+ _isAsyncPool() {
2154
+ return this._slot.handle !== null && this._slot.dispatcher.poolKind(this._slot.handle.poolId) === "async";
2155
+ }
2156
+ _pauseAcquire(lockId) {
2157
+ this._control.pauseLockset.add(lockId);
2158
+ }
2159
+ _pauseRelease(lockId) {
2160
+ if (!this._control.pauseLockset.has(lockId)) return;
2161
+ this._control.pauseLockset.delete(lockId);
2162
+ if (this._slot.pull && this._control.demandOwed) this._fireOwedDemandIfReady();
2163
+ if (this._hasBoundaryPauseLock()) return;
2164
+ scheduleBoundaryDrain(this._core);
2165
+ if (this._control.pauseLockset.size > 0) return;
2166
+ this._onResume();
2167
+ }
2168
+ _onResume() {
2169
+ if (this._value.terminal !== void 0) {
2170
+ this._control.pauseBuffer = [];
2171
+ this._control.pausedDepWaveOccurred = false;
2172
+ this._control.demandOwed = false;
2173
+ return;
2174
+ }
2175
+ if (this._control.pauseBuffer.length > 0) {
2176
+ const buf = this._control.pauseBuffer;
2177
+ this._control.pauseBuffer = [];
2178
+ for (const wave of buf) this._down(wave);
2179
+ }
2180
+ if (this._control.pausedDepWaveOccurred) {
2181
+ this._control.pausedDepWaveOccurred = false;
2182
+ this._tryRun();
2183
+ }
2184
+ }
2185
+ /**
2186
+ * R-pull (D59): can this pull node fire a demand NOW? — not terminal, settle-ready (_pending===0),
2187
+ * and no OTHER (non-pullId) lock holds it paused. The gate that decides fire-now vs OWE.
2188
+ */
2189
+ _canFireDemand() {
2190
+ if (this._value.terminal !== void 0 || this._wave.pending > 0) return false;
2191
+ const own = this._control.pauseLockset.has(this._slot.pullLock) ? 1 : 0;
2192
+ return this._control.pauseLockset.size <= own;
2193
+ }
2194
+ /**
2195
+ * R-pull (D59): deliver ONE demand pulse — release the pullId so the demand wave RELAYS (not
2196
+ * absorbed), fire it, then RE-QUIET (1:1). The pullId re-add + the re-entrancy flag are in a
2197
+ * `finally` so a throwing pull fn (graph-less node, no D30 catch) cannot leave the node
2198
+ * permanently non-quiet (the wedge-fix silently disabled) — QA-found robustness fix.
2199
+ */
2200
+ _deliverPullDemand() {
2201
+ this._control.demandOwed = false;
2202
+ this._control.inDeliverDemand = true;
2203
+ this._control.pauseLockset.delete(this._slot.pullLock);
2204
+ try {
2205
+ this._firePullDemand();
2206
+ } finally {
2207
+ this._control.pauseLockset.add(this._slot.pullLock);
2208
+ this._control.inDeliverDemand = false;
2209
+ }
2210
+ }
2211
+ /**
2212
+ * R-pull (D59): a cone-routed RESUME of THIS node's pullId arrived (R-up-routing) = a DEMAND.
2213
+ * Fire immediately if able; else OWE it — pin-5 (a dep DIRTY in flight, _pending>0) or F4/F5 (an
2214
+ * external PAUSE lock co-holds the node) — and fire when the node next becomes able. A demand
2215
+ * arriving WHILE a delivery is in flight (synchronous re-entry) is DROPPED (1:1, QA guard).
2216
+ */
2217
+ _onDemand() {
2218
+ if (this._control.inDeliverDemand) return;
2219
+ if (this._canFireDemand()) this._deliverPullDemand();
2220
+ else this._control.demandOwed = true;
2221
+ }
2222
+ /**
2223
+ * R-pull (D55): service ONE demand. Delivery content = the orthogonal pausable mode:
2224
+ * - 'resumeAll' → drain the buffered BACKLOG (each `_down` re-synthesizes a leading DIRTY, so
2225
+ * the per-entry replay is DIRTY-before-DATA — R-pause-modes per-entry arrival order);
2226
+ * - true → deliver the coalesced LATEST as ONE DIRTY-before-DATA wave (pin 2: the quiet absorb
2227
+ * suppressed the dep's original DIRTY, so the demand wave restores it before the value).
2228
+ * Neither branch fires when nothing changed since the last demand → the demand is SILENT.
2229
+ * Called by `_deliverPullDemand` only when settle-ready; the caller has released the pullId, so
2230
+ * `_markDirty` relays the leading DIRTY (not absorbed).
2231
+ */
2232
+ _firePullDemand() {
2233
+ if (this._control.pauseBuffer.length > 0) {
2234
+ const buf = this._control.pauseBuffer;
2235
+ this._control.pauseBuffer = [];
2236
+ for (const wave of buf) this._down(wave);
2237
+ }
2238
+ if (this._control.pausedDepWaveOccurred) {
2239
+ const gated = this._slot.handle !== null && !this._wave.hasCalledFnOnce && !(this._slot.partial || this._allDepsSettled());
2240
+ if (this._wave.pending > 0 || gated) return;
2241
+ this._control.pausedDepWaveOccurred = false;
2242
+ this._markDirty();
2243
+ this._tryRun();
2244
+ }
2245
+ }
2246
+ /**
2247
+ * R-pull (D55/D59): fire a demand that was OWED (deferred at demand time) once the node becomes
2248
+ * able — called from the dep-settle arms (DATA/RESOLVED/INVALIDATE/terminal drain _pending, pin-5
2249
+ * + B1/F6) and from `_pauseRelease` (an external PAUSE lock releases, F4/F5).
2250
+ */
2251
+ _fireOwedDemandIfReady() {
2252
+ if (this._control.inDeliverDemand) return;
2253
+ if (this._slot.pull && this._control.demandOwed && this._canFireDemand())
2254
+ this._deliverPullDemand();
2255
+ }
2256
+ /** Should an outgoing settle slice be deferred into the pause buffer? */
2257
+ _shouldBufferOnPause() {
2258
+ if (this._slot.pausable === false) return false;
2259
+ if (!this._isPaused()) return false;
2260
+ if (this._slot.pausable === "resumeAll") return true;
2261
+ if (!this._wave.insideRunWave && this._isAsyncPool() && this._slot.deps.length > 0) return true;
2262
+ return false;
2263
+ }
2264
+ /** R-invalidate-idempotent: clear cache + flush + cascade; no-op if nothing cached. */
2265
+ _invalidate(delivery) {
2266
+ if (!this._value.hasData) return;
2267
+ this._value.cache = SENTINEL;
2268
+ this._value.hasData = false;
2269
+ this._value.status = "sentinel";
2270
+ this._value.replayRing = [];
2271
+ for (const fn of this._hooks.onInvalidate) fn();
2272
+ this._emitToSubs(["INVALIDATE"], delivery);
2273
+ }
2274
+ // B42 (R-deps-terminal): ALL deps TERMINAL = every dep has reached COMPLETE *or* an ABSORBED
2275
+ // ERROR. Block only on a LIVE dep (_depTerminal[i] === undefined); an errored dep (terminal = the
2276
+ // error payload, which R-data-payload guarantees is !== undefined and non-boolean) COUNTS as
2277
+ // terminal-done. Was
2278
+ // `tm !== true`, which wedged a node whose errorWhenDepsError:false dep ERRORed (it never
2279
+ // auto-completed even after every other dep completed). Drives the completeWhenDepsComplete cascade.
2280
+ _allDepsTerminal() {
2281
+ if (this._slot.deps.length === 0) return false;
2282
+ for (const tm of this._dep.terminal) if (tm === void 0) return false;
2283
+ return true;
2284
+ }
2285
+ /** R-terminal: resubscribable reset clears terminal + dep state + re-arms the gate. */
2286
+ _resetLifecycle() {
2287
+ for (const u of this._dep.unsubs) if (u) u();
2288
+ this._dep.unsubs = [];
2289
+ this._dep.idxBoxes = [];
2290
+ this._lifecycle.subscribers.clear();
2291
+ this._lifecycle.activated = false;
2292
+ this._value.terminal = void 0;
2293
+ this._value.hasTorndown = false;
2294
+ this._wave.hasCalledFnOnce = false;
2295
+ this._resetDepState();
2296
+ this._control.pauseLockset.clear();
2297
+ this._control.pauseBuffer = [];
2298
+ this._control.pausedDepWaveOccurred = false;
2299
+ this._control.demandOwed = false;
2300
+ this._value.replayRing = [];
2301
+ const isCompute = this._slot.handle !== null || this._slot.deps.length > 0;
2302
+ if (isCompute) {
2303
+ this._value.cache = SENTINEL;
2304
+ this._value.hasData = false;
2305
+ this._value.status = "sentinel";
2306
+ } else {
2307
+ this._value.status = this._value.hasData ? "settled" : "sentinel";
2308
+ }
2309
+ if (!this._privateState.persist) this._privateState.value = SENTINEL;
2310
+ }
2311
+ _emitToSubs(msg, delivery) {
2312
+ if (this._released) return;
2313
+ const subs = [...this._lifecycle.subscribers];
2314
+ for (const sink of subs) sink(msg, delivery);
2315
+ }
2316
+ /** Batch commit (R-batch-coalesce): deliver the deferred tier-3 wave now. */
2317
+ __commitBatchedWave(wave) {
2318
+ this._wave.batchDirtyOwed = false;
2319
+ this._down(wave);
2320
+ }
2321
+ /** Batch rollback: balance the immediate DIRTY with a RESOLVED so downstream un-dirties. */
2322
+ __rollbackBatched() {
2323
+ if (this._wave.batchDirtyOwed) {
2324
+ this._wave.batchDirtyOwed = false;
2325
+ this._wave.emittedDirtyThisWave = false;
2326
+ this._value.status = this._value.hasData ? "settled" : "sentinel";
2327
+ this._emitToSubs(["RESOLVED"]);
2328
+ }
2329
+ }
2330
+ /** B49: enqueue a committed-boundary task on this node's graph-local core. */
2331
+ __deferBoundary(fn, batchToken) {
2332
+ deferRewire(this._core, fn, {
2333
+ batchToken,
2334
+ isReady: () => !this._hasBoundaryPauseLock()
2335
+ });
2336
+ }
2337
+ };
2338
+
2339
+ // src/graph/operators.ts
2340
+ function initNode(op, deps, opts = {}) {
2341
+ return makeInitNode(op, deps, opts);
2342
+ }
2343
+ function makeInitNode(op, deps, opts) {
2344
+ const body = operatorNodeFn(op);
2345
+ return new Node([...deps], body, { factory: op.factory, ...op.opts, ...opts });
2346
+ }
2347
+ function operatorNodeFn(op) {
2348
+ return (ctx) => {
2349
+ try {
2350
+ op.body(ctx);
2351
+ } catch (e) {
2352
+ ctx.down([["ERROR", errorPayload(e, "operator threw without a valid error payload")]]);
2353
+ }
2354
+ };
2355
+ }
2356
+
2357
+ // src/graph/composition.ts
2358
+ function metaEqual(a, b) {
2359
+ if (Object.is(a, b)) return true;
2360
+ if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;
2361
+ if (Array.isArray(a) || Array.isArray(b)) {
2362
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
2363
+ for (let i = 0; i < a.length; i++) if (!metaEqual(a[i], b[i])) return false;
2364
+ return true;
2365
+ }
2366
+ const ak = Object.keys(a).sort();
2367
+ const bk = Object.keys(b).sort();
2368
+ if (ak.length !== bk.length) return false;
2369
+ for (let i = 0; i < ak.length; i++) {
2370
+ if (ak[i] !== bk[i]) return false;
2371
+ if (!metaEqual(a[ak[i]], b[bk[i]]))
2372
+ return false;
2373
+ }
2374
+ return true;
2375
+ }
2376
+ function edgeKey(e) {
2377
+ return `${e.from}\0${e.to}`;
2378
+ }
2379
+ function cloneNode(n) {
2380
+ return {
2381
+ ...n,
2382
+ deps: [...n.deps],
2383
+ ...n.meta ? { meta: { ...n.meta } } : {}
2384
+ };
2385
+ }
2386
+ function flattenSnapshot(snap) {
2387
+ const nodes = /* @__PURE__ */ new Map();
2388
+ const edges = /* @__PURE__ */ new Map();
2389
+ const subgraphs = /* @__PURE__ */ new Set();
2390
+ const visit = (s, indexPath = "") => {
2391
+ for (const n of s.nodes) nodes.set(n.id, n);
2392
+ for (const e of s.edges) edges.set(edgeKey(e), e);
2393
+ s.subgraphs?.forEach((child, i) => {
2394
+ const prefixed = child.nodes.find((n) => n.id.includes("::"))?.id;
2395
+ const key = prefixed?.slice(0, prefixed.lastIndexOf("::")) ?? (child.name ? `${indexPath}${child.name}` : `${indexPath}${i}`);
2396
+ subgraphs.add(key);
2397
+ visit(child, `${key}/`);
2398
+ });
2399
+ };
2400
+ visit(snap);
2401
+ return { nodes, edges, subgraphs };
2402
+ }
2403
+ function topologyDiff(prev, next) {
2404
+ const p = flattenSnapshot(prev);
2405
+ const n = flattenSnapshot(next);
2406
+ const events = [];
2407
+ for (const path of [...n.subgraphs].filter((x) => !p.subgraphs.has(x)).sort())
2408
+ events.push({ type: "subgraph-mounted", path });
2409
+ for (const id of [...n.nodes.keys()].filter((x) => !p.nodes.has(x)).sort()) {
2410
+ events.push({ type: "node-added", id, node: cloneNode(n.nodes.get(id)) });
2411
+ }
2412
+ for (const id of [...n.nodes.keys()].filter((x) => p.nodes.has(x)).sort()) {
2413
+ const prevMeta = p.nodes.get(id)?.meta ?? {};
2414
+ const nextMeta = n.nodes.get(id)?.meta ?? {};
2415
+ if (!metaEqual(prevMeta, nextMeta)) {
2416
+ events.push({
2417
+ type: "node-meta-changed",
2418
+ id,
2419
+ prevMeta: { ...prevMeta },
2420
+ nextMeta: { ...nextMeta }
2421
+ });
2422
+ }
2423
+ }
2424
+ for (const [k, e] of [...n.edges.entries()].sort()) {
2425
+ if (!p.edges.has(k)) events.push({ type: "edge-added", from: e.from, to: e.to });
2426
+ }
2427
+ for (const [k, e] of [...p.edges.entries()].sort()) {
2428
+ if (!n.edges.has(k)) events.push({ type: "edge-removed", from: e.from, to: e.to });
2429
+ }
2430
+ for (const id of [...p.nodes.keys()].filter((x) => !n.nodes.has(x)).sort())
2431
+ events.push({ type: "node-removed", id });
2432
+ for (const path of [...p.subgraphs].filter((x) => !n.subgraphs.has(x)).sort())
2433
+ events.push({ type: "subgraph-unmounted", path });
2434
+ return { events };
2435
+ }
2436
+ function pipe(g, source, ...ops) {
2437
+ let current = source;
2438
+ for (const op of ops) current = g.initNode(op, [current]);
2439
+ return current;
2440
+ }
2441
+ function stratifyBranch(source, rules, classifier, opts = {}) {
2442
+ const op = stratifyBranchOperator(classifier);
2443
+ return initNode(op, [source, rules], opts);
2444
+ }
2445
+ function stratifyBranchOperator(classifier) {
2446
+ return {
2447
+ factory: "stratifyBranch",
2448
+ opts: {
2449
+ completeWhenDepsComplete: false,
2450
+ errorWhenDepsError: false,
2451
+ terminalAsRealInput: true
2452
+ },
2453
+ body: (ctx) => {
2454
+ const sourceBatch = depBatch(ctx, 0);
2455
+ const sourceTerminal = depTerminal(ctx, 0);
2456
+ const rules = depLatest(ctx, 1);
2457
+ if (rules !== void 0 && sourceBatch !== null) {
2458
+ for (const value of sourceBatch) {
2459
+ if (classifier(rules, value)) ctx.down([["DATA", value]]);
2460
+ }
2461
+ }
2462
+ if (isTerminalComplete(sourceTerminal)) {
2463
+ ctx.down([["COMPLETE"]]);
2464
+ } else if (isTerminalError(sourceTerminal)) {
2465
+ ctx.down([["ERROR", terminalErrorValue(sourceTerminal)]]);
2466
+ }
2467
+ }
2468
+ };
2469
+ }
2470
+ function stratify(g, source, rules, classifier, opts = {}) {
2471
+ const prefix = opts.prefix ?? "branch";
2472
+ const seen = /* @__PURE__ */ new Set();
2473
+ for (const { name } of rules) {
2474
+ if (seen.has(name)) throw new Error(`stratify: duplicate rule name '${name}'`);
2475
+ seen.add(name);
2476
+ }
2477
+ const { meta: rulesMeta, ...rulesOpts } = opts.rules ?? {};
2478
+ const rulesNode = g.state([...rules], {
2479
+ ...rulesOpts,
2480
+ name: rulesOpts.name ?? `${prefix}/rules`,
2481
+ meta: { ...rulesMeta ?? {}, kind: "stratify_rules" }
2482
+ });
2483
+ const branches = {};
2484
+ for (const rule of rules) {
2485
+ const op = stratifyBranchOperator((all, value) => {
2486
+ const current = all.find((r) => r.name === rule.name);
2487
+ return current === void 0 ? false : classifier(current.rule, value);
2488
+ });
2489
+ const { meta: branchMeta, ...branchOpts } = opts.branches?.[rule.name] ?? {};
2490
+ branches[rule.name] = g.initNode(op, [source, rulesNode], {
2491
+ ...branchOpts,
2492
+ name: branchOpts.name ?? `${prefix}/${rule.name}`,
2493
+ meta: { ...rule.meta ?? {}, ...branchMeta ?? {}, branch: rule.name }
2494
+ });
2495
+ }
2496
+ return { rules: rulesNode, branches };
2497
+ }
2498
+ // Annotate the CommonJS export names for ESM import in node:
2499
+ 0 && (module.exports = {
2500
+ pipe,
2501
+ stratify,
2502
+ stratifyBranch,
2503
+ topologyDiff
2504
+ });
2505
+ //# sourceMappingURL=index.cjs.map