@solidjs/signals 0.7.5 → 0.8.1

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/dev.js CHANGED
@@ -1,8 +1,8 @@
1
1
  // src/core/error.ts
2
2
  var NotReadyError = class extends Error {
3
- constructor(node) {
3
+ constructor(cause) {
4
4
  super();
5
- this.cause = node;
5
+ this.cause = cause;
6
6
  }
7
7
  };
8
8
  var NoOwnerError = class extends Error {
@@ -19,31 +19,136 @@ var ContextNotFoundError = class extends Error {
19
19
  };
20
20
 
21
21
  // src/core/constants.ts
22
- var STATE_CLEAN = 0;
23
- var STATE_CHECK = 1;
24
- var STATE_DIRTY = 2;
25
- var STATE_DISPOSED = 3;
26
- var EFFECT_PURE = 0;
27
- var EFFECT_RENDER = 1;
28
- var EFFECT_USER = 2;
22
+ var NOT_PENDING = {};
29
23
  var SUPPORTS_PROXY = typeof Proxy === "function";
30
24
 
31
- // src/core/flags.ts
32
- var ERROR_OFFSET = 0;
33
- var ERROR_BIT = 1 << ERROR_OFFSET;
34
- var LOADING_OFFSET = 1;
35
- var LOADING_BIT = 1 << LOADING_OFFSET;
36
- var UNINITIALIZED_OFFSET = 2;
37
- var UNINITIALIZED_BIT = 1 << UNINITIALIZED_OFFSET;
38
- var DEFAULT_FLAGS = ERROR_BIT;
25
+ // src/core/heap.ts
26
+ function actualInsertIntoHeap(n, heap) {
27
+ const parentHeight = (n._parent?._root ? n._parent._parentComputed?._height : n._parent?._height) ?? -1;
28
+ if (parentHeight >= n._height)
29
+ n._height = parentHeight + 1;
30
+ const height = n._height;
31
+ const heapAtHeight = heap._heap[height];
32
+ if (heapAtHeight === void 0) {
33
+ heap._heap[height] = n;
34
+ } else {
35
+ const tail = heapAtHeight._prevHeap;
36
+ tail._nextHeap = n;
37
+ n._prevHeap = tail;
38
+ heapAtHeight._prevHeap = n;
39
+ }
40
+ if (height > heap._max) {
41
+ heap._max = height;
42
+ }
43
+ }
44
+ function insertIntoHeap(n, heap) {
45
+ let flags = n._flags;
46
+ if (flags & (8 /* InHeap */ | 4 /* RecomputingDeps */))
47
+ return;
48
+ if (flags & 1 /* Check */) {
49
+ n._flags = flags & ~(1 /* Check */ | 2 /* Dirty */) | 2 /* Dirty */ | 8 /* InHeap */;
50
+ } else
51
+ n._flags = flags | 8 /* InHeap */;
52
+ if (!(flags & 16 /* InHeapHeight */)) {
53
+ actualInsertIntoHeap(n, heap);
54
+ }
55
+ }
56
+ function insertIntoHeapHeight(n, heap) {
57
+ let flags = n._flags;
58
+ if (flags & (8 /* InHeap */ | 4 /* RecomputingDeps */ | 16 /* InHeapHeight */))
59
+ return;
60
+ n._flags = flags | 16 /* InHeapHeight */;
61
+ actualInsertIntoHeap(n, heap);
62
+ }
63
+ function deleteFromHeap(n, heap) {
64
+ const flags = n._flags;
65
+ if (!(flags & (8 /* InHeap */ | 16 /* InHeapHeight */)))
66
+ return;
67
+ n._flags = flags & ~(8 /* InHeap */ | 16 /* InHeapHeight */);
68
+ const height = n._height;
69
+ if (n._prevHeap === n) {
70
+ heap._heap[height] = void 0;
71
+ } else {
72
+ const next = n._nextHeap;
73
+ const dhh = heap._heap[height];
74
+ const end = next ?? dhh;
75
+ if (n === dhh) {
76
+ heap._heap[height] = next;
77
+ } else {
78
+ n._prevHeap._nextHeap = next;
79
+ }
80
+ end._prevHeap = n._prevHeap;
81
+ }
82
+ n._prevHeap = n;
83
+ n._nextHeap = void 0;
84
+ }
85
+ function markHeap(heap) {
86
+ if (heap._marked)
87
+ return;
88
+ heap._marked = true;
89
+ for (let i = 0; i <= heap._max; i++) {
90
+ for (let el = heap._heap[i]; el !== void 0; el = el._nextHeap) {
91
+ if (el._flags & 8 /* InHeap */)
92
+ markNode(el);
93
+ }
94
+ }
95
+ }
96
+ function markNode(el, newState = 2 /* Dirty */) {
97
+ const flags = el._flags;
98
+ if ((flags & (1 /* Check */ | 2 /* Dirty */)) >= newState)
99
+ return;
100
+ el._flags = flags & ~(1 /* Check */ | 2 /* Dirty */) | newState;
101
+ for (let link2 = el._subs; link2 !== null; link2 = link2._nextSub) {
102
+ markNode(link2._sub, 1 /* Check */);
103
+ }
104
+ if (el._child !== null) {
105
+ for (let child = el._child; child !== null; child = child._nextChild) {
106
+ for (let link2 = child._subs; link2 !== null; link2 = link2._nextSub) {
107
+ markNode(link2._sub, 1 /* Check */);
108
+ }
109
+ }
110
+ }
111
+ }
112
+ function runHeap(heap, recompute2) {
113
+ heap._marked = false;
114
+ for (heap._min = 0; heap._min <= heap._max; heap._min++) {
115
+ let el = heap._heap[heap._min];
116
+ while (el !== void 0) {
117
+ if (el._flags & 8 /* InHeap */)
118
+ recompute2(el);
119
+ else {
120
+ adjustHeight(el, heap);
121
+ }
122
+ el = heap._heap[heap._min];
123
+ }
124
+ }
125
+ heap._max = 0;
126
+ }
127
+ function adjustHeight(el, heap) {
128
+ deleteFromHeap(el, heap);
129
+ let newHeight = el._height;
130
+ for (let d = el._deps; d; d = d._nextDep) {
131
+ const dep1 = d._dep;
132
+ const dep = "_owner" in dep1 ? dep1._owner : dep1;
133
+ if ("_fn" in dep) {
134
+ if (dep._height >= newHeight) {
135
+ newHeight = dep._height + 1;
136
+ }
137
+ }
138
+ }
139
+ if (el._height !== newHeight) {
140
+ el._height = newHeight;
141
+ for (let s = el._subs; s !== null; s = s._nextSub) {
142
+ insertIntoHeapHeight(s._sub, heap);
143
+ }
144
+ }
145
+ }
39
146
 
40
147
  // src/core/scheduler.ts
41
148
  var clock = 0;
42
- function incrementClock() {
43
- clock++;
44
- }
45
- var ActiveTransition = null;
46
- var Unobserved = [];
149
+ var activeTransition = null;
150
+ var unobserved = [];
151
+ var transitions = /* @__PURE__ */ new Set();
47
152
  var scheduled = false;
48
153
  function schedule() {
49
154
  if (scheduled)
@@ -52,33 +157,41 @@ function schedule() {
52
157
  if (!globalQueue._running)
53
158
  queueMicrotask(flush);
54
159
  }
55
- function notifyUnobserved() {
56
- for (let i = 0; i < Unobserved.length; i++) {
57
- const source = Unobserved[i];
58
- if (!source._observers || !source._observers.length)
59
- Unobserved[i]._unobserved?.();
60
- }
61
- Unobserved = [];
62
- }
63
- var pureQueue = [];
160
+ var dirtyQueue = {
161
+ _heap: new Array(2e3).fill(void 0),
162
+ _marked: false,
163
+ _min: 0,
164
+ _max: 0
165
+ };
166
+ var zombieQueue = {
167
+ _heap: new Array(2e3).fill(void 0),
168
+ _marked: false,
169
+ _min: 0,
170
+ _max: 0
171
+ };
64
172
  var Queue = class {
65
173
  _parent = null;
66
- _running = false;
67
174
  _queues = [[], []];
68
175
  _children = [];
69
176
  created = clock;
70
- enqueue(type, fn) {
71
- pureQueue.push(fn);
72
- if (type)
73
- this._queues[type - 1].push(fn);
74
- schedule();
177
+ addChild(child) {
178
+ this._children.push(child);
179
+ child._parent = this;
180
+ }
181
+ removeChild(child) {
182
+ const index = this._children.indexOf(child);
183
+ if (index >= 0) {
184
+ this._children.splice(index, 1);
185
+ child._parent = null;
186
+ }
187
+ }
188
+ notify(node, mask, flags) {
189
+ if (this._parent)
190
+ return this._parent.notify(node, mask, flags);
191
+ return false;
75
192
  }
76
193
  run(type) {
77
- if (type === EFFECT_PURE) {
78
- pureQueue.length && runQueue(pureQueue, type);
79
- pureQueue = [];
80
- return;
81
- } else if (this._queues[type - 1].length) {
194
+ if (this._queues[type - 1].length) {
82
195
  const effects = this._queues[type - 1];
83
196
  this._queues[type - 1] = [];
84
197
  runQueue(effects, type);
@@ -87,54 +200,109 @@ var Queue = class {
87
200
  this._children[i].run(type);
88
201
  }
89
202
  }
203
+ enqueue(type, fn) {
204
+ if (type)
205
+ this._queues[type - 1].push(fn);
206
+ schedule();
207
+ }
208
+ };
209
+ var GlobalQueue = class _GlobalQueue extends Queue {
210
+ _running = false;
211
+ _pendingNodes = [];
212
+ static _update;
213
+ static _dispose;
90
214
  flush() {
91
215
  if (this._running)
92
216
  return;
93
217
  this._running = true;
94
218
  try {
95
- this.run(EFFECT_PURE);
96
- incrementClock();
219
+ runHeap(dirtyQueue, _GlobalQueue._update);
220
+ if (activeTransition) {
221
+ if (!transitionComplete(activeTransition)) {
222
+ runHeap(zombieQueue, _GlobalQueue._update);
223
+ globalQueue._pendingNodes = [];
224
+ activeTransition.queues[0].push(...globalQueue._queues[0]);
225
+ activeTransition.queues[1].push(...globalQueue._queues[1]);
226
+ globalQueue._queues = [[], []];
227
+ clock++;
228
+ scheduled = false;
229
+ runPending(activeTransition.pendingNodes, true);
230
+ activeTransition = null;
231
+ return;
232
+ }
233
+ globalQueue._pendingNodes.push(...activeTransition.pendingNodes);
234
+ globalQueue._queues[0].push(...activeTransition.queues[0]);
235
+ globalQueue._queues[1].push(...activeTransition.queues[1]);
236
+ transitions.delete(activeTransition);
237
+ activeTransition = null;
238
+ if (runPending(globalQueue._pendingNodes, false))
239
+ runHeap(dirtyQueue, _GlobalQueue._update);
240
+ } else if (transitions.size)
241
+ runHeap(zombieQueue, _GlobalQueue._update);
242
+ for (let i = 0; i < globalQueue._pendingNodes.length; i++) {
243
+ const n = globalQueue._pendingNodes[i];
244
+ if (n._pendingValue !== NOT_PENDING) {
245
+ n._value = n._pendingValue;
246
+ n._pendingValue = NOT_PENDING;
247
+ }
248
+ if (n._fn)
249
+ _GlobalQueue._dispose(n, false, true);
250
+ }
251
+ globalQueue._pendingNodes.length = 0;
252
+ clock++;
97
253
  scheduled = false;
98
- this.run(EFFECT_RENDER);
99
- this.run(EFFECT_USER);
254
+ this.run(1 /* Render */);
255
+ this.run(2 /* User */);
100
256
  } finally {
101
257
  this._running = false;
102
- Unobserved.length && notifyUnobserved();
258
+ unobserved.length && notifyUnobserved();
103
259
  }
104
260
  }
105
- addChild(child) {
106
- if (ActiveTransition && ActiveTransition._clonedQueues.has(this))
107
- return ActiveTransition._clonedQueues.get(this).addChild(child);
108
- this._children.push(child);
109
- child._parent = this;
110
- }
111
- removeChild(child) {
112
- if (ActiveTransition && ActiveTransition._clonedQueues.has(this))
113
- return ActiveTransition._clonedQueues.get(this).removeChild(child);
114
- const index = this._children.indexOf(child);
115
- if (index >= 0) {
116
- this._children.splice(index, 1);
117
- child._parent = null;
261
+ notify(node, mask, flags) {
262
+ if (mask & 1 /* Pending */) {
263
+ if (flags & 1 /* Pending */) {
264
+ if (activeTransition && !activeTransition.asyncNodes.includes(node._error.cause))
265
+ activeTransition.asyncNodes.push(node._error.cause);
266
+ }
267
+ return true;
118
268
  }
119
- }
120
- notify(...args) {
121
- if (this._parent)
122
- return this._parent.notify(...args);
123
269
  return false;
124
270
  }
125
- merge(queue) {
126
- this._queues[0].push.apply(this._queues[0], queue._queues[0]);
127
- this._queues[1].push.apply(this._queues[1], queue._queues[1]);
128
- for (let i = 0; i < queue._children.length; i++) {
129
- const og = this._children.find((c) => c._cloned === queue._children[i]._cloned);
130
- if (og)
131
- og.merge(queue._children[i]);
132
- else
133
- this.addChild(queue._children[i]);
271
+ initTransition(node) {
272
+ if (activeTransition && activeTransition.time === clock)
273
+ return;
274
+ if (!activeTransition) {
275
+ activeTransition = node._transition ?? {
276
+ time: clock,
277
+ pendingNodes: [],
278
+ asyncNodes: [],
279
+ queues: [[], []]
280
+ };
281
+ }
282
+ transitions.add(activeTransition);
283
+ activeTransition.time = clock;
284
+ for (let i = 0; i < globalQueue._pendingNodes.length; i++) {
285
+ const n = globalQueue._pendingNodes[i];
286
+ n._transition = activeTransition;
287
+ activeTransition.pendingNodes.push(n);
134
288
  }
289
+ globalQueue._pendingNodes = activeTransition.pendingNodes;
135
290
  }
136
291
  };
137
- var globalQueue = new Queue();
292
+ function runPending(pendingNodes, value) {
293
+ let needsReset = false;
294
+ const p = pendingNodes.slice();
295
+ for (let i = 0; i < p.length; i++) {
296
+ const n = p[i];
297
+ n._transition = activeTransition;
298
+ if (n._pendingCheck) {
299
+ n._pendingCheck._set(value);
300
+ needsReset = true;
301
+ }
302
+ }
303
+ return needsReset;
304
+ }
305
+ var globalQueue = new GlobalQueue();
138
306
  function flush() {
139
307
  let count = 0;
140
308
  while (scheduled) {
@@ -143,826 +311,621 @@ function flush() {
143
311
  globalQueue.flush();
144
312
  }
145
313
  }
146
- function removeSourceObservers(node, index) {
147
- let source;
148
- let swap;
149
- for (let i = index; i < node._sources.length; i++) {
150
- source = getTransitionSource(node._sources[i]);
151
- if (source._observers) {
152
- if ((swap = source._observers.indexOf(node)) !== -1) {
153
- source._observers[swap] = source._observers[source._observers.length - 1];
154
- source._observers.pop();
155
- }
156
- if (!source._observers.length)
157
- Unobserved.push(source);
158
- }
159
- }
160
- }
161
314
  function runQueue(queue, type) {
162
315
  for (let i = 0; i < queue.length; i++)
163
316
  queue[i](type);
164
317
  }
165
- var Transition = class _Transition {
166
- _sources = /* @__PURE__ */ new Map();
167
- _pendingNodes = /* @__PURE__ */ new Set();
168
- _promises = /* @__PURE__ */ new Set();
169
- _optimistic = /* @__PURE__ */ new Set();
170
- _done = false;
171
- _queues = [[], []];
172
- _clonedQueues = /* @__PURE__ */ new Map();
173
- _pureQueue = [];
174
- _children = [];
175
- _parent = null;
176
- _running = false;
177
- _scheduled = false;
178
- _cloned = globalQueue;
179
- _signal;
180
- created = clock;
181
- constructor(signal) {
182
- this._signal = signal;
183
- this._clonedQueues.set(globalQueue, this);
184
- for (const child of globalQueue._children) {
185
- cloneQueue(child, this, this);
318
+ function transitionComplete(transition) {
319
+ let done = true;
320
+ for (let i = 0; i < transition.asyncNodes.length; i++) {
321
+ if (transition.asyncNodes[i]._statusFlags & 1 /* Pending */) {
322
+ done = false;
323
+ break;
186
324
  }
187
325
  }
188
- enqueue(type, fn) {
189
- this._pureQueue.push(fn);
190
- if (type)
191
- this._queues[type - 1].push(fn);
192
- this.schedule();
193
- }
194
- run(type) {
195
- if (type === EFFECT_PURE) {
196
- this._pureQueue.length && runQueue(this._pureQueue, type);
197
- this._pureQueue = [];
198
- return;
199
- } else if (this._queues[type - 1].length) {
200
- const effects = this._queues[type - 1];
201
- this._queues[type - 1] = [];
202
- runQueue(effects, type);
203
- }
204
- for (let i = 0; i < this._children.length; i++) {
205
- this._children[i].run(type);
206
- }
326
+ return done;
327
+ }
328
+ function notifyUnobserved() {
329
+ for (let i = 0; i < unobserved.length; i++) {
330
+ const source = unobserved[i];
331
+ if (!source._subs)
332
+ unobserved[i]._unobserved?.();
207
333
  }
208
- flush() {
209
- if (this._running || this._done)
210
- return;
211
- globalQueue.flush();
212
- this._running = true;
213
- let currentTransition = ActiveTransition;
214
- ActiveTransition = this;
215
- try {
216
- this.run(EFFECT_PURE);
217
- incrementClock();
218
- this._scheduled = false;
219
- ActiveTransition = currentTransition;
220
- finishTransition(this);
221
- } finally {
222
- this._running = false;
223
- ActiveTransition = currentTransition;
334
+ unobserved = [];
335
+ }
336
+
337
+ // src/core/core.ts
338
+ GlobalQueue._update = recompute;
339
+ GlobalQueue._dispose = disposeChildren;
340
+ var tracking = false;
341
+ var stale = false;
342
+ var pendingValueCheck = false;
343
+ var pendingCheck = null;
344
+ var context = null;
345
+ var defaultContext = {};
346
+ function recompute(el, create = false) {
347
+ deleteFromHeap(el, el._flags & 32 /* Zombie */ ? zombieQueue : dirtyQueue);
348
+ if (el._pendingValue !== NOT_PENDING || el._pendingFirstChild || el._pendingDisposal)
349
+ disposeChildren(el);
350
+ else {
351
+ markDisposal(el);
352
+ globalQueue._pendingNodes.push(el);
353
+ el._pendingDisposal = el._disposal;
354
+ el._pendingFirstChild = el._firstChild;
355
+ el._disposal = null;
356
+ el._firstChild = null;
357
+ }
358
+ const oldcontext = context;
359
+ context = el;
360
+ el._depsTail = null;
361
+ el._flags = 4 /* RecomputingDeps */;
362
+ el._time = clock;
363
+ let value = el._pendingValue === NOT_PENDING ? el._value : el._pendingValue;
364
+ let oldHeight = el._height;
365
+ let prevStatusFlags = el._statusFlags;
366
+ let prevError = el._error;
367
+ let prevTracking = tracking;
368
+ clearStatusFlags(el);
369
+ tracking = true;
370
+ try {
371
+ value = el._fn(value);
372
+ } catch (e) {
373
+ if (e instanceof NotReadyError) {
374
+ if (e.cause !== el)
375
+ link(e.cause, el);
376
+ setStatusFlags(el, prevStatusFlags & ~2 /* Error */ | 1 /* Pending */, e);
377
+ } else {
378
+ setError(el, e);
224
379
  }
380
+ } finally {
381
+ tracking = prevTracking;
225
382
  }
226
- addChild(child) {
227
- this._children.push(child);
228
- child._parent = this;
229
- }
230
- removeChild(child) {
231
- const index = this._children.indexOf(child);
232
- if (index >= 0)
233
- this._children.splice(index, 1);
234
- }
235
- notify(node, type, flags) {
236
- if (!(type & LOADING_BIT))
237
- return false;
238
- if (flags & LOADING_BIT) {
239
- this._pendingNodes.add(node);
383
+ el._flags = 0 /* None */;
384
+ context = oldcontext;
385
+ const depsTail = el._depsTail;
386
+ let toRemove = depsTail !== null ? depsTail._nextDep : el._deps;
387
+ if (toRemove !== null) {
388
+ do {
389
+ toRemove = unlinkSubs(toRemove);
390
+ } while (toRemove !== null);
391
+ if (depsTail !== null) {
392
+ depsTail._nextDep = null;
240
393
  } else {
241
- this._pendingNodes.delete(node);
394
+ el._deps = null;
242
395
  }
243
- return true;
244
396
  }
245
- merge(queue) {
246
- this._queues[0].push.apply(this._queues[0], queue._queues[0]);
247
- this._queues[1].push.apply(this._queues[1], queue._queues[1]);
248
- this._pureQueue.push.apply(this._pureQueue, queue._pureQueue);
249
- queue._queues[0].length = 0;
250
- queue._queues[1].length = 0;
251
- queue._pureQueue.length = 0;
252
- for (let i = 0; i < queue._children.length; i++) {
253
- const og = this._children.find((c) => c._cloned === queue._children[i]._cloned);
254
- if (og)
255
- og.merge(queue._children[i]);
256
- else
257
- this.addChild(queue._children[i]);
258
- }
259
- }
260
- schedule() {
261
- if (this._scheduled)
262
- return;
263
- this._scheduled = true;
264
- if (!this._running)
265
- queueMicrotask(() => this.flush());
266
- }
267
- runTransition(fn, force = false) {
268
- if (this._done) {
269
- if (this._done instanceof _Transition)
270
- return this._done.runTransition(fn, force);
271
- if (!force)
272
- throw new Error("Transition already completed");
273
- fn();
274
- return;
275
- }
276
- ActiveTransition = this;
277
- try {
278
- let result = fn();
279
- let transition2 = ActiveTransition;
280
- if (result?.next) {
281
- (async function() {
282
- let temp, value;
283
- while (!(temp = result.next(value)).done) {
284
- transition2 = ActiveTransition;
285
- if (temp.value instanceof Promise) {
286
- transition2._promises.add(temp.value);
287
- try {
288
- value = await temp.value;
289
- } finally {
290
- transition2 = latestTransition(transition2);
291
- transition2._promises.delete(temp.value);
292
- }
293
- ActiveTransition = transition2;
294
- } else
295
- value = temp.value;
296
- }
297
- ActiveTransition = null;
298
- finishTransition(transition2);
299
- })();
300
- }
301
- if (result instanceof Promise) {
302
- transition2._promises.add(result);
303
- result.finally(() => {
304
- transition2 = latestTransition(transition2);
305
- transition2._promises.delete(result);
306
- ActiveTransition = null;
307
- finishTransition(transition2);
308
- });
397
+ const valueChanged = !el._equals || !el._equals(el._pendingValue === NOT_PENDING ? el._value : el._pendingValue, value);
398
+ const statusFlagsChanged = el._statusFlags !== prevStatusFlags || el._error !== prevError;
399
+ el._notifyQueue?.(statusFlagsChanged, prevStatusFlags);
400
+ if (valueChanged || statusFlagsChanged) {
401
+ if (valueChanged) {
402
+ if (create || el._optimistic || el._type)
403
+ el._value = value;
404
+ else {
405
+ if (el._pendingValue === NOT_PENDING)
406
+ globalQueue._pendingNodes.push(el);
407
+ el._pendingValue = value;
309
408
  }
310
- } finally {
311
- const transition2 = ActiveTransition;
312
- ActiveTransition = null;
313
- finishTransition(transition2);
409
+ if (el._pendingSignal)
410
+ el._pendingSignal._set(value);
314
411
  }
315
- }
316
- addOptimistic(fn) {
317
- if (fn._transition && fn._transition !== this) {
318
- mergeTransitions(fn._transition, this);
319
- ActiveTransition = fn._transition;
320
- return;
412
+ for (let s = el._subs; s !== null; s = s._nextSub) {
413
+ const queue = s._sub._flags & 32 /* Zombie */ ? zombieQueue : dirtyQueue;
414
+ if (s._sub._height < el._height && queue._min > s._sub._height)
415
+ queue._min = s._sub._height;
416
+ insertIntoHeap(s._sub, queue);
321
417
  }
322
- fn._transition = this;
323
- this._optimistic.add(fn);
324
- }
325
- };
326
- function cloneGraph(node) {
327
- if (node._optimistic) {
328
- if (node._state !== STATE_DISPOSED) {
329
- !node._transition && node._optimistic._init?.();
330
- ActiveTransition.addOptimistic(node._optimistic);
331
- }
332
- return node;
333
- }
334
- if (node._transition) {
335
- if (node._transition !== ActiveTransition) {
336
- mergeTransitions(node._transition, ActiveTransition);
337
- ActiveTransition = node._transition;
418
+ } else if (el._height != oldHeight) {
419
+ for (let s = el._subs; s !== null; s = s._nextSub) {
420
+ insertIntoHeapHeight(s._sub, s._sub._flags & 32 /* Zombie */ ? zombieQueue : dirtyQueue);
338
421
  }
339
- return node._transition._sources.get(node);
340
422
  }
341
- const clone = Object.create(Object.getPrototypeOf(node));
342
- Object.assign(clone, node, {
343
- _disposal: null,
344
- _nextSibling: null,
345
- _observers: null,
346
- _sources: node._sources ? [...node._sources] : null,
347
- _cloned: node
348
- });
349
- delete clone._prevValue;
350
- ActiveTransition._sources.set(node, clone);
351
- node._transition = ActiveTransition;
352
- if (node._sources) {
353
- for (let i = 0; i < node._sources.length; i++)
354
- node._sources[i]._observers.push(clone);
355
- }
356
- if (node._observers) {
357
- clone._observers = [];
358
- for (let i = 0, length = node._observers.length; i < length; i++) {
359
- !node._observers[i]._cloned && clone._observers.push(cloneGraph(node._observers[i]));
360
- }
361
- }
362
- return clone;
363
- }
364
- function latestTransition(t) {
365
- while (t._done instanceof Transition)
366
- t = t._done;
367
- return t;
368
- }
369
- function replaceSourceObservers(node, transition2) {
370
- let source;
371
- let transitionSource;
372
- let swap;
373
- for (let i = 0; i < node._sources.length; i++) {
374
- transitionSource = transition2._sources.get(node._sources[i]);
375
- source = transitionSource || node._sources[i];
376
- if (source._observers && (swap = source._observers.indexOf(node)) !== -1) {
377
- source._observers[swap] = transitionSource ? node._cloned : source._observers[source._observers.length - 1];
378
- !transitionSource && source._observers.pop();
379
- }
380
- }
381
- }
382
- function cloneQueue(queue, parent, transition2) {
383
- const clone = Object.create(Object.getPrototypeOf(queue));
384
- Object.assign(clone, queue, {
385
- _cloned: queue,
386
- _parent: parent,
387
- _children: [],
388
- enqueue(type, fn) {
389
- transition2 = latestTransition(transition2);
390
- transition2.enqueue(type, fn);
391
- },
392
- notify(node, type, flags) {
393
- node = node._cloned || node;
394
- if (!clone._collectionType || type & LOADING_BIT) {
395
- type &= ~LOADING_BIT;
396
- transition2 = latestTransition(transition2);
397
- transition2.notify(node, LOADING_BIT, flags);
398
- if (!type)
399
- return true;
423
+ }
424
+ function updateIfNecessary(el) {
425
+ if (el._flags & 1 /* Check */) {
426
+ for (let d = el._deps; d; d = d._nextDep) {
427
+ const dep1 = d._dep;
428
+ const dep = "_owner" in dep1 ? dep1._owner : dep1;
429
+ if ("_fn" in dep) {
430
+ updateIfNecessary(dep);
431
+ }
432
+ if (el._flags & 2 /* Dirty */) {
433
+ break;
400
434
  }
401
- return queue.notify.call(this, node, type, flags);
402
- }
403
- });
404
- parent._children.push(clone);
405
- transition2._clonedQueues.set(queue, clone);
406
- for (const child of queue._children) {
407
- cloneQueue(child, clone, transition2);
408
- }
409
- }
410
- function resolveQueues(children) {
411
- for (const child of children) {
412
- const og = child._cloned;
413
- if (og) {
414
- const clonedChildren = child._children;
415
- delete child.enqueue;
416
- delete child.notify;
417
- delete child._parent;
418
- delete child._children;
419
- Object.assign(og, child);
420
- delete og._cloned;
421
- resolveQueues(clonedChildren);
422
- } else if (child._parent._cloned) {
423
- child._parent._cloned.addChild(child);
424
- }
425
- }
426
- }
427
- function mergeTransitions(t1, t2) {
428
- t2._sources.forEach((value, key) => {
429
- key._transition = t1;
430
- t1._sources.set(key, value);
431
- });
432
- t2._optimistic.forEach((c) => {
433
- c._transition = t1;
434
- t1._optimistic.add(c);
435
- });
436
- t2._promises.forEach((p) => t1._promises.add(p));
437
- t2._pendingNodes.forEach((n) => t1._pendingNodes.add(n));
438
- t1.merge(t2);
439
- t2._done = t1;
440
- }
441
- function getTransitionSource(input) {
442
- return ActiveTransition && ActiveTransition._sources.get(input) || input;
443
- }
444
- function getQueue(node) {
445
- const transition2 = ActiveTransition || node._cloned?._transition;
446
- return transition2 && transition2._clonedQueues.get(node._queue) || node._queue;
447
- }
448
- function initialDispose(node) {
449
- let current = node._nextSibling;
450
- while (current !== null && current._parent === node) {
451
- initialDispose(current);
452
- const clone = ActiveTransition._sources.get(current);
453
- if (clone && !clone._updated)
454
- clone.dispose(true);
455
- current = current._nextSibling;
456
- }
457
- }
458
- function finishTransition(transition2) {
459
- if (transition2._done || transition2._scheduled || transition2._promises.size || transition2._pendingNodes.size)
460
- return;
461
- globalQueue._queues[0].push.apply(globalQueue._queues[0], transition2._queues[0]);
462
- globalQueue._queues[1].push.apply(globalQueue._queues[1], transition2._queues[1]);
463
- resolveQueues(transition2._children);
464
- for (const [source, clone] of transition2._sources) {
465
- if (source === clone || source._transition !== transition2) {
466
- delete source._transition;
467
- continue;
468
- }
469
- if (clone._sources)
470
- replaceSourceObservers(clone, transition2);
471
- if (clone._updated || clone._state === STATE_DISPOSED) {
472
- source.dispose(clone._state === STATE_DISPOSED);
473
- source.emptyDisposal();
474
- delete clone._updated;
475
- } else {
476
- delete clone._nextSibling;
477
- delete clone._disposal;
478
- }
479
- Object.assign(source, clone);
480
- delete source._cloned;
481
- let current = clone._nextSibling;
482
- if (current?._prevSibling === clone)
483
- current._prevSibling = source;
484
- while (current?._parent === clone) {
485
- current._parent = source;
486
- current = current._nextSibling;
487
435
  }
488
- delete source._transition;
489
436
  }
490
- transition2._done = true;
491
- for (const reset of transition2._optimistic) {
492
- delete reset._transition;
493
- reset();
437
+ if (el._flags & 2 /* Dirty */) {
438
+ recompute(el);
494
439
  }
495
- transition2._signal.write(true);
496
- globalQueue.flush();
497
- }
498
-
499
- // src/core/owner.ts
500
- var currentOwner = null;
501
- var defaultContext = {};
502
- function getOwner() {
503
- return currentOwner;
440
+ el._flags = 0 /* None */;
504
441
  }
505
- function setOwner(owner) {
506
- const out = currentOwner;
507
- currentOwner = owner;
508
- return out;
442
+ function unlinkSubs(link2) {
443
+ const dep = link2._dep;
444
+ const nextDep = link2._nextDep;
445
+ const nextSub = link2._nextSub;
446
+ const prevSub = link2._prevSub;
447
+ if (nextSub !== null) {
448
+ nextSub._prevSub = prevSub;
449
+ } else {
450
+ dep._subsTail = prevSub;
451
+ }
452
+ if (prevSub !== null) {
453
+ prevSub._nextSub = nextSub;
454
+ } else {
455
+ dep._subs = nextSub;
456
+ }
457
+ return nextDep;
509
458
  }
510
- var Owner = class {
511
- // We flatten the owner tree into a linked list so that we don't need a pointer to .firstChild
512
- // However, the children are actually added in reverse creation order
513
- // See comment at the top of the file for an example of the _nextSibling traversal
514
- _parent = null;
515
- _nextSibling = null;
516
- _prevSibling = null;
517
- _state = STATE_CLEAN;
518
- _disposal = null;
519
- _context = defaultContext;
520
- _queue = globalQueue;
521
- _childCount = 0;
522
- id = null;
523
- constructor(id = null, skipAppend = false) {
524
- this.id = id;
525
- if (currentOwner) {
526
- !skipAppend && currentOwner.append(this);
527
- }
528
- }
529
- append(child) {
530
- child._parent = this;
531
- child._prevSibling = this;
532
- if (this._nextSibling)
533
- this._nextSibling._prevSibling = child;
534
- child._nextSibling = this._nextSibling;
535
- this._nextSibling = child;
536
- if (this.id != null && child.id == null)
537
- child.id = this.getNextChildId();
538
- if (child._context !== this._context) {
539
- child._context = { ...this._context, ...child._context };
540
- }
541
- if (this._queue)
542
- child._queue = this._queue;
543
- }
544
- dispose(self = true) {
545
- if (this._state === STATE_DISPOSED)
546
- return;
547
- let head = self ? this._prevSibling || this._parent : this, current = this._nextSibling, next = null;
548
- while (current && current._parent === this) {
549
- current.dispose(true);
550
- next = current._nextSibling;
551
- current._nextSibling = null;
552
- current = next;
553
- }
554
- this._childCount = 0;
555
- if (self)
556
- this._disposeNode();
557
- if (current)
558
- current._prevSibling = !self ? this : this._prevSibling;
559
- if (head)
560
- head._nextSibling = current;
561
- }
562
- _disposeNode() {
563
- if (this._prevSibling)
564
- this._prevSibling._nextSibling = null;
565
- this._parent = null;
566
- this._prevSibling = null;
567
- this._context = defaultContext;
568
- this._state = STATE_DISPOSED;
569
- this.emptyDisposal();
570
- }
571
- emptyDisposal() {
572
- if (!this._disposal)
459
+ function link(dep, sub) {
460
+ const prevDep = sub._depsTail;
461
+ if (prevDep !== null && prevDep._dep === dep) {
462
+ return;
463
+ }
464
+ let nextDep = null;
465
+ const isRecomputing = sub._flags & 4 /* RecomputingDeps */;
466
+ if (isRecomputing) {
467
+ nextDep = prevDep !== null ? prevDep._nextDep : sub._deps;
468
+ if (nextDep !== null && nextDep._dep === dep) {
469
+ sub._depsTail = nextDep;
573
470
  return;
574
- if (Array.isArray(this._disposal)) {
575
- for (let i = 0; i < this._disposal.length; i++) {
576
- const callable = this._disposal[i];
577
- callable.call(callable);
578
- }
579
- } else {
580
- this._disposal.call(this._disposal);
581
471
  }
582
- this._disposal = null;
583
472
  }
584
- getNextChildId() {
585
- if (this.id != null)
586
- return formatId(this.id, this._childCount++);
587
- throw new Error("Cannot get child id from owner without an id");
473
+ const prevSub = dep._subsTail;
474
+ if (prevSub !== null && prevSub._sub === sub && (!isRecomputing || isValidLink(prevSub, sub))) {
475
+ return;
588
476
  }
589
- };
590
- function createContext(defaultValue, description) {
591
- return { id: Symbol(description), defaultValue };
592
- }
593
- function getContext(context, owner = currentOwner) {
594
- if (!owner) {
595
- throw new NoOwnerError();
477
+ const newLink = sub._depsTail = dep._subsTail = {
478
+ _dep: dep,
479
+ _sub: sub,
480
+ _nextDep: nextDep,
481
+ _prevSub: prevSub,
482
+ _nextSub: null
483
+ };
484
+ if (prevDep !== null) {
485
+ prevDep._nextDep = newLink;
486
+ } else {
487
+ sub._deps = newLink;
596
488
  }
597
- const value = hasContext(context, owner) ? owner._context[context.id] : context.defaultValue;
598
- if (isUndefined(value)) {
599
- throw new ContextNotFoundError();
489
+ if (prevSub !== null) {
490
+ prevSub._nextSub = newLink;
491
+ } else {
492
+ dep._subs = newLink;
600
493
  }
601
- return value;
602
494
  }
603
- function setContext(context, value, owner = currentOwner) {
604
- if (!owner) {
605
- throw new NoOwnerError();
495
+ function isValidLink(checkLink, sub) {
496
+ const depsTail = sub._depsTail;
497
+ if (depsTail !== null) {
498
+ let link2 = sub._deps;
499
+ do {
500
+ if (link2 === checkLink) {
501
+ return true;
502
+ }
503
+ if (link2 === depsTail) {
504
+ break;
505
+ }
506
+ link2 = link2._nextDep;
507
+ } while (link2 !== null);
606
508
  }
607
- owner._context = {
608
- ...owner._context,
609
- [context.id]: isUndefined(value) ? context.defaultValue : value
610
- };
509
+ return false;
611
510
  }
612
- function hasContext(context, owner = currentOwner) {
613
- return !isUndefined(owner?._context[context.id]);
511
+ function setStatusFlags(signal2, flags, error = null) {
512
+ signal2._statusFlags = flags;
513
+ signal2._error = error;
614
514
  }
615
- function onCleanup(fn) {
616
- if (!currentOwner)
617
- return fn;
618
- const node = currentOwner;
619
- if (!node._disposal) {
620
- node._disposal = fn;
621
- } else if (Array.isArray(node._disposal)) {
622
- node._disposal.push(fn);
515
+ function setError(signal2, error) {
516
+ setStatusFlags(signal2, 2 /* Error */ | 4 /* Uninitialized */, error);
517
+ }
518
+ function clearStatusFlags(signal2) {
519
+ setStatusFlags(signal2, 0 /* None */);
520
+ }
521
+ function markDisposal(el) {
522
+ let child = el._firstChild;
523
+ while (child) {
524
+ child._flags |= 32 /* Zombie */;
525
+ const inHeap = child._flags & 8 /* InHeap */;
526
+ if (inHeap) {
527
+ deleteFromHeap(child, dirtyQueue);
528
+ insertIntoHeap(child, zombieQueue);
529
+ }
530
+ markDisposal(child);
531
+ child = child._nextSibling;
532
+ }
533
+ }
534
+ function disposeChildren(node, self = false, zombie) {
535
+ if (node._flags & 64 /* Disposed */)
536
+ return;
537
+ if (self)
538
+ node._flags = 64 /* Disposed */;
539
+ let child = zombie ? node._pendingFirstChild : node._firstChild;
540
+ while (child) {
541
+ const nextChild = child._nextSibling;
542
+ if (child._deps) {
543
+ const n = child;
544
+ deleteFromHeap(n, n._flags & 32 /* Zombie */ ? zombieQueue : dirtyQueue);
545
+ let toRemove = n._deps;
546
+ do {
547
+ toRemove = unlinkSubs(toRemove);
548
+ } while (toRemove !== null);
549
+ n._deps = null;
550
+ n._depsTail = null;
551
+ }
552
+ disposeChildren(child, true);
553
+ child = nextChild;
554
+ }
555
+ if (zombie) {
556
+ node._pendingFirstChild = null;
623
557
  } else {
624
- node._disposal = [node._disposal, fn];
558
+ node._firstChild = null;
559
+ node._nextSibling = null;
625
560
  }
626
- return fn;
561
+ runDisposal(node, zombie);
562
+ }
563
+ function runDisposal(node, zombie) {
564
+ let disposal = zombie ? node._pendingDisposal : node._disposal;
565
+ if (!disposal)
566
+ return;
567
+ if (Array.isArray(disposal)) {
568
+ for (let i = 0; i < disposal.length; i++) {
569
+ const callable = disposal[i];
570
+ callable.call(callable);
571
+ }
572
+ } else {
573
+ disposal.call(disposal);
574
+ }
575
+ zombie ? node._pendingDisposal = null : node._disposal = null;
576
+ }
577
+ function withOptions(obj, options) {
578
+ obj._name = options?.name ?? (obj._fn ? "computed" : "signal");
579
+ obj.id = options?.id ?? (context?.id != null ? getNextChildId(context) : void 0);
580
+ obj._equals = options?.equals != null ? options.equals : isEqual;
581
+ obj._pureWrite = !!options?.pureWrite;
582
+ obj._unobserved = options?.unobserved;
583
+ if (options?._internal)
584
+ Object.assign(obj, options._internal);
585
+ return obj;
586
+ }
587
+ function getNextChildId(owner) {
588
+ if (owner.id != null)
589
+ return formatId(owner.id, owner._childCount++);
590
+ throw new Error("Cannot get child id from owner without an id");
627
591
  }
628
592
  function formatId(prefix, id) {
629
593
  const num = id.toString(36), len = num.length - 1;
630
594
  return prefix + (len ? String.fromCharCode(64 + len) : "") + num;
631
595
  }
632
- function isUndefined(value) {
633
- return typeof value === "undefined";
596
+ function computed(fn, initialValue, options) {
597
+ const self = withOptions(
598
+ {
599
+ _disposal: null,
600
+ _queue: globalQueue,
601
+ _context: defaultContext,
602
+ _childCount: 0,
603
+ _fn: fn,
604
+ _value: initialValue,
605
+ _height: 0,
606
+ _child: null,
607
+ _nextHeap: void 0,
608
+ _prevHeap: null,
609
+ _deps: null,
610
+ _depsTail: null,
611
+ _subs: null,
612
+ _subsTail: null,
613
+ _parent: context,
614
+ _nextSibling: null,
615
+ _firstChild: null,
616
+ _flags: 0 /* None */,
617
+ _statusFlags: 4 /* Uninitialized */,
618
+ _time: clock,
619
+ _pendingValue: NOT_PENDING,
620
+ _pendingDisposal: null,
621
+ _pendingFirstChild: null
622
+ },
623
+ options
624
+ );
625
+ self._prevHeap = self;
626
+ const parent = context?._root ? context._parentComputed : context;
627
+ if (context) {
628
+ context._queue && (self._queue = context._queue);
629
+ context._context && (self._context = context._context);
630
+ const lastChild = context._firstChild;
631
+ if (lastChild === null) {
632
+ context._firstChild = self;
633
+ } else {
634
+ self._nextSibling = lastChild;
635
+ context._firstChild = self;
636
+ }
637
+ }
638
+ if (parent)
639
+ self._height = parent._height + 1;
640
+ recompute(self, true);
641
+ return self;
634
642
  }
635
-
636
- // src/core/core.ts
637
- var currentObserver = null;
638
- var currentMask = DEFAULT_FLAGS;
639
- var newSources = null;
640
- var newSourcesIndex = 0;
641
- var newFlags = 0;
642
- var notStale = false;
643
- var updateCheck = null;
644
- var staleCheck = null;
645
- function getObserver() {
646
- return currentObserver;
647
- }
648
- var UNCHANGED = Symbol("unchanged" );
649
- var Computation = class extends Owner {
650
- _sources = null;
651
- _observers = null;
652
- _value;
653
- _error;
654
- _compute;
655
- // Used in __DEV__ mode, hopefully removed in production
656
- _name;
657
- // Using false is an optimization as an alternative to _equals: () => false
658
- // which could enable more efficient DIRTY notification
659
- _equals = isEqual;
660
- _unobserved;
661
- _pureWrite = false;
662
- /** Whether the computation is an error or has ancestors that are unresolved */
663
- _stateFlags = 0;
664
- /** Which flags raised by sources are handled, vs. being passed through. */
665
- _handlerMask = DEFAULT_FLAGS;
666
- _time = -1;
667
- _forceNotify = false;
668
- _transition;
669
- _cloned;
670
- _optimistic;
671
- constructor(initialValue, compute2, options) {
672
- super(options?.id, compute2 === null);
673
- this._compute = compute2;
674
- this._state = compute2 ? STATE_DIRTY : STATE_CLEAN;
675
- this._stateFlags = compute2 && initialValue === void 0 ? UNINITIALIZED_BIT : 0;
676
- this._value = initialValue;
677
- this._name = options?.name ?? (this._compute ? "computed" : "signal");
678
- if (options?.equals !== void 0)
679
- this._equals = options.equals;
680
- this._pureWrite = !!options?.pureWrite;
681
- this._unobserved = options?.unobserved;
682
- if (ActiveTransition) {
683
- this._transition = ActiveTransition;
684
- ActiveTransition._sources.set(this, this);
685
- }
686
- }
687
- _read() {
688
- if (staleCheck && (this._stateFlags & LOADING_BIT || this._transition)) {
689
- staleCheck._value = true;
690
- this._transition?._signal.read();
691
- }
692
- track(this);
693
- newFlags |= this._stateFlags & ~currentMask;
694
- if (this._stateFlags & ERROR_BIT) {
695
- throw this._error;
643
+ function asyncComputed(asyncFn, initialValue, options) {
644
+ let lastResult = void 0;
645
+ let refreshing = false;
646
+ const fn = (prev) => {
647
+ const result = asyncFn(prev, refreshing);
648
+ refreshing = false;
649
+ lastResult = result;
650
+ const isPromise = result instanceof Promise;
651
+ const iterator = result[Symbol.asyncIterator];
652
+ if (!isPromise && !iterator) {
653
+ return result;
654
+ }
655
+ if (isPromise) {
656
+ result.then((v) => {
657
+ if (lastResult !== result)
658
+ return;
659
+ globalQueue.initTransition(self);
660
+ setSignal(self, () => v);
661
+ flush();
662
+ }).catch((e) => {
663
+ if (lastResult !== result)
664
+ return;
665
+ globalQueue.initTransition(self);
666
+ setError(self, e);
667
+ flush();
668
+ });
696
669
  } else {
697
- return this._value;
698
- }
699
- }
700
- /**
701
- * Return the current value of this computation
702
- * Automatically re-executes the surrounding computation when the value changes
703
- */
704
- read() {
705
- if (ActiveTransition && (ActiveTransition._sources.has(this) || !this._cloned && this._stateFlags & (UNINITIALIZED_BIT | ERROR_BIT))) {
706
- const clone = ActiveTransition._sources.get(this) || cloneGraph(this);
707
- if (clone !== this)
708
- return clone.read();
709
- }
710
- if (this._compute) {
711
- if (this._stateFlags & ERROR_BIT && this._time <= clock)
712
- update(this);
713
- else
714
- this._updateIfNecessary();
715
- }
716
- return this._read();
717
- }
718
- /**
719
- * Return the current value of this computation
720
- * Automatically re-executes the surrounding computation when the value changes
721
- *
722
- * If the computation has any unresolved ancestors, this function waits for the value to resolve
723
- * before continuing
724
- */
725
- wait() {
726
- if (ActiveTransition && (ActiveTransition._sources.has(this) || !this._cloned && this._stateFlags & (UNINITIALIZED_BIT | ERROR_BIT))) {
727
- const clone = ActiveTransition._sources.get(this) || cloneGraph(this);
728
- if (clone !== this)
729
- return clone.wait();
730
- }
731
- if (this._compute) {
732
- if (this._stateFlags & ERROR_BIT && this._time <= clock)
733
- update(this);
734
- else
735
- this._updateIfNecessary();
736
- }
737
- if ((notStale || this._stateFlags & UNINITIALIZED_BIT) && this._stateFlags & LOADING_BIT) {
738
- throw new NotReadyError(this);
739
- }
740
- return this._read();
741
- }
742
- /** Update the computation with a new value. */
743
- write(value, flags = 0, raw = false) {
744
- if (ActiveTransition && !this._cloned) {
745
- const clone = cloneGraph(this);
746
- if (clone !== this)
747
- return clone.write(value, flags, raw);
748
- }
749
- if (!this._compute && !this._pureWrite && getOwner() && !getOwner().firewall)
750
- console.warn("A Signal was written to in an owned scope.");
751
- const newValue = !raw && typeof value === "function" ? value(this._value) : value;
752
- const valueChanged = newValue !== UNCHANGED && (!!(this._stateFlags & UNINITIALIZED_BIT) || // this._stateFlags & LOADING_BIT & ~flags ||
753
- this._equals === false || !this._equals(this._value, newValue));
754
- if (valueChanged) {
755
- this._value = newValue;
756
- this._error = void 0;
757
- }
758
- const changedFlagsMask = this._stateFlags ^ flags, changedFlags = changedFlagsMask & flags;
759
- this._stateFlags = flags;
760
- this._time = clock + 1;
761
- if (this._observers && !(this._optimistic && ActiveTransition)) {
762
- for (let i = 0; i < this._observers.length; i++) {
763
- if (valueChanged) {
764
- this._observers[i]._notify(STATE_DIRTY);
765
- } else if (changedFlagsMask) {
766
- this._observers[i]._notifyFlags(changedFlagsMask, changedFlags);
670
+ (async () => {
671
+ try {
672
+ for await (let value of result) {
673
+ if (lastResult !== result)
674
+ return;
675
+ globalQueue.initTransition(self);
676
+ setSignal(self, () => value);
677
+ flush();
678
+ }
679
+ } catch (error) {
680
+ if (lastResult !== result)
681
+ return;
682
+ globalQueue.initTransition(self);
683
+ setError(self, error);
684
+ flush();
767
685
  }
768
- }
686
+ })();
769
687
  }
770
- return this._value;
688
+ globalQueue.initTransition(context);
689
+ throw new NotReadyError(context);
690
+ };
691
+ const self = computed(fn, initialValue, options);
692
+ self._refresh = () => {
693
+ refreshing = true;
694
+ recompute(self);
695
+ flush();
696
+ };
697
+ return self;
698
+ }
699
+ function signal(v, options, firewall = null) {
700
+ if (firewall !== null) {
701
+ return firewall._child = withOptions(
702
+ {
703
+ _value: v,
704
+ _subs: null,
705
+ _subsTail: null,
706
+ _owner: firewall,
707
+ _nextChild: firewall._child,
708
+ _statusFlags: 0 /* None */,
709
+ _time: clock,
710
+ _pendingValue: NOT_PENDING
711
+ },
712
+ options
713
+ );
714
+ } else {
715
+ return withOptions(
716
+ {
717
+ _value: v,
718
+ _subs: null,
719
+ _subsTail: null,
720
+ _statusFlags: 0 /* None */,
721
+ _time: clock,
722
+ _pendingValue: NOT_PENDING
723
+ },
724
+ options
725
+ );
771
726
  }
772
- /**
773
- * Set the current node's state, and recursively mark all of this node's observers as STATE_CHECK
774
- */
775
- _notify(state, skipQueue) {
776
- if (this._state >= state && !this._forceNotify)
777
- return;
778
- this._forceNotify = !!skipQueue;
779
- this._state = state;
780
- if (this._observers && !(this._optimistic && ActiveTransition)) {
781
- for (let i = 0; i < this._observers.length; i++) {
782
- this._observers[i]._notify(STATE_CHECK, skipQueue);
727
+ }
728
+ function isEqual(a, b) {
729
+ return a === b;
730
+ }
731
+ function untrack(fn) {
732
+ if (!tracking)
733
+ return fn();
734
+ tracking = false;
735
+ try {
736
+ return fn();
737
+ } finally {
738
+ tracking = true;
739
+ }
740
+ }
741
+ function read(el) {
742
+ let c = context;
743
+ if (c?._root)
744
+ c = c._parentComputed;
745
+ if (c && tracking) {
746
+ link(el, c);
747
+ const owner = "_owner" in el ? el._owner : el;
748
+ if ("_fn" in owner) {
749
+ const isZombie = el._flags & 32 /* Zombie */;
750
+ if (owner._height >= (isZombie ? zombieQueue._min : dirtyQueue._min)) {
751
+ markNode(c);
752
+ markHeap(isZombie ? zombieQueue : dirtyQueue);
753
+ updateIfNecessary(owner);
783
754
  }
784
- }
785
- }
786
- /**
787
- * Notify the computation that one of its sources has changed flags.
788
- *
789
- * @param mask A bitmask for which flag(s) were changed.
790
- * @param newFlags The source's new flags, masked to just the changed ones.
791
- */
792
- _notifyFlags(mask, newFlags2) {
793
- if (this._state >= STATE_DIRTY)
794
- return;
795
- if (mask & this._handlerMask || this._optimistic && ActiveTransition) {
796
- this._notify(STATE_DIRTY);
797
- return;
798
- }
799
- if (this._state >= STATE_CHECK && !this._forceNotify)
800
- return;
801
- const prevFlags = this._stateFlags & mask;
802
- const deltaFlags = prevFlags ^ newFlags2;
803
- if (newFlags2 === prevFlags) ; else if (deltaFlags & prevFlags & mask) {
804
- this._notify(STATE_CHECK);
805
- } else {
806
- this._stateFlags ^= deltaFlags;
807
- if (this._observers) {
808
- for (let i = 0; i < this._observers.length; i++) {
809
- this._observers[i]._notifyFlags(mask, newFlags2);
810
- }
755
+ const height = owner._height;
756
+ if (height >= c._height && el._parent !== c) {
757
+ c._height = height + 1;
811
758
  }
812
759
  }
813
760
  }
814
- _setError(error) {
815
- if (ActiveTransition && !this._cloned) {
816
- const clone = cloneGraph(this);
817
- if (clone !== this)
818
- return clone._setError(error);
819
- }
820
- this._error = error;
821
- this.write(UNCHANGED, this._stateFlags & ~LOADING_BIT | ERROR_BIT | UNINITIALIZED_BIT);
822
- }
823
- /**
824
- * This is the core part of the reactivity system, which makes sure that the values are updated
825
- * before they are read. We've also adapted it to return the loading state of the computation,
826
- * so that we can propagate that to the computation's observers.
827
- *
828
- * This function will ensure that the value and states we read from the computation are up to date
829
- */
830
- _updateIfNecessary() {
831
- if (!this._compute) {
832
- return;
761
+ if (pendingCheck) {
762
+ const pendingResult = (el._statusFlags & 1 /* Pending */) !== 0 || !!el._transition || false;
763
+ if (!el._pendingCheck) {
764
+ el._pendingCheck = signal(pendingResult);
765
+ el._pendingCheck._optimistic = true;
766
+ el._pendingCheck._set = (v) => setSignal(el._pendingCheck, v);
833
767
  }
834
- if (this._state === STATE_DISPOSED) {
835
- return;
768
+ const prev = pendingCheck;
769
+ pendingCheck = null;
770
+ read(el._pendingCheck);
771
+ pendingCheck = prev;
772
+ prev._value = pendingResult || prev._value;
773
+ }
774
+ if (pendingValueCheck) {
775
+ if (!el._pendingSignal) {
776
+ el._pendingSignal = signal(
777
+ el._pendingValue === NOT_PENDING ? el._value : el._pendingValue
778
+ );
779
+ el._pendingSignal._optimistic = true;
780
+ el._pendingSignal._set = (v) => queueMicrotask(() => queueMicrotask(() => setSignal(el._pendingSignal, v)));
836
781
  }
837
- if (this._state === STATE_CLEAN) {
838
- return;
782
+ pendingValueCheck = false;
783
+ try {
784
+ return read(el._pendingSignal);
785
+ } finally {
786
+ pendingValueCheck = true;
839
787
  }
840
- let observerFlags = 0;
841
- if (this._state === STATE_CHECK) {
842
- for (let i = 0; i < this._sources.length; i++) {
843
- const source = getTransitionSource(this._sources[i]);
844
- source._updateIfNecessary();
845
- observerFlags |= source._stateFlags & ~UNINITIALIZED_BIT;
846
- if (this._state === STATE_DIRTY) {
847
- break;
848
- }
849
- }
788
+ }
789
+ if (el._statusFlags & 1 /* Pending */) {
790
+ if (c && !stale || el._statusFlags & 4 /* Uninitialized */)
791
+ throw el._error;
792
+ else if (c && stale && !pendingCheck) {
793
+ setStatusFlags(
794
+ c,
795
+ c._statusFlags | 1,
796
+ el._error
797
+ );
850
798
  }
851
- if (this._state === STATE_DIRTY) {
852
- update(this);
799
+ }
800
+ if (el._statusFlags & 2 /* Error */) {
801
+ if (el._time < clock) {
802
+ recompute(el, true);
803
+ return read(el);
853
804
  } else {
854
- this.write(UNCHANGED, observerFlags);
855
- this._state = STATE_CLEAN;
805
+ throw el._error;
856
806
  }
857
807
  }
858
- /**
859
- * Remove ourselves from the owner graph and the computation graph
860
- */
861
- _disposeNode() {
862
- if (this._state === STATE_DISPOSED)
863
- return;
864
- if (this._sources)
865
- removeSourceObservers(this, 0);
866
- super._disposeNode();
808
+ return !c || el._pendingValue === NOT_PENDING || stale && !pendingCheck && el._transition && activeTransition !== el._transition ? el._value : el._pendingValue;
809
+ }
810
+ function setSignal(el, v) {
811
+ if (!el._pureWrite && context && !context.firewall)
812
+ console.warn("A Signal was written to in an owned scope.");
813
+ if (typeof v === "function") {
814
+ v = v(
815
+ el._pendingValue === NOT_PENDING ? el._value : el._pendingValue
816
+ );
867
817
  }
868
- };
869
- function track(computation) {
870
- if (ActiveTransition && computation._cloned)
871
- computation = computation._cloned;
872
- if (currentObserver) {
873
- if (!newSources && currentObserver._sources && currentObserver._sources[newSourcesIndex] === computation) {
874
- newSourcesIndex++;
875
- } else if (!newSources)
876
- newSources = [computation];
877
- else if (computation !== newSources[newSources.length - 1]) {
878
- newSources.push(computation);
879
- }
880
- if (updateCheck) {
881
- updateCheck._value = computation._time > currentObserver._time;
882
- }
883
- }
884
- }
885
- function update(node) {
886
- const prevSources = newSources, prevSourcesIndex = newSourcesIndex, prevFlags = newFlags;
887
- newSources = null;
888
- newSourcesIndex = 0;
889
- newFlags = 0;
890
- try {
891
- if (ActiveTransition && node._cloned && !node._updated) {
892
- initialDispose(node._cloned);
893
- node._updated = true;
894
- }
895
- node.dispose(false);
896
- node.emptyDisposal();
897
- const result = compute(node, node._compute, node);
898
- node.write(result, newFlags, true);
899
- } catch (error) {
900
- if (error instanceof NotReadyError) {
901
- if (error.cause !== node)
902
- compute(
903
- node,
904
- () => track(error.cause),
905
- node
906
- );
907
- node.write(UNCHANGED, newFlags | LOADING_BIT | node._stateFlags & UNINITIALIZED_BIT);
908
- } else {
909
- node._setError(error);
818
+ const valueChanged = !el._equals || !el._equals(el._pendingValue === NOT_PENDING ? el._value : el._pendingValue, v);
819
+ if (!valueChanged && !el._statusFlags)
820
+ return v;
821
+ if (valueChanged) {
822
+ if (el._optimistic)
823
+ el._value = v;
824
+ else {
825
+ if (el._pendingValue === NOT_PENDING)
826
+ globalQueue._pendingNodes.push(el);
827
+ el._pendingValue = v;
828
+ }
829
+ if (el._pendingSignal)
830
+ el._pendingSignal._set(v);
831
+ }
832
+ clearStatusFlags(el);
833
+ el._time = clock;
834
+ for (let s = el._subs; s !== null; s = s._nextSub) {
835
+ const queue = s._sub._flags & 32 /* Zombie */ ? zombieQueue : dirtyQueue;
836
+ if (queue._min > s._sub._height)
837
+ queue._min = s._sub._height;
838
+ insertIntoHeap(s._sub, queue);
839
+ }
840
+ schedule();
841
+ return v;
842
+ }
843
+ function getObserver() {
844
+ return tracking ? context : null;
845
+ }
846
+ function getOwner() {
847
+ return context;
848
+ }
849
+ function onCleanup(fn) {
850
+ if (!context)
851
+ return fn;
852
+ const node = context;
853
+ if (!node._disposal) {
854
+ node._disposal = fn;
855
+ } else if (Array.isArray(node._disposal)) {
856
+ node._disposal.push(fn);
857
+ } else {
858
+ node._disposal = [node._disposal, fn];
859
+ }
860
+ return fn;
861
+ }
862
+ function createOwner(options) {
863
+ const parent = context;
864
+ const owner = {
865
+ _root: true,
866
+ _parentComputed: parent?._root ? parent._parentComputed : parent,
867
+ _firstChild: null,
868
+ _nextSibling: null,
869
+ _disposal: null,
870
+ id: options?.id ?? (parent?.id != null ? getNextChildId(parent) : void 0),
871
+ _queue: parent?._queue ?? globalQueue,
872
+ _context: parent?._context || defaultContext,
873
+ _childCount: 0,
874
+ _pendingDisposal: null,
875
+ _pendingFirstChild: null,
876
+ _parent: parent,
877
+ dispose(self = true) {
878
+ disposeChildren(owner, self);
910
879
  }
911
- } finally {
912
- if (newSources) {
913
- if (node._sources)
914
- removeSourceObservers(node, newSourcesIndex);
915
- if (node._sources && newSourcesIndex > 0) {
916
- node._sources.length = newSourcesIndex + newSources.length;
917
- for (let i = 0; i < newSources.length; i++) {
918
- node._sources[newSourcesIndex + i] = newSources[i];
919
- }
920
- } else {
921
- node._sources = newSources;
922
- }
923
- let source;
924
- for (let i = newSourcesIndex; i < node._sources.length; i++) {
925
- source = getTransitionSource(node._sources[i]);
926
- if (!source._observers)
927
- source._observers = [node];
928
- else
929
- source._observers.push(node);
930
- }
931
- } else if (node._sources && newSourcesIndex < node._sources.length) {
932
- removeSourceObservers(node, newSourcesIndex);
933
- node._sources.length = newSourcesIndex;
880
+ };
881
+ if (parent) {
882
+ const lastChild = parent._firstChild;
883
+ if (lastChild === null) {
884
+ parent._firstChild = owner;
885
+ } else {
886
+ owner._nextSibling = lastChild;
887
+ parent._firstChild = owner;
934
888
  }
935
- newSources = prevSources;
936
- newSourcesIndex = prevSourcesIndex;
937
- newFlags = prevFlags;
938
- node._time = clock + 1;
939
- node._state = STATE_CLEAN;
940
889
  }
890
+ return owner;
941
891
  }
942
- function isEqual(a, b) {
943
- return a === b;
892
+ function createRoot(init, options) {
893
+ const owner = createOwner(options);
894
+ return runWithOwner(owner, () => init(owner.dispose));
944
895
  }
945
- function untrack(fn) {
946
- if (currentObserver === null)
896
+ function runWithOwner(owner, fn) {
897
+ const oldContext = context;
898
+ context = owner;
899
+ try {
947
900
  return fn();
948
- return compute(getOwner(), fn, null);
901
+ } finally {
902
+ context = oldContext;
903
+ }
949
904
  }
950
- function hasUpdated(fn) {
951
- const current = updateCheck;
952
- updateCheck = { _value: false };
905
+ function staleValues(fn, set = true) {
906
+ const prevStale = stale;
907
+ stale = set;
953
908
  try {
954
- fn();
955
- return updateCheck._value;
909
+ return fn();
956
910
  } finally {
957
- updateCheck = current;
911
+ stale = prevStale;
958
912
  }
959
913
  }
960
- function pendingCheck(fn, loadingValue) {
961
- const current = staleCheck;
962
- staleCheck = { _value: false };
914
+ function pending(fn) {
915
+ const prevLatest = pendingValueCheck;
916
+ pendingValueCheck = true;
963
917
  try {
964
- latest(fn);
965
- return staleCheck._value;
918
+ return staleValues(fn, false);
919
+ } finally {
920
+ pendingValueCheck = prevLatest;
921
+ }
922
+ }
923
+ function isPending(fn, loadingValue) {
924
+ const current = pendingCheck;
925
+ pendingCheck = { _value: false };
926
+ try {
927
+ staleValues(fn);
928
+ return pendingCheck._value;
966
929
  } catch (err) {
967
930
  if (!(err instanceof NotReadyError))
968
931
  return false;
@@ -970,421 +933,163 @@ function pendingCheck(fn, loadingValue) {
970
933
  return loadingValue;
971
934
  throw err;
972
935
  } finally {
973
- staleCheck = current;
936
+ pendingCheck = current;
974
937
  }
975
938
  }
976
- function isPending(fn, loadingValue) {
977
- if (!currentObserver)
978
- return pendingCheck(fn, loadingValue);
979
- const c = new Computation(void 0, () => pendingCheck(fn, loadingValue));
980
- c._optimistic = () => c.write(false);
981
- c._optimistic._init = () => globalQueue.enqueue(0, () => c._optimistic._transition && c.write(true));
982
- c._handlerMask |= LOADING_BIT;
983
- const res = c.wait();
984
- c._disposal = () => {
985
- if (c._optimistic._transition) {
986
- c._optimistic._transition._optimistic.delete(c._optimistic);
987
- delete c._optimistic._transition;
988
- }
989
- };
990
- return res;
939
+
940
+ // src/core/context.ts
941
+ function createContext(defaultValue, description) {
942
+ return { id: Symbol(description), defaultValue };
991
943
  }
992
- function latest(fn, fallback) {
993
- const argLength = arguments.length;
994
- const prevFlags = newFlags;
995
- const prevNotStale = notStale;
996
- notStale = false;
997
- try {
998
- return fn();
999
- } catch (err) {
1000
- if (argLength > 1 && err instanceof NotReadyError)
1001
- return fallback;
1002
- throw err;
1003
- } finally {
1004
- newFlags = prevFlags;
1005
- notStale = prevNotStale;
944
+ function getContext(context2, owner = getOwner()) {
945
+ if (!owner) {
946
+ throw new NoOwnerError();
947
+ }
948
+ const value = hasContext(context2, owner) ? owner._context[context2.id] : context2.defaultValue;
949
+ if (isUndefined(value)) {
950
+ throw new ContextNotFoundError();
1006
951
  }
952
+ return value;
1007
953
  }
1008
- function compute(owner, fn, observer) {
1009
- const prevOwner = setOwner(owner), prevObserver = currentObserver, prevMask = currentMask, prevNotStale = notStale;
1010
- currentObserver = observer;
1011
- currentMask = observer?._handlerMask ?? DEFAULT_FLAGS;
1012
- notStale = true;
1013
- try {
1014
- return fn.call(observer, observer ? observer._value : void 0);
1015
- } finally {
1016
- setOwner(prevOwner);
1017
- currentObserver = prevObserver;
1018
- currentMask = prevMask;
1019
- notStale = prevNotStale;
954
+ function setContext(context2, value, owner = getOwner()) {
955
+ if (!owner) {
956
+ throw new NoOwnerError();
1020
957
  }
958
+ owner._context = {
959
+ ...owner._context,
960
+ [context2.id]: isUndefined(value) ? context2.defaultValue : value
961
+ };
962
+ }
963
+ function hasContext(context2, owner) {
964
+ return !isUndefined(owner?._context[context2.id]);
965
+ }
966
+ function isUndefined(value) {
967
+ return typeof value === "undefined";
1021
968
  }
1022
969
 
1023
970
  // src/core/effect.ts
1024
- var Effect = class extends Computation {
1025
- _effect;
1026
- _onerror;
1027
- _cleanup;
1028
- _modified = false;
1029
- _prevValue;
1030
- _type;
1031
- constructor(initialValue, compute2, effect, error, options) {
1032
- super(initialValue, compute2, options);
1033
- this._effect = effect;
1034
- this._onerror = error;
1035
- this._prevValue = initialValue;
1036
- this._type = options?.render ? EFFECT_RENDER : EFFECT_USER;
1037
- if (this._type === EFFECT_RENDER) {
1038
- this._compute = function(p) {
1039
- return !this._cloned && clock > this._queue.created && !(this._stateFlags & ERROR_BIT) ? latest(() => compute2(p)) : compute2(p);
1040
- };
1041
- }
1042
- this._updateIfNecessary();
1043
- !options?.defer && (this._type === EFFECT_USER ? getQueue(this).enqueue(this._type, this._run.bind(this)) : this._run(this._type));
1044
- if (!this._parent)
1045
- console.warn("Effects created outside a reactive context will never be disposed");
1046
- }
1047
- write(value, flags = 0) {
1048
- if (this._state == STATE_DIRTY) {
1049
- this._stateFlags = flags;
1050
- if (this._type === EFFECT_RENDER) {
1051
- getQueue(this).notify(this, LOADING_BIT | ERROR_BIT, this._stateFlags);
1052
- }
1053
- }
1054
- if (value === UNCHANGED)
1055
- return this._value;
1056
- this._value = value;
1057
- this._modified = true;
1058
- this._error = void 0;
1059
- return value;
1060
- }
1061
- _notify(state, skipQueue) {
1062
- if (this._state >= state || skipQueue)
1063
- return;
1064
- if (this._state === STATE_CLEAN || this._cloned && !ActiveTransition)
1065
- getQueue(this).enqueue(this._type, this._run.bind(this));
1066
- this._state = state;
1067
- }
1068
- _notifyFlags(mask, newFlags2) {
1069
- if (this._cloned) {
1070
- if (this._state >= STATE_DIRTY)
1071
- return;
1072
- if (mask & 3) {
1073
- this._notify(STATE_DIRTY);
1074
- return;
1075
- }
1076
- }
1077
- super._notifyFlags(mask, newFlags2);
1078
- }
1079
- _setError(error) {
1080
- this._error = error;
1081
- getQueue(this).notify(this, LOADING_BIT, 0);
1082
- this._stateFlags = ERROR_BIT;
1083
- if (this._type === EFFECT_USER) {
1084
- try {
1085
- return this._onerror ? this._onerror(error, () => {
1086
- this._cleanup?.();
1087
- this._cleanup = void 0;
1088
- }) : console.error(error);
1089
- } catch (e) {
1090
- error = e;
1091
- }
1092
- }
1093
- if (!getQueue(this).notify(this, ERROR_BIT, ERROR_BIT))
1094
- throw error;
1095
- }
1096
- _disposeNode() {
1097
- if (this._state === STATE_DISPOSED)
1098
- return;
1099
- this._effect = void 0;
1100
- this._prevValue = void 0;
1101
- this._onerror = void 0;
1102
- this._cleanup?.();
1103
- this._cleanup = void 0;
1104
- getQueue(this).notify(this, ERROR_BIT | LOADING_BIT, 0);
1105
- super._disposeNode();
1106
- }
1107
- _run(type) {
1108
- if (type) {
1109
- const effect = this._cloned || this;
1110
- if (effect._modified && effect._state !== STATE_DISPOSED) {
1111
- effect._cleanup?.();
1112
- try {
1113
- effect._cleanup = effect._effect(effect._value, effect._prevValue);
1114
- } catch (e) {
1115
- if (!getQueue(effect).notify(effect, ERROR_BIT, ERROR_BIT))
1116
- throw e;
1117
- } finally {
1118
- effect._prevValue = effect._value;
1119
- effect._modified = false;
971
+ function effect(compute, effect2, error, initialValue, options) {
972
+ let initialized = false;
973
+ const node = computed(compute, initialValue, {
974
+ ...options,
975
+ _internal: {
976
+ _modified: true,
977
+ _prevValue: initialValue,
978
+ _effectFn: effect2,
979
+ _errorFn: error,
980
+ _cleanup: void 0,
981
+ _queue: getOwner()?._queue ?? globalQueue,
982
+ _type: options?.render ? 1 /* Render */ : 2 /* User */,
983
+ _notifyQueue(statusFlagsChanged, prevStatusFlags) {
984
+ if (initialized) {
985
+ const errorChanged = this._statusFlags && this._statusFlags === prevStatusFlags && statusFlagsChanged;
986
+ this._modified = !(this._statusFlags & 2 /* Error */) && !(this._statusFlags & 1 /* Pending */ & ~prevStatusFlags) && !errorChanged;
987
+ if (this._modified)
988
+ this._queue.enqueue(this._type, runEffect.bind(this));
989
+ }
990
+ if (this._statusFlags & 2 /* Error */) {
991
+ let error2 = this._error;
992
+ this._queue.notify(this, 1 /* Pending */, 0);
993
+ if (this._type === 2 /* User */) {
994
+ try {
995
+ return this._errorFn ? this._errorFn(error2, () => {
996
+ this._cleanup?.();
997
+ this._cleanup = void 0;
998
+ }) : console.error(error2);
999
+ } catch (e) {
1000
+ error2 = e;
1001
+ }
1002
+ }
1003
+ if (!this._queue.notify(this, 2 /* Error */, 2 /* Error */))
1004
+ throw error2;
1005
+ } else if (this._type === 1 /* Render */) {
1006
+ this._queue.notify(
1007
+ this,
1008
+ 1 /* Pending */ | 2 /* Error */,
1009
+ this._statusFlags
1010
+ );
1120
1011
  }
1121
1012
  }
1122
- } else
1123
- this._state !== STATE_CLEAN && runTop(this);
1124
- }
1125
- };
1126
- var TrackedEffect = class extends Computation {
1127
- _type = EFFECT_USER;
1128
- _cleanup;
1129
- constructor(compute2, options) {
1130
- super(
1131
- void 0,
1132
- () => {
1133
- this._cleanup?.();
1134
- this._cleanup = latest(compute2);
1135
- return void 0;
1136
- },
1137
- options
1138
- );
1139
- getQueue(this).enqueue(this._type, this._run.bind(this));
1140
- if (!this._parent)
1141
- console.warn("Effects created outside a reactive context will never be disposed");
1142
- }
1143
- _notify(state, skipQueue) {
1144
- if (this._state >= state || skipQueue)
1145
- return;
1146
- if (this._state === STATE_CLEAN || this._cloned && !ActiveTransition)
1147
- getQueue(this).enqueue(this._type, this._run.bind(this));
1148
- this._state = state;
1149
- }
1150
- _disposeNode() {
1151
- if (this._state === STATE_DISPOSED)
1152
- return;
1153
- this._cleanup?.();
1154
- this._cleanup = void 0;
1155
- getQueue(this).notify(this, ERROR_BIT | LOADING_BIT, 0);
1156
- super._disposeNode();
1157
- }
1158
- _run(type) {
1159
- if (type)
1160
- this._state !== STATE_CLEAN && runTop(this);
1161
- }
1162
- };
1163
- var EagerComputation = class extends Computation {
1164
- constructor(initialValue, compute2, options) {
1165
- super(initialValue, compute2, options);
1166
- !options?.defer && this._updateIfNecessary();
1167
- if (!this._parent)
1168
- console.warn("Eager Computations created outside a reactive context will never be disposed");
1169
- }
1170
- _notify(state, skipQueue) {
1171
- if (this._state >= state && !this._forceNotify)
1172
- return;
1173
- if (!skipQueue && (this._state === STATE_CLEAN || this._state === STATE_CHECK && this._forceNotify))
1174
- getQueue(this).enqueue(EFFECT_PURE, this._run.bind(this));
1175
- super._notify(state, skipQueue);
1176
- }
1177
- _run() {
1178
- this._state !== STATE_CLEAN && runTop(this);
1179
- }
1180
- };
1181
- var FirewallComputation = class extends Computation {
1182
- firewall = true;
1183
- constructor(compute2) {
1184
- super(void 0, compute2);
1185
- if (!this._parent)
1186
- console.warn("Eager Computations created outside a reactive context will never be disposed");
1187
- }
1188
- _notify(state, skipQueue) {
1189
- if (this._state >= state && !this._forceNotify)
1190
- return;
1191
- if (!skipQueue && (this._state === STATE_CLEAN || this._state === STATE_CHECK && this._forceNotify))
1192
- getQueue(this).enqueue(EFFECT_PURE, this._run.bind(this));
1193
- super._notify(state, true);
1194
- this._forceNotify = !!skipQueue;
1195
- }
1196
- _run() {
1197
- const prevFlags = this._stateFlags;
1198
- this._state !== STATE_CLEAN && runTop(this);
1199
- if (ActiveTransition && this._optimistic && (this._stateFlags !== prevFlags || this._stateFlags !== this._optimistic.flags)) {
1200
- getQueue(this).notify(this, LOADING_BIT | ERROR_BIT, this._stateFlags);
1201
- this._optimistic.flags = this._stateFlags;
1202
- this._stateFlags = prevFlags;
1203
- }
1204
- }
1205
- };
1206
- function runTop(node) {
1207
- const ancestors = [];
1208
- for (let current = node; current !== null; current = current._parent) {
1209
- if (ActiveTransition && current._transition)
1210
- current = ActiveTransition._sources.get(current);
1211
- if (current._state !== STATE_CLEAN) {
1212
- ancestors.push(current);
1213
1013
  }
1014
+ });
1015
+ initialized = true;
1016
+ if (node._type === 1 /* Render */) {
1017
+ node._fn = (p) => !(node._statusFlags & 2 /* Error */) ? staleValues(() => compute(p)) : compute(p);
1214
1018
  }
1215
- for (let i = ancestors.length - 1; i >= 0; i--) {
1216
- if (ancestors[i]._state !== STATE_DISPOSED)
1217
- ancestors[i]._updateIfNecessary();
1019
+ !options?.defer && !(node._statusFlags & (2 /* Error */ | 1 /* Pending */)) && (node._type === 2 /* User */ ? node._queue.enqueue(node._type, runEffect.bind(node)) : runEffect.call(node));
1020
+ onCleanup(() => node._cleanup?.());
1021
+ if (!node._parent)
1022
+ console.warn("Effects created outside a reactive context will never be disposed");
1023
+ }
1024
+ function runEffect() {
1025
+ if (!this._modified || this._flags & 64 /* Disposed */)
1026
+ return;
1027
+ this._cleanup?.();
1028
+ this._cleanup = void 0;
1029
+ try {
1030
+ this._cleanup = this._effectFn(this._value, this._prevValue);
1031
+ } catch (error) {
1032
+ if (!this._queue.notify(this, 2 /* Error */, 2 /* Error */))
1033
+ throw error;
1034
+ } finally {
1035
+ this._prevValue = this._value;
1036
+ this._modified = false;
1218
1037
  }
1219
1038
  }
1220
1039
 
1221
1040
  // src/signals.ts
1222
1041
  function createSignal(first, second, third) {
1223
1042
  if (typeof first === "function") {
1224
- const node2 = new Computation(second, first, third);
1043
+ const node2 = computed(first, second, third);
1225
1044
  return [
1226
- node2.wait.bind(node2),
1227
- (v) => {
1228
- node2._updateIfNecessary();
1229
- return node2.write(v);
1230
- }
1045
+ read.bind(null, node2),
1046
+ setSignal.bind(null, node2)
1231
1047
  ];
1232
1048
  }
1233
1049
  const o = getOwner();
1234
1050
  const needsId = o?.id != null;
1235
- const node = new Computation(
1051
+ const node = signal(
1236
1052
  first,
1237
- null,
1238
- needsId ? { id: o.getNextChildId(), ...second } : second
1053
+ needsId ? { id: getNextChildId(o), ...second } : second
1239
1054
  );
1240
- return [node.read.bind(node), node.write.bind(node)];
1241
- }
1242
- function createMemo(compute2, value, options) {
1243
- let node = new Computation(
1055
+ return [
1056
+ read.bind(null, node),
1057
+ setSignal.bind(null, node)
1058
+ ];
1059
+ }
1060
+ function createMemo(compute, value, options) {
1061
+ let node = computed(compute, value, options);
1062
+ return read.bind(null, node);
1063
+ }
1064
+ function createAsync(compute, value, options) {
1065
+ const node = asyncComputed(compute, value, options);
1066
+ const ret = read.bind(null, node);
1067
+ ret.refresh = node._refresh;
1068
+ return ret;
1069
+ }
1070
+ function createEffect(compute, effectFn, value, options) {
1071
+ void effect(
1072
+ compute,
1073
+ effectFn.effect || effectFn,
1074
+ effectFn.error,
1244
1075
  value,
1245
- compute2,
1246
- options
1247
- );
1248
- let resolvedValue;
1249
- return () => {
1250
- if (node) {
1251
- if (node._state === STATE_DISPOSED) {
1252
- node = void 0;
1253
- return resolvedValue;
1254
- }
1255
- resolvedValue = node.wait();
1256
- if (!node._sources?.length && node._nextSibling?._parent !== node && !(node._stateFlags & UNINITIALIZED_BIT)) {
1257
- node.dispose();
1258
- node = void 0;
1259
- }
1260
- }
1261
- return resolvedValue;
1262
- };
1263
- }
1264
- function createAsync(compute2, value, options) {
1265
- let refreshing = false;
1266
- const node = new EagerComputation(
1267
- value,
1268
- (p) => {
1269
- const source = compute2(p, refreshing);
1270
- refreshing = false;
1271
- const isPromise = source instanceof Promise;
1272
- const iterator = source[Symbol.asyncIterator];
1273
- if (!isPromise && !iterator) {
1274
- return source;
1275
- }
1276
- let abort = false;
1277
- onCleanup(() => abort = true);
1278
- let transition2 = ActiveTransition;
1279
- if (isPromise) {
1280
- source.then(
1281
- (value3) => {
1282
- if (abort)
1283
- return;
1284
- if (transition2)
1285
- return transition2.runTransition(() => {
1286
- node.write(value3, 0, true);
1287
- }, true);
1288
- node.write(value3, 0, true);
1289
- },
1290
- (error) => {
1291
- if (abort)
1292
- return;
1293
- if (transition2)
1294
- return transition2.runTransition(() => node._setError(error), true);
1295
- node._setError(error);
1296
- }
1297
- );
1298
- } else {
1299
- (async () => {
1300
- try {
1301
- for await (let value3 of source) {
1302
- if (abort)
1303
- return;
1304
- if (transition2)
1305
- return transition2.runTransition(() => {
1306
- node.write(value3, 0, true);
1307
- transition2 = null;
1308
- }, true);
1309
- node.write(value3, 0, true);
1310
- }
1311
- } catch (error) {
1312
- if (abort)
1313
- return;
1314
- if (transition2)
1315
- return transition2.runTransition(() => {
1316
- node._setError(error);
1317
- transition2 = null;
1318
- }, true);
1319
- node._setError(error);
1320
- }
1321
- })();
1322
- }
1323
- throw new NotReadyError(getOwner());
1324
- },
1325
- options
1326
- );
1327
- const read = node.wait.bind(node);
1328
- read.refresh = () => {
1329
- let n = node;
1330
- if (ActiveTransition && !node._cloned) {
1331
- n = cloneGraph(node);
1332
- }
1333
- n._state = STATE_DIRTY;
1334
- refreshing = true;
1335
- n._updateIfNecessary();
1336
- };
1337
- return read;
1338
- }
1339
- function createEffect(compute2, effect, value, options) {
1340
- void new Effect(
1341
- value,
1342
- compute2,
1343
- effect.effect || effect,
1344
- effect.error,
1345
1076
  { ...options, name: options?.name ?? "effect" }
1346
1077
  );
1347
1078
  }
1348
- function createRenderEffect(compute2, effect, value, options) {
1349
- void new Effect(value, compute2, effect, void 0, {
1079
+ function createRenderEffect(compute, effectFn, value, options) {
1080
+ void effect(compute, effectFn, void 0, value, {
1350
1081
  render: true,
1351
1082
  ...{ ...options, name: options?.name ?? "effect" }
1352
1083
  });
1353
1084
  }
1354
- function createTrackedEffect(compute2, options) {
1355
- void new TrackedEffect(compute2, options);
1356
- }
1357
- function createReaction(effect, options) {
1358
- let cleanup = void 0;
1359
- onCleanup(() => cleanup?.());
1360
- return (tracking) => {
1361
- const node = new Effect(
1362
- void 0,
1363
- tracking,
1364
- () => {
1365
- cleanup?.();
1366
- cleanup = (effect.effect || effect)?.();
1367
- node.dispose(true);
1368
- },
1369
- effect.error,
1370
- {
1371
- defer: true,
1372
- ...{ ...options, name: options?.name ?? "effect" }
1373
- }
1374
- );
1375
- };
1376
- }
1377
- function createRoot(init, options) {
1378
- const owner = new Owner(options?.id);
1379
- return compute(owner, !init.length ? init : () => init(() => owner.dispose()), null);
1085
+ function createTrackedEffect(compute, options) {
1380
1086
  }
1381
- function runWithOwner(owner, run) {
1382
- return compute(owner, run, null);
1087
+ function createReaction(effect2, options) {
1383
1088
  }
1384
1089
  function resolve(fn) {
1385
1090
  return new Promise((res, rej) => {
1386
1091
  createRoot((dispose) => {
1387
- new EagerComputation(void 0, () => {
1092
+ computed(() => {
1388
1093
  try {
1389
1094
  res(fn());
1390
1095
  } catch (err) {
@@ -1398,44 +1103,9 @@ function resolve(fn) {
1398
1103
  });
1399
1104
  }
1400
1105
  function createOptimistic(first, second, third) {
1401
- const node = typeof first === "function" ? new Computation(
1402
- second,
1403
- (prev) => {
1404
- if (node._optimistic._transition) {
1405
- latest(() => first(prev));
1406
- return prev;
1407
- }
1408
- return first(prev);
1409
- },
1410
- third
1411
- ) : new Computation(first, null, second);
1412
- node._optimistic = () => node.write(first);
1413
- function write(v) {
1414
- if (!ActiveTransition)
1415
- throw new Error("createOptimistic can only be updated inside a transition");
1416
- ActiveTransition.addOptimistic(node._optimistic);
1417
- queueMicrotask(() => {
1418
- if (node._optimistic._transition) {
1419
- node._updateIfNecessary();
1420
- node.write(v);
1421
- }
1422
- });
1423
- }
1424
- return [node.wait.bind(node), write];
1106
+ return {};
1425
1107
  }
1426
- function transition(fn) {
1427
- let t = new Transition(new Computation(void 0, null));
1428
- queueMicrotask(() => t.runTransition(() => fn((fn2) => t.runTransition(fn2))));
1429
- }
1430
- function useTransition() {
1431
- const [pending, setPending] = createOptimistic(false);
1432
- function start(fn) {
1433
- transition((resume) => {
1434
- setPending(true);
1435
- return fn(resume);
1436
- });
1437
- }
1438
- return [pending, start];
1108
+ function onSettled(callback) {
1439
1109
  }
1440
1110
 
1441
1111
  // src/store/reconcile.ts
@@ -1443,7 +1113,7 @@ function unwrap(value) {
1443
1113
  return value?.[$TARGET]?.[STORE_NODE] ?? value;
1444
1114
  }
1445
1115
  function getOverrideValue(value, override, nodes, key) {
1446
- return nodes && key in nodes ? nodes[key].read() : override && key in override ? override[key] : value[key];
1116
+ return nodes && key in nodes ? read(nodes[key]) : override && key in override ? override[key] : value[key];
1447
1117
  }
1448
1118
  function getAllKeys(value, override, next) {
1449
1119
  const keys = getKeys(value, override);
@@ -1477,16 +1147,16 @@ function applyState(next, state, keyFn, all) {
1477
1147
  if (start > newEnd || start > end) {
1478
1148
  for (j = start; j <= newEnd; j++) {
1479
1149
  changed = true;
1480
- target[STORE_NODE][j]?.write(wrap(next[j], target));
1150
+ target[STORE_NODE][j] && setSignal(target[STORE_NODE][j], wrap(next[j], target));
1481
1151
  }
1482
1152
  for (; j < next.length; j++) {
1483
1153
  changed = true;
1484
1154
  const wrapped = wrap(temp[j], target);
1485
- target[STORE_NODE][j]?.write(wrapped);
1155
+ target[STORE_NODE][j] && setSignal(target[STORE_NODE][j], wrapped);
1486
1156
  applyState(next[j], wrapped, keyFn, all);
1487
1157
  }
1488
- changed && target[STORE_NODE][$TRACK]?.write(void 0);
1489
- prevLength !== next.length && target[STORE_NODE].length?.write(next.length);
1158
+ changed && target[STORE_NODE][$TRACK] && setSignal(target[STORE_NODE][$TRACK], void 0);
1159
+ prevLength !== next.length && target[STORE_NODE].length && setSignal(target[STORE_NODE].length, next.length);
1490
1160
  return;
1491
1161
  }
1492
1162
  newIndicesNext = new Array(newEnd + 1);
@@ -1510,10 +1180,10 @@ function applyState(next, state, keyFn, all) {
1510
1180
  for (j = start; j < next.length; j++) {
1511
1181
  if (j in temp) {
1512
1182
  const wrapped = wrap(temp[j], target);
1513
- target[STORE_NODE][j]?.write(wrapped);
1183
+ target[STORE_NODE][j] && setSignal(target[STORE_NODE][j], wrapped);
1514
1184
  applyState(next[j], wrapped, keyFn, all);
1515
1185
  } else
1516
- target[STORE_NODE][j]?.write(wrap(next[j], target));
1186
+ target[STORE_NODE][j] && setSignal(target[STORE_NODE][j], wrap(next[j], target));
1517
1187
  }
1518
1188
  if (start < next.length)
1519
1189
  changed = true;
@@ -1525,9 +1195,9 @@ function applyState(next, state, keyFn, all) {
1525
1195
  }
1526
1196
  if (prevLength !== next.length) {
1527
1197
  changed = true;
1528
- target[STORE_NODE].length?.write(next.length);
1198
+ target[STORE_NODE].length && setSignal(target[STORE_NODE].length, next.length);
1529
1199
  }
1530
- changed && target[STORE_NODE][$TRACK]?.write(void 0);
1200
+ changed && target[STORE_NODE][$TRACK] && setSignal(target[STORE_NODE][$TRACK], void 0);
1531
1201
  return;
1532
1202
  }
1533
1203
  if (nodes) {
@@ -1541,8 +1211,8 @@ function applyState(next, state, keyFn, all) {
1541
1211
  if (previousValue === nextValue)
1542
1212
  continue;
1543
1213
  if (!previousValue || !isWrappable(previousValue) || keyFn(previousValue) != null && keyFn(previousValue) !== keyFn(nextValue)) {
1544
- tracked?.write(void 0);
1545
- node?.write(isWrappable(nextValue) ? wrap(nextValue, target) : nextValue);
1214
+ tracked && setSignal(tracked, void 0);
1215
+ node && setSignal(node, isWrappable(nextValue) ? wrap(nextValue, target) : nextValue);
1546
1216
  } else
1547
1217
  applyState(nextValue, wrap(previousValue, target), keyFn, all);
1548
1218
  }
@@ -1550,7 +1220,8 @@ function applyState(next, state, keyFn, all) {
1550
1220
  if (nodes = target[STORE_HAS]) {
1551
1221
  const keys = Object.keys(nodes);
1552
1222
  for (let i = 0, len = keys.length; i < len; i++) {
1553
- nodes[keys[i]].write(keys[i] in next);
1223
+ const key = keys[i];
1224
+ setSignal(nodes[key], key in next);
1554
1225
  }
1555
1226
  }
1556
1227
  }
@@ -1568,13 +1239,14 @@ function reconcile(value, key, all = false) {
1568
1239
 
1569
1240
  // src/store/projection.ts
1570
1241
  function createProjectionInternal(fn, initialValue = {}, options) {
1242
+ let node;
1571
1243
  const wrappedMap = /* @__PURE__ */ new WeakMap();
1572
1244
  const traps = {
1573
1245
  ...storeTraps,
1574
1246
  get(target, property, receiver) {
1575
1247
  const o = getOwner();
1576
- const n = getTransitionSource(node);
1577
- (!o || o !== n) && n.wait();
1248
+ const n = node;
1249
+ (!o || o !== n) && n && read(n);
1578
1250
  return storeTraps.get(target, property, receiver);
1579
1251
  }
1580
1252
  };
@@ -1591,7 +1263,7 @@ function createProjectionInternal(fn, initialValue = {}, options) {
1591
1263
  return wrapped;
1592
1264
  };
1593
1265
  const wrappedStore = wrapProjection(initialValue);
1594
- const node = new FirewallComputation(() => {
1266
+ node = computed(() => {
1595
1267
  storeSetter(wrappedStore, (s) => {
1596
1268
  const value = fn(s);
1597
1269
  if (value !== s && value !== void 0) {
@@ -1649,7 +1321,7 @@ function getNodes(target, type) {
1649
1321
  function getNode(nodes, property, value, equals = isEqual) {
1650
1322
  if (nodes[property])
1651
1323
  return nodes[property];
1652
- return nodes[property] = new Computation(value, null, {
1324
+ return nodes[property] = signal(value, {
1653
1325
  equals,
1654
1326
  unobserved() {
1655
1327
  delete nodes[property];
@@ -1657,7 +1329,7 @@ function getNode(nodes, property, value, equals = isEqual) {
1657
1329
  });
1658
1330
  }
1659
1331
  function trackSelf(target, symbol = $TRACK) {
1660
- getObserver() && getNode(getNodes(target, STORE_NODE), symbol, void 0, false).read();
1332
+ getObserver() && read(getNode(getNodes(target, STORE_NODE), symbol, void 0, false));
1661
1333
  }
1662
1334
  function getKeys(source, override, enumerable = true) {
1663
1335
  const baseKeys = untrack(() => enumerable ? Object.keys(source) : Reflect.ownKeys(source));
@@ -1705,7 +1377,7 @@ var storeTraps = {
1705
1377
  return desc.get.call(receiver);
1706
1378
  }
1707
1379
  if (Writing?.has(receiver)) {
1708
- let value2 = tracked && (overridden || !proxySource) ? tracked._value : storeValue[property];
1380
+ let value2 = tracked && (overridden || !proxySource) ? tracked._pendingValue !== NOT_PENDING ? tracked._pendingValue : tracked._value : storeValue[property];
1709
1381
  value2 === $DELETED && (value2 = void 0);
1710
1382
  if (!isWrappable(value2))
1711
1383
  return value2;
@@ -1713,14 +1385,14 @@ var storeTraps = {
1713
1385
  Writing.add(wrapped);
1714
1386
  return wrapped;
1715
1387
  }
1716
- let value = tracked ? overridden || !proxySource ? nodes[property].read() : (nodes[property].read(), storeValue[property]) : storeValue[property];
1388
+ let value = tracked ? overridden || !proxySource ? read(nodes[property]) : (read(nodes[property]), storeValue[property]) : storeValue[property];
1717
1389
  value === $DELETED && (value = void 0);
1718
1390
  if (!tracked) {
1719
1391
  if (!overridden && typeof value === "function" && !storeValue.hasOwnProperty(property)) {
1720
1392
  let proto;
1721
1393
  return !Array.isArray(target[STORE_VALUE]) && (proto = Object.getPrototypeOf(target[STORE_VALUE])) && proto !== Object.prototype ? value.bind(storeValue) : value;
1722
1394
  } else if (getObserver()) {
1723
- return getNode(nodes, property, isWrappable(value) ? wrap(value, target) : value).read();
1395
+ return read(getNode(nodes, property, isWrappable(value) ? wrap(value, target) : value));
1724
1396
  }
1725
1397
  }
1726
1398
  return isWrappable(value) ? wrap(value, target) : value;
@@ -1729,7 +1401,7 @@ var storeTraps = {
1729
1401
  if (property === $PROXY || property === $TRACK || property === "__proto__")
1730
1402
  return true;
1731
1403
  const has = target[STORE_OVERRIDE] && property in target[STORE_OVERRIDE] ? target[STORE_OVERRIDE][property] !== $DELETED : property in target[STORE_VALUE];
1732
- getObserver() && getNode(getNodes(target, STORE_HAS), property, has).read();
1404
+ getObserver() && read(getNode(getNodes(target, STORE_HAS), property, has));
1733
1405
  return has;
1734
1406
  },
1735
1407
  set(target, property, rawValue) {
@@ -1754,15 +1426,15 @@ var storeTraps = {
1754
1426
  }
1755
1427
  if (recursivelyNotify(store, storeLookup) && wrappable)
1756
1428
  recursivelyAddParent(value, store);
1757
- target[STORE_HAS]?.[property]?.write(true);
1429
+ target[STORE_HAS]?.[property] && setSignal(target[STORE_HAS][property], true);
1758
1430
  const nodes = getNodes(target, STORE_NODE);
1759
- nodes[property]?.write(wrappable ? wrap(value, target) : value);
1431
+ nodes[property] && setSignal(nodes[property], () => wrappable ? wrap(value, target) : value);
1760
1432
  if (Array.isArray(state)) {
1761
1433
  const index = parseInt(property) + 1;
1762
1434
  if (index > len)
1763
- nodes.length?.write(index);
1435
+ nodes.length && setSignal(nodes.length, index);
1764
1436
  }
1765
- nodes[$TRACK]?.write(void 0);
1437
+ nodes[$TRACK] && setSignal(nodes[$TRACK], void 0);
1766
1438
  });
1767
1439
  }
1768
1440
  return true;
@@ -1781,10 +1453,11 @@ var storeTraps = {
1781
1453
  const parents = PARENTS.get(prev);
1782
1454
  parents && (parents instanceof Set ? parents.delete(target) : PARENTS.delete(prev));
1783
1455
  }
1784
- target[STORE_HAS]?.[property]?.write(false);
1456
+ if (target[STORE_HAS]?.[property])
1457
+ setSignal(target[STORE_HAS][property], false);
1785
1458
  const nodes = getNodes(target, STORE_NODE);
1786
- nodes[property]?.write(void 0);
1787
- nodes[$TRACK]?.write(void 0);
1459
+ nodes[property] && setSignal(nodes[property], void 0);
1460
+ nodes[$TRACK] && setSignal(nodes[$TRACK], void 0);
1788
1461
  });
1789
1462
  }
1790
1463
  return true;
@@ -1838,7 +1511,7 @@ function recursivelyNotify(state, lookup) {
1838
1511
  if (target) {
1839
1512
  const deep2 = getNodes(target, STORE_NODE)[$DEEP];
1840
1513
  if (deep2) {
1841
- deep2.write(void 0);
1514
+ setSignal(deep2, void 0);
1842
1515
  notified = true;
1843
1516
  }
1844
1517
  lookup = target[STORE_LOOKUP] || lookup;
@@ -1895,31 +1568,7 @@ function deep(store) {
1895
1568
 
1896
1569
  // src/store/optimistic.ts
1897
1570
  function createOptimisticStore(first, second, options) {
1898
- const derived = typeof first === "function";
1899
- const { store, node } = derived ? createProjectionInternal(
1900
- (draft) => {
1901
- if (reset._transition) {
1902
- latest(() => first(draft));
1903
- return draft;
1904
- }
1905
- return first(draft);
1906
- },
1907
- second,
1908
- options
1909
- ) : createProjectionInternal(() => {
1910
- }, first);
1911
- const reset = () => storeSetter(
1912
- store,
1913
- reconcile(derived ? first(store) || store : first, options?.key || "id", options?.all)
1914
- );
1915
- const write = (v) => {
1916
- if (!ActiveTransition)
1917
- throw new Error("createOptimisticStore can only be updated inside a transition");
1918
- ActiveTransition.addOptimistic(reset);
1919
- queueMicrotask(() => reset._transition && storeSetter(store, v));
1920
- };
1921
- node._optimistic = reset;
1922
- return [store, write];
1571
+ return [];
1923
1572
  }
1924
1573
 
1925
1574
  // src/store/utils.ts
@@ -2125,19 +1774,21 @@ function omit(props, ...keys) {
2125
1774
  // src/map.ts
2126
1775
  function mapArray(list, map, options) {
2127
1776
  const keyFn = typeof options?.keyed === "function" ? options.keyed : void 0;
2128
- return updateKeyedMap.bind({
2129
- _owner: new Owner(),
2130
- _len: 0,
2131
- _list: list,
2132
- _items: [],
2133
- _map: map,
2134
- _mappings: [],
2135
- _nodes: [],
2136
- _key: keyFn,
2137
- _rows: keyFn || options?.keyed === false ? [] : void 0,
2138
- _indexes: map.length > 1 ? [] : void 0,
2139
- _fallback: options?.fallback
2140
- });
1777
+ return createMemo(
1778
+ updateKeyedMap.bind({
1779
+ _owner: createOwner(),
1780
+ _len: 0,
1781
+ _list: list,
1782
+ _items: [],
1783
+ _map: map,
1784
+ _mappings: [],
1785
+ _nodes: [],
1786
+ _key: keyFn,
1787
+ _rows: keyFn || options?.keyed === false ? [] : void 0,
1788
+ _indexes: map.length > 1 ? [] : void 0,
1789
+ _fallback: options?.fallback
1790
+ })
1791
+ );
2141
1792
  }
2142
1793
  var pureOptions = { pureWrite: true };
2143
1794
  function updateKeyedMap() {
@@ -2145,16 +1796,19 @@ function updateKeyedMap() {
2145
1796
  newItems[$TRACK];
2146
1797
  runWithOwner(this._owner, () => {
2147
1798
  let i, j, mapper = this._rows ? () => {
2148
- this._rows[j] = new Computation(newItems[j], null, pureOptions);
2149
- this._indexes && (this._indexes[j] = new Computation(j, null, pureOptions));
1799
+ this._rows[j] = signal(newItems[j], pureOptions);
1800
+ this._indexes && (this._indexes[j] = signal(j, pureOptions));
2150
1801
  return this._map(
2151
- Computation.prototype.read.bind(this._rows[j]),
2152
- this._indexes ? Computation.prototype.read.bind(this._indexes[j]) : void 0
1802
+ read.bind(null, this._rows[j]),
1803
+ this._indexes ? read.bind(null, this._indexes[j]) : void 0
2153
1804
  );
2154
1805
  } : this._indexes ? () => {
2155
1806
  const item = newItems[j];
2156
- this._indexes[j] = new Computation(j, null, pureOptions);
2157
- return this._map(() => item, Computation.prototype.read.bind(this._indexes[j]));
1807
+ this._indexes[j] = signal(j, pureOptions);
1808
+ return this._map(
1809
+ () => item,
1810
+ read.bind(null, this._indexes[j])
1811
+ );
2158
1812
  } : () => {
2159
1813
  const item = newItems[j];
2160
1814
  return this._map(() => item);
@@ -2170,10 +1824,9 @@ function updateKeyedMap() {
2170
1824
  this._indexes && (this._indexes = []);
2171
1825
  }
2172
1826
  if (this._fallback && !this._mappings[0]) {
2173
- this._mappings[0] = compute(
2174
- this._nodes[0] = new Owner(),
2175
- this._fallback,
2176
- null
1827
+ this._mappings[0] = runWithOwner(
1828
+ this._nodes[0] = createOwner(),
1829
+ this._fallback
2177
1830
  );
2178
1831
  }
2179
1832
  } else if (this._len === 0) {
@@ -2182,14 +1835,14 @@ function updateKeyedMap() {
2182
1835
  this._mappings = new Array(newLen);
2183
1836
  for (j = 0; j < newLen; j++) {
2184
1837
  this._items[j] = newItems[j];
2185
- this._mappings[j] = compute(this._nodes[j] = new Owner(), mapper, null);
1838
+ this._mappings[j] = runWithOwner(this._nodes[j] = createOwner(), mapper);
2186
1839
  }
2187
1840
  this._len = newLen;
2188
1841
  } else {
2189
1842
  let start, end, newEnd, item, key, newIndices, newIndicesNext, temp = new Array(newLen), tempNodes = new Array(newLen), tempRows = this._rows ? new Array(newLen) : void 0, tempIndexes = this._indexes ? new Array(newLen) : void 0;
2190
1843
  for (start = 0, end = Math.min(this._len, newLen); start < end && (this._items[start] === newItems[start] || this._rows && compare(this._key, this._items[start], newItems[start])); start++) {
2191
1844
  if (this._rows)
2192
- this._rows[start].write(newItems[start]);
1845
+ setSignal(this._rows[start], newItems[start]);
2193
1846
  }
2194
1847
  for (end = this._len - 1, newEnd = newLen - 1; end >= start && newEnd >= start && (this._items[end] === newItems[newEnd] || this._rows && compare(this._key, this._items[end], newItems[newEnd])); end--, newEnd--) {
2195
1848
  temp[newEnd] = this._mappings[end];
@@ -2226,14 +1879,14 @@ function updateKeyedMap() {
2226
1879
  this._nodes[j] = tempNodes[j];
2227
1880
  if (tempRows) {
2228
1881
  this._rows[j] = tempRows[j];
2229
- this._rows[j].write(newItems[j]);
1882
+ setSignal(this._rows[j], newItems[j]);
2230
1883
  }
2231
1884
  if (tempIndexes) {
2232
1885
  this._indexes[j] = tempIndexes[j];
2233
- this._indexes[j].write(j);
1886
+ setSignal(this._indexes[j], j);
2234
1887
  }
2235
1888
  } else {
2236
- this._mappings[j] = compute(this._nodes[j] = new Owner(), mapper, null);
1889
+ this._mappings[j] = runWithOwner(this._nodes[j] = createOwner(), mapper);
2237
1890
  }
2238
1891
  }
2239
1892
  this._mappings = this._mappings.slice(0, this._len = newLen);
@@ -2244,7 +1897,7 @@ function updateKeyedMap() {
2244
1897
  }
2245
1898
  function repeat(count, map, options) {
2246
1899
  return updateRepeat.bind({
2247
- _owner: new Owner(),
1900
+ _owner: createOwner(),
2248
1901
  _len: 0,
2249
1902
  _offset: 0,
2250
1903
  _count: count,
@@ -2267,10 +1920,9 @@ function updateRepeat() {
2267
1920
  this._len = 0;
2268
1921
  }
2269
1922
  if (this._fallback && !this._mappings[0]) {
2270
- this._mappings[0] = compute(
2271
- this._nodes[0] = new Owner(),
2272
- this._fallback,
2273
- null
1923
+ this._mappings[0] = runWithOwner(
1924
+ this._nodes[0] = createOwner(),
1925
+ this._fallback
2274
1926
  );
2275
1927
  }
2276
1928
  return;
@@ -2297,18 +1949,16 @@ function updateRepeat() {
2297
1949
  i--;
2298
1950
  }
2299
1951
  for (let i2 = 0; i2 < difference; i2++) {
2300
- this._mappings[i2] = compute(
2301
- this._nodes[i2] = new Owner(),
2302
- () => this._map(i2 + from),
2303
- null
1952
+ this._mappings[i2] = runWithOwner(
1953
+ this._nodes[i2] = createOwner(),
1954
+ () => this._map(i2 + from)
2304
1955
  );
2305
1956
  }
2306
1957
  }
2307
1958
  for (let i = prevTo; i < to; i++) {
2308
- this._mappings[i - from] = compute(
2309
- this._nodes[i - from] = new Owner(),
2310
- () => this._map(i),
2311
- null
1959
+ this._mappings[i - from] = runWithOwner(
1960
+ this._nodes[i - from] = createOwner(),
1961
+ () => this._map(i)
2312
1962
  );
2313
1963
  }
2314
1964
  this._mappings = this._mappings.slice(0, newLen);
@@ -2322,33 +1972,31 @@ function compare(key, a, b) {
2322
1972
  }
2323
1973
 
2324
1974
  // src/boundaries.ts
2325
- var BoundaryComputation = class extends EagerComputation {
2326
- _propagationMask;
2327
- constructor(compute2, propagationMask) {
2328
- super(void 0, compute2, { defer: true });
2329
- this._propagationMask = propagationMask;
2330
- }
2331
- write(value, flags) {
2332
- super.write(value, flags & ~this._propagationMask);
2333
- if (this._propagationMask & LOADING_BIT && !(this._stateFlags & UNINITIALIZED_BIT || ActiveTransition)) {
2334
- flags &= ~LOADING_BIT;
1975
+ function boundaryComputed(fn, propagationMask) {
1976
+ const node = computed(fn, void 0, {
1977
+ _internal: {
1978
+ _notifyQueue() {
1979
+ let flags = this._statusFlags;
1980
+ this._statusFlags &= ~this._propagationMask;
1981
+ if (this._propagationMask & 1 /* Pending */ && !(this._statusFlags & 4 /* Uninitialized */)) {
1982
+ flags &= ~1 /* Pending */;
1983
+ }
1984
+ this._queue.notify(this, this._propagationMask, flags);
1985
+ },
1986
+ _propagationMask: propagationMask
2335
1987
  }
2336
- getQueue(this).notify(this, this._propagationMask, flags);
2337
- return this._value;
2338
- }
2339
- };
1988
+ });
1989
+ node._propagationMask = propagationMask;
1990
+ return node;
1991
+ }
2340
1992
  function createBoundChildren(owner, fn, queue, mask) {
2341
1993
  const parentQueue = owner._queue;
2342
1994
  parentQueue.addChild(owner._queue = queue);
2343
1995
  onCleanup(() => parentQueue.removeChild(owner._queue));
2344
- return compute(
2345
- owner,
2346
- () => {
2347
- const c = new Computation(void 0, fn);
2348
- return new BoundaryComputation(() => latest(() => flatten(c.wait())), mask);
2349
- },
2350
- null
2351
- );
1996
+ return runWithOwner(owner, () => {
1997
+ const c = computed(fn);
1998
+ return boundaryComputed(() => staleValues(() => flatten(read(c))), mask);
1999
+ });
2352
2000
  }
2353
2001
  var ConditionalQueue = class extends Queue {
2354
2002
  _disabled;
@@ -2359,113 +2007,108 @@ var ConditionalQueue = class extends Queue {
2359
2007
  this._disabled = disabled;
2360
2008
  }
2361
2009
  run(type) {
2362
- if (!type || this._disabled.read())
2010
+ if (!type || read(this._disabled))
2363
2011
  return;
2364
2012
  return super.run(type);
2365
2013
  }
2366
2014
  notify(node, type, flags) {
2367
- if (this._disabled.read()) {
2368
- if (type & LOADING_BIT) {
2369
- if (flags & LOADING_BIT) {
2015
+ if (read(this._disabled)) {
2016
+ if (type & 1 /* Pending */) {
2017
+ if (flags & 1 /* Pending */) {
2370
2018
  this._pendingNodes.add(node);
2371
- type &= ~LOADING_BIT;
2019
+ type &= ~1 /* Pending */;
2372
2020
  } else if (this._pendingNodes.delete(node))
2373
- type &= ~LOADING_BIT;
2021
+ type &= ~1 /* Pending */;
2374
2022
  }
2375
- if (type & ERROR_BIT) {
2376
- if (flags & ERROR_BIT) {
2023
+ if (type & 2 /* Error */) {
2024
+ if (flags & 2 /* Error */) {
2377
2025
  this._errorNodes.add(node);
2378
- type &= ~ERROR_BIT;
2026
+ type &= ~2 /* Error */;
2379
2027
  } else if (this._errorNodes.delete(node))
2380
- type &= ~ERROR_BIT;
2028
+ type &= ~2 /* Error */;
2381
2029
  }
2382
2030
  }
2383
2031
  return type ? super.notify(node, type, flags) : true;
2384
2032
  }
2385
- merge(queue) {
2386
- queue._pendingNodes.forEach((n) => this.notify(n, LOADING_BIT, LOADING_BIT));
2387
- queue._errorNodes.forEach((n) => this.notify(n, ERROR_BIT, ERROR_BIT));
2388
- super.merge(queue);
2389
- }
2390
2033
  };
2391
2034
  var CollectionQueue = class extends Queue {
2392
2035
  _collectionType;
2393
2036
  _nodes = /* @__PURE__ */ new Set();
2394
- _disabled = new Computation(false, null, { pureWrite: true });
2037
+ _disabled = signal(false, { pureWrite: true });
2038
+ _initialized = false;
2395
2039
  constructor(type) {
2396
2040
  super();
2397
2041
  this._collectionType = type;
2398
2042
  }
2399
2043
  run(type) {
2400
- if (!type || this._disabled.read())
2044
+ if (!type || read(this._disabled))
2401
2045
  return;
2402
2046
  return super.run(type);
2403
2047
  }
2048
+ enqueue(type, fn) {
2049
+ if (this._collectionType & 1 /* Pending */ && this._initialized) {
2050
+ return this._parent?.enqueue(type, fn);
2051
+ }
2052
+ return super.enqueue(type, fn);
2053
+ }
2404
2054
  notify(node, type, flags) {
2405
- if (!(type & this._collectionType))
2055
+ if (!(type & this._collectionType) || this._collectionType & 1 /* Pending */ && this._initialized)
2406
2056
  return super.notify(node, type, flags);
2407
2057
  if (flags & this._collectionType) {
2408
2058
  this._nodes.add(node);
2409
2059
  if (this._nodes.size === 1)
2410
- this._disabled.write(true);
2060
+ setSignal(this._disabled, true);
2411
2061
  } else if (this._nodes.size > 0) {
2412
2062
  this._nodes.delete(node);
2413
2063
  if (this._nodes.size === 0)
2414
- this._disabled.write(false);
2064
+ setSignal(this._disabled, false);
2415
2065
  }
2416
2066
  type &= ~this._collectionType;
2417
2067
  return type ? super.notify(node, type, flags) : true;
2418
2068
  }
2419
- merge(queue) {
2420
- queue._nodes.forEach((n) => this.notify(n, this._collectionType, this._collectionType));
2421
- super.merge(queue);
2422
- }
2423
2069
  };
2424
2070
  function createBoundary(fn, condition) {
2425
- const owner = new Owner();
2426
- const queue = new ConditionalQueue(
2427
- new Computation(void 0, () => condition() === "hidden" /* HIDDEN */)
2428
- );
2071
+ const owner = createOwner();
2072
+ const queue = new ConditionalQueue(computed(() => condition() === "hidden" /* HIDDEN */));
2429
2073
  const tree = createBoundChildren(owner, fn, queue, 0);
2430
- new EagerComputation(void 0, () => {
2431
- const disabled = queue._disabled.read();
2432
- tree._propagationMask = disabled ? ERROR_BIT | LOADING_BIT : 0;
2074
+ computed(() => {
2075
+ const disabled = read(queue._disabled);
2076
+ tree._propagationMask = disabled ? 2 /* Error */ | 1 /* Pending */ : 0;
2433
2077
  if (!disabled) {
2434
- queue._pendingNodes.forEach((node) => queue.notify(node, LOADING_BIT, LOADING_BIT));
2435
- queue._errorNodes.forEach((node) => queue.notify(node, ERROR_BIT, ERROR_BIT));
2078
+ queue._pendingNodes.forEach(
2079
+ (node) => queue.notify(node, 1 /* Pending */, 1 /* Pending */)
2080
+ );
2081
+ queue._errorNodes.forEach((node) => queue.notify(node, 2 /* Error */, 2 /* Error */));
2436
2082
  queue._pendingNodes.clear();
2437
2083
  queue._errorNodes.clear();
2438
2084
  }
2439
2085
  });
2440
- return () => queue._disabled.read() ? void 0 : tree.read();
2086
+ return () => read(queue._disabled) ? void 0 : read(tree);
2441
2087
  }
2442
2088
  function createCollectionBoundary(type, fn, fallback) {
2443
- const owner = new Owner();
2089
+ const owner = createOwner();
2444
2090
  const queue = new CollectionQueue(type);
2445
2091
  const tree = createBoundChildren(owner, fn, queue, type);
2446
- const decision = new Computation(void 0, () => {
2447
- if (!queue._disabled.read()) {
2448
- const resolved = tree.read();
2449
- if (!untrack(() => queue._disabled.read()))
2450
- return resolved;
2092
+ const decision = computed(() => {
2093
+ if (!read(queue._disabled)) {
2094
+ const resolved = read(tree);
2095
+ if (!untrack(() => read(queue._disabled)))
2096
+ queue._initialized = true;
2097
+ return resolved;
2451
2098
  }
2452
2099
  return fallback(queue);
2453
2100
  });
2454
- return decision.read.bind(decision);
2101
+ return read.bind(null, decision);
2455
2102
  }
2456
- function createSuspense(fn, fallback) {
2457
- return createCollectionBoundary(LOADING_BIT, fn, () => fallback());
2103
+ function createLoadBoundary(fn, fallback) {
2104
+ return createCollectionBoundary(1 /* Pending */, fn, () => fallback());
2458
2105
  }
2459
2106
  function createErrorBoundary(fn, fallback) {
2460
- return createCollectionBoundary(ERROR_BIT, fn, (queue) => {
2461
- let node = getTransitionSource(queue._nodes.values().next().value);
2107
+ return createCollectionBoundary(2 /* Error */, fn, (queue) => {
2108
+ let node = queue._nodes.values().next().value;
2462
2109
  return fallback(node._error, () => {
2463
- incrementClock();
2464
2110
  for (let node2 of queue._nodes) {
2465
- if (ActiveTransition && !node2._cloned)
2466
- node2 = cloneGraph(node2);
2467
- node2._state = STATE_DIRTY;
2468
- getQueue(node2).enqueue(node2._type, node2._run.bind(node2));
2111
+ recompute(node2, true);
2469
2112
  }
2470
2113
  });
2471
2114
  });
@@ -2525,4 +2168,4 @@ function flattenArray(children, results = [], options) {
2525
2168
  return needsUnwrap;
2526
2169
  }
2527
2170
 
2528
- export { $PROXY, $TARGET, $TRACK, Computation, ContextNotFoundError, NoOwnerError, NotReadyError, Owner, Queue, SUPPORTS_PROXY, createAsync, createBoundary, createContext, createEffect, createErrorBoundary, createMemo, createOptimistic, createOptimisticStore, createProjection, createReaction, createRenderEffect, createRoot, createSignal, createStore, createSuspense, createTrackedEffect, deep, flatten, flush, getContext, getObserver, getOwner, hasContext, hasUpdated, isEqual, isPending, isWrappable, latest, mapArray, merge, omit, onCleanup, reconcile, repeat, resolve, runWithOwner, setContext, snapshot, transition, untrack, useTransition };
2171
+ export { $PROXY, $TARGET, $TRACK, ContextNotFoundError, NoOwnerError, NotReadyError, SUPPORTS_PROXY, createAsync, createBoundary, createContext, createEffect, createErrorBoundary, createLoadBoundary, createMemo, createOptimistic, createOptimisticStore, createProjection, createReaction, createRenderEffect, createRoot, createSignal, createStore, createTrackedEffect, deep, flatten, flush, getContext, getNextChildId, getObserver, getOwner, isEqual, isPending, isWrappable, mapArray, merge, omit, onCleanup, onSettled, pending, reconcile, repeat, resolve, runWithOwner, setContext, snapshot, untrack };