@solidjs/signals 2.0.0-rc.0 → 2.0.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/README.md +1 -1
  2. package/dist/dev-shared.js +7138 -0
  3. package/dist/dev.attribution.js +3307 -0
  4. package/dist/dev.js +8076 -6692
  5. package/dist/observe/affects.js +129 -0
  6. package/dist/observe/attribution.js +7 -0
  7. package/dist/observe/boundaries.js +793 -0
  8. package/dist/observe/core/action.js +177 -0
  9. package/dist/observe/core/async.js +849 -0
  10. package/dist/observe/core/attribution-costs.js +66 -0
  11. package/dist/observe/core/attribution-feedback.js +280 -0
  12. package/dist/observe/core/attribution-hooks.js +83 -0
  13. package/dist/observe/core/attribution-queries.js +43 -0
  14. package/dist/observe/core/attribution.js +2904 -0
  15. package/dist/observe/core/constants.js +283 -0
  16. package/dist/{types-cjs/core/context.d.cts → observe/core/context.js} +37 -12
  17. package/dist/observe/core/core.js +1999 -0
  18. package/dist/observe/core/dev.js +343 -0
  19. package/dist/observe/core/effect.js +200 -0
  20. package/dist/observe/core/error-hooks.js +71 -0
  21. package/dist/observe/core/error.js +80 -0
  22. package/dist/observe/core/external.js +98 -0
  23. package/dist/observe/core/graph.js +155 -0
  24. package/dist/observe/core/heap.js +147 -0
  25. package/dist/observe/core/invariants.js +45 -0
  26. package/dist/observe/core/lanes.js +205 -0
  27. package/dist/observe/core/optimistic.js +627 -0
  28. package/dist/observe/core/owner.js +353 -0
  29. package/dist/observe/core/scheduler.js +1547 -0
  30. package/dist/observe/core/verdict.js +674 -0
  31. package/dist/observe/index.js +59 -0
  32. package/dist/observe/map.js +484 -0
  33. package/dist/observe/signals.js +731 -0
  34. package/dist/observe/store/index.js +44 -0
  35. package/dist/observe/store/next/optimistic.js +717 -0
  36. package/dist/observe/store/next/projection.js +266 -0
  37. package/dist/observe/store/next/reconcile.js +375 -0
  38. package/dist/observe/store/next/store.js +2480 -0
  39. package/dist/observe/store/next/target.js +51 -0
  40. package/dist/observe/store/store.js +331 -0
  41. package/dist/observe/store/storePath.js +103 -0
  42. package/dist/observe/store/utils.js +1070 -0
  43. package/dist/prod/affects.js +10 -9
  44. package/dist/prod/attribution.js +45 -0
  45. package/dist/prod/boundaries.js +388 -178
  46. package/dist/prod/core/action.js +65 -37
  47. package/dist/prod/core/async.js +477 -208
  48. package/dist/prod/core/attribution-hooks.js +3 -0
  49. package/dist/prod/core/constants.js +186 -1
  50. package/dist/prod/core/context.js +10 -16
  51. package/dist/prod/core/core.js +1556 -415
  52. package/dist/prod/core/dev.js +18 -1
  53. package/dist/prod/core/effect.js +119 -79
  54. package/dist/prod/core/error-hooks.js +71 -0
  55. package/dist/prod/core/error.js +13 -1
  56. package/dist/prod/core/external.js +4 -4
  57. package/dist/prod/core/graph.js +105 -54
  58. package/dist/prod/core/heap.js +72 -65
  59. package/dist/prod/core/invariants.js +3 -2
  60. package/dist/prod/core/lanes.js +117 -52
  61. package/dist/prod/core/optimistic.js +474 -103
  62. package/dist/prod/core/owner.js +131 -84
  63. package/dist/prod/core/scheduler.js +1013 -248
  64. package/dist/prod/core/verdict.js +418 -113
  65. package/dist/prod/index.js +25 -13
  66. package/dist/prod/map.js +314 -151
  67. package/dist/prod/signals.js +382 -32
  68. package/dist/prod/store/index.js +38 -0
  69. package/dist/prod/store/next/optimistic.js +710 -0
  70. package/dist/prod/store/next/projection.js +257 -0
  71. package/dist/prod/store/next/reconcile.js +373 -0
  72. package/dist/prod/store/next/store.js +2356 -0
  73. package/dist/prod/store/next/target.js +51 -0
  74. package/dist/prod/store/store.js +129 -881
  75. package/dist/prod/store/utils.js +982 -242
  76. package/dist/types/attribution.d.ts +19 -0
  77. package/dist/types/attribution.prod.d.ts +22 -0
  78. package/dist/types/boundaries.d.ts +78 -5
  79. package/dist/types/core/action.d.ts +12 -5
  80. package/dist/types/core/async.d.ts +3 -1
  81. package/dist/types/core/attribution-costs.d.ts +35 -0
  82. package/dist/types/core/attribution-feedback.d.ts +133 -0
  83. package/dist/types/core/attribution-hooks.d.ts +304 -0
  84. package/dist/types/core/attribution-queries.d.ts +24 -0
  85. package/dist/types/core/attribution.d.ts +892 -0
  86. package/dist/types/core/constants.d.ts +179 -0
  87. package/dist/types/core/core.d.ts +305 -23
  88. package/dist/types/core/dev.d.ts +421 -8
  89. package/dist/types/core/effect.d.ts +8 -1
  90. package/dist/types/core/error-hooks.d.ts +71 -0
  91. package/dist/types/core/error.d.ts +9 -0
  92. package/dist/types/core/graph.d.ts +23 -0
  93. package/dist/types/core/heap.d.ts +5 -3
  94. package/dist/types/core/index.d.ts +6 -3
  95. package/dist/types/core/invariants.d.ts +5 -1
  96. package/dist/types/core/lanes.d.ts +51 -19
  97. package/dist/types/core/owner.d.ts +15 -3
  98. package/dist/types/core/scheduler.d.ts +252 -3
  99. package/dist/types/core/types.d.ts +124 -41
  100. package/dist/types/index.d.ts +18 -5
  101. package/dist/types/map.d.ts +2 -0
  102. package/dist/types/signals.d.ts +164 -13
  103. package/dist/types/store/index.d.ts +16 -5
  104. package/dist/types/store/next/optimistic.d.ts +25 -0
  105. package/dist/types/store/next/projection.d.ts +27 -0
  106. package/dist/types/store/next/reconcile.d.ts +10 -0
  107. package/dist/types/store/next/store.d.ts +143 -0
  108. package/dist/types/store/next/target.d.ts +196 -0
  109. package/dist/types/store/store.d.ts +46 -112
  110. package/dist/types/store/utils.d.ts +188 -40
  111. package/package.json +32 -26
  112. package/dist/node.cjs +0 -7938
  113. package/dist/prod/store/optimistic.js +0 -217
  114. package/dist/prod/store/projection.js +0 -231
  115. package/dist/prod/store/reconcile.js +0 -707
  116. package/dist/types/store/optimistic.d.ts +0 -45
  117. package/dist/types/store/projection.d.ts +0 -70
  118. package/dist/types/store/reconcile.d.ts +0 -46
  119. package/dist/types-cjs/affects.d.cts +0 -47
  120. package/dist/types-cjs/boundaries.d.cts +0 -175
  121. package/dist/types-cjs/core/action.d.cts +0 -64
  122. package/dist/types-cjs/core/async.d.cts +0 -21
  123. package/dist/types-cjs/core/constants.d.cts +0 -71
  124. package/dist/types-cjs/core/core.d.cts +0 -148
  125. package/dist/types-cjs/core/dev.d.cts +0 -64
  126. package/dist/types-cjs/core/effect.d.cts +0 -30
  127. package/dist/types-cjs/core/error.d.cts +0 -47
  128. package/dist/types-cjs/core/external.d.cts +0 -15
  129. package/dist/types-cjs/core/graph.d.cts +0 -5
  130. package/dist/types-cjs/core/heap.d.cts +0 -22
  131. package/dist/types-cjs/core/index.d.cts +0 -13
  132. package/dist/types-cjs/core/invariants.d.cts +0 -59
  133. package/dist/types-cjs/core/lanes.d.cts +0 -56
  134. package/dist/types-cjs/core/optimistic.d.cts +0 -6
  135. package/dist/types-cjs/core/owner.d.cts +0 -124
  136. package/dist/types-cjs/core/scheduler.d.cts +0 -170
  137. package/dist/types-cjs/core/types.d.cts +0 -148
  138. package/dist/types-cjs/core/verdict.d.cts +0 -2
  139. package/dist/types-cjs/index.d.cts +0 -10
  140. package/dist/types-cjs/map.d.cts +0 -69
  141. package/dist/types-cjs/package.json +0 -3
  142. package/dist/types-cjs/signals.d.cts +0 -605
  143. package/dist/types-cjs/store/index.d.cts +0 -9
  144. package/dist/types-cjs/store/optimistic.d.cts +0 -45
  145. package/dist/types-cjs/store/projection.d.cts +0 -70
  146. package/dist/types-cjs/store/reconcile.d.cts +0 -46
  147. package/dist/types-cjs/store/store.d.cts +0 -213
  148. package/dist/types-cjs/store/storePath.d.cts +0 -58
  149. package/dist/types-cjs/store/utils.d.cts +0 -114
@@ -0,0 +1,343 @@
1
+ import { currentOrigin, withOrigin, withInteraction, attrHooks } from "./attribution-hooks.js";
2
+
3
+ import { context } from "./core.js";
4
+
5
+ /** First warning when a change reaches (or a pass tracks) this many edges. */ const GRAPH_SIZE_WARN_AT = 2e3;
6
+
7
+ /** Re-warn once the count has grown by this much since the last warning. */ const GRAPH_SIZE_WARN_EVERY = 500;
8
+
9
+ const diagnosticListeners = new Set;
10
+
11
+ const diagnosticCaptures = new Set;
12
+
13
+ let diagnosticSequence = 0;
14
+
15
+ /**
16
+ * Registers the console footer appended to the first console report of
17
+ * each diagnostic code — a discovery pointer to deeper guidance. Reported
18
+ * events carry it as trailing lines of the same console entry; events that
19
+ * surface as a thrown error instead get it as a follow-up line. Returning
20
+ * undefined for an event suppresses the footer. Passing undefined
21
+ * unregisters and resets the once-per-code memory.
22
+ *
23
+ * @internal A seam for `solid-js`, which owns the repair skill the footer
24
+ * names and installs it from both of its entries; not part of `DEV`. No-op
25
+ * outside dev builds, where nothing reports to the console.
26
+ */ function setConsoleFooter(e) {
27
+ return;
28
+ }
29
+
30
+ const diagnostics = {
31
+ subscribe(e) {
32
+ diagnosticListeners.add(e);
33
+ return () => diagnosticListeners.delete(e);
34
+ },
35
+ emit(e, n = null) {
36
+ return emitDiagnostic(e, n);
37
+ },
38
+ capture() {
39
+ const e = [];
40
+ diagnosticCaptures.add(e);
41
+ return {
42
+ get events() {
43
+ return e;
44
+ },
45
+ clear() {
46
+ e.length = 0;
47
+ },
48
+ stop() {
49
+ diagnosticCaptures.delete(e);
50
+ return [ ...e ];
51
+ }
52
+ };
53
+ }
54
+ };
55
+
56
+ const attributionSlot = {
57
+ get installed() {
58
+ return attrHooks;
59
+ },
60
+ withInteraction: withInteraction,
61
+ withOrigin: withOrigin,
62
+ currentOrigin: currentOrigin
63
+ };
64
+
65
+ const RECORDS = Symbol.for("@solidjs/signals/observe/records");
66
+
67
+ function recordsChannel() {
68
+ const e = globalThis;
69
+ if (e[RECORDS]) return e[RECORDS];
70
+ const n = new Map;
71
+ return e[RECORDS] = {
72
+ subscribe(e, t) {
73
+ const o = n.get(e);
74
+ // Set semantics: one entry per function, however often it is passed.
75
+ if (o === undefined) n.set(e, [ t ]); else if (!o.includes(t)) n.set(e, [ ...o, t ]);
76
+ return () => {
77
+ const o = n.get(e);
78
+ if (o === undefined) return;
79
+ const r = o.filter(e => e !== t);
80
+ if (r.length > 0) n.set(e, r); else n.delete(e);
81
+ };
82
+ },
83
+ observed(e) {
84
+ return n.has(e);
85
+ },
86
+ emit(e, t, o) {
87
+ const r = n.get(e);
88
+ if (r === undefined) return;
89
+ // A throwing listener is reported and the rest still hear the record.
90
+ // The try/catch per call allocates nothing unless something throws.
91
+ for (let e = 0; e < r.length; e++) {
92
+ try {
93
+ r[e](t, o);
94
+ } catch (e) {
95
+ console.error(e);
96
+ }
97
+ }
98
+ }
99
+ };
100
+ }
101
+
102
+ const OBSERVE = {
103
+ diagnostics: diagnostics,
104
+ records: recordsChannel(),
105
+ attribution: attributionSlot,
106
+ // Replaced by solid-js's server entry (see `ServerObserve`); on the
107
+ // client the slot stays this placeholder. The cast: the interface is
108
+ // empty HERE and gains its members by augmentation downstream.
109
+ server: {},
110
+ exclude(e) {
111
+ excludedOwners.add(e);
112
+ hasExclusions = true;
113
+ },
114
+ isExcluded: isExcluded,
115
+ ownerPath: ownerPath
116
+ };
117
+
118
+ // --- Excluded owners ---------------------------------------------------------------
119
+
120
+ // An observer that lives inside the observed app (an adapter's panel,
121
+ // devtools) marks its root; both channels check the subject's owner chain —
122
+ // the same walk `ownerPath` already makes — and stay silent under it. The
123
+ // flag short-circuits the walk for the common case of no exclusions.
124
+ const excludedOwners = new WeakSet;
125
+
126
+ let hasExclusions = false;
127
+
128
+ /** Events built for an excluded subject: never delivered, never reported. */ const suppressedEvents = new WeakSet;
129
+
130
+ function isExcluded(e) {
131
+ if (!hasExclusions || !e) return false;
132
+ let n = "_parent" in e ? e : e.ie ?? null;
133
+ for (;n !== null; n = n._parent) if (excludedOwners.has(n)) return true;
134
+ return false;
135
+ }
136
+
137
+ /** For engines that cache the verdict per node: is anything excluded at all? */ function anyExcluded() {
138
+ return hasExclusions;
139
+ }
140
+
141
+ /** Was `entry` built for an excluded subject? Once-per-key reporters must not spend their slot on it. */ function isSuppressed(e) {
142
+ return suppressedEvents.has(e);
143
+ }
144
+
145
+ const DEV = undefined;
146
+
147
+ /**
148
+ * Root-first names of the owners enclosing `subject` (inclusive when the
149
+ * subject is itself a named owner). Signals hop to their registering owner
150
+ * (`_owner`, set by registerGraph). Unnamed owners are skipped so the path
151
+ * reads as the component tree plus the scope: `<App> › <TodoRow> › effect`.
152
+ * Public as `OBSERVE.ownerPath`; the core's own sites import it directly.
153
+ */ function ownerPath(e) {
154
+ if (!e) return undefined;
155
+ let n = "_parent" in e ? e : e.ie ?? null;
156
+ const t = [];
157
+ for (;n !== null; n = n._parent) {
158
+ const e = n._name;
159
+ if (typeof e === "string" && e.length) t.push(e);
160
+ }
161
+ return t.length ? t.reverse() : undefined;
162
+ }
163
+
164
+ /**
165
+ * Records a diagnostic on the structured channel (listeners, captures) and
166
+ * returns the entry. `subject` locates it: the current reactive `context` by
167
+ * default (right for the synchronous rule checks — they fire inside the
168
+ * scope that misbehaved); pass the node for scheduler-time findings whose
169
+ * ambient context is the flush, or `null` for events that have no location
170
+ * by nature. An `ownerPath` already on the event wins over the subject walk
171
+ * (hosts whose owners are not signals' owners compute their own). Console
172
+ * output is a separate, dev-tier step — see `reportDiagnostic`.
173
+ */ function emitDiagnostic(e, n = context) {
174
+ const t = {
175
+ sequence: ++diagnosticSequence,
176
+ ...e
177
+ };
178
+ // The observer's own subtree: build the entry (the caller may throw its
179
+ // message) but tell nobody.
180
+ if (isExcluded(n)) {
181
+ suppressedEvents.add(t);
182
+ return t;
183
+ }
184
+ if (t.ownerPath === undefined) {
185
+ const e = ownerPath(n);
186
+ if (e) t.ownerPath = e;
187
+ }
188
+ const o = n ?? undefined;
189
+ if (o !== undefined) eventSubjects.set(t, o);
190
+ for (const e of diagnosticListeners) e(t, o);
191
+ for (const e of diagnosticCaptures) e.push(t);
192
+ return t;
193
+ }
194
+
195
+ /**
196
+ * The subject each emitted event was about, for the console step, which
197
+ * runs after `emitDiagnostic` returned and can show what the node knows: a
198
+ * rendering runtime may stamp a binding effect with the DOM element it
199
+ * writes (`_devElement`), and a live element reference beside the message
200
+ * is the most addressable pointer a console can print. Listeners get the
201
+ * subject as their second argument instead; the map exists only to carry
202
+ * it from `emitDiagnostic` to `reportDiagnostic` across the call site's
203
+ * `reportDiagnostic(emitDiagnostic(…))`. Weak, keyed by the entry.
204
+ */ const eventSubjects = new WeakMap;
205
+
206
+ /**
207
+ * The console face of a diagnostic — ONE entry per finding: the message, the
208
+ * owner path (`in <App> › <TodoRow> › effect`) so a human can locate it, the
209
+ * once-per-code footer as trailing lines, and — when the subject is a
210
+ * binding effect the rendering runtime tagged — the element it writes, as a
211
+ * second console argument (hover highlights it, click jumps to Elements).
212
+ * Severity picks the console method. Call sites report the entry
213
+ * `emitDiagnostic` returned so the structured and console channels never
214
+ * disagree. Dev-tier: in an observe build this is a no-op, so wiring paths
215
+ * that both emit and report (graph-size warnings) reach the channel only —
216
+ * production observability never writes to the console.
217
+ */ function reportDiagnostic(e) {
218
+ return;
219
+ }
220
+
221
+ /**
222
+ * Observe-tier: stamp a signal with its creating owner so `ownerPath` can
223
+ * locate signal subjects. The per-owner `_signals` list and the devtools
224
+ * `onGraph` hook are dev-tier — the observe build pays one property write.
225
+ */ function registerGraph(e, n) {
226
+ e.ie = n;
227
+ }
228
+
229
+ /**
230
+ * Observe-tier: the live top-level roots — owners created with no parent
231
+ * (`render()`'s root, a `createRoot()` at module scope, a devtools panel).
232
+ * Held weakly so an undisposed root nothing references still collects; a
233
+ * root a subscription keeps alive is exactly the leak `graphSize()` exists
234
+ * to count. Registered by `createOwner` and released by its disposal, so
235
+ * the cost is one Set write per top-level root, never per node.
236
+ */ const liveRoots = new Set;
237
+
238
+ const rootRefs = new WeakMap;
239
+
240
+ const rootReaper = typeof FinalizationRegistry === "function" ? new FinalizationRegistry(e => liveRoots.delete(e)) : null;
241
+
242
+ function registerRoot(e) {
243
+ // Observe-tier bodies: folded to a bare return in prod so the mangler and
244
+ // the bundle never see the walk.
245
+ if (typeof WeakRef !== "function") return;
246
+ const n = new WeakRef(e);
247
+ rootRefs.set(e, n);
248
+ liveRoots.add(n);
249
+ rootReaper?.register(e, n, n);
250
+ }
251
+
252
+ function unregisterRoot(e) {
253
+ const n = rootRefs.get(e);
254
+ if (n === undefined) return;
255
+ rootRefs.delete(e);
256
+ liveRoots.delete(n);
257
+ rootReaper?.unregister(n);
258
+ }
259
+
260
+ /**
261
+ * The live top-level roots, for a walk of the owner tree (the engine's
262
+ * `graphSize`): dead refs are dropped as they are met. Empty in prod.
263
+ */ function liveRootOwners() {
264
+ const e = [];
265
+ for (const n of liveRoots) {
266
+ const t = n.deref();
267
+ if (t === undefined) liveRoots.delete(n); else e.push(t);
268
+ }
269
+ return e;
270
+ }
271
+
272
+ /**
273
+ * Graph-size warnings are once per node, re-warning only when the count has
274
+ * grown by GRAPH_SIZE_WARN_EVERY since the last one — off-node, so the
275
+ * pathological handful of nodes that ever reach the threshold are the only
276
+ * ones that cost anything, and no node carries a bookkeeping field for it.
277
+ */ const graphSizeWarnedAt = new WeakMap;
278
+
279
+ function shouldWarnGraphSize(e, n) {
280
+ const t = graphSizeWarnedAt.get(e);
281
+ if (t !== undefined && n < t + GRAPH_SIZE_WARN_EVERY) return false;
282
+ graphSizeWarnedAt.set(e, n);
283
+ return true;
284
+ }
285
+
286
+ /**
287
+ * Observe-tier: a committed change on `node` is about to re-run `count`
288
+ * subscribers. Two reporters, one finding, one dedupe: the core counts the
289
+ * notify walk in `insertSubs` as it goes (fan-out costs exactly one local
290
+ * increment in a loop that already visits every edge, and nothing at link
291
+ * time) and fires from GRAPH_SIZE_WARN_AT up, always-on wherever the
292
+ * channel exists — a graph-size pathology should surface without asking.
293
+ * The attribution engine, while enabled, reports the same code from its
294
+ * lower `fanOut` threshold (default 250) on the root writes it stamps, with
295
+ * the write kind it knows, and hands over to the core at
296
+ * GRAPH_SIZE_WARN_AT so one change never carries two findings. Both fire on
297
+ * the write rather than the link: a fan-out that is never written costs
298
+ * nothing, and one that is re-runs every subscriber this flush. Once per
299
+ * node, re-warning only once the count has grown by GRAPH_SIZE_WARN_EVERY.
300
+ */ function noteFanOut(e, n, t) {
301
+ if (!shouldWarnGraphSize(e, n)) return;
302
+ const o = e._name;
303
+ const r = `[HUGE_FAN_OUT] ${o ? `Signal "${o}"` : "A signal"} changed with ${n} subscribers — ` + `every one re-runs this flush. If many independent computations read the same value ` + `(for example every row of a list comparing against one selected id), prefer a per-key ` + `store or projection so only the items whose result flipped update.`;
304
+ reportDiagnostic(emitDiagnostic({
305
+ code: "HUGE_FAN_OUT",
306
+ kind: "graph",
307
+ severity: "warn",
308
+ message: r,
309
+ nodeName: o,
310
+ ownerId: e.id,
311
+ ownerName: o,
312
+ data: t === undefined ? {
313
+ count: n
314
+ } : {
315
+ count: n,
316
+ write: t
317
+ }
318
+ }, e));
319
+ }
320
+
321
+ /**
322
+ * Observe-tier: a recompute pass of `node` tracked `count` distinct sources
323
+ * (its trimmed dep list, walked once at the end of the pass — see recompute;
324
+ * no per-link work, no pass bracket). Fires from GRAPH_SIZE_WARN_AT up.
325
+ */ function noteFanIn(e, n) {
326
+ if (!shouldWarnGraphSize(e, n)) return;
327
+ const t = e._name;
328
+ const o = `[HUGE_FAN_IN] ${t ? `Computation "${t}"` : "A computation"} tracked ${n} sources. ` + `It will re-run when any of them change. Narrow the read or split the derivation so each ` + `computation tracks only what it needs.`;
329
+ reportDiagnostic(emitDiagnostic({
330
+ code: "HUGE_FAN_IN",
331
+ kind: "graph",
332
+ severity: "warn",
333
+ message: o,
334
+ nodeName: t,
335
+ ownerId: e.id,
336
+ ownerName: t,
337
+ data: {
338
+ count: n
339
+ }
340
+ }, e));
341
+ }
342
+
343
+ export { DEV, GRAPH_SIZE_WARN_AT, GRAPH_SIZE_WARN_EVERY, OBSERVE, anyExcluded, emitDiagnostic, isExcluded, isSuppressed, liveRootOwners, noteFanIn, noteFanOut, ownerPath, registerGraph, registerRoot, reportDiagnostic, setConsoleFooter, unregisterRoot };
@@ -0,0 +1,200 @@
1
+ import { REACTIVE_DISPOSED, LANE_RUN, STATUS_ERROR, EFFECT_USER, NOT_PENDING, CONFIG_AUTO_DISPOSE, CONFIG_CHILDREN_FORBIDDEN, EFFECT_TRACKED, EFFECT_RENDER, STATUS_PENDING } from "./constants.js";
2
+
3
+ import { setEffectStatusNotify, ext, createEffectNode, recompute, computed, staleValues } from "./core.js";
4
+
5
+ import { attrHooks } from "./attribution-hooks.js";
6
+
7
+ import "./dev.js";
8
+
9
+ import { unwrapStatusError, StatusError } from "./error.js";
10
+
11
+ import { trimStaleDeps } from "./graph.js";
12
+
13
+ import { enqueueSub } from "./heap.js";
14
+
15
+ import { GlobalQueue, currentTransition, activeTransition, haltReactivity, schedule } from "./scheduler.js";
16
+
17
+ /**
18
+ * Effects are the leaf nodes of our reactive graph. When their sources change, they are
19
+ * automatically added to the queue of effects to re-execute, which will cause them to fetch their
20
+ * sources and recompute
21
+ */ function effect(t, e, r, E) {
22
+ const i = !!E?.user;
23
+ const n = createEffectNode(t, e, r, i ? EFFECT_USER : EFFECT_RENDER, E);
24
+ recompute(n, true);
25
+ // A first pass that derived from a live transaction's staged world was
26
+ // staged into that transaction (recompute: born held); the transaction's
27
+ // commit replays this effect. Its first run is not this creation's (A29).
28
+ !E?.defer && n._e === NOT_PENDING && (n.He === EFFECT_USER || E?.schedule ? n.T.enqueue(n.He, runEffect.bind(null, n)) : runEffect(n, LANE_RUN));
29
+ }
30
+
31
+ function notifyEffectStatus(t, e) {
32
+ // Use passed values if provided, otherwise read from node
33
+ const r = t !== undefined ? t : this.S;
34
+ const E = e !== undefined ? e : this.o?._;
35
+ if (r & STATUS_ERROR) {
36
+ this.T.notify(this, STATUS_PENDING, 0);
37
+ if (this.He === EFFECT_USER) {
38
+ // The error handler is the error arm of the effect phase (#2840 ruling):
39
+ // queue it like the effect function. It runs in the same imperative,
40
+ // writable scope, throws escalate the same way, and a held transition
41
+ // (or optimistic lane) defers it exactly as it defers the success arm.
42
+ // No payload is queued — the node already carries `_statusFlags`/`_error`,
43
+ // and the runner dispatches on them, so a recovery before the effect
44
+ // phase takes the success arm instead. Blocked forwards (explicit
45
+ // `status` arg without node-state writes) don't queue: the status
46
+ // re-propagates unblocked at commit.
47
+ if (this.S & STATUS_ERROR) {
48
+ this.it = true;
49
+ this.T.enqueue(this.He, this.Ct ??= runEffect.bind(null, this));
50
+ }
51
+ return;
52
+ }
53
+ if (!this.T.notify(this, STATUS_ERROR, STATUS_ERROR)) {
54
+ haltReactivity(unwrapStatusError(E));
55
+ throw E;
56
+ }
57
+ } else if (this.He === EFFECT_RENDER) {
58
+ this.T.notify(this, STATUS_PENDING | STATUS_ERROR, r, E);
59
+ }
60
+ }
61
+
62
+ function runEffect(t, e) {
63
+ if (!t.it || t.oe & REACTIVE_DISPOSED) return;
64
+ // Ownership (#3319): a value computed under a transaction is applied by that
65
+ // transaction's commit. The ordinary effect phase runs with a transaction
66
+ // active only when the flush's finalize ENTERED one (every other path parks
67
+ // or settles first): leave a run owned by a still-held transaction queued —
68
+ // `_modified` stays set — and the next gate stashes it with the owner.
69
+ // Mainline-owned runs (null) apply now. Lanes are exempt by design (they
70
+ // apply their own effects ahead of their transaction — the optimistic view)
71
+ // and mark their runs with LANE_RUN.
72
+
73
+ // Lane exemption has one exception (#3331): a lane runner for an effect that
74
+ // no longer rides a lane — its optimistic source was superseded, so the lane
75
+ // has no optimistic view left to apply, and the value this effect now
76
+ // carries (or will, once its plain recompute lands) belongs to the still-held
77
+ // transaction. Hand the run to the regular queue, where the transaction's
78
+ // gate stashes it with the owner. Lane-less runners with no live owner
79
+ // (reverts, wake-only lanes) apply now.
80
+ if (t.Gt !== null && !currentTransition(t.Gt).Dt && (e & LANE_RUN ? !t.o?.Ce : activeTransition !== null)) {
81
+ t.T.enqueue(t.He, t.Ct);
82
+ return;
83
+ }
84
+ // Error arm (#2840), user effects only: a compute-phase error that is still
85
+ // the node's settled state at effect time runs the bundle's error handler in
86
+ // this same imperative, writable scope. Unwrap the StatusError used for
87
+ // source tracking — user code gets the error it threw, as boundaries do. No
88
+ // handler: log and keep the system alive (the run was skipped). A handler
89
+ // (or logging) consumes the error; a handler throw falls to the shared
90
+ // catch below and escalates boundary-or-halt like any effect-phase throw.
91
+ // Render effects bypass: their errors route to boundaries synchronously in
92
+ // notifyEffectStatus, and a runner queued by an earlier valueChanged in the
93
+ // same flush must not be hijacked by a later-arriving error status.
94
+ if (t.S & STATUS_ERROR && t.He === EFFECT_USER) {
95
+ const e = unwrapStatusError(t.o?._);
96
+ t.Mt = t.ce;
97
+ t.it = false;
98
+ try {
99
+ t.Wt ? t.Wt(e, () => {
100
+ const e = t.qt;
101
+ t.qt = undefined;
102
+ e?.();
103
+ }) : console.error(e);
104
+ } catch (e) {
105
+ if (!t.T.notify(t, STATUS_ERROR, STATUS_ERROR)) {
106
+ haltReactivity(e);
107
+ throw e;
108
+ }
109
+ }
110
+ return;
111
+ }
112
+ // Captured before the callback: its own throw errors the node below, but
113
+ // the compute pass that produced `_value` was clean, so its tail still goes.
114
+ const r = t.o?._ == null;
115
+ // Observe tier, like its `effectRunEnd` twin below: the frame the engine
116
+ // opens here is what stamps the callback's writes as the effect's (the
117
+ // cascade an observer reports) and what times the callback (the `effect`
118
+ // record) — facts a production observer needs, not only a dev console.
119
+ if (attrHooks !== null) attrHooks.effectRunStart(t);
120
+ const E = t.qt;
121
+ t.qt = undefined;
122
+ try {
123
+ E?.();
124
+ const e = t.wt(t.ce, t.Mt);
125
+ if (false && e !== undefined && typeof e !== "function") ;
126
+ // The final cleanup is invoked by disposeChildren at true disposal.
127
+ t.qt = e;
128
+ } catch (e) {
129
+ ext(t)._ = new StatusError(t, e);
130
+ t.S |= STATUS_ERROR;
131
+ if (!t.T.notify(t, STATUS_ERROR, STATUS_ERROR)) {
132
+ haltReactivity(e);
133
+ throw e;
134
+ }
135
+ } finally {
136
+ t.Mt = t.ce;
137
+ t.it = false;
138
+ // The run applied: this is the frame now, so the dependency tail the
139
+ // compute pass left linked goes (A30, #3438 — `recompute` defers an
140
+ // effect's trim while a run is owed; the twin of `commitPendingNode`'s
141
+ // trim for a staged pass). An errored compute kept its full list with
142
+ // `_depsTail` marking where it stopped; leave it, as the commit does.
143
+ if (r) trimStaleDeps(t);
144
+ }
145
+ // Outside the try (see the rule in attribution-hooks.ts). Reached whether or
146
+ // not the callback threw — a throw that escapes the catch above halts.
147
+ if (attrHooks !== null) attrHooks.effectRunEnd(t);
148
+ }
149
+
150
+ GlobalQueue.Rt = runEffect;
151
+
152
+ /**
153
+ * Internal tracked effect - bypasses heap, goes directly to effect queue.
154
+ * Runs as a leaf owner: child primitives and onCleanup are forbidden (false throws).
155
+ * Uses stale reads.
156
+ */ function trackedEffect(t, e) {
157
+ const run = () => {
158
+ // `_modified` is NOT redundant with the heap: the heap dedups within a
159
+ // pass, but a held transition's passes each enqueue `_run` into the same
160
+ // user queue, and this gate is what collapses them into one run at commit.
161
+ if (!r.it || r.oe & REACTIVE_DISPOSED) return;
162
+ try {
163
+ r.it = false;
164
+ recompute(r);
165
+ } finally {}
166
+ };
167
+ const r = computed(() => {
168
+ const e = r.qt;
169
+ r.qt = undefined;
170
+ e?.();
171
+ const E = staleValues(t);
172
+ r.qt = E;
173
+ }, {
174
+ ...e,
175
+ lazy: true
176
+ });
177
+ r.qt = undefined;
178
+ r.C = r.C & ~CONFIG_AUTO_DISPOSE | CONFIG_CHILDREN_FORBIDDEN;
179
+ r.it = true;
180
+ r.He = EFFECT_TRACKED;
181
+ // Observe-tier label: the computed literal defaulted its `_name` slot to
182
+ // "computed"; relabel by kind (a store into the slot, not a new field).
183
+ if (e?.name === undefined) r._name = "trackedEffect";
184
+ // Status dispatch rides the SHARED notifier (statusNotifierOf keys off
185
+ // _type): its error arm is behavior-identical to the closure that used to
186
+ // live here, without the per-node NodeExtension allocation.
187
+ r.lt = run;
188
+ // The first run rides the heap like every wake (GlobalQueue._update), so a
189
+ // tracked effect created inside a render-effect callback runs after that
190
+ // pass's staged writes commit, not before.
191
+ enqueueSub(r);
192
+ schedule();
193
+ }
194
+
195
+ // Install the shared effect status notifier (statusNotifierOf serves it to
196
+ // every effect node) — module-scope: any bundle that creates effects
197
+ // evaluates this module.
198
+ setEffectStatusNotify(notifyEffectStatus);
199
+
200
+ export { effect, trackedEffect };
@@ -0,0 +1,71 @@
1
+ import { ROOT_ERROR_HOOK } from "./scheduler.js";
2
+
3
+ let ambientHook;
4
+
5
+ const reported = new WeakSet;
6
+
7
+ /**
8
+ * Registers the ambient client error hook — the one call a browser `init()`
9
+ * makes to see every failure a boundary renders a fallback for, in
10
+ * production. (Uncaught errors reach `reportError` / `window.onerror`.)
11
+ *
12
+ * ```ts
13
+ * configureClientErrors({
14
+ * onError: (error, { ownerPath }) =>
15
+ * Sentry.captureException(error, {
16
+ * mechanism: { type: "solid.error_boundary", handled: true }
17
+ * })
18
+ * });
19
+ * ```
20
+ */ function configureClientErrors(e) {
21
+ if (e && e.onError !== undefined && typeof e.onError !== "function") {
22
+ throw new TypeError(`Invalid onError: expected a function, received ${typeof e.onError}.`);
23
+ }
24
+ ambientHook = e ? e.onError : undefined;
25
+ }
26
+
27
+ /** The nearest root's hook above `owner` (parked under `ROOT_ERROR_HOOK`), else the ambient one. */ function hookFor(e) {
28
+ for (let n = e; n; n = n._parent) {
29
+ const e = n[ROOT_ERROR_HOOK];
30
+ if (e !== undefined) return e;
31
+ }
32
+ return ambientHook;
33
+ }
34
+
35
+ /** Component labels up the owner chain, root first — `_name` where the runtime keeps it. */ function labels(e) {
36
+ const n = [];
37
+ for (let o = e; o; o = o._parent) {
38
+ const e = o._name;
39
+ if (typeof e === "string" && e.length) n.push(e);
40
+ }
41
+ return n.length ? n.reverse() : undefined;
42
+ }
43
+
44
+ /**
45
+ * Tells the client error hook about `error`, caught by the boundary whose
46
+ * owner is `owner`, thrown by `thrower` (the computation the engine's status
47
+ * wrapper named; unknown for a value that never crossed one) — once per
48
+ * error object. A throwing hook is reported on the console and otherwise
49
+ * ignored — a monitor must never take the app down.
50
+ * @internal
51
+ */ function reportClientError(e, n, o) {
52
+ const r = e !== null && (typeof e === "object" || typeof e === "function");
53
+ if (r) {
54
+ if (reported.has(e)) return;
55
+ reported.add(e);
56
+ }
57
+ const t = hookFor(n);
58
+ if (t === undefined) return;
59
+ const i = {};
60
+ const f = labels(n);
61
+ const c = labels(o) ?? f;
62
+ if (c !== undefined) i.ownerPath = c;
63
+ if (f !== undefined) i.boundaryPath = f;
64
+ try {
65
+ t(e, i);
66
+ } catch (e) {
67
+ console.error(e);
68
+ }
69
+ }
70
+
71
+ export { configureClientErrors, reportClientError };
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Thrown by a tracked read whose value is currently pending (an async memo /
3
+ * `createSignal(asyncFn)` / projection / store derivation that hasn't settled
4
+ * yet). Surfacing through the reactive graph is what suspends the consumer
5
+ * scope — the nearest enclosing `<Loading>` boundary catches the throw and
6
+ * renders its fallback until the source resolves.
7
+ *
8
+ * App code rarely catches this directly; `<Loading>` is the canonical
9
+ * handler. The error type is exposed for advanced cases — e.g. interop layers
10
+ * that bridge Solid's pending-throw protocol to a different async strategy,
11
+ * or tests that want to assert on the suspension shape.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * // Advanced: distinguish "not ready yet" from a real error in custom
16
+ * // boundary plumbing. App code should rely on `<Loading>` / `<Errored>`.
17
+ * try {
18
+ * const value = readReactiveSource();
19
+ * } catch (err) {
20
+ * if (err instanceof NotReadyError) throw err; // re-throw to suspend
21
+ * reportError(err);
22
+ * }
23
+ * ```
24
+ */
25
+ class NotReadyError extends Error {
26
+ source;
27
+ constructor(r) {
28
+ // Control-flow throw: it happens on every read of a pending source, so in
29
+ // production skip V8's eager stack capture (proportional to stack depth —
30
+ // real cost under SSR) by zeroing the V8-specific stackTraceLimit around
31
+ // super(). Dev keeps the stack for debuggability; non-V8 engines (no
32
+ // stackTraceLimit) take the plain path.
33
+ const o = Error;
34
+ const t = o.stackTraceLimit;
35
+ if (t !== undefined) o.stackTraceLimit = 0;
36
+ super();
37
+ if (t !== undefined) o.stackTraceLimit = t;
38
+ this.source = r;
39
+ }
40
+ }
41
+
42
+ class StatusError extends Error {
43
+ source;
44
+ constructor(r, o) {
45
+ super(o instanceof Error ? o.message : String(o), {
46
+ cause: o
47
+ });
48
+ this.source = r;
49
+ }
50
+ }
51
+
52
+ /** Return the user's error from an internal status wrapper. */ function unwrapStatusError(r) {
53
+ return r instanceof StatusError ? r.cause : r;
54
+ }
55
+
56
+ /**
57
+ * Rejection value of `until(fn, { timeout })` when the predicate does not turn
58
+ * truthy within the window. Inside an `action()`, the rejection is thrown back
59
+ * in at the `yield` point — catchable there, or the action fails and its
60
+ * optimistic state reverts.
61
+ */ class TimeoutError extends Error {
62
+ constructor(r = "Timed out waiting for condition") {
63
+ super(r);
64
+ this.name = "TimeoutError";
65
+ }
66
+ }
67
+
68
+ class NoOwnerError extends Error {
69
+ constructor() {
70
+ super("");
71
+ }
72
+ }
73
+
74
+ class ContextNotFoundError extends Error {
75
+ constructor() {
76
+ super("");
77
+ }
78
+ }
79
+
80
+ export { ContextNotFoundError, NoOwnerError, NotReadyError, StatusError, TimeoutError, unwrapStatusError };