@isograph/pico 0.0.0-main-5f205c00

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.
package/dist/index.mjs ADDED
@@ -0,0 +1,1139 @@
1
+ //#region src/graph/marking.ts
2
+ function storeSourceValueAndFindDependentsToMark(source, value) {
3
+ source.value = value;
4
+ if (source.dependentsStatus === 1) return;
5
+ source.dependentsStatus = 1;
6
+ return source.firstDependent;
7
+ }
8
+ /**
9
+ * A source write makes its direct readers DIRTY. Readers farther up the
10
+ * graph become MAYBE_DIRTY. Queue the first node with a callback on each
11
+ * path. If its value changes, its refresh queues the next affected callbacks.
12
+ */
13
+ function markDependentsOfWrittenSource(initialQueue, first) {
14
+ let queue = initialQueue;
15
+ let pendingLazyBranches;
16
+ let firstLazyBranch;
17
+ let beyondCallbackStack;
18
+ let edge = first;
19
+ while (edge !== void 0) {
20
+ const node = edge.dependent;
21
+ edge = edge.nextDependentEdge;
22
+ const status = node.status;
23
+ if (status === 3) {
24
+ node.status = 1;
25
+ if (node.callbackState === 1) {
26
+ queue = queueNodeWithCallback(queue, node);
27
+ const firstDependent = node.firstDependent;
28
+ if (firstDependent !== void 0 && firstDependent !== node.firstKnownMarkedDependentEdge) (beyondCallbackStack ??= []).push(node);
29
+ } else if (node.firstDependent !== void 0) {
30
+ if (firstLazyBranch !== void 0) (pendingLazyBranches ??= []).push(firstLazyBranch);
31
+ firstLazyBranch = node;
32
+ } else if (node.firstRetain === void 0) recordMarkedUnneededNode(node);
33
+ } else if (status === 2) {
34
+ node.status = 1;
35
+ if ((node.traversalFlags & 1) !== 0) {
36
+ node.traversalFlags &= ~1;
37
+ if (node.callbackState === 1) queue = queueNodeWithCallback(queue, node);
38
+ else if (node.firstDependent !== void 0) {
39
+ if (firstLazyBranch !== void 0) (pendingLazyBranches ??= []).push(firstLazyBranch);
40
+ firstLazyBranch = node;
41
+ }
42
+ }
43
+ }
44
+ }
45
+ if (firstLazyBranch !== void 0) return markTransitiveDependentsMaybeDirty(queue, firstLazyBranch, pendingLazyBranches, beyondCallbackStack);
46
+ if (beyondCallbackStack !== void 0) markReadersBeyondQueuedCallbacks(beyondCallbackStack);
47
+ return queue;
48
+ }
49
+ function queueNodeWithCallback(queue, node) {
50
+ if (queue === void 0) return [node];
51
+ queue.push(node);
52
+ return queue;
53
+ }
54
+ function recordMarkedUnneededNode(node) {
55
+ markedUnneeded[markedUnneededCount] = node;
56
+ markedUnneededCount += 1;
57
+ }
58
+ /**
59
+ * Internal invariant: the first `markedUnneededCount` entries of
60
+ * `markedUnneeded` are the nodes that marking took out of `CLEAN` while they
61
+ * were unneeded, and every later entry is `undefined`. `markedUnneededCount`
62
+ * is 0 when an outermost operation returns.
63
+ */
64
+ const markedUnneeded = [];
65
+ let markedUnneededCount = 0;
66
+ /**
67
+ * Follow lazy readers until each path reaches a node with a callback.
68
+ * Queue that node for refresh. Collect its readers for marking beyond the
69
+ * callback after this walk finishes.
70
+ */
71
+ function markTransitiveDependentsMaybeDirty(initialQueue, firstLazyBranch, initialLazyStack, initialBeyondCallbackStack) {
72
+ let queue = initialQueue;
73
+ let pendingLazyBranches = initialLazyStack;
74
+ let beyondCallbackStack = initialBeyondCallbackStack;
75
+ let marked = firstLazyBranch;
76
+ while (marked !== void 0) {
77
+ let dependentEdge = marked.firstDependent;
78
+ while (dependentEdge !== void 0) {
79
+ const dependent = dependentEdge.dependent;
80
+ dependentEdge = dependentEdge.nextDependentEdge;
81
+ switch (dependent.status) {
82
+ case 3:
83
+ dependent.status = 2;
84
+ dependent.traversalFlags &= ~1;
85
+ if (dependent.callbackState === 1) {
86
+ queue = queueNodeWithCallback(queue, dependent);
87
+ const firstDependent = dependent.firstDependent;
88
+ if (firstDependent !== void 0 && firstDependent !== dependent.firstKnownMarkedDependentEdge) (beyondCallbackStack ??= []).push(dependent);
89
+ } else if (dependent.firstDependent !== void 0) if (dependentEdge === void 0) dependentEdge = dependent.firstDependent;
90
+ else (pendingLazyBranches ??= []).push(dependent);
91
+ else if (dependent.firstRetain === void 0) recordMarkedUnneededNode(dependent);
92
+ break;
93
+ case 2:
94
+ if ((dependent.traversalFlags & 1) !== 0) {
95
+ dependent.traversalFlags &= ~1;
96
+ if (dependent.callbackState === 1) queue = queueNodeWithCallback(queue, dependent);
97
+ else if (dependent.firstDependent !== void 0) if (dependentEdge === void 0) dependentEdge = dependent.firstDependent;
98
+ else (pendingLazyBranches ??= []).push(dependent);
99
+ }
100
+ break;
101
+ case 1:
102
+ case 0: break;
103
+ }
104
+ }
105
+ marked = pendingLazyBranches === void 0 ? void 0 : pendingLazyBranches.pop();
106
+ }
107
+ if (beyondCallbackStack !== void 0) markReadersBeyondQueuedCallbacks(beyondCallbackStack);
108
+ return queue;
109
+ }
110
+ /**
111
+ * A queued callback node may keep its value. Mark its readers MAYBE_DIRTY so
112
+ * a nested read can verify them. If the callback node changes, its refresh
113
+ * queues the readers that need to run.
114
+ */
115
+ function markReadersBeyondQueuedCallbacks(beyondCallbackStack) {
116
+ let marked = beyondCallbackStack.pop();
117
+ while (marked !== void 0) {
118
+ let dependentEdge = marked.firstDependent;
119
+ const stop = marked.firstKnownMarkedDependentEdge;
120
+ if (dependentEdge !== stop) {
121
+ marked.firstKnownMarkedDependentEdge = dependentEdge;
122
+ while (dependentEdge !== stop) {
123
+ const dependent = dependentEdge.dependent;
124
+ dependentEdge = dependentEdge.nextDependentEdge;
125
+ if (dependent.status === 3) {
126
+ dependent.status = 2;
127
+ dependent.traversalFlags |= 1;
128
+ const firstDependent = dependent.firstDependent;
129
+ if (firstDependent !== void 0) {
130
+ if (firstDependent !== dependent.firstKnownMarkedDependentEdge) beyondCallbackStack.push(dependent);
131
+ } else if (dependent.firstRetain === void 0) recordMarkedUnneededNode(dependent);
132
+ }
133
+ }
134
+ }
135
+ marked = beyondCallbackStack.pop();
136
+ }
137
+ }
138
+ /**
139
+ * A callback node changed during the flush. Its direct readers now need
140
+ * recomputing. A reader marked only through this callback (MARKED_BEYOND)
141
+ * still needs its callbacks queued. Follow its lazy readers until the
142
+ * next callback on each path, which will propagate its own change in turn.
143
+ *
144
+ * Every direct reader was already marked by the write. A reader reached
145
+ * earlier without crossing a callback already has its callbacks queued.
146
+ */
147
+ function markDependentsOfChangedDerivedNode(flushQueue, node) {
148
+ node.firstKnownMarkedDependentEdge = void 0;
149
+ let pendingLazyBranches;
150
+ let firstLazyBranch;
151
+ let edge = node.firstDependent;
152
+ while (edge !== void 0) {
153
+ const dependent = edge.dependent;
154
+ edge = edge.nextDependentEdge;
155
+ switch (dependent.status) {
156
+ case 2:
157
+ dependent.status = 1;
158
+ if ((dependent.traversalFlags & 1) !== 0) {
159
+ dependent.traversalFlags &= ~1;
160
+ if (dependent.callbackState === 1) flushQueue.push(dependent);
161
+ else if (dependent.firstDependent !== void 0) {
162
+ if (firstLazyBranch !== void 0) (pendingLazyBranches ??= []).push(firstLazyBranch);
163
+ firstLazyBranch = dependent;
164
+ }
165
+ }
166
+ break;
167
+ case 3:
168
+ case 1:
169
+ case 0: break;
170
+ }
171
+ }
172
+ if (firstLazyBranch !== void 0) markTransitiveDependentsMaybeDirty(flushQueue, firstLazyBranch, pendingLazyBranches, void 0);
173
+ }
174
+ function markMaybeDirtyDependentsDirty(first) {
175
+ let edge = first;
176
+ while (edge !== void 0) {
177
+ const node = edge.dependent;
178
+ edge = edge.nextDependentEdge;
179
+ if (node.status === 2) node.status = 1;
180
+ }
181
+ }
182
+ /**
183
+ * Keep the allocated array for the next write without retaining the nodes.
184
+ */
185
+ function clearMarkedUnneededNodes() {
186
+ for (let index = 0; index < markedUnneededCount; index += 1) markedUnneeded[index] = void 0;
187
+ markedUnneededCount = 0;
188
+ }
189
+
190
+ //#endregion
191
+ //#region src/graph/edges.ts
192
+ function createSourceEdge(dependency, dependent) {
193
+ return {
194
+ dependency,
195
+ dependent,
196
+ nextDependencyEdge: void 0,
197
+ previousDependentEdge: void 0,
198
+ nextDependentEdge: void 0
199
+ };
200
+ }
201
+ function addEdgeToSourceDependents(edge) {
202
+ const dependency = edge.dependency;
203
+ const head = dependency.firstDependent;
204
+ edge.previousDependentEdge = void 0;
205
+ edge.nextDependentEdge = head;
206
+ if (head !== void 0) head.previousDependentEdge = edge;
207
+ dependency.firstDependent = edge;
208
+ }
209
+ function addEdgeToDerivedDependents(edge) {
210
+ const dependency = edge.dependency;
211
+ const head = dependency.firstDependent;
212
+ edge.previousDependentEdge = void 0;
213
+ edge.nextDependentEdge = head;
214
+ if (head !== void 0) head.previousDependentEdge = edge;
215
+ dependency.firstDependent = edge;
216
+ }
217
+ function unlinkRemainingSourceDependencies(first) {
218
+ let edge = first;
219
+ do {
220
+ removeEdgeFromSourceDependents(edge);
221
+ edge = edge.nextDependencyEdge;
222
+ } while (edge !== void 0);
223
+ }
224
+ /**
225
+ * Unlinking preserves `nextDependencyEdge` so traversal can continue through the removed edge.
226
+ */
227
+ function removeEdgeFromSourceDependents(edge) {
228
+ const previous = edge.previousDependentEdge;
229
+ const next = edge.nextDependentEdge;
230
+ if (previous === void 0) edge.dependency.firstDependent = next;
231
+ else previous.nextDependentEdge = next;
232
+ if (next !== void 0) next.previousDependentEdge = previous;
233
+ }
234
+ /**
235
+ * Unlinking preserves `nextDependencyEdge` so traversal can continue through the removed edge.
236
+ */
237
+ function removeEdgeFromDerivedDependents(edge) {
238
+ const dependency = edge.dependency;
239
+ const next = edge.nextDependentEdge;
240
+ if (dependency.firstKnownMarkedDependentEdge === edge) dependency.firstKnownMarkedDependentEdge = next;
241
+ const previous = edge.previousDependentEdge;
242
+ if (previous === void 0) dependency.firstDependent = next;
243
+ else previous.nextDependentEdge = next;
244
+ if (next !== void 0) next.previousDependentEdge = previous;
245
+ }
246
+ /**
247
+ * Moves `edge` strictly before `edge.dependency.firstKnownMarkedDependentEdge` so `edge`'s
248
+ * dependent can become `CLEAN` while preserving the `firstKnownMarkedDependentEdge` invariant.
249
+ *
250
+ * Contract: `edge.dependency.firstKnownMarkedDependentEdge !== undefined`.
251
+ */
252
+ function moveEdgeBeforeKnownMarkedDependents(edge) {
253
+ const dependency = edge.dependency;
254
+ if (edge === dependency.firstKnownMarkedDependentEdge) dependency.firstKnownMarkedDependentEdge = edge.nextDependentEdge;
255
+ const previous = edge.previousDependentEdge;
256
+ if (previous !== void 0) {
257
+ const next = edge.nextDependentEdge;
258
+ previous.nextDependentEdge = next;
259
+ if (next !== void 0) next.previousDependentEdge = previous;
260
+ const head = dependency.firstDependent;
261
+ edge.previousDependentEdge = void 0;
262
+ edge.nextDependentEdge = head;
263
+ head.previousDependentEdge = edge;
264
+ dependency.firstDependent = edge;
265
+ }
266
+ }
267
+
268
+ //#endregion
269
+ //#region src/disposal/cleanup.ts
270
+ /**
271
+ * Pops one entry off the cleanup queue and disposes its node if the node is
272
+ * still unneeded and not `UNCOMPUTED`. Disposing a node puts each of its
273
+ * derived dependencies that becomes unneeded on the cleanup queue. Returns
274
+ * whether the cleanup queue is non-empty.
275
+ *
276
+ * Contract: called outside computations, batches, and `onChange` callbacks.
277
+ */
278
+ function disposeNext() {
279
+ const node = cleanupQueue.pop();
280
+ if (node !== void 0 && node.firstRetain === void 0 && node.firstDependent === void 0 && node.status !== 0) disposeNode(node, 0, void 0);
281
+ if (cleanupQueue.length > 0) return true;
282
+ scheduleStatus = 0;
283
+ return false;
284
+ }
285
+ /**
286
+ * The same node can be queued more than once and can become needed again
287
+ * before disposal. Each queue entry must be checked when it is drained.
288
+ * An unneeded node with a cached value belongs here or on the current write's
289
+ * marked-unneeded list. A tracked read can briefly hold it between pulling
290
+ * its value and linking its new dependent.
291
+ */
292
+ const cleanupQueue = [];
293
+ /** A pending request runs at the end of the outermost operation. */
294
+ let scheduleStatus = 0;
295
+ /**
296
+ * During a drain, push dependencies directly to the cleanup queue so the
297
+ * drain cannot schedule itself again. Queue callers pass no stack and can
298
+ * ignore the return value. Only DISPOSE_MARKED can create a stack to return:
299
+ * it collects newly unneeded dirty dependencies for disposal in the same pass.
300
+ * Clean dependencies go on the cleanup queue.
301
+ */
302
+ function disposeNode(node, kind, initialStack) {
303
+ let stack = initialStack;
304
+ const firstSource = node.firstSourceDependency;
305
+ if (firstSource !== void 0) unlinkRemainingSourceDependencies(firstSource);
306
+ let edge = node.firstDerivedDependency;
307
+ while (edge !== void 0) {
308
+ removeEdgeFromDerivedDependents(edge);
309
+ const dependency = edge.dependency;
310
+ if (dependency.firstDependent === void 0 && dependency.firstRetain === void 0) if (kind === 1) if (dependency.status === 3) addToCleanupQueue(dependency);
311
+ else (stack ??= []).push(dependency);
312
+ else cleanupQueue.push(dependency);
313
+ edge = edge.nextDependencyEdge;
314
+ }
315
+ node.firstSourceDependency = void 0;
316
+ node.lastSourceDependency = void 0;
317
+ node.firstDerivedDependency = void 0;
318
+ node.lastDerivedDependency = void 0;
319
+ node.firstKnownMarkedDependentEdge = void 0;
320
+ node.status = 0;
321
+ node.value = void 0;
322
+ return stack;
323
+ }
324
+ function addToCleanupQueue(node) {
325
+ if (cleanupQueue.length === 0) scheduleStatus = 1;
326
+ cleanupQueue.push(node);
327
+ }
328
+ /**
329
+ * Disposes every unneeded node on the cleanup queue, and each node that a
330
+ * disposal leaves unneeded.
331
+ *
332
+ * Guarantee: after `disposeNext` returns false, and after `disposeAll`
333
+ * returns, the cleanup queue is empty and no scheduler call is pending.
334
+ *
335
+ * Contract: as `disposeNext`.
336
+ */
337
+ function disposeAll() {
338
+ while (true) {
339
+ const node = cleanupQueue.pop();
340
+ if (node === void 0) {
341
+ scheduleStatus = 0;
342
+ return;
343
+ }
344
+ if (node.firstRetain === void 0 && node.firstDependent === void 0 && node.status !== 0) disposeNode(node, 0, void 0);
345
+ }
346
+ }
347
+ /**
348
+ * Internal invariant: a dependency that a disposal here leaves unneeded is
349
+ * disposed too if it is not `CLEAN`, because the same write marked it. If it
350
+ * is `CLEAN`, it goes on the cleanup queue with its value.
351
+ */
352
+ function disposeMarkedUnneededNodes() {
353
+ let stack;
354
+ for (let index = 0; index < markedUnneededCount; index += 1) {
355
+ let node = markedUnneeded[index];
356
+ while (node !== void 0) {
357
+ if (node.firstRetain === void 0 && node.firstDependent === void 0 && node.status !== 0 && node.status !== 3) stack = disposeNode(node, 1, stack);
358
+ node = stack?.pop();
359
+ }
360
+ }
361
+ clearMarkedUnneededNodes();
362
+ }
363
+ function requestCleanupScheduling() {
364
+ scheduleStatus = 1;
365
+ }
366
+ function clearPendingCleanupRequest() {
367
+ scheduleStatus = 0;
368
+ }
369
+
370
+ //#endregion
371
+ //#region src/batch/notifications.ts
372
+ /** Called once for each callback node whose recomputation changed its value. */
373
+ function recordChangedNode(node) {
374
+ changedNodes[changedCount] = node;
375
+ changedCount += 1;
376
+ }
377
+ /**
378
+ * Nodes whose callbacks are due after the current flush. Each changed node
379
+ * becomes `CLEAN` during refresh, so a later queue entry for it cannot add it
380
+ * again. Callbacks finish before another flush can reuse this array.
381
+ */
382
+ const changedNodes = [];
383
+ let changedCount = 0;
384
+ /**
385
+ * Calls the `onChange` of each retain of each node whose refresh changed its
386
+ * value, in the order of each node's first refresh that changed it.
387
+ */
388
+ function notifyRetainsOfChangedNodes() {
389
+ for (let index = 0; index < changedCount; index += 1) {
390
+ const node = changedNodes[index];
391
+ changedNodes[index] = void 0;
392
+ const value = node.value;
393
+ let retain = node.firstRetain;
394
+ while (retain !== void 0) {
395
+ if (retain.onChange !== void 0) retain.onChange(value);
396
+ retain = retain.nextRetain;
397
+ }
398
+ }
399
+ changedCount = 0;
400
+ }
401
+
402
+ //#endregion
403
+ //#region src/graph/recompute.ts
404
+ /**
405
+ * The first run starts with empty dependency lists. Every edge it creates
406
+ * belongs to this run, so there are no old edges to unlink.
407
+ */
408
+ function computeInitialDerivedValue(node) {
409
+ const value = node.computation(node, void 0);
410
+ node.status = 3;
411
+ node.value = value;
412
+ return value;
413
+ }
414
+ function recomputeValueAndMarkDependents(node) {
415
+ const previous = node.value;
416
+ const value = rerunComputationAndUpdateDependencies(node, previous);
417
+ if (value === previous) return previous;
418
+ node.value = value;
419
+ markMaybeDirtyDependentsDirty(node.firstDependent);
420
+ return value;
421
+ }
422
+ function rerunComputationAndUpdateDependencies(node, previous) {
423
+ node.lastSourceDependency = void 0;
424
+ node.lastDerivedDependency = void 0;
425
+ const value = node.computation(node, previous);
426
+ unlinkUnreadDependencies(node);
427
+ node.status = 3;
428
+ return value;
429
+ }
430
+ /**
431
+ * Unlink the edges after the last read in each dependency list. If the
432
+ * computation read no inputs of that kind, unlink the whole list.
433
+ */
434
+ function unlinkUnreadDependencies(node) {
435
+ const lastSource = node.lastSourceDependency;
436
+ if (lastSource === void 0) {
437
+ const first = node.firstSourceDependency;
438
+ if (first !== void 0) {
439
+ unlinkRemainingSourceDependencies(first);
440
+ node.firstSourceDependency = void 0;
441
+ }
442
+ } else if (lastSource.nextDependencyEdge !== void 0) {
443
+ unlinkRemainingSourceDependencies(lastSource.nextDependencyEdge);
444
+ lastSource.nextDependencyEdge = void 0;
445
+ }
446
+ const lastDerived = node.lastDerivedDependency;
447
+ if (lastDerived === void 0) {
448
+ const first = node.firstDerivedDependency;
449
+ if (first !== void 0) {
450
+ unlinkRemainingDerivedDependencies(first);
451
+ node.firstDerivedDependency = void 0;
452
+ }
453
+ } else if (lastDerived.nextDependencyEdge !== void 0) {
454
+ unlinkRemainingDerivedDependencies(lastDerived.nextDependencyEdge);
455
+ lastDerived.nextDependencyEdge = void 0;
456
+ }
457
+ }
458
+ function unlinkRemainingDerivedDependencies(first) {
459
+ let edge = first;
460
+ do {
461
+ removeEdgeFromDerivedDependents(edge);
462
+ const dependency = edge.dependency;
463
+ if (dependency.firstDependent === void 0 && dependency.firstRetain === void 0) addToCleanupQueue(dependency);
464
+ edge = edge.nextDependencyEdge;
465
+ } while (edge !== void 0);
466
+ }
467
+ /**
468
+ * A downstream node with a callback can be waiting for this result. If it
469
+ * changes, `markDependentsOfChangedDerivedNode` queues those readers for refresh. Returning
470
+ * `CHANGED` tells `refreshNodeAndRecordChange` to record this node for notification.
471
+ */
472
+ function recomputeAndQueueAffectedDependents(flushQueue, node) {
473
+ const previous = node.value;
474
+ const value = rerunComputationAndUpdateDependencies(node, previous);
475
+ if (value === previous) return 1;
476
+ node.value = value;
477
+ if (node.firstDependent !== void 0) markDependentsOfChangedDerivedNode(flushQueue, node);
478
+ return 0;
479
+ }
480
+
481
+ //#endregion
482
+ //#region src/graph/refresh.ts
483
+ /**
484
+ * Returns the current value of a derived node. During a flush, reading a node
485
+ * with a callback can refresh it ahead of its turn in the queue. The flush
486
+ * records any change so it can notify the callback after all refreshes finish.
487
+ */
488
+ function getCurrentDerivedValue(node) {
489
+ switch (node.status) {
490
+ case 3: return node.value;
491
+ case 1: return node.callbackState === 1 ? getCurrentValueForNodeWithCallback(node) : recomputeValueAndMarkDependents(node);
492
+ case 2: return node.callbackState === 1 ? getCurrentValueForNodeWithCallback(node) : getValueAfterVerifyingDependencies(node);
493
+ case 0: return computeInitialDerivedValue(node);
494
+ }
495
+ }
496
+ function getValueAfterVerifyingDependencies(node) {
497
+ return verifyDerivedDependencies(node) === 1 ? recomputeValueAndMarkDependents(node) : node.value;
498
+ }
499
+ /**
500
+ * During a flush, use the active queue so this read can record a change
501
+ * and queue downstream nodes that need refreshing. Outside a flush,
502
+ * a node can still be `MAYBE_DIRTY` after an input kept its value. A read
503
+ * verifies that input before deciding whether to rerun the node.
504
+ */
505
+ function getCurrentValueForNodeWithCallback(node) {
506
+ const queue = refreshQueue;
507
+ if (queue !== void 0) {
508
+ refreshNodeAndRecordChange(queue, node);
509
+ return node.value;
510
+ }
511
+ return node.status === 1 ? recomputeValueAndMarkDependents(node) : getValueAfterVerifyingDependencies(node);
512
+ }
513
+ /**
514
+ * Can requestedNode reuse its cached value? A write to a direct source
515
+ * already marks its reader DIRTY. Here the reader is MAYBE_DIRTY, so only
516
+ * its derived inputs need checking.
517
+ *
518
+ * Suppose A read B1, then B2. The outer loop checks A → B1 first. If B1
519
+ * is lazy and MAYBE_DIRTY, the loop starts checking B1's inputs. Once B1
520
+ * is up to date, the inner loop recovers A → B1 to get back to A.
521
+ * A must rerun if either B1 or B2 changed. If A is still MAYBE_DIRTY
522
+ * after checking B1, check B2. If either input marks A DIRTY, stop
523
+ * checking. A's rerun will read the inputs it needs. If both inputs kept
524
+ * their values, A becomes CLEAN and keeps its cached value.
525
+ */
526
+ function verifyDerivedDependencies(requestedNode) {
527
+ let savedReaderEdges;
528
+ let nodeBeingVerified = requestedNode;
529
+ let nextInputEdge = requestedNode.firstDerivedDependency;
530
+ while (true) {
531
+ if (nextInputEdge !== void 0) {
532
+ const derivedInput = nextInputEdge.dependency;
533
+ if (derivedInput.firstKnownMarkedDependentEdge !== void 0) moveEdgeBeforeKnownMarkedDependents(nextInputEdge);
534
+ if (derivedInput.status === 2 && derivedInput.callbackState !== 1) {
535
+ if (nextInputEdge.previousDependentEdge !== void 0 || nextInputEdge.nextDependentEdge !== void 0) (savedReaderEdges ??= []).push(nextInputEdge);
536
+ nodeBeingVerified = derivedInput;
537
+ nextInputEdge = derivedInput.firstDerivedDependency;
538
+ continue;
539
+ }
540
+ if (derivedInput.status !== 3) getCurrentDerivedValue(derivedInput);
541
+ if (nodeBeingVerified.status !== 1) {
542
+ nextInputEdge = nextInputEdge.nextDependencyEdge;
543
+ continue;
544
+ }
545
+ if (nodeBeingVerified === requestedNode) return 1;
546
+ recomputeValueAndMarkDependents(nodeBeingVerified);
547
+ } else nodeBeingVerified.status = 3;
548
+ while (true) {
549
+ if (nodeBeingVerified === requestedNode) return 3;
550
+ let edgeBackToReader;
551
+ if (savedReaderEdges !== void 0 && savedReaderEdges.length > 0 && savedReaderEdges[savedReaderEdges.length - 1].dependency === nodeBeingVerified) edgeBackToReader = savedReaderEdges.pop();
552
+ else edgeBackToReader = nodeBeingVerified.firstDependent;
553
+ nodeBeingVerified = edgeBackToReader.dependent;
554
+ if (nodeBeingVerified.status !== 1) {
555
+ nextInputEdge = edgeBackToReader.nextDependencyEdge;
556
+ break;
557
+ }
558
+ if (nodeBeingVerified === requestedNode) return 1;
559
+ recomputeValueAndMarkDependents(nodeBeingVerified);
560
+ }
561
+ }
562
+ }
563
+ function refreshNodeAndRecordChange(flushQueue, node) {
564
+ if (refreshNodeIfItHasCallback(flushQueue, node) === 0) recordChangedNode(node);
565
+ }
566
+ function refreshNodeIfItHasCallback(flushQueue, node) {
567
+ if (node.callbackState !== 1) return 1;
568
+ switch (node.status) {
569
+ case 1: return recomputeAndQueueAffectedDependents(flushQueue, node);
570
+ case 2: return verifyDerivedDependencies(node) === 1 ? recomputeAndQueueAffectedDependents(flushQueue, node) : 1;
571
+ case 3:
572
+ case 0: return 1;
573
+ }
574
+ }
575
+ /**
576
+ * While the flush refreshes A, A's computation can read B before B's turn
577
+ * in the queue. That read refreshes B immediately. If B changes, the pull
578
+ * uses this same queue for B's affected readers and records B for notification.
579
+ * The refresh loop clears this reference before callbacks run.
580
+ */
581
+ let refreshQueue;
582
+ function refreshNodesInFlushQueue(flushQueue) {
583
+ refreshQueue = flushQueue;
584
+ for (let index = 0; index < flushQueue.length; index += 1) refreshNodeAndRecordChange(flushQueue, flushQueue[index]);
585
+ refreshQueue = void 0;
586
+ }
587
+
588
+ //#endregion
589
+ //#region src/batch/flush.ts
590
+ let flushState = 0;
591
+ /**
592
+ * Guarantee: every `onChange` runs after the flush has refreshed every node
593
+ * on the flush queue, in the order of each node's first recompute that
594
+ * changed its value.
595
+ *
596
+ * Internal invariant: an `onChange` writes nothing, so it puts no node on the
597
+ * flush queue and no node on the marked-unneeded list.
598
+ */
599
+ function refreshQueuedNodesAndNotifyCallbacks(flushQueue) {
600
+ flushState = 1;
601
+ refreshNodesInFlushQueue(flushQueue);
602
+ if (markedUnneededCount > 0) disposeMarkedUnneededNodes();
603
+ notifyRetainsOfChangedNodes();
604
+ flushState = 0;
605
+ }
606
+
607
+ //#endregion
608
+ //#region src/disposal/age-drain.ts
609
+ /**
610
+ * Disposes unneeded nodes whose newest queue entry is older than the age
611
+ * boundary, then any dependencies those disposals leave unneeded. Returns
612
+ * the number of remaining entries, excluding the boundary marker.
613
+ *
614
+ * Each boundary in positions must still refer to the same group of surviving
615
+ * entries after compaction. The backward scan counts entries after each
616
+ * boundary. The final pass converts those counts back into queue indices.
617
+ * All SCAN_SEEN bits are clear on entry and again before disposal begins.
618
+ */
619
+ function disposeEligibleCleanupEntries(eligibleEnd, positions, count, marker, outOfTime) {
620
+ const queue = cleanupQueue;
621
+ const originalLength = queue.length;
622
+ let firstKept = originalLength;
623
+ let eligibleCount = 0;
624
+ let boundaryIndex = count - 1;
625
+ for (let index = originalLength - 1; index >= 0; index -= 1) {
626
+ while (boundaryIndex >= 0 && positions[boundaryIndex] > index) {
627
+ positions[boundaryIndex] = originalLength - firstKept;
628
+ boundaryIndex -= 1;
629
+ }
630
+ const node = queue[index];
631
+ if (node.firstRetain !== void 0 || node.firstDependent !== void 0 || node.status === 0 || (node.traversalFlags & 2) !== 0) continue;
632
+ node.traversalFlags |= 2;
633
+ firstKept -= 1;
634
+ queue[firstKept] = node;
635
+ if (index < eligibleEnd) eligibleCount += 1;
636
+ }
637
+ for (let index = firstKept; index < originalLength; index += 1) queue[index].traversalFlags &= ~2;
638
+ const firstYoung = firstKept + eligibleCount;
639
+ let nextEligible = firstKept;
640
+ let budgetExpired = false;
641
+ for (; nextEligible < firstYoung; nextEligible += 1) {
642
+ if (nextEligible > firstKept && outOfTime !== void 0 && outOfTime()) {
643
+ budgetExpired = true;
644
+ break;
645
+ }
646
+ disposeNode(queue[nextEligible], 0, void 0);
647
+ }
648
+ const disposedCount = nextEligible - firstKept;
649
+ let nextCascade = originalLength;
650
+ if (!budgetExpired) for (; nextCascade < queue.length; nextCascade += 1) {
651
+ const node = queue[nextCascade];
652
+ if (node.firstRetain === void 0 && node.firstDependent === void 0 && node.status !== 0) {
653
+ if (outOfTime !== void 0 && outOfTime()) {
654
+ budgetExpired = true;
655
+ break;
656
+ }
657
+ disposeNode(node, 0, void 0);
658
+ }
659
+ }
660
+ const pendingCascade = budgetExpired ? queue.slice(nextCascade) : void 0;
661
+ const pendingCount = pendingCascade === void 0 ? 0 : pendingCascade.length;
662
+ const keptCount = originalLength - firstKept;
663
+ const remainingCount = keptCount - disposedCount;
664
+ queue.copyWithin(pendingCount, firstKept + disposedCount, originalLength);
665
+ if (pendingCascade !== void 0) for (let index = 0; index < pendingCount; index += 1) queue[index] = pendingCascade[index];
666
+ queue.length = pendingCount + remainingCount;
667
+ for (let index = 0; index < count; index += 1) positions[index] = pendingCount + keptCount - positions[index] - disposedCount;
668
+ if (pendingCount + remainingCount > 0) queue.push(marker);
669
+ drainReachedTimeLimit = budgetExpired;
670
+ pendingCascadeCount = pendingCount;
671
+ return pendingCount + remainingCount;
672
+ }
673
+ /** True if the last drain skipped eligible work because its time budget expired. */
674
+ let drainReachedTimeLimit = false;
675
+ /** Nodes left at the front of the queue for disposal regardless of age. */
676
+ let pendingCascadeCount = 0;
677
+
678
+ //#endregion
679
+ //#region src/graph/nodes.ts
680
+ function createSourceNode(value) {
681
+ return {
682
+ value,
683
+ firstDependent: void 0,
684
+ dependentsStatus: 1
685
+ };
686
+ }
687
+ /**
688
+ * Returns an `UNCOMPUTED` derived node.
689
+ *
690
+ * Contract: `computation` is synchronous. `computation` reads other nodes
691
+ * only through `readSource` and `readDerived`, called with the `callingNode`
692
+ * that `computation` receives, and does not keep that `callingNode` for use
693
+ * after it returns. `computation` does not write, start or end a batch, retain,
694
+ * release, dispose, or call `readDerivedOutsideComputation`.
695
+ */
696
+ function createDerivedNode(computation) {
697
+ return {
698
+ value: void 0,
699
+ firstRetain: void 0,
700
+ traversalFlags: 0,
701
+ status: 0,
702
+ callbackState: 0,
703
+ firstSourceDependency: void 0,
704
+ lastSourceDependency: void 0,
705
+ firstDerivedDependency: void 0,
706
+ lastDerivedDependency: void 0,
707
+ firstDependent: void 0,
708
+ firstKnownMarkedDependentEdge: void 0,
709
+ computation
710
+ };
711
+ }
712
+
713
+ //#endregion
714
+ //#region src/disposal/update-counter.ts
715
+ function incrementUpdateCount() {
716
+ updateCount += 1;
717
+ }
718
+ /**
719
+ * Counts outermost updates that reach the end of write processing. Cleanup
720
+ * uses this count to age queue entries.
721
+ */
722
+ let updateCount = 0;
723
+
724
+ //#endregion
725
+ //#region src/disposal/older-than-updates.ts
726
+ /**
727
+ * Disposes unneeded nodes whose newest cleanup entry is at least minAge
728
+ * updates old. Age starts at the first drain that sees an entry. A write
729
+ * or batch commit advances the update count. Repeated drains do not.
730
+ * Disposing a node can leave its inputs unneeded; these are eligible immediately.
731
+ *
732
+ * An optional idle deadline or performance.now() timestamp limits disposal.
733
+ * The queue scan always finishes, and the first eligible disposal always
734
+ * runs. Unfinished entries keep their ages for the next drain. If another
735
+ * disposal strategy removed the boundary marker between drains, the
736
+ * remaining entries start aging again at the current update count.
737
+ *
738
+ * Returns the number of entries still queued. When entries remain, request
739
+ * another scheduler call at the end of the next outermost operation.
740
+ * Call outside computations, batches, and callbacks, with an integer minAge.
741
+ */
742
+ function disposeOlderThanUpdates(minAge, budget) {
743
+ const length = cleanupQueue.length;
744
+ const now = updateCount;
745
+ let count = boundaryCount;
746
+ if (count > 0 && cleanupQueue[positions[count - 1]] !== marker) count = 0;
747
+ let eligibleEnd = minAge <= 0 ? length : 0;
748
+ if (minAge > 0) {
749
+ for (let index = count - 1; index >= 0; index -= 1) if (now - updates[index] >= minAge) {
750
+ eligibleEnd = positions[index];
751
+ break;
752
+ }
753
+ }
754
+ marker ??= createDerivedNode(() => void 0);
755
+ const queued = disposeEligibleCleanupEntries(eligibleEnd, positions, count, marker, budget === void 0 ? void 0 : typeof budget === "number" ? () => performance.now() >= budget : () => budget.timeRemaining() <= 0);
756
+ const front = pendingCascadeCount;
757
+ let next = 0;
758
+ for (let index = 0; index < count; index += 1) {
759
+ const position = positions[index];
760
+ if (position > front) {
761
+ positions[next] = position;
762
+ updates[next] = updates[index];
763
+ next += 1;
764
+ }
765
+ }
766
+ if (front > 0) {
767
+ for (let index = next; index > 0; index -= 1) {
768
+ positions[index] = positions[index - 1];
769
+ updates[index] = updates[index - 1];
770
+ }
771
+ positions[0] = front;
772
+ updates[0] = -Infinity;
773
+ next += 1;
774
+ }
775
+ if (queued === 0) {
776
+ boundaryCount = 0;
777
+ clearPendingCleanupRequest();
778
+ return 0;
779
+ }
780
+ if (next > 0 && positions[next - 1] === queued) boundaryCount = next;
781
+ else if (next > 0 && updates[next - 1] === now) {
782
+ positions[next - 1] = queued;
783
+ boundaryCount = next;
784
+ } else {
785
+ positions[next] = queued;
786
+ updates[next] = now;
787
+ boundaryCount = next + 1;
788
+ }
789
+ requestCleanupScheduling();
790
+ return queued;
791
+ }
792
+ const positions = [];
793
+ const updates = [];
794
+ let boundaryCount = 0;
795
+ /**
796
+ * An `UNCOMPUTED` node that a drain puts at its boundary. A disposal skips an
797
+ * `UNCOMPUTED` node, and nothing else queues this node, so it stays at its
798
+ * index until a call removes it together with every entry above it.
799
+ */
800
+ let marker;
801
+
802
+ //#endregion
803
+ //#region src/disposal/schedule.ts
804
+ /**
805
+ * `scheduler.schedule` is called with no arguments at the end of an outermost
806
+ * operation after the cleanup queue went from empty to non-empty, or after a
807
+ * `disposeOlderThanUpdates` that left entries. A `writeSource` to a source that
808
+ * has no dependents, or that no computation read since the source was created
809
+ * or last written, returns before that call. `schedule` may call `disposeAll`
810
+ * synchronously. The default calls `disposeOlderThanUpdates(2)` once per call
811
+ * of `schedule`, with the time of a `requestIdleCallback` callback where that
812
+ * exists and of a 5 ms `setTimeout` task elsewhere, and requests another
813
+ * callback or task only when that drain ran out of time before an old entry.
814
+ * Assigning `scheduler.schedule` replaces the default.
815
+ *
816
+ * Contract: after a call, the scheduler calls `disposeNext` until it returns
817
+ * false, calls `disposeAll`, or calls `disposeOlderThanUpdates` once.
818
+ */
819
+ const scheduler = { schedule: scheduleCleanupDuringIdleTime };
820
+ function scheduleCleanupDuringIdleTime() {
821
+ if (defaultScheduleStatus === 1) return;
822
+ defaultScheduleStatus = 1;
823
+ if (typeof requestIdleCallback === "function") requestIdleCallback(disposeOldNodesWithinTimeBudget);
824
+ else setTimeout(disposeOldNodesWithinTimeBudget, 0);
825
+ }
826
+ /**
827
+ * One drain with the idle period's time, or 5 ms in a `setTimeout` task,
828
+ * which passes no deadline. A drain disposes at least one old entry before it
829
+ * checks the time, so each callback that a cut-off requests makes progress. A
830
+ * drain that leaves only young entries requests nothing: the next outermost
831
+ * operation calls `schedule` again.
832
+ */
833
+ function disposeOldNodesWithinTimeBudget(deadline) {
834
+ defaultScheduleStatus = 0;
835
+ if (cleanupQueue.length === 0) return;
836
+ disposeOlderThanUpdates(DEFAULT_MIN_AGE, deadline ?? performance.now() + TIMEOUT_DISPOSAL_MS);
837
+ if (drainReachedTimeLimit) {
838
+ clearPendingCleanupRequest();
839
+ scheduleCleanupDuringIdleTime();
840
+ }
841
+ }
842
+ const DEFAULT_MIN_AGE = 2;
843
+ const TIMEOUT_DISPOSAL_MS = 5;
844
+ let defaultScheduleStatus = 0;
845
+ function scheduleCleanupIfRequested() {
846
+ if (scheduleStatus === 1) {
847
+ clearPendingCleanupRequest();
848
+ scheduler.schedule();
849
+ }
850
+ }
851
+
852
+ //#endregion
853
+ //#region src/batch/batch.ts
854
+ /** Stage a write in the open batch, or publish it immediately when no batch is open. */
855
+ function writeSource(source, value) {
856
+ if (firstPendingSource !== CLOSED_BATCH) {
857
+ const pending = source;
858
+ if (firstPendingSource === pending) firstPendingValue = value;
859
+ else if (firstPendingSource === void 0) {
860
+ firstPendingSource = pending;
861
+ firstPendingValue = value;
862
+ } else (otherWrites ??= /* @__PURE__ */ new Map()).set(pending, value);
863
+ return;
864
+ }
865
+ const firstDependentToMark = storeSourceValueAndFindDependentsToMark(source, value);
866
+ if (firstDependentToMark === void 0) return;
867
+ flushQueuedNodesOrDisposeMarkedNodes(markDependentsOfWrittenSource(void 0, firstDependentToMark));
868
+ countUpdateAndScheduleCleanupIfIdle();
869
+ }
870
+ const CLOSED_BATCH = Symbol("closed batch");
871
+ let firstPendingSource = CLOSED_BATCH;
872
+ let firstPendingValue;
873
+ let otherWrites;
874
+ function flushQueuedNodesOrDisposeMarkedNodes(queue) {
875
+ if (queue !== void 0) refreshQueuedNodesAndNotifyCallbacks(queue);
876
+ else if (markedUnneededCount > 0) disposeMarkedUnneededNodes();
877
+ }
878
+ function countUpdateAndScheduleCleanupIfIdle() {
879
+ if (flushState === 0) {
880
+ incrementUpdateCount();
881
+ scheduleCleanupIfRequested();
882
+ }
883
+ }
884
+ /** Open one synchronous write batch. Callers must not nest batches or read or retain nodes inside one. */
885
+ function startWriteBatch() {
886
+ if (firstPendingSource !== CLOSED_BATCH) throw new Error("A write batch is already open.");
887
+ firstPendingSource = void 0;
888
+ }
889
+ /** Publish the last write to each source, refresh the graph, then notify subscribers. */
890
+ function endWriteBatch() {
891
+ const source = firstPendingSource;
892
+ if (source === CLOSED_BATCH) return;
893
+ firstPendingSource = CLOSED_BATCH;
894
+ let queue;
895
+ if (source !== void 0) {
896
+ const firstDependentToMark = storeSourceValueAndFindDependentsToMark(source, firstPendingValue);
897
+ firstPendingValue = void 0;
898
+ if (firstDependentToMark !== void 0) queue = markDependentsOfWrittenSource(void 0, firstDependentToMark);
899
+ if (otherWrites !== void 0) {
900
+ for (const [other, value] of otherWrites) {
901
+ const edge = storeSourceValueAndFindDependentsToMark(other, value);
902
+ if (edge !== void 0) queue = markDependentsOfWrittenSource(queue, edge);
903
+ }
904
+ otherWrites = void 0;
905
+ }
906
+ }
907
+ flushQueuedNodesOrDisposeMarkedNodes(queue);
908
+ countUpdateAndScheduleCleanupIfIdle();
909
+ }
910
+ /**
911
+ * An outermost operation is a call to `writeSource`, `endWriteBatch`,
912
+ * `retainDerivedNode`, `releaseRetain`, or `readDerivedOutsideComputation` made with no
913
+ * batch open and no flush running, or the `endWriteBatch` that commits the writes.
914
+ *
915
+ * Internal invariant: a top-level read never runs inside a computation or a
916
+ * batch body (its contract), so a top-level read inside an `onChange` is the
917
+ * only nesting of operations outside a batch, and the flush state covers it.
918
+ */
919
+ function scheduleCleanupIfOutsideBatchAndFlush() {
920
+ if (firstPendingSource === CLOSED_BATCH && flushState === 0) scheduleCleanupIfRequested();
921
+ }
922
+ /**
923
+ * Top-level reads are forbidden in batch bodies. An onChange callback can
924
+ * still read during a flush.
925
+ */
926
+ function scheduleCleanupIfNotFlushing() {
927
+ if (flushState === 0) scheduleCleanupIfRequested();
928
+ }
929
+
930
+ //#endregion
931
+ //#region src/graph/read.ts
932
+ /**
933
+ * Returns the value of `source` and records it as a dependency of
934
+ * `callingNode`.
935
+ *
936
+ * Contract: called only while the computation of `callingNode` runs.
937
+ */
938
+ function readSource(callingNode, source) {
939
+ const mutableCallingNode = callingNode;
940
+ const mutableSource = source;
941
+ mutableSource.dependentsStatus = 0;
942
+ const lastReadEdge = mutableCallingNode.lastSourceDependency;
943
+ const reusableEdge = lastReadEdge === void 0 ? mutableCallingNode.firstSourceDependency : lastReadEdge.nextDependencyEdge;
944
+ if (reusableEdge !== void 0) {
945
+ if (reusableEdge.dependency !== mutableSource) {
946
+ removeEdgeFromSourceDependents(reusableEdge);
947
+ reusableEdge.dependency = mutableSource;
948
+ addEdgeToSourceDependents(reusableEdge);
949
+ }
950
+ mutableCallingNode.lastSourceDependency = reusableEdge;
951
+ } else if (lastReadEdge === void 0 || lastReadEdge.dependency !== mutableSource) {
952
+ const edge = createSourceEdge(mutableSource, mutableCallingNode);
953
+ addEdgeToSourceDependents(edge);
954
+ if (lastReadEdge === void 0) mutableCallingNode.firstSourceDependency = edge;
955
+ else lastReadEdge.nextDependencyEdge = edge;
956
+ mutableCallingNode.lastSourceDependency = edge;
957
+ }
958
+ return source.value;
959
+ }
960
+ /**
961
+ * Brings `node` up to date, returns its value, and records it as a dependency
962
+ * of `callingNode`.
963
+ *
964
+ * Contract: called only while the computation of `callingNode` runs.
965
+ */
966
+ function readDerived(callingNode, node) {
967
+ const mutableCallingNode = callingNode;
968
+ const mutableNode = node;
969
+ const value = getCurrentDerivedValue(mutableNode);
970
+ const lastReadEdge = mutableCallingNode.lastDerivedDependency;
971
+ const reusableEdge = lastReadEdge === void 0 ? mutableCallingNode.firstDerivedDependency : lastReadEdge.nextDependencyEdge;
972
+ if (reusableEdge !== void 0) {
973
+ if (reusableEdge.dependency !== mutableNode) {
974
+ const previousDependency = reusableEdge.dependency;
975
+ removeEdgeFromDerivedDependents(reusableEdge);
976
+ reusableEdge.dependency = mutableNode;
977
+ addEdgeToDerivedDependents(reusableEdge);
978
+ if (previousDependency.firstDependent === void 0 && previousDependency.firstRetain === void 0) addToCleanupQueue(previousDependency);
979
+ } else if (mutableNode.firstKnownMarkedDependentEdge !== void 0) moveEdgeBeforeKnownMarkedDependents(reusableEdge);
980
+ mutableCallingNode.lastDerivedDependency = reusableEdge;
981
+ } else if (lastReadEdge === void 0 || lastReadEdge.dependency !== mutableNode) {
982
+ const edge = {
983
+ dependency: mutableNode,
984
+ dependent: mutableCallingNode,
985
+ nextDependencyEdge: void 0,
986
+ previousDependentEdge: void 0,
987
+ nextDependentEdge: void 0
988
+ };
989
+ addEdgeToDerivedDependents(edge);
990
+ if (lastReadEdge === void 0) mutableCallingNode.firstDerivedDependency = edge;
991
+ else lastReadEdge.nextDependencyEdge = edge;
992
+ mutableCallingNode.lastDerivedDependency = edge;
993
+ }
994
+ return value;
995
+ }
996
+ /**
997
+ * Top-level read of `node`: brings `node` up to date and returns its value. A
998
+ * recompute links edges as in a tracked read. A node left unneeded goes on the
999
+ * cleanup queue, so the scheduler can dispose it and each dependency that its
1000
+ * disposal leaves unneeded.
1001
+ *
1002
+ * Contract: called outside computations and write batch bodies. Inside an
1003
+ * `onChange`, it is allowed.
1004
+ */
1005
+ function readDerivedOutsideComputation(node) {
1006
+ const mutableNode = node;
1007
+ const value = getCurrentDerivedValue(mutableNode);
1008
+ if (mutableNode.firstRetain === void 0 && mutableNode.firstDependent === void 0) addToCleanupQueue(mutableNode);
1009
+ scheduleCleanupIfNotFlushing();
1010
+ return value;
1011
+ }
1012
+
1013
+ //#endregion
1014
+ //#region src/retention/retain.ts
1015
+ /**
1016
+ * Brings `node` up to date, adds a retain to the head of its retain list, and
1017
+ * returns the retain. A retained node keeps its value and its edges to its
1018
+ * dependencies until its last retain is released. A retain with an
1019
+ * `onChange` gives the node a callback.
1020
+ *
1021
+ * Guarantee: the flush calls `onChange` with the node's value once for each
1022
+ * update or batch that changed the node's value, after the flush has
1023
+ * refreshed every node on the flush queue. The first recompute of a node does
1024
+ * not call `onChange`.
1025
+ *
1026
+ * Contract: called outside computations, `onChange` callbacks, and write
1027
+ * batch bodies, because retaining computes the node. `onChange` does not
1028
+ * write, start or end a batch, retain, release, or dispose. It may call
1029
+ * `readDerivedOutsideComputation`.
1030
+ */
1031
+ function retainDerivedNode(node, onChange) {
1032
+ const mutableNode = node;
1033
+ getCurrentDerivedValue(mutableNode);
1034
+ const head = mutableNode.firstRetain;
1035
+ const retain = {
1036
+ node: mutableNode,
1037
+ onChange,
1038
+ previousRetain: void 0,
1039
+ nextRetain: head
1040
+ };
1041
+ if (head !== void 0) head.previousRetain = retain;
1042
+ mutableNode.firstRetain = retain;
1043
+ if (onChange !== void 0) mutableNode.callbackState = 1;
1044
+ scheduleCleanupIfRequested();
1045
+ return retain;
1046
+ }
1047
+ /**
1048
+ * Releases `retain`. A release that leaves the node unneeded puts the node on
1049
+ * the cleanup queue. The node keeps its value and its edges until a disposal,
1050
+ * or the marking of a write, reaches it.
1051
+ *
1052
+ * Contract: called once per retain, outside computations and `onChange`
1053
+ * callbacks.
1054
+ */
1055
+ function releaseRetain(retain) {
1056
+ const mutableRetain = retain;
1057
+ const mutableNode = mutableRetain.node;
1058
+ mutableRetain.node = void 0;
1059
+ const previous = mutableRetain.previousRetain;
1060
+ const next = mutableRetain.nextRetain;
1061
+ if (previous === void 0) mutableNode.firstRetain = next;
1062
+ else {
1063
+ previous.nextRetain = next;
1064
+ mutableRetain.previousRetain = void 0;
1065
+ }
1066
+ if (next !== void 0) {
1067
+ next.previousRetain = previous;
1068
+ mutableRetain.nextRetain = void 0;
1069
+ }
1070
+ if (mutableRetain.onChange !== void 0) {
1071
+ mutableRetain.onChange = void 0;
1072
+ clearCallbackStateIfNoCallbackRetainsRemain(mutableNode);
1073
+ }
1074
+ if (mutableNode.firstRetain === void 0 && mutableNode.firstDependent === void 0) addToCleanupQueue(mutableNode);
1075
+ scheduleCleanupIfOutsideBatchAndFlush();
1076
+ }
1077
+ /**
1078
+ * Internal invariant: a node that loses its last callback while `DIRTY` or
1079
+ * `MAYBE_DIRTY` has no `CLEAN` dependents, and its dependents may be
1080
+ * `MAYBE_DIRTY` with `MARKED_BEYOND`, waiting for its refresh to put the
1081
+ * nodes with callbacks among them on the flush queue. The walk through lazy nodes
1082
+ * from the node clears that bit on them, as the dependents of a lazy node that
1083
+ * is `DIRTY` or `MAYBE_DIRTY` require, and puts those nodes with callbacks on the
1084
+ * flush queue. A node that gets a callback was brought
1085
+ * up to date first, so it is `CLEAN`.
1086
+ */
1087
+ function clearCallbackStateIfNoCallbackRetainsRemain(node) {
1088
+ if (hasOnChangeRetain(node)) return;
1089
+ node.callbackState = 0;
1090
+ if (node.status !== 3) flushQueuedNodesOrDisposeMarkedNodes(markTransitiveDependentsMaybeDirty(void 0, node, void 0, void 0));
1091
+ }
1092
+ function hasOnChangeRetain(node) {
1093
+ let retain = node.firstRetain;
1094
+ while (retain !== void 0) {
1095
+ if (retain.onChange !== void 0) return true;
1096
+ retain = retain.nextRetain;
1097
+ }
1098
+ return false;
1099
+ }
1100
+
1101
+ //#endregion
1102
+ //#region src/disposal/take.ts
1103
+ /**
1104
+ * Empties the cleanup queue and returns the node of each entry whose node is
1105
+ * still unneeded and not `UNCOMPUTED`, oldest entry first. A node with several
1106
+ * entries appears once per entry. pico-js no longer holds a taken node for
1107
+ * disposal: it queues the node again only when the node becomes unneeded again
1108
+ * after it is needed, or on a top-level read while it is unneeded.
1109
+ *
1110
+ * Contract: called outside computations, batches, and `onChange` callbacks.
1111
+ */
1112
+ function takeUnneeded() {
1113
+ const taken = cleanupQueue.filter(isUnneededComputedNode);
1114
+ cleanupQueue.length = 0;
1115
+ clearPendingCleanupRequest();
1116
+ return taken;
1117
+ }
1118
+ function isUnneededComputedNode(node) {
1119
+ return node.firstRetain === void 0 && node.firstDependent === void 0 && node.status !== 0;
1120
+ }
1121
+ /**
1122
+ * Disposes `node` if it is unneeded and not `UNCOMPUTED`, and returns whether
1123
+ * it did. The dependencies that the disposal leaves unneeded go on the cleanup
1124
+ * queue.
1125
+ *
1126
+ * Contract: called outside computations, batches, and `onChange` callbacks.
1127
+ */
1128
+ function disposeIfUnneeded(node) {
1129
+ const mutableNode = node;
1130
+ if (!isUnneededComputedNode(mutableNode)) return false;
1131
+ const wasEmpty = cleanupQueue.length === 0;
1132
+ disposeNode(mutableNode, 0, void 0);
1133
+ if (wasEmpty && cleanupQueue.length > 0) requestCleanupScheduling();
1134
+ return true;
1135
+ }
1136
+
1137
+ //#endregion
1138
+ export { createDerivedNode, createSourceNode, disposeAll, disposeIfUnneeded, disposeNext, disposeOlderThanUpdates, endWriteBatch, readDerived, readDerivedOutsideComputation, readSource, releaseRetain, retainDerivedNode, scheduler, startWriteBatch, takeUnneeded, writeSource };
1139
+ //# sourceMappingURL=index.mjs.map