@shadow-js/core 1.0.0 → 1.0.2

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 (240) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/dev/action.d.ts +0 -2
  3. package/dist/dev/action.js +1 -2
  4. package/dist/dev/cache.d.ts +2 -3
  5. package/dist/dev/cache.js +6 -5
  6. package/dist/dev/cache.js.map +1 -1
  7. package/dist/dev/context.d.ts +0 -2
  8. package/dist/dev/context.js +1 -2
  9. package/dist/dev/effect.d.ts +0 -2
  10. package/dist/dev/effect.js +18 -35
  11. package/dist/dev/effect.js.map +1 -1
  12. package/dist/dev/env.d.ts +0 -2
  13. package/dist/dev/env.js +1 -2
  14. package/dist/dev/events.d.ts +0 -2
  15. package/dist/dev/events.js +1 -2
  16. package/dist/dev/extend/index.d.ts +7 -8
  17. package/dist/dev/extend/index.js +8 -9
  18. package/dist/dev/extend/index.js.map +1 -1
  19. package/dist/dev/external-store.d.ts +0 -2
  20. package/dist/dev/external-store.js +9 -5
  21. package/dist/dev/external-store.js.map +1 -1
  22. package/dist/dev/internal/concurrency.d.ts +0 -2
  23. package/dist/dev/internal/concurrency.js +43 -22
  24. package/dist/dev/internal/concurrency.js.map +1 -1
  25. package/dist/dev/internal/devtools.d.ts +0 -2
  26. package/dist/dev/internal/devtools.js +1 -2
  27. package/dist/dev/internal/diagnostics.d.ts +0 -2
  28. package/dist/dev/internal/diagnostics.js +1 -4
  29. package/dist/dev/internal/diagnostics.js.map +1 -1
  30. package/dist/dev/internal/dispose.d.ts +0 -2
  31. package/dist/dev/internal/dispose.js +1 -2
  32. package/dist/dev/internal/flags.js +2 -5
  33. package/dist/dev/internal/flags.js.map +1 -1
  34. package/dist/dev/internal/graph.d.ts +0 -3
  35. package/dist/dev/internal/graph.js +21 -39
  36. package/dist/dev/internal/graph.js.map +1 -1
  37. package/dist/dev/internal/hydration-flag.d.ts +0 -2
  38. package/dist/dev/internal/hydration-flag.js +1 -2
  39. package/dist/dev/internal/messages.d.ts +0 -2
  40. package/dist/dev/internal/messages.js +1 -2
  41. package/dist/dev/internal/owner.d.ts +7 -7
  42. package/dist/dev/internal/owner.js +13 -24
  43. package/dist/dev/internal/owner.js.map +1 -1
  44. package/dist/dev/internal/queue.js +1 -2
  45. package/dist/dev/internal/scheduler.d.ts +0 -2
  46. package/dist/dev/internal/scheduler.js +34 -73
  47. package/dist/dev/internal/scheduler.js.map +1 -1
  48. package/dist/dev/internal/state.d.ts +0 -2
  49. package/dist/dev/internal/state.js +1 -2
  50. package/dist/dev/internal/suspension.d.ts +0 -2
  51. package/dist/dev/internal/suspension.js +1 -2
  52. package/dist/dev/internal/types.d.ts +0 -2
  53. package/dist/dev/list.d.ts +0 -2
  54. package/dist/dev/list.js +1 -10
  55. package/dist/dev/list.js.map +1 -1
  56. package/dist/dev/memo.d.ts +2 -3
  57. package/dist/dev/memo.js +5 -6
  58. package/dist/dev/memo.js.map +1 -1
  59. package/dist/dev/optimistic.d.ts +0 -2
  60. package/dist/dev/optimistic.js +1 -2
  61. package/dist/dev/ownership.d.ts +4 -4
  62. package/dist/dev/ownership.js +60 -5
  63. package/dist/dev/ownership.js.map +1 -1
  64. package/dist/dev/props.d.ts +0 -2
  65. package/dist/dev/props.js +19 -13
  66. package/dist/dev/props.js.map +1 -1
  67. package/dist/dev/reaction.d.ts +1 -3
  68. package/dist/dev/reaction.js +6 -3
  69. package/dist/dev/reaction.js.map +1 -1
  70. package/dist/dev/reducer.d.ts +0 -2
  71. package/dist/dev/reducer.js +2 -3
  72. package/dist/dev/reducer.js.map +1 -1
  73. package/dist/dev/refs.d.ts +0 -2
  74. package/dist/dev/refs.js +1 -2
  75. package/dist/dev/resource.d.ts +0 -2
  76. package/dist/dev/resource.js +22 -14
  77. package/dist/dev/resource.js.map +1 -1
  78. package/dist/dev/selector.d.ts +0 -2
  79. package/dist/dev/selector.js +2 -7
  80. package/dist/dev/selector.js.map +1 -1
  81. package/dist/dev/signal.d.ts +3 -4
  82. package/dist/dev/signal.js +1 -2
  83. package/dist/dev/signal.js.map +1 -1
  84. package/dist/dev/store/nodes.js +7 -2
  85. package/dist/dev/store/nodes.js.map +1 -1
  86. package/dist/dev/store/proxies.js +1 -2
  87. package/dist/dev/store/read.d.ts +0 -2
  88. package/dist/dev/store/read.js +1 -2
  89. package/dist/dev/store/reconcile.d.ts +0 -2
  90. package/dist/dev/store/reconcile.js +1 -2
  91. package/dist/dev/store/types.d.ts +0 -2
  92. package/dist/dev/store/use-store.d.ts +5 -2
  93. package/dist/dev/store/use-store.js +1 -2
  94. package/dist/dev/store/use-store.js.map +1 -1
  95. package/dist/dev/suspense.d.ts +0 -2
  96. package/dist/dev/suspense.js +1 -2
  97. package/dist/dev/transitions.d.ts +0 -2
  98. package/dist/dev/transitions.js +2 -3
  99. package/dist/dev/transitions.js.map +1 -1
  100. package/dist/prod/cache.js +1 -1
  101. package/dist/prod/cache.js.map +1 -1
  102. package/dist/prod/effect.js +1 -1
  103. package/dist/prod/effect.js.map +1 -1
  104. package/dist/prod/extend/index.js +1 -1
  105. package/dist/prod/extend/index.js.map +1 -1
  106. package/dist/prod/external-store.js +1 -1
  107. package/dist/prod/external-store.js.map +1 -1
  108. package/dist/prod/internal/concurrency.js +1 -1
  109. package/dist/prod/internal/concurrency.js.map +1 -1
  110. package/dist/prod/internal/diagnostics.js +1 -1
  111. package/dist/prod/internal/diagnostics.js.map +1 -1
  112. package/dist/prod/internal/flags.js +1 -1
  113. package/dist/prod/internal/flags.js.map +1 -1
  114. package/dist/prod/internal/graph.js +1 -1
  115. package/dist/prod/internal/graph.js.map +1 -1
  116. package/dist/prod/internal/owner.js +1 -1
  117. package/dist/prod/internal/owner.js.map +1 -1
  118. package/dist/prod/internal/scheduler.js +1 -1
  119. package/dist/prod/internal/scheduler.js.map +1 -1
  120. package/dist/prod/list.js +1 -1
  121. package/dist/prod/list.js.map +1 -1
  122. package/dist/prod/memo.js +1 -1
  123. package/dist/prod/memo.js.map +1 -1
  124. package/dist/prod/ownership.js +1 -1
  125. package/dist/prod/ownership.js.map +1 -1
  126. package/dist/prod/props.js.map +1 -1
  127. package/dist/prod/reaction.js +1 -1
  128. package/dist/prod/reaction.js.map +1 -1
  129. package/dist/prod/reducer.js +1 -1
  130. package/dist/prod/reducer.js.map +1 -1
  131. package/dist/prod/resource.js +1 -1
  132. package/dist/prod/resource.js.map +1 -1
  133. package/dist/prod/selector.js +1 -1
  134. package/dist/prod/selector.js.map +1 -1
  135. package/dist/prod/signal.js.map +1 -1
  136. package/dist/prod/store/nodes.js +1 -1
  137. package/dist/prod/store/nodes.js.map +1 -1
  138. package/dist/prod/store/use-store.js.map +1 -1
  139. package/dist/prod/transitions.js +1 -1
  140. package/dist/prod/transitions.js.map +1 -1
  141. package/dist/server/cache.js +1 -1
  142. package/dist/server/cache.js.map +1 -1
  143. package/dist/server/effect.js.map +1 -1
  144. package/dist/server/extend/index.js +1 -1
  145. package/dist/server/extend/index.js.map +1 -1
  146. package/dist/server/external-store.js.map +1 -1
  147. package/dist/server/internal/concurrency.js +1 -1
  148. package/dist/server/internal/concurrency.js.map +1 -1
  149. package/dist/server/internal/diagnostics.js +1 -1
  150. package/dist/server/internal/diagnostics.js.map +1 -1
  151. package/dist/server/internal/flags.js +1 -1
  152. package/dist/server/internal/flags.js.map +1 -1
  153. package/dist/server/internal/graph.js +1 -1
  154. package/dist/server/internal/graph.js.map +1 -1
  155. package/dist/server/internal/owner.js +1 -1
  156. package/dist/server/internal/owner.js.map +1 -1
  157. package/dist/server/internal/scheduler.js +1 -1
  158. package/dist/server/internal/scheduler.js.map +1 -1
  159. package/dist/server/list.js +1 -1
  160. package/dist/server/list.js.map +1 -1
  161. package/dist/server/memo.js +1 -1
  162. package/dist/server/memo.js.map +1 -1
  163. package/dist/server/ownership.js +1 -1
  164. package/dist/server/ownership.js.map +1 -1
  165. package/dist/server/props.js.map +1 -1
  166. package/dist/server/reaction.js +1 -1
  167. package/dist/server/reaction.js.map +1 -1
  168. package/dist/server/reducer.js +1 -1
  169. package/dist/server/reducer.js.map +1 -1
  170. package/dist/server/resource.js +1 -1
  171. package/dist/server/resource.js.map +1 -1
  172. package/dist/server/selector.js +1 -1
  173. package/dist/server/selector.js.map +1 -1
  174. package/dist/server/signal.js.map +1 -1
  175. package/dist/server/store/nodes.js +1 -1
  176. package/dist/server/store/nodes.js.map +1 -1
  177. package/dist/server/store/use-store.js.map +1 -1
  178. package/dist/server/transitions.js.map +1 -1
  179. package/dist/server-dev/action.js +1 -2
  180. package/dist/server-dev/cache.js +6 -5
  181. package/dist/server-dev/cache.js.map +1 -1
  182. package/dist/server-dev/context.js +1 -2
  183. package/dist/server-dev/effect.js +1 -2
  184. package/dist/server-dev/effect.js.map +1 -1
  185. package/dist/server-dev/env.js +1 -2
  186. package/dist/server-dev/events.js +1 -2
  187. package/dist/server-dev/extend/index.js +8 -9
  188. package/dist/server-dev/extend/index.js.map +1 -1
  189. package/dist/server-dev/external-store.js +1 -2
  190. package/dist/server-dev/external-store.js.map +1 -1
  191. package/dist/server-dev/internal/concurrency.js +43 -22
  192. package/dist/server-dev/internal/concurrency.js.map +1 -1
  193. package/dist/server-dev/internal/devtools.js +1 -2
  194. package/dist/server-dev/internal/diagnostics.js +1 -4
  195. package/dist/server-dev/internal/diagnostics.js.map +1 -1
  196. package/dist/server-dev/internal/dispose.js +1 -2
  197. package/dist/server-dev/internal/flags.js +2 -5
  198. package/dist/server-dev/internal/flags.js.map +1 -1
  199. package/dist/server-dev/internal/graph.js +21 -39
  200. package/dist/server-dev/internal/graph.js.map +1 -1
  201. package/dist/server-dev/internal/hydration-flag.js +1 -2
  202. package/dist/server-dev/internal/messages.js +1 -2
  203. package/dist/server-dev/internal/owner.js +13 -24
  204. package/dist/server-dev/internal/owner.js.map +1 -1
  205. package/dist/server-dev/internal/queue.js +1 -2
  206. package/dist/server-dev/internal/scheduler.js +34 -73
  207. package/dist/server-dev/internal/scheduler.js.map +1 -1
  208. package/dist/server-dev/internal/state.js +1 -2
  209. package/dist/server-dev/internal/suspension.js +1 -2
  210. package/dist/server-dev/list.js +1 -10
  211. package/dist/server-dev/list.js.map +1 -1
  212. package/dist/server-dev/memo.js +5 -6
  213. package/dist/server-dev/memo.js.map +1 -1
  214. package/dist/server-dev/optimistic.js +1 -2
  215. package/dist/server-dev/ownership.js +60 -5
  216. package/dist/server-dev/ownership.js.map +1 -1
  217. package/dist/server-dev/props.js +19 -13
  218. package/dist/server-dev/props.js.map +1 -1
  219. package/dist/server-dev/reaction.js +6 -3
  220. package/dist/server-dev/reaction.js.map +1 -1
  221. package/dist/server-dev/reducer.js +2 -3
  222. package/dist/server-dev/reducer.js.map +1 -1
  223. package/dist/server-dev/refs.js +1 -2
  224. package/dist/server-dev/resource.js +22 -14
  225. package/dist/server-dev/resource.js.map +1 -1
  226. package/dist/server-dev/selector.js +2 -7
  227. package/dist/server-dev/selector.js.map +1 -1
  228. package/dist/server-dev/signal.js +1 -2
  229. package/dist/server-dev/signal.js.map +1 -1
  230. package/dist/server-dev/store/nodes.js +7 -2
  231. package/dist/server-dev/store/nodes.js.map +1 -1
  232. package/dist/server-dev/store/proxies.js +1 -2
  233. package/dist/server-dev/store/read.js +1 -2
  234. package/dist/server-dev/store/reconcile.js +1 -2
  235. package/dist/server-dev/store/use-store.js +1 -2
  236. package/dist/server-dev/store/use-store.js.map +1 -1
  237. package/dist/server-dev/suspense.js +1 -2
  238. package/dist/server-dev/transitions.js +1 -2
  239. package/dist/server-dev/transitions.js.map +1 -1
  240. package/package.json +2 -1
@@ -5,7 +5,7 @@ import { rt } from "./state.js";
5
5
  import { handleError } from "./owner.js";
6
6
  import { clearQueues, hasPending, renderQueue, userQueue } from "./queue.js";
7
7
  import { recompute, updateIfNecessary } from "./graph.js";
8
- //#region src/internal/scheduler.ts
8
+ // src/internal/scheduler.ts
9
9
  /**
10
10
  * Flush passes allowed before the loop guard aborts (R-CODE-12).
11
11
  * @internal
@@ -19,22 +19,10 @@ let microtaskScheduled = false;
19
19
  function byCreation(a, b) {
20
20
  return a.depth - b.depth || a.seq - b.seq;
21
21
  }
22
- /**
23
- * Effects mostly arrive in creation order already; checking is O(n), sorting is not.
24
- * @internal
25
- */
26
- function isOrdered(list) {
27
- for (let i = 1; i < list.length; i += 1) {
28
- const previous = list[i - 1];
29
- const current = list[i];
30
- if (previous !== void 0 && current !== void 0 && byCreation(previous, current) > 0) return false;
31
- }
32
- return true;
33
- }
34
22
  /** Runs every queued effect of one phase, parents before children, siblings by creation. */
35
23
  function drain(queue) {
36
24
  const batch = queue.splice(0, queue.length);
37
- if (!isOrdered(batch)) batch.sort(byCreation);
25
+ batch.sort(byCreation);
38
26
  for (const effect of batch) {
39
27
  effect.flags &= -3;
40
28
  if ((effect.flags & 4) !== 0) continue;
@@ -86,25 +74,13 @@ function flush() {
86
74
  report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);
87
75
  try {
88
76
  while (hasPending()) {
89
- let aborted = false;
90
- while (renderQueue.length > 0) {
91
- passes += 1;
92
- if (passes > 1e3) {
93
- aborted = true;
94
- break;
95
- }
96
- runs += drain(renderQueue);
97
- }
98
- if (!aborted && userQueue.length > 0) {
99
- passes += 1;
100
- if (passes > 1e3) aborted = true;
101
- else runs += drain(userQueue);
102
- }
103
- if (aborted) {
77
+ passes += 1;
78
+ if (passes > 1e3) {
104
79
  clearQueues();
105
80
  rt.uncaught.push(new ShadowError("INFINITE_LOOP"));
106
81
  break;
107
82
  }
83
+ runs += drain(renderQueue.length > 0 ? renderQueue : userQueue);
108
84
  }
109
85
  } finally {
110
86
  rt.flushing = false;
@@ -185,8 +161,32 @@ function group(fn) {
185
161
  if (rt.batchDepth === 0 && hasPending()) schedule();
186
162
  }
187
163
  }
188
- function combine(primary, secondary) {
189
- return new AggregateError([primary, secondary], "Both the callback and the flush threw.");
164
+ /**
165
+ * The body `batch` and `flushSync` share: runs `fn` with the effects deferred, then flushes (always when
166
+ * `sync`, else when this was the outermost batch and no flush is running). A throw of `fn` is held until
167
+ * the flush has run, and thrown with the flush's own error as an `AggregateError` when both threw.
168
+ */
169
+ function runBatched(fn, sync) {
170
+ rt.batchDepth += 1;
171
+ let result;
172
+ let failure;
173
+ let failed = false;
174
+ try {
175
+ result = fn === void 0 ? void 0 : fn();
176
+ } catch (error) {
177
+ failed = true;
178
+ failure = error;
179
+ } finally {
180
+ rt.batchDepth -= 1;
181
+ }
182
+ if (sync || rt.batchDepth === 0 && !rt.flushing && hasPending()) try {
183
+ flush();
184
+ } catch (error) {
185
+ if (failed) throw new AggregateError([failure, error], "Both the callback and the flush threw.");
186
+ throw error;
187
+ }
188
+ if (failed) throw failure;
189
+ return result;
190
190
  }
191
191
  /**
192
192
  * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so
@@ -211,26 +211,7 @@ function combine(primary, secondary) {
211
211
  * @since 1.0.0
212
212
  */
213
213
  function batch(fn) {
214
- rt.batchDepth += 1;
215
- let result;
216
- let failure;
217
- let failed = false;
218
- try {
219
- result = fn();
220
- } catch (error) {
221
- failed = true;
222
- failure = error;
223
- } finally {
224
- rt.batchDepth -= 1;
225
- }
226
- if (rt.batchDepth === 0 && !rt.flushing && hasPending()) try {
227
- flush();
228
- } catch (error) {
229
- if (failed) throw combine(failure, error);
230
- throw error;
231
- }
232
- if (failed) throw failure;
233
- return result;
214
+ return runBatched(fn, false);
234
215
  }
235
216
  /**
236
217
  * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and
@@ -260,28 +241,8 @@ function flushSync(fn) {
260
241
  warn("FLUSH_IN_EFFECT");
261
242
  return fn === void 0 ? void 0 : fn();
262
243
  }
263
- rt.batchDepth += 1;
264
- let result;
265
- let failure;
266
- let failed = false;
267
- try {
268
- result = fn === void 0 ? void 0 : fn();
269
- } catch (error) {
270
- failed = true;
271
- failure = error;
272
- } finally {
273
- rt.batchDepth -= 1;
274
- }
275
- try {
276
- flush();
277
- } catch (error) {
278
- if (failed) throw combine(failure, error);
279
- throw error;
280
- }
281
- if (failed) throw failure;
282
- return result;
244
+ return runBatched(fn, true);
283
245
  }
284
- //#endregion
285
- export { MAX_FLUSH_PASSES, batch, byCreation, flush, flushSync, group, isOrdered, reportUncaught, schedule };
246
+ export { MAX_FLUSH_PASSES, batch, byCreation, flush, flushSync, group, reportUncaught, schedule };
286
247
 
287
248
  //# sourceMappingURL=scheduler.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"scheduler.js","names":[],"sources":["../../../src/internal/scheduler.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError, warn } from \"./diagnostics\";\nimport { DIRTY, FLAG_DISPOSED, FLAG_PARKED, FLAG_QUEUED, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { recompute, updateIfNecessary } from \"./graph\";\nimport { handleError } from \"./owner\";\nimport { clearQueues, hasPending, renderQueue, userQueue } from \"./queue\";\nimport { rt } from \"./state\";\n\n/**\n * Flush passes allowed before the loop guard aborts (R-CODE-12).\n * @internal\n */\nexport const MAX_FLUSH_PASSES = 1000;\n\nlet microtaskScheduled = false;\n\n/**\n * Sort order of queued effects: parents before children (by depth), siblings by creation (G-16).\n * @internal\n */\nexport function byCreation(a: Computation, b: Computation): number {\n return a.depth - b.depth || a.seq - b.seq;\n}\n\n/**\n * Effects mostly arrive in creation order already; checking is O(n), sorting is not.\n * @internal\n */\nexport function isOrdered(list: readonly Computation[]): boolean {\n for (let i = 1; i < list.length; i += 1) {\n const previous = list[i - 1];\n const current = list[i];\n if (previous !== undefined && current !== undefined && byCreation(previous, current) > 0) {\n return false;\n }\n }\n return true;\n}\n\n/** Runs every queued effect of one phase, parents before children, siblings by creation. */\nfunction drain(queue: Computation[]): number {\n const batch = queue.splice(0, queue.length);\n if (!isOrdered(batch)) batch.sort(byCreation);\n for (const effect of batch) {\n effect.flags &= ~FLAG_QUEUED;\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n // Paused after it was queued: wait (unqueued) until the owner resumes.\n effect.flags = (effect.flags & ~FLAG_TRANSITION) | FLAG_PARKED;\n continue;\n }\n try {\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n let aborted = false;\n // Render passes count too: a render effect that keeps writing its own source must abort.\n while (renderQueue.length > 0) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n aborted = true;\n break;\n }\n runs += drain(renderQueue);\n }\n if (!aborted && userQueue.length > 0) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) aborted = true;\n else runs += drain(userQueue);\n }\n if (aborted) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batchDepth > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batchDepth += 1;\n try {\n return fn();\n } finally {\n rt.batchDepth -= 1;\n if (rt.batchDepth === 0 && hasPending()) schedule();\n }\n}\n\nfunction combine(primary: unknown, secondary: unknown): unknown {\n return new AggregateError(\n [primary, secondary],\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n if (rt.batchDepth === 0 && !rt.flushing && hasPending()) {\n try {\n flush();\n } catch (error) {\n if (failed) throw combine(failure, error);\n throw error;\n }\n }\n if (failed) throw failure;\n return result as T;\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.flushing) {\n warn(\"FLUSH_IN_EFFECT\");\n return (fn === undefined ? undefined : fn()) as T;\n }\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n try {\n flush();\n } catch (error) {\n if (failed) throw combine(failure, error);\n throw error;\n }\n if (failed) throw failure;\n return result as T;\n}\n"],"mappings":";;;;;;;;;;;;AAaA,MAAa,mBAAmB;AAEhC,IAAI,qBAAqB;;;;;AAMzB,SAAgB,WAAW,GAAgB,GAAwB;CACjE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE;AACxC;;;;;AAMA,SAAgB,UAAU,MAAuC;CAC/D,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GAAG;EACvC,MAAM,WAAW,KAAK,IAAI;EAC1B,MAAM,UAAU,KAAK;EACrB,IAAI,aAAa,KAAA,KAAa,YAAY,KAAA,KAAa,WAAW,UAAU,OAAO,IAAI,GACrF,OAAO;CAEX;CACA,OAAO;AACT;;AAGA,SAAS,MAAM,OAA8B;CAC3C,MAAM,QAAQ,MAAM,OAAO,GAAG,MAAM,MAAM;CAC1C,IAAI,CAAC,UAAU,KAAK,GAAG,MAA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;CACJ,IAAI;CACJ,IAAI,SAAS;CACb,IAAI;EACF,SAAS,OAAO,KAAA,IAAY,KAAA,IAAY,GAAG;CAC7C,SAAS,OAAO;EACd,SAAS;EACT,UAAU;CACZ,UAAU;EACR,GAAG,cAAc;CACnB;CACA,IAAI;EACF,MAAM;CACR,SAAS,OAAO;EACd,IAAI,QAAQ,MAAM,QAAQ,SAAS,KAAK;EACxC,MAAM;CACR;CACA,IAAI,QAAQ,MAAM;CAClB,OAAO;AACT"}
1
+ {"version":3,"file":"scheduler.js","names":[],"sources":["../../../src/internal/scheduler.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError, warn } from \"./diagnostics\";\nimport { DIRTY, FLAG_DISPOSED, FLAG_PARKED, FLAG_QUEUED, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { recompute, updateIfNecessary } from \"./graph\";\nimport { handleError } from \"./owner\";\nimport { clearQueues, hasPending, renderQueue, userQueue } from \"./queue\";\nimport { rt } from \"./state\";\n\n/**\n * Flush passes allowed before the loop guard aborts (R-CODE-12).\n * @internal\n */\nexport const MAX_FLUSH_PASSES = 1000;\n\nlet microtaskScheduled = false;\n\n/**\n * Sort order of queued effects: parents before children (by depth), siblings by creation (G-16).\n * @internal\n */\nexport function byCreation(a: Computation, b: Computation): number {\n return a.depth - b.depth || a.seq - b.seq;\n}\n\n/** Runs every queued effect of one phase, parents before children, siblings by creation. */\nfunction drain(queue: Computation[]): number {\n const batch = queue.splice(0, queue.length);\n // Effects mostly arrive in creation order already: the sort then finds one ascending run and is O(n).\n batch.sort(byCreation);\n for (const effect of batch) {\n effect.flags &= ~FLAG_QUEUED;\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n // Paused after it was queued: wait (unqueued) until the owner resumes.\n effect.flags = (effect.flags & ~FLAG_TRANSITION) | FLAG_PARKED;\n continue;\n }\n try {\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n // Render effects first, and until none is left; render passes count too: a render effect that\n // keeps writing its own source must abort.\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n runs += drain(renderQueue.length > 0 ? renderQueue : userQueue);\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batchDepth > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batchDepth += 1;\n try {\n return fn();\n } finally {\n rt.batchDepth -= 1;\n if (rt.batchDepth === 0 && hasPending()) schedule();\n }\n}\n\n/**\n * The body `batch` and `flushSync` share: runs `fn` with the effects deferred, then flushes (always when\n * `sync`, else when this was the outermost batch and no flush is running). A throw of `fn` is held until\n * the flush has run, and thrown with the flush's own error as an `AggregateError` when both threw.\n */\nfunction runBatched<T>(fn: (() => T) | undefined, sync: boolean): T {\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n if (sync || (rt.batchDepth === 0 && !rt.flushing && hasPending())) {\n try {\n flush();\n } catch (error) {\n if (failed) {\n throw new AggregateError(\n [failure, error],\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n }\n throw error;\n }\n }\n if (failed) throw failure;\n return result as T;\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n return runBatched(fn, false);\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.flushing) {\n warn(\"FLUSH_IN_EFFECT\");\n return (fn === undefined ? undefined : fn()) as T;\n }\n return runBatched(fn, true);\n}\n"],"mappings":";;;;;;;;;;;;AAaA,MAAa,mBAAmB;AAEhC,IAAI,qBAAqB;;;;;AAMzB,SAAgB,WAAW,GAAgB,GAAwB;CACjE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE;AACxC;;AAGA,SAAS,MAAM,OAA8B;CAC3C,MAAM,QAAQ,MAAM,OAAO,GAAG,MAAM,MAAM;CAE1C,MAAM,KAAK,UAAU;CACrB,KAAK,MAAM,UAAU,OAAO;EAC1B,OAAO,SAAS;EAChB,KAAK,OAAO,QAAA,OAA2B,GAAG;EAC1C,IAAI,OAAO,SAAS,GAAG;GAErB,OAAO,QAAS,OAAO,QAAQ,CAAC,kBAAmB;GACnD;EACF;EACA,IAAI;GAEF,IAAI,OAAO,UAAA,GAAiB,UAAU,MAAM;QACvC,kBAAkB,MAAM;EAC/B,SAAS,OAAO;GACd,YAAY,OAAO,MAAM;EAC3B;CACF;CACA,OAAO,MAAM;AACf;AAEA,SAAS,MAAM,QAAyB;CACtC,MAAM,CAAC,SAAS;CAChB,IAAI,OAAO,WAAW,GAAG,MAAM;CAC/B,MAAM,IAAI,eACR,QACU,oDACZ;AACF;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,QAAc;CAC5B,IAAI,GAAG,UA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O;EACd,SAAS;EACT,UAAU;CACZ,UAAU;EACR,GAAG,cAAc;CACnB;CACA,IAAI,QAAS,GAAG,eAAe,KAAK,CAAC,GAAG,YAAY,WAAW,GAC7D,IAAI;EACF,MAAM;CACR,SAAS,OAAO;EACd,IAAI,QACF,MAAM,IAAI,eACR,CAAC,SAAS,KAAK,GACL,wCACZ;EAEF,MAAM;CACR;CAEF,IAAI,QAAQ,MAAM;CAClB,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,MAAS,IAAgB;CACvC,OAAO,WAAW,IAAI,KAAK;AAC7B;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,UAAoB,IAAiB;CACnD,IAAI,GAAG,UAAU;EACf,KAAK,iBAAiB;EACtB,OAAQ,OAAO,KAAA,IAAY,KAAA,IAAY,GAAG;CAC5C;CACA,OAAO,WAAW,IAAI,IAAI;AAC5B"}
@@ -1,6 +1,5 @@
1
1
  import { Owner } from "./owner.js";
2
2
  import { Computation } from "./graph.js";
3
- //#region src/internal/state.d.ts
4
3
  /**
5
4
  * A hold for a value a transition builds while its reads wait for data (a `Show` branch built during a
6
5
  * transition): the reads that wait count against this hold, not against the Suspense boundary around
@@ -137,5 +136,4 @@ export interface Hooks {
137
136
  /** The engine side of `createTransitionHold`. */
138
137
  createHold(onSettled: () => void): TransitionHold;
139
138
  }
140
- //#endregion
141
139
  //# sourceMappingURL=state.d.ts.map
@@ -1,4 +1,4 @@
1
- //#region src/internal/state.ts
1
+ // src/internal/state.ts
2
2
  /**
3
3
  * The runtime registers (R-CODE-4): the only module-level mutable state of core besides
4
4
  * monotonic counters. Every write is paired with a `finally` restore (R-CODE-5).
@@ -22,7 +22,6 @@ function nextSequence() {
22
22
  counter += 1;
23
23
  return counter;
24
24
  }
25
- //#endregion
26
25
  export { nextSequence, rt };
27
26
 
28
27
  //# sourceMappingURL=state.js.map
@@ -1,4 +1,3 @@
1
- //#region src/internal/suspension.d.ts
2
1
  /**
3
2
  * The value a reader throws when a transition reads data that is still loading inside a Suspense
4
3
  * boundary that is showing content. The reader keeps its previous value (a memo keeps its value, an
@@ -39,5 +38,4 @@ export declare const SUSPENSION: {
39
38
  * @since 1.0.0
40
39
  */
41
40
  export declare function isSuspension(value: unknown): boolean;
42
- //#endregion
43
41
  //# sourceMappingURL=suspension.d.ts.map
@@ -1,4 +1,4 @@
1
- //#region src/internal/suspension.ts
1
+ // src/internal/suspension.ts
2
2
  /**
3
3
  * The value a reader throws when a transition reads data that is still loading inside a Suspense
4
4
  * boundary that is showing content. The reader keeps its previous value (a memo keeps its value, an
@@ -39,7 +39,6 @@ const SUSPENSION = /* @__PURE__ */ Object.freeze({ suspended: true });
39
39
  function isSuspension(value) {
40
40
  return value === SUSPENSION;
41
41
  }
42
- //#endregion
43
42
  export { SUSPENSION, isSuspension };
44
43
 
45
44
  //# sourceMappingURL=suspension.js.map
@@ -1,4 +1,3 @@
1
- //#region src/internal/types.d.ts
2
1
  /**
3
2
  * A function that releases what an owner or an effect set up: a timer, a subscription, a listener.
4
3
  * Register one with `onCleanup` (or `addCleanup` from `@shadow-js/core/extend`), or return one from
@@ -42,5 +41,4 @@ export interface Setter<T> {
42
41
  * @since 1.0.0
43
42
  */
44
43
  export type Equals<T> = false | ((prev: T, next: T) => boolean);
45
- //#endregion
46
44
  //# sourceMappingURL=types.d.ts.map
@@ -1,5 +1,4 @@
1
1
  import { Accessor } from "./internal/types.js";
2
- //#region src/list.d.ts
3
2
  /**
4
3
  * A list as the list primitives read it. `null`, `undefined` and `false` count as an empty list.
5
4
  * @since 1.0.0
@@ -89,5 +88,4 @@ export declare function mapArray<T, U>(list: ListSource<T>, map: (item: () => T,
89
88
  export declare function indexArray<T, U>(list: ListSource<T>, map: (item: () => T, index: number) => U, options?: {
90
89
  fallback?: () => U;
91
90
  }): Accessor<U[]>;
92
- //#endregion
93
91
  //# sourceMappingURL=list.d.ts.map
package/dist/dev/list.js CHANGED
@@ -5,20 +5,12 @@ import { createRoot, getOwner, onCleanup, runWithOwner, untrack } from "./owners
5
5
  import { disposeTree } from "./internal/dispose.js";
6
6
  import { createSignalNode, writeSignal } from "./extend/index.js";
7
7
  import { useMemo } from "./memo.js";
8
- //#region src/list.ts
8
+ // src/list.ts
9
9
  /**
10
10
  * One mapped row: its own root, its mapped value, and the signals behind `item()` and `index()`. The signals are created
11
11
  * by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.
12
12
  */
13
13
  var Row = class {
14
- /** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */
15
- key;
16
- /** False for a later copy of a key in a keyed list. Such a row is never reused. */
17
- first;
18
- /** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */
19
- item;
20
- /** Index last written to the row. */
21
- index;
22
14
  value = void 0;
23
15
  dispose = noop;
24
16
  /** Created by the first `item()` read; null until then. */
@@ -276,7 +268,6 @@ function throwFailures(failures) {
276
268
  if (failures.length === 1) throw failures[0];
277
269
  throw new AggregateError(failures, "Several errors were thrown while disposing list rows.");
278
270
  }
279
- //#endregion
280
271
  export { indexArray, mapArray };
281
272
 
282
273
  //# sourceMappingURL=list.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"list.js","names":[],"sources":["../../src/list.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n disposeOwner,\n Owner,\n readSignal,\n type SignalNode,\n warn,\n writeSignal,\n} from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { createRoot, getOwner, onCleanup, runWithOwner, untrack } from \"./ownership\";\n\n/**\n * A list as the list primitives read it. `null`, `undefined` and `false` count as an empty list.\n * @since 1.0.0\n */\nexport type ListSource<T> = () => readonly T[] | null | undefined | false;\n\n/**\n * One mapped row: its own root, its mapped value, and the signals behind `item()` and `index()`. The signals are created\n * by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.\n */\nclass Row<T, U> {\n /** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */\n readonly key: unknown;\n /** False for a later copy of a key in a keyed list. Such a row is never reused. */\n readonly first: boolean;\n /** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */\n item: T;\n /** Index last written to the row. */\n index: number;\n value: U = undefined as U;\n dispose: () => void = noop;\n /** Created by the first `item()` read; null until then. */\n private itemNode: SignalNode<T> | null = null;\n /** Created by the first `index()` read; null until then. */\n private indexNode: SignalNode<number> | null = null;\n\n constructor(key: unknown, first: boolean, item: T, index: number) {\n this.key = key;\n this.first = first;\n this.item = item;\n this.index = index;\n }\n\n readItem(): T {\n this.itemNode ??= createSignalNode(this.item, Object.is);\n return readSignal(this.itemNode);\n }\n\n readIndex(): number {\n this.indexNode ??= createSignalNode(this.index, Object.is);\n return readSignal(this.indexNode);\n }\n\n /** List bookkeeping, not a user write: allowed while the list memo computes. */\n setItem(next: T): void {\n this.item = next;\n if (this.itemNode !== null) writeSignal(this.itemNode, next, { allowInMemo: true });\n }\n\n setIndex(next: number): void {\n this.index = next;\n if (this.indexNode !== null) writeSignal(this.indexNode, next, { allowInMemo: true });\n }\n}\n\n/** The dispose of a row whose root has not been made yet. */\nfunction noop(): void {\n // Replaced by the root's own dispose before the row is used.\n}\n\n/** One incoming item of a list update, with the key it is matched by. */\ninterface Entry<T> {\n readonly item: T;\n readonly key: unknown;\n readonly first: boolean;\n}\n\n/** How incoming items are matched against the rows of the previous update. */\ninterface Keying<T> {\n /** Reuse key of the item at `position`. User code, so it runs untracked. */\n readonly keyOf: (item: T, position: number) => unknown;\n /** Keyed lists: only the first copy of a key may reuse a row. Otherwise copies pair up in order. */\n readonly distinct: boolean;\n}\n\n/** The row shown while the list is empty, in its own root. */\ninterface Fallback<U> {\n readonly value: U;\n readonly dispose: () => void;\n}\n\n/** A row chosen by one update, in output order. */\ninterface Staged<T, U> {\n readonly row: Row<T, U>;\n readonly item: T;\n readonly position: number;\n readonly fresh: boolean;\n}\n\n/**\n * Maps each item of a list to a row that lives as long as the item does. Rows whose key survives\n * an update keep their mapped value; new items get new rows; removed items have their rows disposed.\n *\n * Unkeyed: rows are matched by item reference, and `map` receives the item value. Equal primitives\n * pair up in order of occurrence. The returned accessor is lazy and memoized: rows are created and\n * disposed when it is read, so a list nobody reads keeps removed rows alive until the next read.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `index()` follows the row.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [users] = useSignal([{ name: \"Ada\" }, { name: \"Linus\" }]);\n * const names = mapArray(users, (user, index) => `${index() + 1}. ${user.name}`);\n * console.log(names()); // [\"1. Ada\", \"2. Linus\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T, index: () => number) => U,\n options?: { key?: undefined; fallback?: () => U },\n): Accessor<U[]>;\n/**\n * Keyed form: rows are matched by `key(item)`. `map` receives an accessor, so a new object under\n * the same key updates `item()` without re-creating the row. A duplicate key warns in dev and its\n * later copies get fresh rows on every update (dev warning `EACH_KEY_DUPLICATE`, once). Keys\n * compare like `Map` keys, so `NaN` matches `NaN`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `item()` and `index()` follow\n * the row.\n * @param options `key` identifies each item and runs untracked; `fallback` is shown while the list\n * is empty.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map`, `key` or a row cleanup threw;\n * several errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * const rows = mapArray(todos, (todo) => `#${todo().id} ${todo().title}`, {\n * key: (todo) => todo.id,\n * });\n * console.log(rows()); // [\"#1 Write docs\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: () => number) => U,\n options: { key: (item: T) => unknown; fallback?: () => U },\n): Accessor<U[]>;\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T | (() => T), index: () => number) => U,\n options?: { key?: ((item: T) => unknown) | undefined; fallback?: (() => U) | undefined },\n): Accessor<U[]> {\n const keyOf = options?.key;\n return listRows(\n list,\n keyOf === undefined\n ? { keyOf: (item: T) => item, distinct: false }\n : { keyOf: (item: T) => keyOf(item), distinct: true },\n (item, readItem, readIndex) => map(keyOf === undefined ? item : readItem, readIndex),\n options?.fallback,\n );\n}\n\n/**\n * Maps each position of a list to a row. Rows are created and removed only when the length\n * changes; the row at position `i` stays, and its `item()` accessor follows the value at `i`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per position, untracked, in the row's own root.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, indexArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [values] = useSignal([\"a\", \"b\"]);\n * const cells = indexArray(values, (value, index) => `${index}: ${value()}`);\n * console.log(cells()); // [\"0: a\", \"1: b\"]\n * });\n * @see mapArray\n * @since 1.0.0\n */\nexport function indexArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: number) => U,\n options?: { fallback?: () => U },\n): Accessor<U[]> {\n return listRows(\n list,\n { keyOf: (_item: T, position: number) => position, distinct: false },\n (_item, readItem, readIndex) => map(readItem, untrack(readIndex)),\n options?.fallback,\n );\n}\n\n/**\n * The shared engine. The memo tracks `list()` and reconciles the previous rows against the new\n * items; each row is a child of a private holder owner, so the memo's own recomputation never\n * disposes rows, and disposing the list's owner disposes the holder with every row in it.\n */\nfunction listRows<T, U>(\n list: ListSource<T>,\n keying: Keying<T>,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n fallback: (() => U) | undefined,\n): Accessor<U[]> {\n const holder = new Owner(getOwner());\n onCleanup(() => {\n disposeOwner(holder);\n });\n let rows: Row<T, U>[] = [];\n let emptyFallback: Fallback<U> | undefined;\n return useMemo<U[]>(\n () => {\n // Reading the list's contents is tracked, so a store array (proxy) updates the list when an\n // item is pushed, removed or replaced; user key functions then run untracked.\n const source = listItems(list());\n const items: readonly unknown[] = Array.isArray(source)\n ? Array.prototype.slice.call(source)\n : source;\n const entries = untrack(() => toEntries(items as readonly never[], keying));\n const reuse = matchRows(rows, entries);\n const created: Row<T, U>[] = [];\n const staged: Staged<T, U>[] = [];\n let nextFallback: Fallback<U> | undefined;\n try {\n entries.forEach((entry, position) => {\n const from = reuse[position] ?? -1;\n const kept = from === -1 ? undefined : rows[from];\n if (kept !== undefined) {\n staged.push({ row: kept, item: entry.item, position, fresh: false });\n return;\n }\n const row = openRow(holder, entry.key, entry.first, entry.item, position, build);\n created.push(row);\n staged.push({ row, item: entry.item, position, fresh: true });\n });\n if (entries.length === 0 && fallback !== undefined) {\n nextFallback = emptyFallback ?? openFallback(holder, fallback);\n }\n } catch (error) {\n // Nothing above touched the previous state, so only the rows made in this pass go.\n const failures: unknown[] = [];\n for (const row of created) disposeCollecting(row.dispose, failures);\n if (nextFallback !== undefined && nextFallback !== emptyFallback) {\n disposeCollecting(nextFallback.dispose, failures);\n }\n throw combineFailures(error, failures);\n }\n\n // Commit. Writes to retained rows come last, after every creation has succeeded.\n const failures: unknown[] = [];\n const previousRows = rows;\n const previousFallback = emptyFallback;\n rows = staged.map((stage) => stage.row);\n emptyFallback = nextFallback;\n const kept = new Uint8Array(previousRows.length);\n for (const from of reuse) {\n if (from !== -1) kept[from] = 1;\n }\n previousRows.forEach((row, from) => {\n if (kept[from] !== 1) disposeCollecting(row.dispose, failures);\n });\n if (previousFallback !== undefined && previousFallback !== nextFallback) {\n disposeCollecting(previousFallback.dispose, failures);\n }\n for (const stage of staged) {\n if (stage.fresh) continue;\n const row = stage.row;\n if (row.index !== stage.position) row.setIndex(stage.position);\n if (!Object.is(row.item, stage.item)) row.setItem(stage.item);\n }\n throwFailures(failures);\n if (nextFallback !== undefined) return [nextFallback.value];\n return rows.map((row) => row.value);\n },\n // The row callbacks build children (components, refs, directives): setup may write signals.\n { lazy: true, allowWrites: true },\n );\n}\n\n/** Treats `null`, `undefined` and `false` as an empty list. */\nfunction listItems<T>(value: readonly T[] | null | undefined | false): readonly T[] {\n return value === null || value === undefined || value === false ? [] : value;\n}\n\n/** Computes each item's reuse key. Keyed lists flag later copies of a key and warn once. */\nfunction toEntries<T>(items: readonly T[], keying: Keying<T>): Entry<T>[] {\n const entries: Entry<T>[] = [];\n const seen = new Set<unknown>();\n let duplicate = false;\n for (const [position, item] of items.entries()) {\n const key = keying.keyOf(item, position);\n let first = true;\n if (keying.distinct) {\n if (seen.has(key)) {\n first = false;\n duplicate = true;\n } else {\n seen.add(key);\n }\n }\n entries.push({ item, key, first });\n }\n if (duplicate) warn(\"EACH_KEY_DUPLICATE\");\n return entries;\n}\n\n/** Keys compare like `Map` keys: `NaN` matches `NaN`. */\nfunction sameKey(a: unknown, b: unknown): boolean {\n return a === b || (Number.isNaN(a) && Number.isNaN(b));\n}\n\nfunction canReuse<T, U>(row: Row<T, U> | undefined, entry: Entry<T> | undefined): boolean {\n return (\n row !== undefined &&\n entry !== undefined &&\n row.first &&\n entry.first &&\n sameKey(row.key, entry.key)\n );\n}\n\n/**\n * Pairs each new position with the old row it reuses; -1 means a fresh row is needed. The prefix\n * and suffix runs settle append, prepend, remove and swap at the ends in one step each. The middle\n * is matched through a Map from key to the chain of old positions with that key (earliest first),\n * so the whole pass is linear on average. Iterative throughout.\n */\nfunction matchRows<T, U>(old: readonly Row<T, U>[], next: readonly Entry<T>[]): Int32Array {\n const m = old.length;\n const n = next.length;\n const reuse = new Int32Array(n).fill(-1);\n let start = 0;\n while (start < m && start < n && canReuse(old[start], next[start])) {\n reuse[start] = start;\n start += 1;\n }\n let oldEnd = m - 1;\n let newEnd = n - 1;\n while (oldEnd >= start && newEnd >= start && canReuse(old[oldEnd], next[newEnd])) {\n reuse[newEnd] = oldEnd;\n oldEnd -= 1;\n newEnd -= 1;\n }\n if (start > oldEnd || start > newEnd) return reuse;\n\n const heads = new Map<unknown, number>();\n const chain = new Int32Array(m).fill(-1);\n for (let i = oldEnd; i >= start; i -= 1) {\n const row = old[i];\n if (row === undefined || !row.first) continue;\n chain[i] = heads.get(row.key) ?? -1;\n heads.set(row.key, i);\n }\n for (let j = start; j <= newEnd; j += 1) {\n const entry = next[j];\n if (entry === undefined || !entry.first) continue;\n const head = heads.get(entry.key);\n if (head === undefined || head === -1) continue;\n reuse[j] = head;\n heads.set(entry.key, chain[head] ?? -1);\n }\n return reuse;\n}\n\n/**\n * Creates one row in its own root under the holder. The row exists before `build` runs, so a read of `item()` or\n * `index()` during the build sees the final values. The root is detached from the memo on purpose.\n */\nfunction openRow<T, U>(\n holder: Owner,\n key: unknown,\n first: boolean,\n item: T,\n index: number,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n): Row<T, U> {\n const row = new Row<T, U>(key, first, item, index);\n const readItem = (): T => row.readItem();\n const readIndex = (): number => row.readIndex();\n runWithOwner(holder, () =>\n createRoot((dispose) => {\n row.dispose = dispose;\n row.value = untrack(() => build(item, readItem, readIndex));\n }),\n );\n return row;\n}\n\n/** Creates the empty-list row in its own root under the holder. */\nfunction openFallback<U>(holder: Owner, fallback: () => U): Fallback<U> {\n return runWithOwner(holder, () =>\n createRoot((dispose) => ({ value: untrack(fallback), dispose })),\n );\n}\n\n/** Disposes one row root. A throwing cleanup is collected so that the other rows still go. */\nfunction disposeCollecting(dispose: () => void, failures: unknown[]): void {\n try {\n dispose();\n } catch (error) {\n failures.push(error);\n }\n}\n\nfunction combineFailures(primary: unknown, failures: readonly unknown[]): unknown {\n if (failures.length === 0) return primary;\n return new AggregateError(\n [primary, ...failures],\n __DEV__ ? \"Several errors were thrown while mapping a list.\" : \"SHADOW_MAP_ERRORS\",\n );\n}\n\n/** Rethrows the one disposal failure, or all of them together. */\nfunction throwFailures(failures: readonly unknown[]): void {\n if (failures.length === 0) return;\n if (failures.length === 1) throw failures[0];\n throw new AggregateError(\n failures,\n __DEV__\n ? \"Several errors were thrown while disposing list rows.\"\n : \"SHADOW_LIST_DISPOSE_ERRORS\",\n );\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,IAAM,MAAN,MAAgB;;CAEd;;CAEA;;CAEA;;CAEA;CACA,QAAW,KAAA;CACX,UAAsB;;CAEtB,WAAyC;;CAEzC,YAA+C;CAE/C,YAAY,KAAc,OAAgB,MAAS,OAAe;EAChE,KAAK,MAAM;EACX,KAAK,QAAQ;EACb,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;CAEA,WAAc;EACZ,KAAK,aAAa,iBAAiB,KAAK,MAAM,OAAO,EAAE;EACvD,OAAO,WAAW,KAAK,QAAQ;CACjC;CAEA,YAAoB;EAClB,KAAK,cAAc,iBAAiB,KAAK,OAAO,OAAO,EAAE;EACzD,OAAO,WAAW,KAAK,SAAS;CAClC;;CAGA,QAAQ,MAAe;EACrB,KAAK,OAAO;EACZ,IAAI,KAAK,aAAa,MAAM,YAAY,KAAK,UAAU,MAAM,EAAE,aAAa,KAAK,CAAC;CACpF;CAEA,SAAS,MAAoB;EAC3B,KAAK,QAAQ;EACb,IAAI,KAAK,cAAc,MAAM,YAAY,KAAK,WAAW,MAAM,EAAE,aAAa,KAAK,CAAC;CACtF;AACF;;AAGA,SAAS,OAAa,CAEtB;AA6FA,SAAgB,SACd,MACA,KACA,SACe;CACf,MAAM,QAAQ,SAAS;CACvB,OAAO,SACL,MACA,UAAU,KAAA,IACN;EAAE,QAAQ,SAAY;EAAM,UAAU;CAAM,IAC5C;EAA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AAoC;CACzD,IAAI,SAAS,WAAW,GAAG;CAC3B,IAAI,SAAS,WAAW,GAAG,MAAM,SAAS;CAC1C,MAAM,IAAI,eACR,UAEI,uDAEN;AACF"}
1
+ {"version":3,"file":"list.js","names":[],"sources":["../../src/list.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n disposeOwner,\n Owner,\n readSignal,\n type SignalNode,\n warn,\n writeSignal,\n} from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { createRoot, getOwner, onCleanup, runWithOwner, untrack } from \"./ownership\";\n\n/**\n * A list as the list primitives read it. `null`, `undefined` and `false` count as an empty list.\n * @since 1.0.0\n */\nexport type ListSource<T> = () => readonly T[] | null | undefined | false;\n\n/**\n * One mapped row: its own root, its mapped value, and the signals behind `item()` and `index()`. The signals are created\n * by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.\n */\nclass Row<T, U> {\n /** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */\n declare readonly key: unknown;\n /** False for a later copy of a key in a keyed list. Such a row is never reused. */\n declare readonly first: boolean;\n /** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */\n declare item: T;\n /** Index last written to the row. */\n declare index: number;\n value: U = undefined as U;\n dispose: () => void = noop;\n /** Created by the first `item()` read; null until then. */\n private itemNode: SignalNode<T> | null = null;\n /** Created by the first `index()` read; null until then. */\n private indexNode: SignalNode<number> | null = null;\n\n constructor(key: unknown, first: boolean, item: T, index: number) {\n this.key = key;\n this.first = first;\n this.item = item;\n this.index = index;\n }\n\n readItem(): T {\n this.itemNode ??= createSignalNode(this.item, Object.is);\n return readSignal(this.itemNode);\n }\n\n readIndex(): number {\n this.indexNode ??= createSignalNode(this.index, Object.is);\n return readSignal(this.indexNode);\n }\n\n /** List bookkeeping, not a user write: allowed while the list memo computes. */\n setItem(next: T): void {\n this.item = next;\n if (this.itemNode !== null) writeSignal(this.itemNode, next, { allowInMemo: true });\n }\n\n setIndex(next: number): void {\n this.index = next;\n if (this.indexNode !== null) writeSignal(this.indexNode, next, { allowInMemo: true });\n }\n}\n\n/** The dispose of a row whose root has not been made yet. */\nfunction noop(): void {\n // Replaced by the root's own dispose before the row is used.\n}\n\n/** One incoming item of a list update, with the key it is matched by. */\ninterface Entry<T> {\n readonly item: T;\n readonly key: unknown;\n readonly first: boolean;\n}\n\n/** How incoming items are matched against the rows of the previous update. */\ninterface Keying<T> {\n /** Reuse key of the item at `position`. User code, so it runs untracked. */\n readonly keyOf: (item: T, position: number) => unknown;\n /** Keyed lists: only the first copy of a key may reuse a row. Otherwise copies pair up in order. */\n readonly distinct: boolean;\n}\n\n/** The row shown while the list is empty, in its own root. */\ninterface Fallback<U> {\n readonly value: U;\n readonly dispose: () => void;\n}\n\n/** A row chosen by one update, in output order. */\ninterface Staged<T, U> {\n readonly row: Row<T, U>;\n readonly item: T;\n readonly position: number;\n readonly fresh: boolean;\n}\n\n/**\n * Maps each item of a list to a row that lives as long as the item does. Rows whose key survives\n * an update keep their mapped value; new items get new rows; removed items have their rows disposed.\n *\n * Unkeyed: rows are matched by item reference, and `map` receives the item value. Equal primitives\n * pair up in order of occurrence. The returned accessor is lazy and memoized: rows are created and\n * disposed when it is read, so a list nobody reads keeps removed rows alive until the next read.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `index()` follows the row.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [users] = useSignal([{ name: \"Ada\" }, { name: \"Linus\" }]);\n * const names = mapArray(users, (user, index) => `${index() + 1}. ${user.name}`);\n * console.log(names()); // [\"1. Ada\", \"2. Linus\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T, index: () => number) => U,\n options?: { key?: undefined; fallback?: () => U },\n): Accessor<U[]>;\n/**\n * Keyed form: rows are matched by `key(item)`. `map` receives an accessor, so a new object under\n * the same key updates `item()` without re-creating the row. A duplicate key warns in dev and its\n * later copies get fresh rows on every update (dev warning `EACH_KEY_DUPLICATE`, once). Keys\n * compare like `Map` keys, so `NaN` matches `NaN`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `item()` and `index()` follow\n * the row.\n * @param options `key` identifies each item and runs untracked; `fallback` is shown while the list\n * is empty.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map`, `key` or a row cleanup threw;\n * several errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * const rows = mapArray(todos, (todo) => `#${todo().id} ${todo().title}`, {\n * key: (todo) => todo.id,\n * });\n * console.log(rows()); // [\"#1 Write docs\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: () => number) => U,\n options: { key: (item: T) => unknown; fallback?: () => U },\n): Accessor<U[]>;\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T | (() => T), index: () => number) => U,\n options?: { key?: ((item: T) => unknown) | undefined; fallback?: (() => U) | undefined },\n): Accessor<U[]> {\n const keyOf = options?.key;\n return listRows(\n list,\n keyOf === undefined\n ? { keyOf: (item: T) => item, distinct: false }\n : { keyOf: (item: T) => keyOf(item), distinct: true },\n (item, readItem, readIndex) => map(keyOf === undefined ? item : readItem, readIndex),\n options?.fallback,\n );\n}\n\n/**\n * Maps each position of a list to a row. Rows are created and removed only when the length\n * changes; the row at position `i` stays, and its `item()` accessor follows the value at `i`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per position, untracked, in the row's own root.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, indexArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [values] = useSignal([\"a\", \"b\"]);\n * const cells = indexArray(values, (value, index) => `${index}: ${value()}`);\n * console.log(cells()); // [\"0: a\", \"1: b\"]\n * });\n * @see mapArray\n * @since 1.0.0\n */\nexport function indexArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: number) => U,\n options?: { fallback?: () => U },\n): Accessor<U[]> {\n return listRows(\n list,\n { keyOf: (_item: T, position: number) => position, distinct: false },\n (_item, readItem, readIndex) => map(readItem, untrack(readIndex)),\n options?.fallback,\n );\n}\n\n/**\n * The shared engine. The memo tracks `list()` and reconciles the previous rows against the new\n * items; each row is a child of a private holder owner, so the memo's own recomputation never\n * disposes rows, and disposing the list's owner disposes the holder with every row in it.\n */\nfunction listRows<T, U>(\n list: ListSource<T>,\n keying: Keying<T>,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n fallback: (() => U) | undefined,\n): Accessor<U[]> {\n const holder = new Owner(getOwner());\n onCleanup(() => {\n disposeOwner(holder);\n });\n let rows: Row<T, U>[] = [];\n let emptyFallback: Fallback<U> | undefined;\n return useMemo<U[]>(\n () => {\n // Reading the list's contents is tracked, so a store array (proxy) updates the list when an\n // item is pushed, removed or replaced; user key functions then run untracked.\n const source = listItems(list());\n const items: readonly unknown[] = Array.isArray(source)\n ? Array.prototype.slice.call(source)\n : source;\n const entries = untrack(() => toEntries(items as readonly never[], keying));\n const reuse = matchRows(rows, entries);\n const created: Row<T, U>[] = [];\n const staged: Staged<T, U>[] = [];\n let nextFallback: Fallback<U> | undefined;\n try {\n entries.forEach((entry, position) => {\n const from = reuse[position] ?? -1;\n const kept = from === -1 ? undefined : rows[from];\n if (kept !== undefined) {\n staged.push({ row: kept, item: entry.item, position, fresh: false });\n return;\n }\n const row = openRow(holder, entry.key, entry.first, entry.item, position, build);\n created.push(row);\n staged.push({ row, item: entry.item, position, fresh: true });\n });\n if (entries.length === 0 && fallback !== undefined) {\n nextFallback = emptyFallback ?? openFallback(holder, fallback);\n }\n } catch (error) {\n // Nothing above touched the previous state, so only the rows made in this pass go.\n const failures: unknown[] = [];\n for (const row of created) disposeCollecting(row.dispose, failures);\n if (nextFallback !== undefined && nextFallback !== emptyFallback) {\n disposeCollecting(nextFallback.dispose, failures);\n }\n throw combineFailures(error, failures);\n }\n\n // Commit. Writes to retained rows come last, after every creation has succeeded.\n const failures: unknown[] = [];\n const previousRows = rows;\n const previousFallback = emptyFallback;\n rows = staged.map((stage) => stage.row);\n emptyFallback = nextFallback;\n const kept = new Uint8Array(previousRows.length);\n for (const from of reuse) {\n if (from !== -1) kept[from] = 1;\n }\n previousRows.forEach((row, from) => {\n if (kept[from] !== 1) disposeCollecting(row.dispose, failures);\n });\n if (previousFallback !== undefined && previousFallback !== nextFallback) {\n disposeCollecting(previousFallback.dispose, failures);\n }\n for (const stage of staged) {\n if (stage.fresh) continue;\n const row = stage.row;\n if (row.index !== stage.position) row.setIndex(stage.position);\n if (!Object.is(row.item, stage.item)) row.setItem(stage.item);\n }\n throwFailures(failures);\n if (nextFallback !== undefined) return [nextFallback.value];\n return rows.map((row) => row.value);\n },\n // The row callbacks build children (components, refs, directives): setup may write signals.\n { lazy: true, allowWrites: true },\n );\n}\n\n/** Treats `null`, `undefined` and `false` as an empty list. */\nfunction listItems<T>(value: readonly T[] | null | undefined | false): readonly T[] {\n return value === null || value === undefined || value === false ? [] : value;\n}\n\n/** Computes each item's reuse key. Keyed lists flag later copies of a key and warn once. */\nfunction toEntries<T>(items: readonly T[], keying: Keying<T>): Entry<T>[] {\n const entries: Entry<T>[] = [];\n const seen = new Set<unknown>();\n let duplicate = false;\n for (const [position, item] of items.entries()) {\n const key = keying.keyOf(item, position);\n let first = true;\n if (keying.distinct) {\n if (seen.has(key)) {\n first = false;\n duplicate = true;\n } else {\n seen.add(key);\n }\n }\n entries.push({ item, key, first });\n }\n if (duplicate) warn(\"EACH_KEY_DUPLICATE\");\n return entries;\n}\n\n/** Keys compare like `Map` keys: `NaN` matches `NaN`. */\nfunction sameKey(a: unknown, b: unknown): boolean {\n return a === b || (Number.isNaN(a) && Number.isNaN(b));\n}\n\nfunction canReuse<T, U>(row: Row<T, U> | undefined, entry: Entry<T> | undefined): boolean {\n return (\n row !== undefined &&\n entry !== undefined &&\n row.first &&\n entry.first &&\n sameKey(row.key, entry.key)\n );\n}\n\n/**\n * Pairs each new position with the old row it reuses; -1 means a fresh row is needed. The prefix\n * and suffix runs settle append, prepend, remove and swap at the ends in one step each. The middle\n * is matched through a Map from key to the chain of old positions with that key (earliest first),\n * so the whole pass is linear on average. Iterative throughout.\n */\nfunction matchRows<T, U>(old: readonly Row<T, U>[], next: readonly Entry<T>[]): Int32Array {\n const m = old.length;\n const n = next.length;\n const reuse = new Int32Array(n).fill(-1);\n let start = 0;\n while (start < m && start < n && canReuse(old[start], next[start])) {\n reuse[start] = start;\n start += 1;\n }\n let oldEnd = m - 1;\n let newEnd = n - 1;\n while (oldEnd >= start && newEnd >= start && canReuse(old[oldEnd], next[newEnd])) {\n reuse[newEnd] = oldEnd;\n oldEnd -= 1;\n newEnd -= 1;\n }\n if (start > oldEnd || start > newEnd) return reuse;\n\n const heads = new Map<unknown, number>();\n const chain = new Int32Array(m).fill(-1);\n for (let i = oldEnd; i >= start; i -= 1) {\n const row = old[i];\n if (row === undefined || !row.first) continue;\n chain[i] = heads.get(row.key) ?? -1;\n heads.set(row.key, i);\n }\n for (let j = start; j <= newEnd; j += 1) {\n const entry = next[j];\n if (entry === undefined || !entry.first) continue;\n const head = heads.get(entry.key);\n if (head === undefined || head === -1) continue;\n reuse[j] = head;\n heads.set(entry.key, chain[head] ?? -1);\n }\n return reuse;\n}\n\n/**\n * Creates one row in its own root under the holder. The row exists before `build` runs, so a read of `item()` or\n * `index()` during the build sees the final values. The root is detached from the memo on purpose.\n */\nfunction openRow<T, U>(\n holder: Owner,\n key: unknown,\n first: boolean,\n item: T,\n index: number,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n): Row<T, U> {\n const row = new Row<T, U>(key, first, item, index);\n const readItem = (): T => row.readItem();\n const readIndex = (): number => row.readIndex();\n runWithOwner(holder, () =>\n createRoot((dispose) => {\n row.dispose = dispose;\n row.value = untrack(() => build(item, readItem, readIndex));\n }),\n );\n return row;\n}\n\n/** Creates the empty-list row in its own root under the holder. */\nfunction openFallback<U>(holder: Owner, fallback: () => U): Fallback<U> {\n return runWithOwner(holder, () =>\n createRoot((dispose) => ({ value: untrack(fallback), dispose })),\n );\n}\n\n/** Disposes one row root. A throwing cleanup is collected so that the other rows still go. */\nfunction disposeCollecting(dispose: () => void, failures: unknown[]): void {\n try {\n dispose();\n } catch (error) {\n failures.push(error);\n }\n}\n\nfunction combineFailures(primary: unknown, failures: readonly unknown[]): unknown {\n if (failures.length === 0) return primary;\n return new AggregateError(\n [primary, ...failures],\n __DEV__ ? \"Several errors were thrown while mapping a list.\" : \"SHADOW_MAP_ERRORS\",\n );\n}\n\n/** Rethrows the one disposal failure, or all of them together. */\nfunction throwFailures(failures: readonly unknown[]): void {\n if (failures.length === 0) return;\n if (failures.length === 1) throw failures[0];\n throw new AggregateError(\n failures,\n __DEV__\n ? \"Several errors were thrown while disposing list rows.\"\n : \"SHADOW_LIST_DISPOSE_ERRORS\",\n );\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,IAAM,MAAN,MAAgB;CASd,QAAW,KAAA;CACX,UAAsB;;CAEtB,WAAyC;;CAEzC,YAA+C;CAE/C,YAAY,KAAc,OAAgB,MAAS,OAAe;EAChE,KAAK,MAAM;EACX,KAAK,QAAQ;EACb,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;CAEA,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K,OAAO,MAAM,KAAK;CACjD,MAAM,iBAAoB,IAAI,SAAS;CACvC,MAAM,kBAA0B,IAAI,UAAU;CAC9C,aAAa,cACX,YAAY,YAAY;EACtB,IAAI,UAAU;EACd,IAAI,QAAQ,cAAc,MAAM,MAAM,UAAU,SAAS,CAAC;CAC5D,CAAC,CACH;CACA,OAAO;AACT;;AAGA,SAAS,aAAgB,QAAe,UAAgC;CACtE,OAAO,aAAa,cAClB,YAAY,aAAa;EAAE,OAAO,QAAQ,QAAQ;EAAG;CAAQ,EAAE,CACjE;AACF;;AAGA,SAAS,kBAAkB,SAAqB,UAA2B;CACzE,IAAI;EACF,QAAQ;CACV,SAAS,OAAO;EACd,SAAS,KAAK,KAAK;CACrB;AACF;AAEA,SAAS,gBAAgB,SAAkB,UAAuC;CAChF,IAAI,SAAS,WAAW,GAAG,OAAO;CAClC,OAAO,IAAI,eACT,CAAC,SAAS,GAAG,QAAQ,GACX,kDACZ;AACF;;AAGA,SAAS,cAAc,UAAoC;CACzD,IAAI,SAAS,WAAW,GAAG;CAC3B,IAAI,SAAS,WAAW,GAAG,MAAM,SAAS;CAC1C,MAAM,IAAI,eACR,UAEI,uDAEN;AACF"}
@@ -1,5 +1,4 @@
1
1
  import { Accessor, Equals } from "./internal/types.js";
2
- //#region src/memo.d.ts
3
2
  /**
4
3
  * Options of {@link useMemo}.
5
4
  * @since 1.0.0
@@ -7,7 +6,8 @@ import { Accessor, Equals } from "./internal/types.js";
7
6
  export interface MemoOptions<T> {
8
7
  /**
9
8
  * Decides whether a recomputation changed the value: readers are notified only when it returns
10
- * `false`. `false` always propagates.
9
+ * `false`. `false` always propagates. It runs untracked: a signal it reads is not a dependency of
10
+ * the memo or of the reader that pulled it.
11
11
  * @default Object.is
12
12
  */
13
13
  equals?: Equals<T>;
@@ -56,5 +56,4 @@ export interface MemoOptions<T> {
56
56
  * @since 1.0.0
57
57
  */
58
58
  export declare function useMemo<T>(fn: (previous: T | undefined) => T, options?: MemoOptions<T>): Accessor<T>;
59
- //#endregion
60
59
  //# sourceMappingURL=memo.d.ts.map
package/dist/dev/memo.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createComputation, readComputation } from "./extend/index.js";
2
- //#region src/memo.ts
2
+ // src/memo.ts
3
3
  /**
4
4
  * Creates a cached derivation that recomputes only when a dependency actually changed.
5
5
  * Dependencies are discovered on every run, so branches that are not taken are not tracked.
@@ -28,14 +28,13 @@ function useMemo(fn, options) {
28
28
  const node = createComputation({
29
29
  kind: "memo",
30
30
  fn,
31
- equals: options?.equals === void 0 ? Object.is : options.equals,
32
- lazy: options?.lazy === true,
33
- allowWrites: options?.allowWrites === true,
34
- ...options?.name === void 0 ? {} : { name: options.name }
31
+ equals: options?.equals,
32
+ lazy: options?.lazy,
33
+ allowWrites: options?.allowWrites,
34
+ name: options?.name
35
35
  });
36
36
  return () => readComputation(node);
37
37
  }
38
- //#endregion
39
38
  export { useMemo };
40
39
 
41
40
  //# sourceMappingURL=memo.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"memo.js","names":[],"sources":["../../src/memo.ts"],"sourcesContent":["import { type Accessor, createComputation, type Equals, readComputation } from \"./extend\";\n\n/**\n * Options of {@link useMemo}.\n * @since 1.0.0\n */\nexport interface MemoOptions<T> {\n /**\n * Decides whether a recomputation changed the value: readers are notified only when it returns\n * `false`. `false` always propagates.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Skip the initial computation until the first read. Without it the memo computes once when it\n * is created.\n * @default false\n */\n lazy?: boolean;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the memo is unnamed)\n */\n name?: string;\n /**\n * Turn off the development check that rejects signal writes while this memo computes. Set it for\n * a memo that builds children (components, `ref` callbacks, directives), where the code that runs\n * is setup and may write a counter or a registry; the control-flow components do. A memo that\n * derives a value must leave it off.\n * @default false\n */\n allowWrites?: boolean;\n}\n\n/**\n * Creates a cached derivation that recomputes only when a dependency actually changed.\n * Dependencies are discovered on every run, so branches that are not taken are not tracked.\n * A memo that throws inside an error boundary (an ancestor `onError` or `catchError`) reports the\n * error there and keeps its previous value; without a boundary it stores the error and rethrows it\n * to every reader.\n *\n * @param fn Computation; receives the previous value (`undefined` on the first run).\n * @param options Equality override, `lazy`, `allowWrites` and a devtools name. Undefined uses the\n * defaults.\n * @returns An accessor returning the current, always fresh value.\n * @throws ShadowError `CYCLE_DETECTED` from the accessor when the memo reads itself while it\n * computes. Outside an error boundary the accessor also rethrows the error `fn` threw on its last\n * run.\n * @example\n * import { useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(2);\n * const doubled = useMemo(() => count() * 2);\n * setCount(5);\n * console.log(doubled()); // 10\n * @see useSignal\n * @since 1.0.0\n */\nexport function useMemo<T>(\n fn: (previous: T | undefined) => T,\n options?: MemoOptions<T>,\n): Accessor<T> {\n const node = createComputation({\n kind: \"memo\",\n fn: fn as (previous: never) => unknown,\n equals: (options?.equals === undefined ? Object.is : options.equals) as Equals<unknown>,\n lazy: options?.lazy === true,\n allowWrites: options?.allowWrites === true,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n return () => readComputation<T>(node);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,QACd,IACA,SACa;CACb,MAAM,OAAO,kBAAkB;EAC7B,MAAM;EACF;EACJ,QAAS,SAAS,WAAW,KAAA,IAAY,OAAO,KAAK,QAAQ;EAC7D,MAAM,SAAS,SAAS;EACxB,aAAa,SAAS,gBAAgB;EACtC,GAAI,SAAS,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,KAAK;CAC9D,CAAC;CACD,aAAa,gBAAmB,IAAI;AACtC"}
1
+ {"version":3,"file":"memo.js","names":[],"sources":["../../src/memo.ts"],"sourcesContent":["import { type Accessor, createComputation, type Equals, readComputation } from \"./extend\";\n\n/**\n * Options of {@link useMemo}.\n * @since 1.0.0\n */\nexport interface MemoOptions<T> {\n /**\n * Decides whether a recomputation changed the value: readers are notified only when it returns\n * `false`. `false` always propagates. It runs untracked: a signal it reads is not a dependency of\n * the memo or of the reader that pulled it.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Skip the initial computation until the first read. Without it the memo computes once when it\n * is created.\n * @default false\n */\n lazy?: boolean;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the memo is unnamed)\n */\n name?: string;\n /**\n * Turn off the development check that rejects signal writes while this memo computes. Set it for\n * a memo that builds children (components, `ref` callbacks, directives), where the code that runs\n * is setup and may write a counter or a registry; the control-flow components do. A memo that\n * derives a value must leave it off.\n * @default false\n */\n allowWrites?: boolean;\n}\n\n/**\n * Creates a cached derivation that recomputes only when a dependency actually changed.\n * Dependencies are discovered on every run, so branches that are not taken are not tracked.\n * A memo that throws inside an error boundary (an ancestor `onError` or `catchError`) reports the\n * error there and keeps its previous value; without a boundary it stores the error and rethrows it\n * to every reader.\n *\n * @param fn Computation; receives the previous value (`undefined` on the first run).\n * @param options Equality override, `lazy`, `allowWrites` and a devtools name. Undefined uses the\n * defaults.\n * @returns An accessor returning the current, always fresh value.\n * @throws ShadowError `CYCLE_DETECTED` from the accessor when the memo reads itself while it\n * computes. Outside an error boundary the accessor also rethrows the error `fn` threw on its last\n * run.\n * @example\n * import { useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(2);\n * const doubled = useMemo(() => count() * 2);\n * setCount(5);\n * console.log(doubled()); // 10\n * @see useSignal\n * @since 1.0.0\n */\nexport function useMemo<T>(\n fn: (previous: T | undefined) => T,\n options?: MemoOptions<T>,\n): Accessor<T> {\n const node = createComputation({\n kind: \"memo\",\n fn: fn as (previous: never) => unknown,\n equals: options?.equals as Equals<unknown> | undefined,\n lazy: options?.lazy,\n allowWrites: options?.allowWrites,\n name: options?.name,\n });\n return () => readComputation<T>(node);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAgB,QACd,IACA,SACa;CACb,MAAM,OAAO,kBAAkB;EAC7B,MAAM;EACF;EACJ,QAAQ,SAAS;EACjB,MAAM,SAAS;EACf,aAAa,SAAS;EACtB,MAAM,SAAS;CACjB,CAAC;CACD,aAAa,gBAAmB,IAAI;AACtC"}
@@ -1,5 +1,4 @@
1
1
  import { Accessor } from "./internal/types.js";
2
- //#region src/optimistic.d.ts
3
2
  /**
4
3
  * Optimistic state: shows `reducer` applied over the real value for every action whose
5
4
  * `settled` promise is still pending. When the promise settles (either way) the action is
@@ -22,5 +21,4 @@ import { Accessor } from "./internal/types.js";
22
21
  * @since 1.0.0
23
22
  */
24
23
  export declare function useOptimistic<T, A>(source: Accessor<T>, reducer: (state: T, action: A) => T): [Accessor<T>, (action: A, settled: Promise<unknown>) => void];
25
- //#endregion
26
24
  //# sourceMappingURL=optimistic.d.ts.map
@@ -1,6 +1,6 @@
1
1
  import { useSignal } from "./signal.js";
2
2
  import { useMemo } from "./memo.js";
3
- //#region src/optimistic.ts
3
+ // src/optimistic.ts
4
4
  /**
5
5
  * Optimistic state: shows `reducer` applied over the real value for every action whose
6
6
  * `settled` promise is still pending. When the promise settles (either way) the action is
@@ -39,7 +39,6 @@ function useOptimistic(source, reducer) {
39
39
  };
40
40
  return [state, apply];
41
41
  }
42
- //#endregion
43
42
  export { useOptimistic };
44
43
 
45
44
  //# sourceMappingURL=optimistic.js.map
@@ -1,6 +1,5 @@
1
1
  import { Cleanup, ErrorHandler } from "./internal/types.js";
2
2
  import { Owner } from "./internal/owner.js";
3
- //#region src/ownership.d.ts
4
3
  /**
5
4
  * Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an
6
5
  * effect or a memo to read a value without re-running when that value changes. The current owner
@@ -39,14 +38,16 @@ export interface RootOptions {
39
38
  * Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is
40
39
  * disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use
41
40
  * it for code that runs outside a component, such as an app entry point, a test or a module that
42
- * owns long-lived effects.
41
+ * owns long-lived effects. Development builds also use the root to find a second copy of core: a root
42
+ * created while a root of another copy is alive warns `DUPLICATE_CORE` once.
43
43
  *
44
44
  * @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.
45
45
  * @param options `detached` keeps the root out of the current owner. Undefined uses the default
46
46
  * (attached).
47
47
  * @returns Whatever `fn` returns.
48
48
  * @throws Rethrows any error thrown by `fn`, after the root and everything created in it are
49
- * disposed.
49
+ * disposed. When a cleanup of the root throws as well, both errors are thrown together as an
50
+ * `AggregateError` (the body's first), so the body's error is never replaced.
50
51
  * @example
51
52
  * import { createRoot, useEffect, useSignal } from "@shadow-js/core";
52
53
  *
@@ -199,6 +200,5 @@ export declare function catchError<T>(fn: () => T, handler: ErrorHandler): T | u
199
200
  * @since 1.0.0
200
201
  */
201
202
  export declare function useId(): string;
202
- //#endregion
203
203
  export type { Owner };
204
204
  //# sourceMappingURL=ownership.d.ts.map