@solidjs/signals 0.7.4 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,618 @@ 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._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
- track(this);
689
- newFlags |= this._stateFlags & ~currentMask;
690
- if (this._stateFlags & ERROR_BIT) {
691
- 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
+ });
692
669
  } else {
693
- return this._value;
694
- }
695
- }
696
- /**
697
- * Return the current value of this computation
698
- * Automatically re-executes the surrounding computation when the value changes
699
- */
700
- read() {
701
- if (ActiveTransition && (ActiveTransition._sources.has(this) || !this._cloned && this._stateFlags & (UNINITIALIZED_BIT | ERROR_BIT))) {
702
- const clone = ActiveTransition._sources.get(this) || cloneGraph(this);
703
- if (clone !== this)
704
- return clone.read();
705
- }
706
- if (this._compute) {
707
- if (this._stateFlags & ERROR_BIT && this._time <= clock)
708
- update(this);
709
- else
710
- this._updateIfNecessary();
711
- }
712
- return this._read();
713
- }
714
- /**
715
- * Return the current value of this computation
716
- * Automatically re-executes the surrounding computation when the value changes
717
- *
718
- * If the computation has any unresolved ancestors, this function waits for the value to resolve
719
- * before continuing
720
- */
721
- wait() {
722
- if (ActiveTransition && (ActiveTransition._sources.has(this) || !this._cloned && this._stateFlags & (UNINITIALIZED_BIT | ERROR_BIT))) {
723
- const clone = ActiveTransition._sources.get(this) || cloneGraph(this);
724
- if (clone !== this)
725
- return clone.wait();
726
- }
727
- if (this._compute) {
728
- if (this._stateFlags & ERROR_BIT && this._time <= clock)
729
- update(this);
730
- else
731
- this._updateIfNecessary();
732
- }
733
- if ((notStale || this._stateFlags & UNINITIALIZED_BIT) && this._stateFlags & LOADING_BIT) {
734
- throw new NotReadyError(this);
735
- }
736
- if (staleCheck && (this._stateFlags & LOADING_BIT || this._transition)) {
737
- staleCheck._value = true;
738
- this._transition?._signal.read();
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;
910
828
  }
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;
829
+ if (el._pendingSignal)
830
+ el._pendingSignal._set(v);
831
+ }
832
+ clearStatusFlags(el);
833
+ el._time = clock;
834
+ for (let link2 = el._subs; link2 !== null; link2 = link2._nextSub) {
835
+ insertIntoHeap(link2._sub, link2._sub._flags & 32 /* Zombie */ ? zombieQueue : dirtyQueue);
836
+ }
837
+ schedule();
838
+ return v;
839
+ }
840
+ function getObserver() {
841
+ return tracking ? context : null;
842
+ }
843
+ function getOwner() {
844
+ return context;
845
+ }
846
+ function onCleanup(fn) {
847
+ if (!context)
848
+ return fn;
849
+ const node = context;
850
+ if (!node._disposal) {
851
+ node._disposal = fn;
852
+ } else if (Array.isArray(node._disposal)) {
853
+ node._disposal.push(fn);
854
+ } else {
855
+ node._disposal = [node._disposal, fn];
856
+ }
857
+ return fn;
858
+ }
859
+ function createOwner(options) {
860
+ const parent = context;
861
+ const owner = {
862
+ _root: true,
863
+ _parentComputed: parent?._root ? parent._parentComputed : parent,
864
+ _firstChild: null,
865
+ _nextSibling: null,
866
+ _disposal: null,
867
+ id: options?.id ?? (parent?.id != null ? getNextChildId(parent) : void 0),
868
+ _queue: parent?._queue ?? globalQueue,
869
+ _context: parent?._context || defaultContext,
870
+ _childCount: 0,
871
+ _pendingDisposal: null,
872
+ _pendingFirstChild: null,
873
+ _parent: parent,
874
+ dispose(self = true) {
875
+ disposeChildren(owner, self);
876
+ }
877
+ };
878
+ if (parent) {
879
+ const lastChild = parent._firstChild;
880
+ if (lastChild === null) {
881
+ parent._firstChild = owner;
882
+ } else {
883
+ owner._nextSibling = lastChild;
884
+ parent._firstChild = owner;
934
885
  }
935
- newSources = prevSources;
936
- newSourcesIndex = prevSourcesIndex;
937
- newFlags = prevFlags;
938
- node._time = clock + 1;
939
- node._state = STATE_CLEAN;
940
886
  }
887
+ return owner;
941
888
  }
942
- function isEqual(a, b) {
943
- return a === b;
889
+ function createRoot(init, options) {
890
+ const owner = createOwner(options);
891
+ return runWithOwner(owner, () => init(owner.dispose));
944
892
  }
945
- function untrack(fn) {
946
- if (currentObserver === null)
893
+ function runWithOwner(owner, fn) {
894
+ const oldContext = context;
895
+ context = owner;
896
+ try {
947
897
  return fn();
948
- return compute(getOwner(), fn, null);
898
+ } finally {
899
+ context = oldContext;
900
+ }
949
901
  }
950
- function hasUpdated(fn) {
951
- const current = updateCheck;
952
- updateCheck = { _value: false };
902
+ function staleValues(fn, set = true) {
903
+ const prevStale = stale;
904
+ stale = set;
953
905
  try {
954
- fn();
955
- return updateCheck._value;
906
+ return fn();
956
907
  } finally {
957
- updateCheck = current;
908
+ stale = prevStale;
958
909
  }
959
910
  }
960
- function pendingCheck(fn, loadingValue) {
961
- const current = staleCheck;
962
- staleCheck = { _value: false };
911
+ function pending(fn) {
912
+ const prevLatest = pendingValueCheck;
913
+ pendingValueCheck = true;
963
914
  try {
964
- latest(fn);
965
- return staleCheck._value;
915
+ return staleValues(fn, false);
916
+ } finally {
917
+ pendingValueCheck = prevLatest;
918
+ }
919
+ }
920
+ function isPending(fn, loadingValue) {
921
+ const current = pendingCheck;
922
+ pendingCheck = { _value: false };
923
+ try {
924
+ staleValues(fn);
925
+ return pendingCheck._value;
966
926
  } catch (err) {
967
927
  if (!(err instanceof NotReadyError))
968
928
  return false;
@@ -970,421 +930,163 @@ function pendingCheck(fn, loadingValue) {
970
930
  return loadingValue;
971
931
  throw err;
972
932
  } finally {
973
- staleCheck = current;
933
+ pendingCheck = current;
974
934
  }
975
935
  }
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;
936
+
937
+ // src/core/context.ts
938
+ function createContext(defaultValue, description) {
939
+ return { id: Symbol(description), defaultValue };
991
940
  }
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;
941
+ function getContext(context2, owner = getOwner()) {
942
+ if (!owner) {
943
+ throw new NoOwnerError();
1006
944
  }
945
+ const value = hasContext(context2, owner) ? owner._context[context2.id] : context2.defaultValue;
946
+ if (isUndefined(value)) {
947
+ throw new ContextNotFoundError();
948
+ }
949
+ return value;
1007
950
  }
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;
951
+ function setContext(context2, value, owner = getOwner()) {
952
+ if (!owner) {
953
+ throw new NoOwnerError();
1020
954
  }
955
+ owner._context = {
956
+ ...owner._context,
957
+ [context2.id]: isUndefined(value) ? context2.defaultValue : value
958
+ };
959
+ }
960
+ function hasContext(context2, owner) {
961
+ return !isUndefined(owner?._context[context2.id]);
962
+ }
963
+ function isUndefined(value) {
964
+ return typeof value === "undefined";
1021
965
  }
1022
966
 
1023
967
  // 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;
968
+ function effect(compute, effect2, error, initialValue, options) {
969
+ let initialized = false;
970
+ const node = computed(compute, initialValue, {
971
+ ...options,
972
+ _internal: {
973
+ _modified: true,
974
+ _prevValue: initialValue,
975
+ _effectFn: effect2,
976
+ _errorFn: error,
977
+ _cleanup: void 0,
978
+ _queue: getOwner()?._queue ?? globalQueue,
979
+ _type: options?.render ? 1 /* Render */ : 2 /* User */,
980
+ _notifyQueue(statusFlagsChanged, prevStatusFlags) {
981
+ if (initialized) {
982
+ const errorChanged = this._statusFlags && this._statusFlags === prevStatusFlags && statusFlagsChanged;
983
+ this._modified = !(this._statusFlags & 2 /* Error */) && !(this._statusFlags & 1 /* Pending */ & ~prevStatusFlags) && !errorChanged;
984
+ if (this._modified)
985
+ this._queue.enqueue(this._type, runEffect.bind(this));
986
+ }
987
+ if (this._statusFlags & 2 /* Error */) {
988
+ let error2 = this._error;
989
+ this._queue.notify(this, 1 /* Pending */, 0);
990
+ if (this._type === 2 /* User */) {
991
+ try {
992
+ return this._errorFn ? this._errorFn(error2, () => {
993
+ this._cleanup?.();
994
+ this._cleanup = void 0;
995
+ }) : console.error(error2);
996
+ } catch (e) {
997
+ error2 = e;
998
+ }
999
+ }
1000
+ if (!this._queue.notify(this, 2 /* Error */, 2 /* Error */))
1001
+ throw error2;
1002
+ } else if (this._type === 1 /* Render */) {
1003
+ this._queue.notify(
1004
+ this,
1005
+ 1 /* Pending */ | 2 /* Error */,
1006
+ this._statusFlags
1007
+ );
1120
1008
  }
1121
1009
  }
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
1010
  }
1011
+ });
1012
+ initialized = true;
1013
+ if (node._type === 1 /* Render */) {
1014
+ node._fn = (p) => !(node._statusFlags & 2 /* Error */) ? staleValues(() => compute(p)) : compute(p);
1214
1015
  }
1215
- for (let i = ancestors.length - 1; i >= 0; i--) {
1216
- if (ancestors[i]._state !== STATE_DISPOSED)
1217
- ancestors[i]._updateIfNecessary();
1016
+ !options?.defer && !(node._statusFlags & (2 /* Error */ | 1 /* Pending */)) && (node._type === 2 /* User */ ? node._queue.enqueue(node._type, runEffect.bind(node)) : runEffect.call(node));
1017
+ onCleanup(() => node._cleanup?.());
1018
+ if (!node._parent)
1019
+ console.warn("Effects created outside a reactive context will never be disposed");
1020
+ }
1021
+ function runEffect() {
1022
+ if (!this._modified || this._flags & 64 /* Disposed */)
1023
+ return;
1024
+ this._cleanup?.();
1025
+ this._cleanup = void 0;
1026
+ try {
1027
+ this._cleanup = this._effectFn(this._value, this._prevValue);
1028
+ } catch (error) {
1029
+ if (!this._queue.notify(this, 2 /* Error */, 2 /* Error */))
1030
+ throw error;
1031
+ } finally {
1032
+ this._prevValue = this._value;
1033
+ this._modified = false;
1218
1034
  }
1219
1035
  }
1220
1036
 
1221
1037
  // src/signals.ts
1222
1038
  function createSignal(first, second, third) {
1223
1039
  if (typeof first === "function") {
1224
- const node2 = new Computation(second, first, third);
1040
+ const node2 = computed(first, second, third);
1225
1041
  return [
1226
- node2.wait.bind(node2),
1227
- (v) => {
1228
- node2._updateIfNecessary();
1229
- return node2.write(v);
1230
- }
1042
+ read.bind(null, node2),
1043
+ setSignal.bind(null, node2)
1231
1044
  ];
1232
1045
  }
1233
1046
  const o = getOwner();
1234
1047
  const needsId = o?.id != null;
1235
- const node = new Computation(
1048
+ const node = signal(
1236
1049
  first,
1237
- null,
1238
- needsId ? { id: o.getNextChildId(), ...second } : second
1050
+ needsId ? { id: getNextChildId(o), ...second } : second
1239
1051
  );
1240
- return [node.read.bind(node), node.write.bind(node)];
1241
- }
1242
- function createMemo(compute2, value, options) {
1243
- let node = new Computation(
1052
+ return [
1053
+ read.bind(null, node),
1054
+ setSignal.bind(null, node)
1055
+ ];
1056
+ }
1057
+ function createMemo(compute, value, options) {
1058
+ let node = computed(compute, value, options);
1059
+ return read.bind(null, node);
1060
+ }
1061
+ function createAsync(compute, value, options) {
1062
+ const node = asyncComputed(compute, value, options);
1063
+ const ret = read.bind(null, node);
1064
+ ret.refresh = node._refresh;
1065
+ return ret;
1066
+ }
1067
+ function createEffect(compute, effectFn, value, options) {
1068
+ void effect(
1069
+ compute,
1070
+ effectFn.effect || effectFn,
1071
+ effectFn.error,
1244
1072
  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
1073
  { ...options, name: options?.name ?? "effect" }
1346
1074
  );
1347
1075
  }
1348
- function createRenderEffect(compute2, effect, value, options) {
1349
- void new Effect(value, compute2, effect, void 0, {
1076
+ function createRenderEffect(compute, effectFn, value, options) {
1077
+ void effect(compute, effectFn, void 0, value, {
1350
1078
  render: true,
1351
1079
  ...{ ...options, name: options?.name ?? "effect" }
1352
1080
  });
1353
1081
  }
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
- };
1082
+ function createTrackedEffect(compute, options) {
1376
1083
  }
1377
- function createRoot(init, options) {
1378
- const owner = new Owner(options?.id);
1379
- return compute(owner, !init.length ? init : () => init(() => owner.dispose()), null);
1380
- }
1381
- function runWithOwner(owner, run) {
1382
- return compute(owner, run, null);
1084
+ function createReaction(effect2, options) {
1383
1085
  }
1384
1086
  function resolve(fn) {
1385
1087
  return new Promise((res, rej) => {
1386
1088
  createRoot((dispose) => {
1387
- new EagerComputation(void 0, () => {
1089
+ computed(() => {
1388
1090
  try {
1389
1091
  res(fn());
1390
1092
  } catch (err) {
@@ -1398,43 +1100,9 @@ function resolve(fn) {
1398
1100
  });
1399
1101
  }
1400
1102
  function createOptimistic(first, second, third) {
1401
- const node = typeof first === "function" ? new Computation(
1402
- second,
1403
- (prev) => {
1404
- const res = first(prev);
1405
- if (node._optimistic._transition)
1406
- return prev;
1407
- return res;
1408
- },
1409
- third
1410
- ) : new Computation(first, null, second);
1411
- node._optimistic = () => node.write(first);
1412
- function write(v) {
1413
- if (!ActiveTransition)
1414
- throw new Error("createOptimistic can only be updated inside a transition");
1415
- ActiveTransition.addOptimistic(node._optimistic);
1416
- queueMicrotask(() => {
1417
- if (node._optimistic._transition) {
1418
- node._updateIfNecessary();
1419
- node.write(v);
1420
- }
1421
- });
1422
- }
1423
- return [node.wait.bind(node), write];
1103
+ return {};
1424
1104
  }
1425
- function transition(fn) {
1426
- let t = new Transition(new Computation(void 0, null));
1427
- queueMicrotask(() => t.runTransition(() => fn((fn2) => t.runTransition(fn2))));
1428
- }
1429
- function useTransition() {
1430
- const [pending, setPending] = createOptimistic(false);
1431
- function start(fn) {
1432
- transition((resume) => {
1433
- setPending(true);
1434
- return fn(resume);
1435
- });
1436
- }
1437
- return [pending, start];
1105
+ function onSettled(callback) {
1438
1106
  }
1439
1107
 
1440
1108
  // src/store/reconcile.ts
@@ -1442,7 +1110,7 @@ function unwrap(value) {
1442
1110
  return value?.[$TARGET]?.[STORE_NODE] ?? value;
1443
1111
  }
1444
1112
  function getOverrideValue(value, override, nodes, key) {
1445
- return nodes && key in nodes ? nodes[key].read() : override && key in override ? override[key] : value[key];
1113
+ return nodes && key in nodes ? read(nodes[key]) : override && key in override ? override[key] : value[key];
1446
1114
  }
1447
1115
  function getAllKeys(value, override, next) {
1448
1116
  const keys = getKeys(value, override);
@@ -1476,16 +1144,16 @@ function applyState(next, state, keyFn, all) {
1476
1144
  if (start > newEnd || start > end) {
1477
1145
  for (j = start; j <= newEnd; j++) {
1478
1146
  changed = true;
1479
- target[STORE_NODE][j]?.write(wrap(next[j], target));
1147
+ target[STORE_NODE][j] && setSignal(target[STORE_NODE][j], wrap(next[j], target));
1480
1148
  }
1481
1149
  for (; j < next.length; j++) {
1482
1150
  changed = true;
1483
1151
  const wrapped = wrap(temp[j], target);
1484
- target[STORE_NODE][j]?.write(wrapped);
1152
+ target[STORE_NODE][j] && setSignal(target[STORE_NODE][j], wrapped);
1485
1153
  applyState(next[j], wrapped, keyFn, all);
1486
1154
  }
1487
- changed && target[STORE_NODE][$TRACK]?.write(void 0);
1488
- prevLength !== next.length && target[STORE_NODE].length?.write(next.length);
1155
+ changed && target[STORE_NODE][$TRACK] && setSignal(target[STORE_NODE][$TRACK], void 0);
1156
+ prevLength !== next.length && target[STORE_NODE].length && setSignal(target[STORE_NODE].length, next.length);
1489
1157
  return;
1490
1158
  }
1491
1159
  newIndicesNext = new Array(newEnd + 1);
@@ -1509,10 +1177,10 @@ function applyState(next, state, keyFn, all) {
1509
1177
  for (j = start; j < next.length; j++) {
1510
1178
  if (j in temp) {
1511
1179
  const wrapped = wrap(temp[j], target);
1512
- target[STORE_NODE][j]?.write(wrapped);
1180
+ target[STORE_NODE][j] && setSignal(target[STORE_NODE][j], wrapped);
1513
1181
  applyState(next[j], wrapped, keyFn, all);
1514
1182
  } else
1515
- target[STORE_NODE][j]?.write(wrap(next[j], target));
1183
+ target[STORE_NODE][j] && setSignal(target[STORE_NODE][j], wrap(next[j], target));
1516
1184
  }
1517
1185
  if (start < next.length)
1518
1186
  changed = true;
@@ -1524,9 +1192,9 @@ function applyState(next, state, keyFn, all) {
1524
1192
  }
1525
1193
  if (prevLength !== next.length) {
1526
1194
  changed = true;
1527
- target[STORE_NODE].length?.write(next.length);
1195
+ target[STORE_NODE].length && setSignal(target[STORE_NODE].length, next.length);
1528
1196
  }
1529
- changed && target[STORE_NODE][$TRACK]?.write(void 0);
1197
+ changed && target[STORE_NODE][$TRACK] && setSignal(target[STORE_NODE][$TRACK], void 0);
1530
1198
  return;
1531
1199
  }
1532
1200
  if (nodes) {
@@ -1540,8 +1208,8 @@ function applyState(next, state, keyFn, all) {
1540
1208
  if (previousValue === nextValue)
1541
1209
  continue;
1542
1210
  if (!previousValue || !isWrappable(previousValue) || keyFn(previousValue) != null && keyFn(previousValue) !== keyFn(nextValue)) {
1543
- tracked?.write(void 0);
1544
- node?.write(isWrappable(nextValue) ? wrap(nextValue, target) : nextValue);
1211
+ tracked && setSignal(tracked, void 0);
1212
+ node && setSignal(node, isWrappable(nextValue) ? wrap(nextValue, target) : nextValue);
1545
1213
  } else
1546
1214
  applyState(nextValue, wrap(previousValue, target), keyFn, all);
1547
1215
  }
@@ -1549,7 +1217,8 @@ function applyState(next, state, keyFn, all) {
1549
1217
  if (nodes = target[STORE_HAS]) {
1550
1218
  const keys = Object.keys(nodes);
1551
1219
  for (let i = 0, len = keys.length; i < len; i++) {
1552
- nodes[keys[i]].write(keys[i] in next);
1220
+ const key = keys[i];
1221
+ setSignal(nodes[key], key in next);
1553
1222
  }
1554
1223
  }
1555
1224
  }
@@ -1567,13 +1236,14 @@ function reconcile(value, key, all = false) {
1567
1236
 
1568
1237
  // src/store/projection.ts
1569
1238
  function createProjectionInternal(fn, initialValue = {}, options) {
1239
+ let node;
1570
1240
  const wrappedMap = /* @__PURE__ */ new WeakMap();
1571
1241
  const traps = {
1572
1242
  ...storeTraps,
1573
1243
  get(target, property, receiver) {
1574
1244
  const o = getOwner();
1575
- const n = getTransitionSource(node);
1576
- (!o || o !== n) && n.wait();
1245
+ const n = node;
1246
+ (!o || o !== n) && n && read(n);
1577
1247
  return storeTraps.get(target, property, receiver);
1578
1248
  }
1579
1249
  };
@@ -1590,7 +1260,7 @@ function createProjectionInternal(fn, initialValue = {}, options) {
1590
1260
  return wrapped;
1591
1261
  };
1592
1262
  const wrappedStore = wrapProjection(initialValue);
1593
- const node = new FirewallComputation(() => {
1263
+ node = computed(() => {
1594
1264
  storeSetter(wrappedStore, (s) => {
1595
1265
  const value = fn(s);
1596
1266
  if (value !== s && value !== void 0) {
@@ -1648,7 +1318,7 @@ function getNodes(target, type) {
1648
1318
  function getNode(nodes, property, value, equals = isEqual) {
1649
1319
  if (nodes[property])
1650
1320
  return nodes[property];
1651
- return nodes[property] = new Computation(value, null, {
1321
+ return nodes[property] = signal(value, {
1652
1322
  equals,
1653
1323
  unobserved() {
1654
1324
  delete nodes[property];
@@ -1656,7 +1326,7 @@ function getNode(nodes, property, value, equals = isEqual) {
1656
1326
  });
1657
1327
  }
1658
1328
  function trackSelf(target, symbol = $TRACK) {
1659
- getObserver() && getNode(getNodes(target, STORE_NODE), symbol, void 0, false).read();
1329
+ getObserver() && read(getNode(getNodes(target, STORE_NODE), symbol, void 0, false));
1660
1330
  }
1661
1331
  function getKeys(source, override, enumerable = true) {
1662
1332
  const baseKeys = untrack(() => enumerable ? Object.keys(source) : Reflect.ownKeys(source));
@@ -1704,7 +1374,7 @@ var storeTraps = {
1704
1374
  return desc.get.call(receiver);
1705
1375
  }
1706
1376
  if (Writing?.has(receiver)) {
1707
- let value2 = tracked && (overridden || !proxySource) ? tracked._value : storeValue[property];
1377
+ let value2 = tracked && (overridden || !proxySource) ? tracked._pendingValue !== NOT_PENDING ? tracked._pendingValue : tracked._value : storeValue[property];
1708
1378
  value2 === $DELETED && (value2 = void 0);
1709
1379
  if (!isWrappable(value2))
1710
1380
  return value2;
@@ -1712,14 +1382,14 @@ var storeTraps = {
1712
1382
  Writing.add(wrapped);
1713
1383
  return wrapped;
1714
1384
  }
1715
- let value = tracked ? overridden || !proxySource ? nodes[property].read() : (nodes[property].read(), storeValue[property]) : storeValue[property];
1385
+ let value = tracked ? overridden || !proxySource ? read(nodes[property]) : (read(nodes[property]), storeValue[property]) : storeValue[property];
1716
1386
  value === $DELETED && (value = void 0);
1717
1387
  if (!tracked) {
1718
1388
  if (!overridden && typeof value === "function" && !storeValue.hasOwnProperty(property)) {
1719
1389
  let proto;
1720
1390
  return !Array.isArray(target[STORE_VALUE]) && (proto = Object.getPrototypeOf(target[STORE_VALUE])) && proto !== Object.prototype ? value.bind(storeValue) : value;
1721
1391
  } else if (getObserver()) {
1722
- return getNode(nodes, property, isWrappable(value) ? wrap(value, target) : value).read();
1392
+ return read(getNode(nodes, property, isWrappable(value) ? wrap(value, target) : value));
1723
1393
  }
1724
1394
  }
1725
1395
  return isWrappable(value) ? wrap(value, target) : value;
@@ -1728,7 +1398,7 @@ var storeTraps = {
1728
1398
  if (property === $PROXY || property === $TRACK || property === "__proto__")
1729
1399
  return true;
1730
1400
  const has = target[STORE_OVERRIDE] && property in target[STORE_OVERRIDE] ? target[STORE_OVERRIDE][property] !== $DELETED : property in target[STORE_VALUE];
1731
- getObserver() && getNode(getNodes(target, STORE_HAS), property, has).read();
1401
+ getObserver() && read(getNode(getNodes(target, STORE_HAS), property, has));
1732
1402
  return has;
1733
1403
  },
1734
1404
  set(target, property, rawValue) {
@@ -1753,15 +1423,15 @@ var storeTraps = {
1753
1423
  }
1754
1424
  if (recursivelyNotify(store, storeLookup) && wrappable)
1755
1425
  recursivelyAddParent(value, store);
1756
- target[STORE_HAS]?.[property]?.write(true);
1426
+ target[STORE_HAS]?.[property] && setSignal(target[STORE_HAS][property], true);
1757
1427
  const nodes = getNodes(target, STORE_NODE);
1758
- nodes[property]?.write(wrappable ? wrap(value, target) : value);
1428
+ nodes[property] && setSignal(nodes[property], () => wrappable ? wrap(value, target) : value);
1759
1429
  if (Array.isArray(state)) {
1760
1430
  const index = parseInt(property) + 1;
1761
1431
  if (index > len)
1762
- nodes.length?.write(index);
1432
+ nodes.length && setSignal(nodes.length, index);
1763
1433
  }
1764
- nodes[$TRACK]?.write(void 0);
1434
+ nodes[$TRACK] && setSignal(nodes[$TRACK], void 0);
1765
1435
  });
1766
1436
  }
1767
1437
  return true;
@@ -1780,10 +1450,11 @@ var storeTraps = {
1780
1450
  const parents = PARENTS.get(prev);
1781
1451
  parents && (parents instanceof Set ? parents.delete(target) : PARENTS.delete(prev));
1782
1452
  }
1783
- target[STORE_HAS]?.[property]?.write(false);
1453
+ if (target[STORE_HAS]?.[property])
1454
+ setSignal(target[STORE_HAS][property], false);
1784
1455
  const nodes = getNodes(target, STORE_NODE);
1785
- nodes[property]?.write(void 0);
1786
- nodes[$TRACK]?.write(void 0);
1456
+ nodes[property] && setSignal(nodes[property], void 0);
1457
+ nodes[$TRACK] && setSignal(nodes[$TRACK], void 0);
1787
1458
  });
1788
1459
  }
1789
1460
  return true;
@@ -1837,7 +1508,7 @@ function recursivelyNotify(state, lookup) {
1837
1508
  if (target) {
1838
1509
  const deep2 = getNodes(target, STORE_NODE)[$DEEP];
1839
1510
  if (deep2) {
1840
- deep2.write(void 0);
1511
+ setSignal(deep2, void 0);
1841
1512
  notified = true;
1842
1513
  }
1843
1514
  lookup = target[STORE_LOOKUP] || lookup;
@@ -1894,30 +1565,7 @@ function deep(store) {
1894
1565
 
1895
1566
  // src/store/optimistic.ts
1896
1567
  function createOptimisticStore(first, second, options) {
1897
- const derived = typeof first === "function";
1898
- const { store, node } = derived ? createProjectionInternal(
1899
- (draft) => {
1900
- const res = first(draft);
1901
- if (reset._transition)
1902
- return draft;
1903
- return res;
1904
- },
1905
- second,
1906
- options
1907
- ) : createProjectionInternal(() => {
1908
- }, first);
1909
- const reset = () => storeSetter(
1910
- store,
1911
- reconcile(derived ? first(store) || store : first, options?.key || "id", options?.all)
1912
- );
1913
- const write = (v) => {
1914
- if (!ActiveTransition)
1915
- throw new Error("createOptimisticStore can only be updated inside a transition");
1916
- ActiveTransition.addOptimistic(reset);
1917
- queueMicrotask(() => reset._transition && storeSetter(store, v));
1918
- };
1919
- node._optimistic = reset;
1920
- return [store, write];
1568
+ return [];
1921
1569
  }
1922
1570
 
1923
1571
  // src/store/utils.ts
@@ -2123,19 +1771,21 @@ function omit(props, ...keys) {
2123
1771
  // src/map.ts
2124
1772
  function mapArray(list, map, options) {
2125
1773
  const keyFn = typeof options?.keyed === "function" ? options.keyed : void 0;
2126
- return updateKeyedMap.bind({
2127
- _owner: new Owner(),
2128
- _len: 0,
2129
- _list: list,
2130
- _items: [],
2131
- _map: map,
2132
- _mappings: [],
2133
- _nodes: [],
2134
- _key: keyFn,
2135
- _rows: keyFn || options?.keyed === false ? [] : void 0,
2136
- _indexes: map.length > 1 ? [] : void 0,
2137
- _fallback: options?.fallback
2138
- });
1774
+ return createMemo(
1775
+ updateKeyedMap.bind({
1776
+ _owner: createOwner(),
1777
+ _len: 0,
1778
+ _list: list,
1779
+ _items: [],
1780
+ _map: map,
1781
+ _mappings: [],
1782
+ _nodes: [],
1783
+ _key: keyFn,
1784
+ _rows: keyFn || options?.keyed === false ? [] : void 0,
1785
+ _indexes: map.length > 1 ? [] : void 0,
1786
+ _fallback: options?.fallback
1787
+ })
1788
+ );
2139
1789
  }
2140
1790
  var pureOptions = { pureWrite: true };
2141
1791
  function updateKeyedMap() {
@@ -2143,16 +1793,19 @@ function updateKeyedMap() {
2143
1793
  newItems[$TRACK];
2144
1794
  runWithOwner(this._owner, () => {
2145
1795
  let i, j, mapper = this._rows ? () => {
2146
- this._rows[j] = new Computation(newItems[j], null, pureOptions);
2147
- this._indexes && (this._indexes[j] = new Computation(j, null, pureOptions));
1796
+ this._rows[j] = signal(newItems[j], pureOptions);
1797
+ this._indexes && (this._indexes[j] = signal(j, pureOptions));
2148
1798
  return this._map(
2149
- Computation.prototype.read.bind(this._rows[j]),
2150
- this._indexes ? Computation.prototype.read.bind(this._indexes[j]) : void 0
1799
+ read.bind(null, this._rows[j]),
1800
+ this._indexes ? read.bind(null, this._indexes[j]) : void 0
2151
1801
  );
2152
1802
  } : this._indexes ? () => {
2153
1803
  const item = newItems[j];
2154
- this._indexes[j] = new Computation(j, null, pureOptions);
2155
- return this._map(() => item, Computation.prototype.read.bind(this._indexes[j]));
1804
+ this._indexes[j] = signal(j, pureOptions);
1805
+ return this._map(
1806
+ () => item,
1807
+ read.bind(null, this._indexes[j])
1808
+ );
2156
1809
  } : () => {
2157
1810
  const item = newItems[j];
2158
1811
  return this._map(() => item);
@@ -2168,10 +1821,9 @@ function updateKeyedMap() {
2168
1821
  this._indexes && (this._indexes = []);
2169
1822
  }
2170
1823
  if (this._fallback && !this._mappings[0]) {
2171
- this._mappings[0] = compute(
2172
- this._nodes[0] = new Owner(),
2173
- this._fallback,
2174
- null
1824
+ this._mappings[0] = runWithOwner(
1825
+ this._nodes[0] = createOwner(),
1826
+ this._fallback
2175
1827
  );
2176
1828
  }
2177
1829
  } else if (this._len === 0) {
@@ -2180,14 +1832,14 @@ function updateKeyedMap() {
2180
1832
  this._mappings = new Array(newLen);
2181
1833
  for (j = 0; j < newLen; j++) {
2182
1834
  this._items[j] = newItems[j];
2183
- this._mappings[j] = compute(this._nodes[j] = new Owner(), mapper, null);
1835
+ this._mappings[j] = runWithOwner(this._nodes[j] = createOwner(), mapper);
2184
1836
  }
2185
1837
  this._len = newLen;
2186
1838
  } else {
2187
1839
  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;
2188
1840
  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++) {
2189
1841
  if (this._rows)
2190
- this._rows[start].write(newItems[start]);
1842
+ setSignal(this._rows[start], newItems[start]);
2191
1843
  }
2192
1844
  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--) {
2193
1845
  temp[newEnd] = this._mappings[end];
@@ -2224,14 +1876,14 @@ function updateKeyedMap() {
2224
1876
  this._nodes[j] = tempNodes[j];
2225
1877
  if (tempRows) {
2226
1878
  this._rows[j] = tempRows[j];
2227
- this._rows[j].write(newItems[j]);
1879
+ setSignal(this._rows[j], newItems[j]);
2228
1880
  }
2229
1881
  if (tempIndexes) {
2230
1882
  this._indexes[j] = tempIndexes[j];
2231
- this._indexes[j].write(j);
1883
+ setSignal(this._indexes[j], j);
2232
1884
  }
2233
1885
  } else {
2234
- this._mappings[j] = compute(this._nodes[j] = new Owner(), mapper, null);
1886
+ this._mappings[j] = runWithOwner(this._nodes[j] = createOwner(), mapper);
2235
1887
  }
2236
1888
  }
2237
1889
  this._mappings = this._mappings.slice(0, this._len = newLen);
@@ -2242,7 +1894,7 @@ function updateKeyedMap() {
2242
1894
  }
2243
1895
  function repeat(count, map, options) {
2244
1896
  return updateRepeat.bind({
2245
- _owner: new Owner(),
1897
+ _owner: createOwner(),
2246
1898
  _len: 0,
2247
1899
  _offset: 0,
2248
1900
  _count: count,
@@ -2265,10 +1917,9 @@ function updateRepeat() {
2265
1917
  this._len = 0;
2266
1918
  }
2267
1919
  if (this._fallback && !this._mappings[0]) {
2268
- this._mappings[0] = compute(
2269
- this._nodes[0] = new Owner(),
2270
- this._fallback,
2271
- null
1920
+ this._mappings[0] = runWithOwner(
1921
+ this._nodes[0] = createOwner(),
1922
+ this._fallback
2272
1923
  );
2273
1924
  }
2274
1925
  return;
@@ -2295,18 +1946,16 @@ function updateRepeat() {
2295
1946
  i--;
2296
1947
  }
2297
1948
  for (let i2 = 0; i2 < difference; i2++) {
2298
- this._mappings[i2] = compute(
2299
- this._nodes[i2] = new Owner(),
2300
- () => this._map(i2 + from),
2301
- null
1949
+ this._mappings[i2] = runWithOwner(
1950
+ this._nodes[i2] = createOwner(),
1951
+ () => this._map(i2 + from)
2302
1952
  );
2303
1953
  }
2304
1954
  }
2305
1955
  for (let i = prevTo; i < to; i++) {
2306
- this._mappings[i - from] = compute(
2307
- this._nodes[i - from] = new Owner(),
2308
- () => this._map(i),
2309
- null
1956
+ this._mappings[i - from] = runWithOwner(
1957
+ this._nodes[i - from] = createOwner(),
1958
+ () => this._map(i)
2310
1959
  );
2311
1960
  }
2312
1961
  this._mappings = this._mappings.slice(0, newLen);
@@ -2320,33 +1969,31 @@ function compare(key, a, b) {
2320
1969
  }
2321
1970
 
2322
1971
  // src/boundaries.ts
2323
- var BoundaryComputation = class extends EagerComputation {
2324
- _propagationMask;
2325
- constructor(compute2, propagationMask) {
2326
- super(void 0, compute2, { defer: true });
2327
- this._propagationMask = propagationMask;
2328
- }
2329
- write(value, flags) {
2330
- super.write(value, flags & ~this._propagationMask);
2331
- if (this._propagationMask & LOADING_BIT && !(this._stateFlags & UNINITIALIZED_BIT || ActiveTransition)) {
2332
- flags &= ~LOADING_BIT;
1972
+ function boundaryComputed(fn, propagationMask) {
1973
+ const node = computed(fn, void 0, {
1974
+ _internal: {
1975
+ _notifyQueue() {
1976
+ let flags = this._statusFlags;
1977
+ this._statusFlags &= ~this._propagationMask;
1978
+ if (this._propagationMask & 1 /* Pending */ && !(this._statusFlags & 4 /* Uninitialized */)) {
1979
+ flags &= ~1 /* Pending */;
1980
+ }
1981
+ this._queue.notify(this, this._propagationMask, flags);
1982
+ },
1983
+ _propagationMask: propagationMask
2333
1984
  }
2334
- getQueue(this).notify(this, this._propagationMask, flags);
2335
- return this._value;
2336
- }
2337
- };
1985
+ });
1986
+ node._propagationMask = propagationMask;
1987
+ return node;
1988
+ }
2338
1989
  function createBoundChildren(owner, fn, queue, mask) {
2339
1990
  const parentQueue = owner._queue;
2340
1991
  parentQueue.addChild(owner._queue = queue);
2341
1992
  onCleanup(() => parentQueue.removeChild(owner._queue));
2342
- return compute(
2343
- owner,
2344
- () => {
2345
- const c = new Computation(void 0, fn);
2346
- return new BoundaryComputation(() => latest(() => flatten(c.wait())), mask);
2347
- },
2348
- null
2349
- );
1993
+ return runWithOwner(owner, () => {
1994
+ const c = computed(fn);
1995
+ return boundaryComputed(() => staleValues(() => flatten(read(c))), mask);
1996
+ });
2350
1997
  }
2351
1998
  var ConditionalQueue = class extends Queue {
2352
1999
  _disabled;
@@ -2357,45 +2004,40 @@ var ConditionalQueue = class extends Queue {
2357
2004
  this._disabled = disabled;
2358
2005
  }
2359
2006
  run(type) {
2360
- if (!type || this._disabled.read())
2007
+ if (!type || read(this._disabled))
2361
2008
  return;
2362
2009
  return super.run(type);
2363
2010
  }
2364
2011
  notify(node, type, flags) {
2365
- if (this._disabled.read()) {
2366
- if (type & LOADING_BIT) {
2367
- if (flags & LOADING_BIT) {
2012
+ if (read(this._disabled)) {
2013
+ if (type & 1 /* Pending */) {
2014
+ if (flags & 1 /* Pending */) {
2368
2015
  this._pendingNodes.add(node);
2369
- type &= ~LOADING_BIT;
2016
+ type &= ~1 /* Pending */;
2370
2017
  } else if (this._pendingNodes.delete(node))
2371
- type &= ~LOADING_BIT;
2018
+ type &= ~1 /* Pending */;
2372
2019
  }
2373
- if (type & ERROR_BIT) {
2374
- if (flags & ERROR_BIT) {
2020
+ if (type & 2 /* Error */) {
2021
+ if (flags & 2 /* Error */) {
2375
2022
  this._errorNodes.add(node);
2376
- type &= ~ERROR_BIT;
2023
+ type &= ~2 /* Error */;
2377
2024
  } else if (this._errorNodes.delete(node))
2378
- type &= ~ERROR_BIT;
2025
+ type &= ~2 /* Error */;
2379
2026
  }
2380
2027
  }
2381
2028
  return type ? super.notify(node, type, flags) : true;
2382
2029
  }
2383
- merge(queue) {
2384
- queue._pendingNodes.forEach((n) => this.notify(n, LOADING_BIT, LOADING_BIT));
2385
- queue._errorNodes.forEach((n) => this.notify(n, ERROR_BIT, ERROR_BIT));
2386
- super.merge(queue);
2387
- }
2388
2030
  };
2389
2031
  var CollectionQueue = class extends Queue {
2390
2032
  _collectionType;
2391
2033
  _nodes = /* @__PURE__ */ new Set();
2392
- _disabled = new Computation(false, null, { pureWrite: true });
2034
+ _disabled = signal(false, { pureWrite: true });
2393
2035
  constructor(type) {
2394
2036
  super();
2395
2037
  this._collectionType = type;
2396
2038
  }
2397
2039
  run(type) {
2398
- if (!type || this._disabled.read())
2040
+ if (!type || read(this._disabled))
2399
2041
  return;
2400
2042
  return super.run(type);
2401
2043
  }
@@ -2405,65 +2047,57 @@ var CollectionQueue = class extends Queue {
2405
2047
  if (flags & this._collectionType) {
2406
2048
  this._nodes.add(node);
2407
2049
  if (this._nodes.size === 1)
2408
- this._disabled.write(true);
2050
+ setSignal(this._disabled, true);
2409
2051
  } else if (this._nodes.size > 0) {
2410
2052
  this._nodes.delete(node);
2411
2053
  if (this._nodes.size === 0)
2412
- this._disabled.write(false);
2054
+ setSignal(this._disabled, false);
2413
2055
  }
2414
2056
  type &= ~this._collectionType;
2415
2057
  return type ? super.notify(node, type, flags) : true;
2416
2058
  }
2417
- merge(queue) {
2418
- queue._nodes.forEach((n) => this.notify(n, this._collectionType, this._collectionType));
2419
- super.merge(queue);
2420
- }
2421
2059
  };
2422
2060
  function createBoundary(fn, condition) {
2423
- const owner = new Owner();
2424
- const queue = new ConditionalQueue(
2425
- new Computation(void 0, () => condition() === "hidden" /* HIDDEN */)
2426
- );
2061
+ const owner = createOwner();
2062
+ const queue = new ConditionalQueue(computed(() => condition() === "hidden" /* HIDDEN */));
2427
2063
  const tree = createBoundChildren(owner, fn, queue, 0);
2428
- new EagerComputation(void 0, () => {
2429
- const disabled = queue._disabled.read();
2430
- tree._propagationMask = disabled ? ERROR_BIT | LOADING_BIT : 0;
2064
+ computed(() => {
2065
+ const disabled = read(queue._disabled);
2066
+ tree._propagationMask = disabled ? 2 /* Error */ | 1 /* Pending */ : 0;
2431
2067
  if (!disabled) {
2432
- queue._pendingNodes.forEach((node) => queue.notify(node, LOADING_BIT, LOADING_BIT));
2433
- queue._errorNodes.forEach((node) => queue.notify(node, ERROR_BIT, ERROR_BIT));
2068
+ queue._pendingNodes.forEach(
2069
+ (node) => queue.notify(node, 1 /* Pending */, 1 /* Pending */)
2070
+ );
2071
+ queue._errorNodes.forEach((node) => queue.notify(node, 2 /* Error */, 2 /* Error */));
2434
2072
  queue._pendingNodes.clear();
2435
2073
  queue._errorNodes.clear();
2436
2074
  }
2437
2075
  });
2438
- return () => queue._disabled.read() ? void 0 : tree.read();
2076
+ return () => read(queue._disabled) ? void 0 : read(tree);
2439
2077
  }
2440
2078
  function createCollectionBoundary(type, fn, fallback) {
2441
- const owner = new Owner();
2079
+ const owner = createOwner();
2442
2080
  const queue = new CollectionQueue(type);
2443
2081
  const tree = createBoundChildren(owner, fn, queue, type);
2444
- const decision = new Computation(void 0, () => {
2445
- if (!queue._disabled.read()) {
2446
- const resolved = tree.read();
2447
- if (!untrack(() => queue._disabled.read()))
2082
+ const decision = computed(() => {
2083
+ if (!read(queue._disabled)) {
2084
+ const resolved = read(tree);
2085
+ if (!untrack(() => read(queue._disabled)))
2448
2086
  return resolved;
2449
2087
  }
2450
2088
  return fallback(queue);
2451
2089
  });
2452
- return decision.read.bind(decision);
2090
+ return read.bind(null, decision);
2453
2091
  }
2454
- function createSuspense(fn, fallback) {
2455
- return createCollectionBoundary(LOADING_BIT, fn, () => fallback());
2092
+ function createLoadBoundary(fn, fallback) {
2093
+ return createCollectionBoundary(1 /* Pending */, fn, () => fallback());
2456
2094
  }
2457
2095
  function createErrorBoundary(fn, fallback) {
2458
- return createCollectionBoundary(ERROR_BIT, fn, (queue) => {
2459
- let node = getTransitionSource(queue._nodes.values().next().value);
2096
+ return createCollectionBoundary(2 /* Error */, fn, (queue) => {
2097
+ let node = queue._nodes.values().next().value;
2460
2098
  return fallback(node._error, () => {
2461
- incrementClock();
2462
2099
  for (let node2 of queue._nodes) {
2463
- if (ActiveTransition && !node2._cloned)
2464
- node2 = cloneGraph(node2);
2465
- node2._state = STATE_DIRTY;
2466
- getQueue(node2).enqueue(node2._type, node2._run.bind(node2));
2100
+ recompute(node2, true);
2467
2101
  }
2468
2102
  });
2469
2103
  });
@@ -2523,4 +2157,4 @@ function flattenArray(children, results = [], options) {
2523
2157
  return needsUnwrap;
2524
2158
  }
2525
2159
 
2526
- 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 };
2160
+ 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 };