-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathcore.ts
More file actions
1359 lines (1290 loc) · 46.3 KB
/
Copy pathcore.ts
File metadata and controls
1359 lines (1290 loc) · 46.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { clearStatus, handleAsync, notifyStatus } from "./async.js";
import {
$REFRESH,
CONFIG_AUTO_DISPOSE,
CONFIG_CHILDREN_FORBIDDEN,
CONFIG_IN_SNAPSHOT_SCOPE,
CONFIG_NO_SNAPSHOT,
CONFIG_OWNED_WRITE,
CONFIG_SYNC,
CONFIG_TRANSPARENT,
defaultContext,
EFFECT_TRACKED,
EFFECT_USER,
NO_SNAPSHOT,
NOT_PENDING,
REACTIVE_CHECK,
REACTIVE_DIRTY,
REACTIVE_DISPOSED,
REACTIVE_IN_HEAP,
REACTIVE_IN_HEAP_HEIGHT,
REACTIVE_LAZY,
REACTIVE_MANUAL_WRITE,
REACTIVE_NONE,
REACTIVE_OPTIMISTIC_DIRTY,
REACTIVE_RECOMPUTING_DEPS,
REACTIVE_SNAPSHOT_STALE,
REACTIVE_ZOMBIE,
STATUS_ERROR,
STATUS_PENDING,
STATUS_UNINITIALIZED,
STORE_SNAPSHOT_PROPS,
type Refreshable
} from "./constants.js";
import { NotReadyError } from "./error.js";
import { externalSourceConfig } from "./external.js";
import { link, trimStaleDeps, unobserved } from "./graph.js";
import {
deleteFromHeap,
insertIntoHeap,
insertIntoHeapHeight,
markHeap,
markNode,
notifyEpoch
} from "./heap.js";
import {
findLane,
getOrCreateLane,
hasActiveOverride,
mergeLanes,
resolveLane,
resolveTransition,
signalLanes,
type OptimisticLane
} from "./lanes.js";
import { clearSignals, DEV, emitDiagnostic } from "./dev.js";
import { cleanup, disposeChildren, getNextChildId, markDisposal } from "./owner.js";
import {
activeTransition,
assignOrMergeLane,
clock,
dirtyQueue,
globalQueue,
GlobalQueue,
insertSubs,
projectionWriteActive,
queuePendingNode,
runInTransition,
schedule,
shouldReadStashedOptimisticValue,
zombieQueue
} from "./scheduler.js";
import type { Computed, FirewallSignal, Link, NodeOptions, Owner, Root, Signal } from "./types.js";
GlobalQueue._update = recompute;
GlobalQueue._dispose = disposeChildren;
export const PRIMITIVE_IN_FORBIDDEN_SCOPE_MESSAGE =
"[PRIMITIVE_IN_FORBIDDEN_SCOPE] Cannot create reactive primitives inside createTrackedEffect or owner-backed onSettled";
export const REACTIVE_WRITE_IN_OWNED_SCOPE_SIGNAL_MESSAGE =
"[REACTIVE_WRITE_IN_OWNED_SCOPE] Writing to reactive state inside an owned scope (component, computation) is not allowed. " +
"Move the write outside or set the `ownedWrite` option if this is intentional.";
export const REACTIVE_WRITE_IN_OWNED_SCOPE_REFRESH_MESSAGE =
"[REACTIVE_WRITE_IN_OWNED_SCOPE] Calling refresh() inside an owned scope (component, computation) is not allowed. " +
"Move the invalidation outside pure computation.";
export let tracking = false;
export let stale = false;
export let pendingCheckActive = false;
export let foundPending = false;
export let latestReadActive = false;
export let context: Owner | null = null;
export let currentOptimisticLane: OptimisticLane | null = null;
let pendingCheckSources: Set<Signal<any> | Computed<any>> | null = null;
export let snapshotCaptureActive = false;
export let snapshotSources: Set<any> | null = null;
function ownerInSnapshotScope(owner: Owner | null): boolean {
while (owner) {
if (owner._snapshotScope) return true;
owner = owner._parent;
}
return false;
}
export function setSnapshotCapture(active: boolean): void {
snapshotCaptureActive = active;
if (active && !snapshotSources) snapshotSources = new Set();
}
export function markSnapshotScope(owner: Owner): void {
owner._snapshotScope = true;
}
export function releaseSnapshotScope(owner: Owner): void {
owner._snapshotScope = false;
releaseSubtree(owner);
schedule();
}
function releaseSubtree(owner: Owner): void {
let child = owner._firstChild;
while (child) {
if (child._snapshotScope) {
child = child._nextSibling;
continue;
}
if ((child as any)._fn) {
const comp = child as Computed<any>;
comp._config &= ~CONFIG_IN_SNAPSHOT_SCOPE;
if (comp._flags & REACTIVE_SNAPSHOT_STALE) {
comp._flags &= ~REACTIVE_SNAPSHOT_STALE;
comp._flags |= REACTIVE_DIRTY;
if (dirtyQueue._min > comp._height) dirtyQueue._min = comp._height;
insertIntoHeap(comp, dirtyQueue);
}
}
releaseSubtree(child);
child = child._nextSibling;
}
}
export function clearSnapshots(): void {
if (snapshotSources) {
for (const source of snapshotSources) {
delete source._snapshotValue;
delete source[STORE_SNAPSHOT_PROPS];
}
snapshotSources = null;
}
snapshotCaptureActive = false;
}
export function recompute(el: Computed<any>, create: boolean = false): void {
const isEffect = (el as any)._type;
if (!create) {
if (el._transition && (!isEffect || activeTransition) && activeTransition !== el._transition)
globalQueue.initTransition(el._transition);
deleteFromHeap(el, el._flags & REACTIVE_ZOMBIE ? zombieQueue : dirtyQueue);
el._inFlight = null;
// Tracked effects run after finalizePureQueue, so dispose immediately instead of deferring
if (el._transition || isEffect === EFFECT_TRACKED) disposeChildren(el);
else if (el._firstChild !== null || el._disposal !== null) {
markDisposal(el);
el._pendingDisposal = el._disposal;
el._pendingFirstChild = el._firstChild;
el._disposal = null;
el._firstChild = null;
el._childCount = 0;
if (__DEV__) clearSignals(el);
} else if (__DEV__) clearSignals(el);
}
let isOptimisticDirty = !!(el._flags & REACTIVE_OPTIMISTIC_DIRTY);
const hasOverride = el._overrideValue !== undefined && el._overrideValue !== NOT_PENDING;
// Track if node was pending (for detecting async resolution)
const wasPending = !!(el._statusFlags & STATUS_PENDING);
const wasUninitialized = !!(el._statusFlags & STATUS_UNINITIALIZED);
const oldcontext = context;
context = el;
el._depsTail = null;
el._depGen++;
el._flags = REACTIVE_RECOMPUTING_DEPS;
el._time = clock;
let value = el._pendingValue === NOT_PENDING ? el._value : el._pendingValue;
let oldHeight = el._height;
let prevTracking = tracking;
let prevLane = currentOptimisticLane;
let prevStrictRead: string | false = false;
if (__DEV__) {
prevStrictRead = strictRead;
strictRead = false;
}
tracking = true;
if (isOptimisticDirty) {
const lane = resolveLane(el);
if (lane) currentOptimisticLane = lane;
} else if (activeTransition && !create && activeTransition._optimisticNodes.length) {
// Lane adoption: parent-deeper-than-owned-child can run before its OPT-dirty
// child propagates. Walk deps once and inherit the OPT lane so this node
// recomputes under the right posture and propagates correctly.
for (let d: Link | null = el._deps; d; d = d._nextDep) {
const dep = d._dep as Computed<any>;
if (dep._flags & REACTIVE_OPTIMISTIC_DIRTY) {
const depLane = resolveLane(dep);
if (depLane) {
isOptimisticDirty = true;
currentOptimisticLane = depLane;
el._flags |= REACTIVE_OPTIMISTIC_DIRTY;
assignOrMergeLane(el as any, depLane);
break;
}
}
}
}
const isStaleEffect = isEffect && isEffect !== EFFECT_USER;
const prevStale = stale;
if (isStaleEffect) stale = true;
try {
if (!__DEV__ && el._config & CONFIG_SYNC) {
value = el._fn(value);
el._inFlight = null;
} else {
// Snapshot `_inFlight` so we can detect whether `_fn` self-registered an async
// subscription (e.g. `createProjection` calls `handleAsync` from inside its body
// with a setter callback). In that case, the outer `handleAsync` call below would
// clobber the fresh subscription, so we skip it and let the internally-registered
// iteration drive updates.
const prevInFlight = el._inFlight;
const fnResult = el._fn(value);
const isAsyncResult = typeof fnResult === "object" && fnResult !== null;
const inFlightChanged = el._inFlight !== prevInFlight;
value = inFlightChanged || !isAsyncResult ? fnResult : handleAsync(el, fnResult);
if (!inFlightChanged && !isAsyncResult) el._inFlight = null;
}
clearStatus(el, create);
if (el._optimisticLane) {
const resolvedLane = resolveLane(el);
if (resolvedLane) {
resolvedLane._pendingAsync.delete(el);
updatePendingSignal(resolvedLane._source);
}
}
} catch (e) {
// Track pending async in the lane (not the lane's source — it creates the lane
// but doesn't belong to it). Set lane BEFORE notifyStatus for downstream propagation.
if (e instanceof NotReadyError && currentOptimisticLane) {
const lane = findLane(currentOptimisticLane);
if (lane._source !== el) {
lane._pendingAsync.add(el);
el._optimisticLane = lane;
updatePendingSignal(lane._source);
}
}
if (e instanceof NotReadyError) el._blocked = true;
notifyStatus(
el,
e instanceof NotReadyError ? STATUS_PENDING : STATUS_ERROR,
e,
undefined,
e instanceof NotReadyError ? el._optimisticLane : undefined
);
} finally {
tracking = prevTracking;
if (__DEV__) strictRead = prevStrictRead;
if (isStaleEffect) stale = prevStale;
el._flags = REACTIVE_NONE | (create ? el._flags & REACTIVE_SNAPSHOT_STALE : 0);
context = oldcontext;
}
if (!el._error) {
trimStaleDeps(el);
const compareValue = hasOverride
? el._overrideValue
: el._pendingValue === NOT_PENDING
? el._value
: el._pendingValue;
const valueChanged =
(!isEffect && wasUninitialized) || !el._equals || !el._equals(compareValue, value);
// Effects use `_equals: false` (no per-effect closure). The side effects that
// the equals closure used to perform — flagging the effect dirty and enqueueing
// its runner — happen here instead. `!create` matches the previous `initialized`
// gate: the explicit recompute(node, true) inside effect() does not enqueue, so
// effect() can call its runner synchronously for the first run.
if (isEffect && valueChanged) {
(el as any)._modified = !el._error;
// Reuse one bound runner per effect — runEffect no-ops on a stale
// `_modified`, so double-enqueueing the same function is harmless.
if (!create)
el._queue.enqueue(
isEffect,
((el as any)._boundRunEffect ??= GlobalQueue._runEffect.bind(null, el))
);
}
if (valueChanged) {
const prevVisible = hasOverride ? el._overrideValue : undefined;
if (create || (isEffect && activeTransition !== el._transition) || isOptimisticDirty) {
el._value = value;
// Lane-propagated correction: upstream data is fresh, correct override unconditionally
if (hasOverride && isOptimisticDirty) {
el._overrideValue = value;
el._pendingValue = value;
}
} else el._pendingValue = value;
// Correct override for async resolution (non-lane path) unless user wrote since lane creation
if (hasOverride && !isOptimisticDirty && wasPending && !(el as any)._overrideSinceLane)
el._overrideValue = value;
if (!hasOverride || isOptimisticDirty || el._overrideValue !== prevVisible)
insertSubs(el, isOptimisticDirty || hasOverride);
} else if (hasOverride) {
el._pendingValue = value;
} else if (el._height != oldHeight) {
for (let s = el._subs; s !== null; s = s._nextSub) {
insertIntoHeapHeight(s._sub, s._sub._flags & REACTIVE_ZOMBIE ? zombieQueue : dirtyQueue);
}
}
}
currentOptimisticLane = prevLane;
const needsPendingCommit =
el._pendingValue !== NOT_PENDING ||
el._pendingFirstChild !== null ||
el._pendingDisposal !== null ||
!!(el._statusFlags & (STATUS_PENDING | STATUS_UNINITIALIZED));
needsPendingCommit &&
(!create || el._statusFlags & STATUS_PENDING) &&
!el._transition &&
!(activeTransition && hasOverride) &&
queuePendingNode(el);
el._transition &&
isEffect &&
activeTransition !== el._transition &&
runInTransition(el._transition, () => recompute(el));
}
function updateIfNecessary(el: Computed<unknown>): void {
if (el._flags & REACTIVE_CHECK) {
for (let d = el._deps; d; d = d._nextDep) {
const dep1 = d._dep;
const dep = (dep1 as FirewallSignal<unknown>)._firewall || dep1;
if ((dep as Computed<unknown>)._fn) {
updateIfNecessary(dep);
}
if (el._flags & REACTIVE_DIRTY) {
break;
}
}
}
if (
el._flags & (REACTIVE_DIRTY | REACTIVE_OPTIMISTIC_DIRTY) ||
(el._error && el._time < clock && !el._inFlight)
) {
recompute(el);
}
el._flags = el._flags & (REACTIVE_SNAPSHOT_STALE | REACTIVE_IN_HEAP | REACTIVE_IN_HEAP_HEIGHT);
}
export function computed<T>(fn: (prev?: T) => T | PromiseLike<T> | AsyncIterable<T>): Computed<T>;
export function computed<T>(
fn: (prev: T) => T | PromiseLike<T> | AsyncIterable<T>,
options?: NodeOptions<T>
): Computed<T>;
export function computed<T>(
fn: (prev?: T) => T | PromiseLike<T> | AsyncIterable<T>,
options?: NodeOptions<T>
): Computed<T> {
const transparent = options?.transparent ?? false;
const self: Computed<T> = {
id:
options?.id ??
(transparent ? context?.id : context?.id != null ? getNextChildId(context) : undefined),
_config:
(transparent ? CONFIG_TRANSPARENT : 0) |
(options?.ownedWrite ? CONFIG_OWNED_WRITE : 0) |
(!context || options?.lazy ? CONFIG_AUTO_DISPOSE : 0) |
(options?.sync ? CONFIG_SYNC : 0) |
(snapshotCaptureActive && ownerInSnapshotScope(context) ? CONFIG_IN_SNAPSHOT_SCOPE : 0),
_equals: options?.equals != null ? options.equals : isEqual,
_unobserved: options?.unobserved,
_disposal: null,
_queue: context?._queue ?? globalQueue,
_context: context?._context ?? defaultContext,
_childCount: 0,
_fn: fn,
_value: undefined as T,
_height: 0,
_child: null,
_nextHeap: undefined,
_prevHeap: null as any,
_deps: null,
_depsTail: null,
_depGen: 0,
_subs: null,
_subsTail: null,
_parent: context,
_nextSibling: null,
_prevSibling: null,
_firstChild: null,
_flags: options?.lazy ? REACTIVE_LAZY : REACTIVE_NONE,
_statusFlags: STATUS_UNINITIALIZED,
_time: clock,
_notifyEpoch: 0,
_pendingValue: NOT_PENDING,
_pendingDisposal: null,
_pendingFirstChild: null,
_inFlight: null,
_transition: null
} as Computed<T>;
if (__DEV__) (self as any)._name = options?.name ?? "computed";
setupComputedNode(self, options);
return self;
}
/**
* Build an Effect node with all effect-specific fields baked into a single object literal,
* so V8 sees the full hidden class shape at construction time. Effects always run in lazy
* mode (recompute is called explicitly by `effect()`), so we hardcode the lazy bits and skip
* the auto-dispose CONFIG bit (effect() previously cleared it post-construction).
*/
export function createEffectNode<T>(
fn: (prev?: T) => T,
effectFn: (val: T, prev: T | undefined) => void | (() => void),
errorFn: ((err: unknown, cleanup: () => void) => void | (() => void)) | undefined,
type: number,
notifyStatus: ((status?: number, error?: any) => void) | undefined,
options: NodeOptions<T> | undefined
): any {
const transparent = options?.transparent ?? false;
const self = {
id:
options?.id ??
(transparent ? context?.id : context?.id != null ? getNextChildId(context) : undefined),
_config:
(transparent ? CONFIG_TRANSPARENT : 0) |
(options?.ownedWrite ? CONFIG_OWNED_WRITE : 0) |
(options?.sync ? CONFIG_SYNC : 0) |
(snapshotCaptureActive && ownerInSnapshotScope(context) ? CONFIG_IN_SNAPSHOT_SCOPE : 0),
_equals: false as unknown as Computed<T>["_equals"],
_unobserved: options?.unobserved,
_disposal: null,
_queue: context?._queue ?? globalQueue,
_context: context?._context ?? defaultContext,
_childCount: 0,
_fn: fn,
_value: undefined as T,
_height: 0,
_child: null,
_nextHeap: undefined,
_prevHeap: null as any,
_deps: null,
_depsTail: null,
_depGen: 0,
_subs: null,
_subsTail: null,
_parent: context,
_nextSibling: null,
_prevSibling: null,
_firstChild: null,
_flags: REACTIVE_LAZY,
_statusFlags: STATUS_UNINITIALIZED,
_time: clock,
_notifyEpoch: 0,
_pendingValue: NOT_PENDING,
_pendingDisposal: null,
_pendingFirstChild: null,
_inFlight: null,
_transition: null,
_modified: false,
_prevValue: undefined as T | undefined,
_effectFn: effectFn,
_errorFn: errorFn,
_cleanup: undefined as (() => void) | undefined,
_cleanupRegistered: false,
_type: type,
_notifyStatus: notifyStatus
} as any;
if (__DEV__) self._name = options?.name ?? "effect";
setupComputedNode(self, lazyOptions);
return self;
}
const lazyOptions = { lazy: true } as const;
function setupComputedNode<T>(self: Computed<T>, options: NodeOptions<T> | undefined): void {
self._prevHeap = self;
const parent = (context as Root)?._root
? (context as Root)._parentComputed
: (context as Computed<any> | null);
if (__DEV__ && context && context._config & CONFIG_CHILDREN_FORBIDDEN) {
emitDiagnostic({
code: "PRIMITIVE_IN_FORBIDDEN_SCOPE",
kind: "lifecycle",
severity: "error",
message: PRIMITIVE_IN_FORBIDDEN_SCOPE_MESSAGE,
ownerId: context.id,
ownerName: (context as any)._name
});
throw new Error(PRIMITIVE_IN_FORBIDDEN_SCOPE_MESSAGE);
}
if (context) {
const lastChild = context._firstChild;
if (lastChild === null) {
context._firstChild = self;
} else {
self._nextSibling = lastChild;
lastChild._prevSibling = self;
context._firstChild = self;
}
}
if (__DEV__) DEV.hooks.onOwner?.(self);
if (parent) self._height = parent._height + 1;
if (externalSourceConfig) {
const bridgeSignal = signal<undefined>(undefined, { equals: false, ownedWrite: true });
const source = externalSourceConfig.factory(self._fn as any, () => {
setSignal(bridgeSignal, undefined);
});
cleanup(() => source.dispose());
self._fn = ((prev: any) => {
read(bridgeSignal);
return source.track(prev);
}) as any;
}
!options?.lazy && recompute(self, true);
if (snapshotCaptureActive && !options?.lazy) {
if (!(self._statusFlags & STATUS_PENDING)) {
self._snapshotValue = self._value === undefined ? NO_SNAPSHOT : self._value;
snapshotSources!.add(self);
}
}
}
export function signal<T>(v: T, options?: NodeOptions<T>): Signal<T>;
export function signal<T>(
v: T,
options?: NodeOptions<T>,
firewall?: Computed<any>
): FirewallSignal<T>;
export function signal<T>(
v: T,
options?: NodeOptions<T>,
firewall: Computed<unknown> | null = null
): Signal<T> {
const s = {
_equals: options?.equals != null ? options.equals : isEqual,
_config:
(options?.ownedWrite ? CONFIG_OWNED_WRITE : 0) |
(options?._noSnapshot ? CONFIG_NO_SNAPSHOT : 0),
_unobserved: options?.unobserved,
_value: v,
_subs: null,
_subsTail: null,
_time: clock,
_notifyEpoch: 0,
_firewall: firewall,
_nextChild: firewall?._child || null,
_pendingValue: NOT_PENDING
};
if (__DEV__) {
(s as any)._name = options?.name ?? "signal";
(s as any)._internal = !!firewall;
}
firewall && (firewall._child = s as FirewallSignal<unknown>);
if (
snapshotCaptureActive &&
!(s._config & CONFIG_NO_SNAPSHOT) &&
!((firewall?._statusFlags ?? 0) & STATUS_PENDING)
) {
(s as any)._snapshotValue = v === undefined ? NO_SNAPSHOT : v;
snapshotSources!.add(s);
}
return s as Signal<T>;
}
export function optimisticSignal<T>(v: T, options?: NodeOptions<T>): Signal<T> {
const s = signal(v, options);
s._overrideValue = NOT_PENDING;
return s;
}
export function optimisticComputed<T>(
fn: (prev?: T) => T | PromiseLike<T> | AsyncIterable<T>,
options?: NodeOptions<T>
): Computed<T> {
const c = computed(fn, options);
c._overrideValue = NOT_PENDING;
return c;
}
export function isEqual<T>(a: T, b: T): boolean {
return a === b;
}
/**
* When set to a component name string, any reactive read that is not inside a nested tracking
* scope will log a dev-mode warning. Managed automatically by `untrack(fn, strictReadLabel)`.
*/
export let strictRead: string | false = false;
export function setStrictRead(v: string | false): string | false {
const prev = strictRead;
strictRead = v;
return prev;
}
/**
* Runs `fn` outside of any reactive tracking — reads inside `fn` will not
* subscribe the current scope. Returns whatever `fn` returns.
*
* Use `untrack` inside a memo or effect when you need to read a signal once
* without making the surrounding computation depend on its future changes.
*
* Pass a `strictReadLabel` string to enable a dev-mode warning: any reactive
* read inside `fn` that isn't inside a nested tracking scope will log a
* warning naming the label.
*
* @example
* ```ts
* createEffect(
* () => trigger(), // tracks `trigger` only
* () => {
* const snapshot = untrack(() => state); // read once, untracked
* log(snapshot);
* }
* );
* ```
*/
export function untrack<T>(fn: () => T, strictReadLabel?: string | false): T {
if (!externalSourceConfig && !tracking && (!__DEV__ || (!strictRead && !strictReadLabel)))
return fn();
const prevTracking = tracking;
const prevStrictRead = strictRead;
tracking = false;
if (__DEV__) strictRead = strictReadLabel || false;
try {
if (externalSourceConfig) return externalSourceConfig.untrack(fn);
return fn();
} finally {
tracking = prevTracking;
if (__DEV__) strictRead = prevStrictRead;
}
}
export function read<T>(el: Signal<T> | Computed<T>): T {
// Handle latest() mode: read from _latestValueComputed
// Checked before isPending so that isPending(() => latest(x)) checks
// the _pendingSignal of _latestValueComputed (async in flight) rather
// than the original node (which stays "pending" while held in a transition).
if (latestReadActive) {
const pendingComputed = getLatestValueComputed(el);
const prevPending = latestReadActive;
latestReadActive = false;
const visibleValue = (
el._overrideValue !== undefined && el._overrideValue !== NOT_PENDING
? el._overrideValue
: el._value
) as T;
let value: T;
try {
value = read(pendingComputed);
} catch (e) {
if (!context && e instanceof NotReadyError) return visibleValue;
throw e;
} finally {
latestReadActive = prevPending;
}
if (pendingComputed._statusFlags & STATUS_PENDING) return visibleValue;
// Cross-lane stale read: a child lane should keep seeing the parent's
// committed value until the parent lane resolves.
if (stale && currentOptimisticLane && pendingComputed._optimisticLane) {
const pcLane = findLane(pendingComputed._optimisticLane);
const curLane = findLane(currentOptimisticLane);
if (pcLane !== curLane && pcLane._pendingAsync.size > 0) {
return visibleValue;
}
}
return value as T;
}
// Handle isPending() mode: collect pending state while preserving normal read semantics.
if (pendingCheckActive) {
const firewall = (el as FirewallSignal<any>)._firewall;
const prevCheck = pendingCheckActive;
pendingCheckActive = false;
let c = context;
if ((c as Root)?._root) c = (c as Root)._parentComputed;
const owner = firewall || (el as Computed<any>);
const pendingComputed = el as Partial<Computed<unknown>>;
if (typeof pendingComputed._fn === "function") {
const comp = el as Computed<unknown>;
if (comp._flags & REACTIVE_LAZY) {
comp._flags &= ~REACTIVE_LAZY;
recompute(comp as Computed<any>, true);
} else if (comp._flags & REACTIVE_DISPOSED) {
recompute(comp as Computed<any>, true);
} else {
updateIfNecessary(comp);
}
}
if (c && owner._statusFlags & STATUS_PENDING && owner._statusFlags & STATUS_UNINITIALIZED) {
if (tracking && el !== c) link(el, c as Computed<any>);
pendingCheckActive = prevCheck;
throw owner._error;
}
if (firewall && el._overrideValue !== undefined) {
if (
el._overrideValue !== NOT_PENDING &&
(firewall._inFlight || !!(firewall._statusFlags & STATUS_PENDING))
) {
foundPending = true;
}
collectPendingSources(el);
collectPendingSources(firewall);
if (c && tracking) link(el, c as Computed<any>);
} else {
collectPendingSources(el);
if (firewall) collectPendingSources(firewall);
}
pendingCheckActive = prevCheck;
}
let c = context;
if ((c as Root)?._root) c = (c as Root)._parentComputed;
const computed = el as Partial<Computed<unknown>>;
if (typeof computed._fn === "function") {
const comp = el as Computed<unknown>;
if (comp._flags & REACTIVE_LAZY) {
comp._flags &= ~REACTIVE_LAZY;
recompute(comp as Computed<any>, true);
} else if (comp._flags & REACTIVE_DISPOSED) {
recompute(comp as Computed<any>, true);
}
}
const owner = (el as FirewallSignal<any>)._firewall || el;
if (
!computed._fn &&
owner === el &&
el._overrideValue === undefined &&
el._snapshotValue === undefined &&
activeTransition === null &&
currentOptimisticLane === null &&
!snapshotCaptureActive &&
(!__DEV__ || !strictRead)
) {
if (c && tracking) link(el, c as Computed<any>);
return (!c || el._pendingValue === NOT_PENDING ? el._value : el._pendingValue) as T;
}
if (__DEV__ && strictRead && owner._statusFlags & STATUS_PENDING) {
const message =
`[PENDING_ASYNC_UNTRACKED_READ] Reading a pending async value directly in ${strictRead}. ` +
`Async values must be read within a tracking scope (JSX, a memo, or an effect's compute function).`;
emitDiagnostic({
code: "PENDING_ASYNC_UNTRACKED_READ",
kind: "async",
severity: "error",
message,
ownerId: c?.id,
ownerName: (c as any)?._name,
nodeName: (owner as any)?._name,
data: { strictRead }
});
throw new Error(message);
}
if (c && tracking) {
link(el, c as Computed<any>);
if ((owner as Computed<unknown>)._fn) {
const isZombie = (el as Computed<unknown>)._flags & REACTIVE_ZOMBIE;
if (owner._height >= (isZombie ? zombieQueue._min : dirtyQueue._min)) {
markNode(c as Computed<any>);
markHeap(isZombie ? zombieQueue : dirtyQueue);
updateIfNecessary(owner);
}
const height = owner._height;
// parent check is shallow, might need to be recursive
if (height >= (c as Computed<any>)._height && (el as Computed<any>)._parent !== c) {
(c as Computed<any>)._height = height + 1;
}
}
}
if (owner._statusFlags & STATUS_PENDING) {
if (c && !(stale && owner._transition && activeTransition !== owner._transition)) {
if (__DEV__ && c && c._config & CONFIG_CHILDREN_FORBIDDEN) {
const message =
"[PENDING_ASYNC_FORBIDDEN_SCOPE] Reading a pending async value inside createTrackedEffect or onSettled will throw. " +
"Use createEffect instead which supports async-aware reactivity.";
emitDiagnostic({
code: "PENDING_ASYNC_FORBIDDEN_SCOPE",
kind: "async",
severity: "warn",
message,
ownerId: c.id,
ownerName: (c as any)._name,
nodeName: (owner as any)?._name
});
console.warn(message);
}
if (currentOptimisticLane) {
// Per-lane suspension: only throw if in same lane as pending async
// AND the node doesn't have an active override (overrides are the visible value,
// downstream in the lane should read the override, not throw)
const pendingLane = (owner as any)._optimisticLane;
const lane = findLane(currentOptimisticLane);
if (pendingLane && findLane(pendingLane) === lane && !hasActiveOverride(owner)) {
if (!tracking && el !== c) link(el, c as Computed<any>);
throw owner._error;
}
} else {
if (!tracking && el !== c) link(el, c as Computed<any>);
throw owner._error;
}
} else if (c && owner !== el && owner._statusFlags & STATUS_UNINITIALIZED) {
if (!tracking && el !== c) link(el, c as Computed<any>);
throw owner._error;
} else if (!c && owner._statusFlags & STATUS_UNINITIALIZED) {
throw owner._error;
}
}
if ((el as Computed<any>)._fn && (el as Computed<any>)._statusFlags & STATUS_ERROR) {
if (el._time < clock) {
recompute(el as Computed<unknown>);
return read(el);
} else throw (el as Computed<any>)._error;
}
if (snapshotCaptureActive && c && (c as Computed<any>)._config & CONFIG_IN_SNAPSHOT_SCOPE) {
const sv = el._snapshotValue;
if (sv !== undefined) {
const snapshot = sv === NO_SNAPSHOT ? undefined : sv;
const current = el._pendingValue !== NOT_PENDING ? el._pendingValue : el._value;
if (current !== snapshot) (c as Computed<any>)._flags |= REACTIVE_SNAPSHOT_STALE;
return snapshot as T;
}
}
if (__DEV__ && strictRead) {
const message =
`[STRICT_READ_UNTRACKED] Reactive value read directly in ${strictRead} will not update. ` +
`Move it into a tracking scope (JSX, a memo, or an effect's compute function).`;
emitDiagnostic({
code: "STRICT_READ_UNTRACKED",
kind: "strict-read",
severity: "warn",
message,
ownerId: c?.id,
ownerName: (c as any)?._name,
nodeName: (owner as any)?._name,
data: { strictRead }
});
console.warn(message);
}
if (el._overrideValue !== undefined && el._overrideValue !== NOT_PENDING) {
if (c && stale && shouldReadStashedOptimisticValue(el as Signal<any>)) return el._value as T;
return el._overrideValue as T;
}
// Entanglement gate: a reader recomputing under an optimistic lane that reads
// a pending mid-transition write sees the committed value. Projection-store
// manual writes use the firewall's manual-write flag to opt into this path.
// Async drivers are not under an optimistic lane and so bypass this, reading
// _pendingValue for correct fetching. The sub is recorded for replay at commit
// so it re-runs with the new committed view.
if (
activeTransition !== null &&
currentOptimisticLane !== null &&
!latestReadActive &&
el._pendingValue !== NOT_PENDING &&
(owner === el || !!((owner as Computed<unknown>)._flags & REACTIVE_MANUAL_WRITE)) &&
!(el as Partial<Computed<unknown>>)._fn &&
c
) {
activeTransition._gatedSubs.add(c as Computed<any>);
return el._value as T;
}
// In optimistic lane context, return _value for optimistic/lane-assigned signals
// and for regular signals in stale mode (render effects). Non-stale readers (user
// effects) see _pendingValue so that latest() and direct reads stay consistent.
// Exception: resolved projection store properties (firewall, owner !== el) whose
// STATUS_PENDING has been cleared always return _pendingValue.
const value =
!c ||
(currentOptimisticLane !== null &&
(el._overrideValue !== undefined ||
(el as any)._optimisticLane ||
(owner === el && stale) ||
!!(owner._statusFlags & STATUS_PENDING))) ||
el._pendingValue === NOT_PENDING ||
(stale && el._transition && activeTransition !== el._transition)
? el._value
: (el._pendingValue as T);
if (
!c &&
owner === el &&
typeof computed._fn === "function" &&
el._config & CONFIG_AUTO_DISPOSE &&
!(owner._statusFlags & STATUS_PENDING) &&
!el._subs
) {
unobserved(el as Computed<unknown>);
}
return value;
}
export function setSignal<T>(el: Signal<T> | Computed<T>, v: T | ((prev: T) => T)): T {
if (
__DEV__ &&
!(el._config & CONFIG_OWNED_WRITE) &&
!(context && context._config & CONFIG_CHILDREN_FORBIDDEN) &&
context &&
(el as FirewallSignal<any>)._firewall !== context
) {
emitDiagnostic({
code: "REACTIVE_WRITE_IN_OWNED_SCOPE",
kind: "write",
severity: "error",
message: REACTIVE_WRITE_IN_OWNED_SCOPE_SIGNAL_MESSAGE,
ownerId: context.id,
ownerName: (context as any)._name,
nodeName: (el as any)._name,
data: { operation: "setSignal" }
});
throw new Error(REACTIVE_WRITE_IN_OWNED_SCOPE_SIGNAL_MESSAGE);
}
if (el._transition && activeTransition !== el._transition)
globalQueue.initTransition(el._transition);
const isOptimistic = el._overrideValue !== undefined && !projectionWriteActive;
const hasOverride = el._overrideValue !== undefined && el._overrideValue !== NOT_PENDING;
const currentValue = isOptimistic
? hasOverride
? (el._overrideValue as T)
: el._value
: el._pendingValue === NOT_PENDING
? el._value
: (el._pendingValue as T);
if (typeof v === "function") v = (v as (prev: T) => T)(currentValue);
const valueChanged =
!el._equals ||
!el._equals(currentValue, v) ||
!!((el as Computed<T>)._statusFlags & STATUS_UNINITIALIZED);
if (!valueChanged) {
// Re-propagate for optimistic computeds with active override — downstream
// nodes may have stale _inFlight based on old upstream data.
if (isOptimistic && hasOverride) {
const transition = resolveTransition(el as any);
if (transition && activeTransition !== transition) globalQueue.initTransition(transition);
if ((el as Computed<T>)._fn) {
insertSubs(el, true);
schedule();
}
}
return v;
}
if (isOptimistic) {
const firstOverride = el._overrideValue === NOT_PENDING;
if (!firstOverride) globalQueue.initTransition(resolveTransition(el as any));
if (firstOverride) {
el._pendingValue = el._value;
globalQueue._optimisticNodes.push(el);
}
(el as any)._overrideSinceLane = true;
const lane = getOrCreateLane(el);
el._optimisticLane = lane;
el._overrideValue = v;
} else {
if (el._pendingValue === NOT_PENDING) queuePendingNode(el);
el._pendingValue = v;
}
// Update pending signal if it exists (for isPending reactivity)
if (el._pendingSignal) updatePendingSignal(el);
// Also write to latest value computed if it exists (for latest())
if (el._latestValueComputed) {
setSignal(el._latestValueComputed, v);
}
el._time = clock;
if (isOptimistic) {
// Optimistic walks mutate subscriber lane state, so they always run and
// never count as a cacheable plain notification.
el._notifyEpoch = 0;