@shadow-js/core 1.0.1 → 1.0.3

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 (191) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/dev/action.js +11 -7
  3. package/dist/dev/action.js.map +1 -1
  4. package/dist/dev/cache.d.ts +2 -1
  5. package/dist/dev/cache.js +5 -3
  6. package/dist/dev/cache.js.map +1 -1
  7. package/dist/dev/effect.js +17 -33
  8. package/dist/dev/effect.js.map +1 -1
  9. package/dist/dev/extend/index.d.ts +7 -6
  10. package/dist/dev/extend/index.js +7 -7
  11. package/dist/dev/extend/index.js.map +1 -1
  12. package/dist/dev/external-store.js +8 -3
  13. package/dist/dev/external-store.js.map +1 -1
  14. package/dist/dev/internal/concurrency.js +56 -30
  15. package/dist/dev/internal/concurrency.js.map +1 -1
  16. package/dist/dev/internal/diagnostics.js +0 -2
  17. package/dist/dev/internal/diagnostics.js.map +1 -1
  18. package/dist/dev/internal/dispose.js +1 -1
  19. package/dist/dev/internal/dispose.js.map +1 -1
  20. package/dist/dev/internal/flags.js +1 -3
  21. package/dist/dev/internal/flags.js.map +1 -1
  22. package/dist/dev/internal/graph.d.ts +1 -2
  23. package/dist/dev/internal/graph.js +47 -69
  24. package/dist/dev/internal/graph.js.map +1 -1
  25. package/dist/dev/internal/owner.d.ts +9 -6
  26. package/dist/dev/internal/owner.js +22 -30
  27. package/dist/dev/internal/owner.js.map +1 -1
  28. package/dist/dev/internal/scheduler.js +44 -73
  29. package/dist/dev/internal/scheduler.js.map +1 -1
  30. package/dist/dev/list.js +4 -12
  31. package/dist/dev/list.js.map +1 -1
  32. package/dist/dev/memo.d.ts +2 -1
  33. package/dist/dev/memo.js +4 -4
  34. package/dist/dev/memo.js.map +1 -1
  35. package/dist/dev/ownership.d.ts +4 -2
  36. package/dist/dev/ownership.js +59 -3
  37. package/dist/dev/ownership.js.map +1 -1
  38. package/dist/dev/props.js +18 -11
  39. package/dist/dev/props.js.map +1 -1
  40. package/dist/dev/reaction.d.ts +1 -1
  41. package/dist/dev/reaction.js +5 -1
  42. package/dist/dev/reaction.js.map +1 -1
  43. package/dist/dev/reducer.js +1 -1
  44. package/dist/dev/reducer.js.map +1 -1
  45. package/dist/dev/resource.js +24 -15
  46. package/dist/dev/resource.js.map +1 -1
  47. package/dist/dev/selector.js +1 -5
  48. package/dist/dev/selector.js.map +1 -1
  49. package/dist/dev/signal.d.ts +3 -2
  50. package/dist/dev/signal.js +3 -3
  51. package/dist/dev/signal.js.map +1 -1
  52. package/dist/dev/store/nodes.js +10 -4
  53. package/dist/dev/store/nodes.js.map +1 -1
  54. package/dist/dev/store/use-store.d.ts +5 -0
  55. package/dist/dev/store/use-store.js.map +1 -1
  56. package/dist/dev/transitions.js +1 -1
  57. package/dist/dev/transitions.js.map +1 -1
  58. package/dist/prod/action.js +1 -1
  59. package/dist/prod/action.js.map +1 -1
  60. package/dist/prod/cache.js +1 -1
  61. package/dist/prod/cache.js.map +1 -1
  62. package/dist/prod/effect.js +1 -1
  63. package/dist/prod/effect.js.map +1 -1
  64. package/dist/prod/extend/index.js +1 -1
  65. package/dist/prod/extend/index.js.map +1 -1
  66. package/dist/prod/external-store.js +1 -1
  67. package/dist/prod/external-store.js.map +1 -1
  68. package/dist/prod/internal/concurrency.js +1 -1
  69. package/dist/prod/internal/concurrency.js.map +1 -1
  70. package/dist/prod/internal/diagnostics.js +1 -1
  71. package/dist/prod/internal/diagnostics.js.map +1 -1
  72. package/dist/prod/internal/dispose.js +1 -1
  73. package/dist/prod/internal/dispose.js.map +1 -1
  74. package/dist/prod/internal/flags.js +1 -1
  75. package/dist/prod/internal/flags.js.map +1 -1
  76. package/dist/prod/internal/graph.js +1 -1
  77. package/dist/prod/internal/graph.js.map +1 -1
  78. package/dist/prod/internal/owner.js +1 -1
  79. package/dist/prod/internal/owner.js.map +1 -1
  80. package/dist/prod/internal/scheduler.js +1 -1
  81. package/dist/prod/internal/scheduler.js.map +1 -1
  82. package/dist/prod/list.js +1 -1
  83. package/dist/prod/list.js.map +1 -1
  84. package/dist/prod/memo.js +1 -1
  85. package/dist/prod/memo.js.map +1 -1
  86. package/dist/prod/ownership.js +1 -1
  87. package/dist/prod/ownership.js.map +1 -1
  88. package/dist/prod/props.js.map +1 -1
  89. package/dist/prod/reaction.js +1 -1
  90. package/dist/prod/reaction.js.map +1 -1
  91. package/dist/prod/reducer.js +1 -1
  92. package/dist/prod/reducer.js.map +1 -1
  93. package/dist/prod/resource.js +1 -1
  94. package/dist/prod/resource.js.map +1 -1
  95. package/dist/prod/selector.js +1 -1
  96. package/dist/prod/selector.js.map +1 -1
  97. package/dist/prod/signal.js +1 -1
  98. package/dist/prod/signal.js.map +1 -1
  99. package/dist/prod/store/nodes.js +1 -1
  100. package/dist/prod/store/nodes.js.map +1 -1
  101. package/dist/prod/store/use-store.js.map +1 -1
  102. package/dist/prod/transitions.js +1 -1
  103. package/dist/prod/transitions.js.map +1 -1
  104. package/dist/server/action.js +1 -1
  105. package/dist/server/action.js.map +1 -1
  106. package/dist/server/cache.js +1 -1
  107. package/dist/server/cache.js.map +1 -1
  108. package/dist/server/effect.js.map +1 -1
  109. package/dist/server/extend/index.js +1 -1
  110. package/dist/server/extend/index.js.map +1 -1
  111. package/dist/server/external-store.js.map +1 -1
  112. package/dist/server/internal/concurrency.js +1 -1
  113. package/dist/server/internal/concurrency.js.map +1 -1
  114. package/dist/server/internal/diagnostics.js +1 -1
  115. package/dist/server/internal/diagnostics.js.map +1 -1
  116. package/dist/server/internal/dispose.js +1 -1
  117. package/dist/server/internal/dispose.js.map +1 -1
  118. package/dist/server/internal/flags.js +1 -1
  119. package/dist/server/internal/flags.js.map +1 -1
  120. package/dist/server/internal/graph.js +1 -1
  121. package/dist/server/internal/graph.js.map +1 -1
  122. package/dist/server/internal/owner.js +1 -1
  123. package/dist/server/internal/owner.js.map +1 -1
  124. package/dist/server/internal/scheduler.js +1 -1
  125. package/dist/server/internal/scheduler.js.map +1 -1
  126. package/dist/server/list.js +1 -1
  127. package/dist/server/list.js.map +1 -1
  128. package/dist/server/memo.js +1 -1
  129. package/dist/server/memo.js.map +1 -1
  130. package/dist/server/ownership.js +1 -1
  131. package/dist/server/ownership.js.map +1 -1
  132. package/dist/server/props.js.map +1 -1
  133. package/dist/server/reaction.js +1 -1
  134. package/dist/server/reaction.js.map +1 -1
  135. package/dist/server/reducer.js +1 -1
  136. package/dist/server/reducer.js.map +1 -1
  137. package/dist/server/resource.js +1 -1
  138. package/dist/server/resource.js.map +1 -1
  139. package/dist/server/selector.js +1 -1
  140. package/dist/server/selector.js.map +1 -1
  141. package/dist/server/signal.js +1 -1
  142. package/dist/server/signal.js.map +1 -1
  143. package/dist/server/store/nodes.js +1 -1
  144. package/dist/server/store/nodes.js.map +1 -1
  145. package/dist/server/store/use-store.js.map +1 -1
  146. package/dist/server/transitions.js.map +1 -1
  147. package/dist/server-dev/action.js +11 -7
  148. package/dist/server-dev/action.js.map +1 -1
  149. package/dist/server-dev/cache.js +5 -3
  150. package/dist/server-dev/cache.js.map +1 -1
  151. package/dist/server-dev/effect.js.map +1 -1
  152. package/dist/server-dev/extend/index.js +7 -7
  153. package/dist/server-dev/extend/index.js.map +1 -1
  154. package/dist/server-dev/external-store.js.map +1 -1
  155. package/dist/server-dev/internal/concurrency.js +56 -30
  156. package/dist/server-dev/internal/concurrency.js.map +1 -1
  157. package/dist/server-dev/internal/diagnostics.js +0 -2
  158. package/dist/server-dev/internal/diagnostics.js.map +1 -1
  159. package/dist/server-dev/internal/dispose.js +1 -1
  160. package/dist/server-dev/internal/dispose.js.map +1 -1
  161. package/dist/server-dev/internal/flags.js +1 -3
  162. package/dist/server-dev/internal/flags.js.map +1 -1
  163. package/dist/server-dev/internal/graph.js +47 -69
  164. package/dist/server-dev/internal/graph.js.map +1 -1
  165. package/dist/server-dev/internal/owner.js +22 -30
  166. package/dist/server-dev/internal/owner.js.map +1 -1
  167. package/dist/server-dev/internal/scheduler.js +44 -73
  168. package/dist/server-dev/internal/scheduler.js.map +1 -1
  169. package/dist/server-dev/list.js +4 -12
  170. package/dist/server-dev/list.js.map +1 -1
  171. package/dist/server-dev/memo.js +4 -4
  172. package/dist/server-dev/memo.js.map +1 -1
  173. package/dist/server-dev/ownership.js +59 -3
  174. package/dist/server-dev/ownership.js.map +1 -1
  175. package/dist/server-dev/props.js +18 -11
  176. package/dist/server-dev/props.js.map +1 -1
  177. package/dist/server-dev/reaction.js +5 -1
  178. package/dist/server-dev/reaction.js.map +1 -1
  179. package/dist/server-dev/reducer.js +1 -1
  180. package/dist/server-dev/reducer.js.map +1 -1
  181. package/dist/server-dev/resource.js +24 -15
  182. package/dist/server-dev/resource.js.map +1 -1
  183. package/dist/server-dev/selector.js +1 -5
  184. package/dist/server-dev/selector.js.map +1 -1
  185. package/dist/server-dev/signal.js +3 -3
  186. package/dist/server-dev/signal.js.map +1 -1
  187. package/dist/server-dev/store/nodes.js +10 -4
  188. package/dist/server-dev/store/nodes.js.map +1 -1
  189. package/dist/server-dev/store/use-store.js.map +1 -1
  190. package/dist/server-dev/transitions.js.map +1 -1
  191. package/package.json +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"graph.js","names":["NO_SOURCES","Signal","value","equals","name","Computation","Owner","parent","kind","flags","fn","nextSequence","unlinkSources","removeObserver","observers","source","last","at","moved","movedAt","unlinkFrom","node","sources","from","i","withEdge","length","array","first","second","next","track","listener","rt","position","index","sourcesOf","everyOther","observersOf","hasObservers","out","edges","markStack","stale","previous","observer","enqueue","trySuspend","error","isFrozen","markObservers","staleObservers","frameNodes","frameIndex","frameTop","updateIfNecessary","root","base","eagerSources","cursor","descended","dependency","ShadowError","refreshAncestors","recompute","pending","owner","ancestor","readSignal","signal","readMemo","memo","disposeChildren","previousOwner","previousListener","previousRunning","result","failed","failure","settleMemo","settleEffect","hadError","changed","routeToHandler","comparatorError","hasErrorHandler","handleError","unhandled","apply","cleanup","deferred","previousValue","addCleanup"],"sources":["../../../src/internal/graph.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport {\n CHECK,\n CLEAN,\n DIRTY,\n FLAG_DEFER,\n FLAG_DISPOSED,\n FLAG_HAS_ERROR,\n FLAG_REFRESHING,\n FLAG_RENDER,\n FLAG_RUNNING,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n KIND_SIGNAL,\n} from \"./flags\";\nimport { addCleanup, disposeChildren, handleError, hasErrorHandler, Owner } from \"./owner\";\nimport { enqueue } from \"./queue\";\nimport { nextSequence, rt } from \"./state\";\nimport type { Cleanup, Equals } from \"./types\";\n\n// Shared and frozen until a computation reads its first source: most effects and memos in a large\n// tree own few edges, and an empty array per node dominates creation cost.\nconst NO_SOURCES: Edges<Source> = Object.freeze([]) as unknown as Edges<Source>;\n\n/** Memo nesting depth after which pulls switch from recursion to the iterative walk. */\nconst DEEP_LIMIT = 128;\n\n/**\n * Anything that can be read reactively and notify observers: a signal, a memo, or a custom source\n * of a primitive. Exported from `@shadow-js/core/extend` as `SourceNode`. Read one with\n * {@link track}; after changing it, call {@link markObservers} and `schedule` (or `notify`).\n * @since 1.0.0\n */\nexport interface Source {\n /**\n * The node kind: 0 for a signal and for any custom source, which have no sources of their own; a\n * computation has its own kind. A refresh walks only the sources whose kind is not 0.\n */\n readonly kind: number;\n /** The current value. */\n value: unknown;\n /**\n * The computations that read this source in their last run, as pairs: an observer, then the index of this source in\n * that observer's `sources`. Null or empty when none. Read it with `observersOf`, which returns the observers alone.\n */\n observers: Edges<Computation> | null;\n /** Stamp of the last computation run that tracked this source (dedupes repeated reads). */\n stamp: number;\n}\n\n/**\n * The edges of one node, stored as pairs in one array: the node on the other side of the edge, then the index of this\n * node's entry in that node's own edge array. One array per side costs half the memory of two parallel ones, and\n * removing an edge stays O(1): the last pair moves into the vacated place and tells its owner where it went.\n */\nexport type Edges<T> = Array<T | number>;\n\n/**\n * The storage of a signal: its value, its equality and the computations that read it. Exported from\n * `@shadow-js/core/extend` as `SignalNode`; create one with `createSignalNode`, read it with\n * {@link readSignal} and write it with `writeSignal`, which notifies its readers. Build a custom\n * primitive on it the way `useSignal` does.\n *\n * @example\n * import { createSignalNode, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(0, Object.is, \"count\");\n * writeSignal(count, 1);\n * console.log(readSignal(count), count instanceof SignalNode); // 1 true\n * @see createSignalNode\n * @since 1.0.0\n */\nexport class Signal<T = unknown> implements Source {\n /** Always 0, the kind of a signal. */\n readonly kind: number = KIND_SIGNAL;\n /**\n * The current value. Assigning it directly notifies no one: use `writeSignal`, or call `notify`\n * after the assignment.\n */\n value: T;\n /** Decides whether a write is a change; `false` treats every write as one. */\n equals: Equals<T>;\n /** The computations that read this signal in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the last computation run that tracked this signal (dedupes repeated reads). */\n stamp = 0;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name: string | undefined;\n\n /**\n * Creates a signal. Prefer `createSignalNode`, which takes the same arguments.\n * @param value Initial value.\n * @param equals Equality that decides whether a write is a change.\n * @param name Devtools label, or undefined for an unnamed signal.\n */\n constructor(value: T, equals: Equals<T>, name: string | undefined) {\n this.value = value;\n this.equals = equals;\n this.name = name;\n if (__DEV__) report(DEVTOOLS_EVENT.SIGNAL_CREATED, this, rt.owner, name, value);\n }\n}\n\n/**\n * A memo or an effect: an owner that reads sources and (for memos) is itself a source. Exported from\n * `@shadow-js/core/extend` as `ComputationNode`; create one with `createComputation` and read a memo\n * with `readComputation`. It owns what its function creates: each run first disposes the children\n * and runs the cleanups of the previous run.\n *\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode(10, Object.is);\n * const total = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 2 });\n * console.log(readComputation<number>(total)); // 20\n * @see createComputation\n * @since 1.0.0\n */\nexport class Computation extends Owner implements Source {\n /** 1 for a memo, 2 for an effect. */\n kind: number;\n /** How stale the node is: 0 (clean), 1 (a transitive source changed), 2 (a direct source changed). */\n state: number;\n /** Engine bit flags (queued, running, disposed, render phase, ...). Read-only outside the engine. */\n flags: number;\n /** A memo's last value; an effect's last computed value when it has an `apply` stage. */\n value: unknown;\n /** The error a memo's last run threw, rethrown to its readers; undefined when it succeeded. */\n error: unknown = undefined;\n /** A memo's equality: readers are notified only when it says the new value differs. */\n equals: Equals<unknown>;\n /** The function each run calls with the previous value; null once disposed. */\n fn: ((previous: never) => unknown) | null;\n /**\n * An effect's second stage, run untracked with the computed value and the previous one; null for\n * none and once disposed.\n */\n apply: ((value: never, previous: never) => unknown) | null = null;\n /**\n * The sources the last run read, in reading order, as pairs: a source, then the index of this computation in that\n * source's `observers`. Read it with `sourcesOf`, which returns the sources alone.\n */\n sources: Edges<Source> = NO_SOURCES;\n /** The computations that read this memo in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the current run while it tracks, and of the last run that tracked this memo. */\n stamp = 0;\n /** During a run: how many leading entries of `sources` were confirmed again (they keep their edges). */\n trackIndex = 0;\n /** Creation order; breaks ties between effects at equal depth (G-16). */\n seq: number;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the computation is unnamed)\n */\n name: string | undefined;\n\n /**\n * Creates a computation that has not run yet. Prefer `createComputation`, which also runs or\n * queues it.\n * @param parent The owner to attach to, or null.\n * @param kind 1 for a memo, 2 for an effect.\n * @param flags Initial engine bit flags.\n * @param fn The function each run calls.\n * @param equals A memo's equality; `false` for an effect.\n * @param name Devtools label, or undefined.\n */\n constructor(\n parent: Owner | null,\n kind: number,\n flags: number,\n fn: (previous: never) => unknown,\n equals: Equals<unknown>,\n name: string | undefined,\n ) {\n super(parent);\n this.kind = kind;\n this.flags = flags;\n this.state = DIRTY;\n this.fn = fn;\n this.equals = equals;\n this.name = name;\n this.value = undefined;\n this.seq = nextSequence();\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_CREATED,\n this,\n parent,\n kind === KIND_MEMO ? \"memo\" : \"effect\",\n name,\n (flags & FLAG_RENDER) !== 0,\n );\n }\n }\n\n protected override reportDisposed(): void {\n if (__DEV__) report(DEVTOOLS_EVENT.COMPUTATION_DISPOSED, this);\n }\n\n protected override release(): void {\n this.flags |= FLAG_DISPOSED;\n unlinkSources(this);\n this.fn = null;\n this.apply = null;\n }\n}\n\n/**\n * Removes the pair at `at` from `source.observers` in O(1): the last pair moves into its place, and its observer is told\n * where it went.\n */\nfunction removeObserver(source: Source, at: number): void {\n const observers = source.observers;\n if (observers === null) return;\n const last = observers.length - 2;\n if (at !== last) {\n const moved = observers[last] as Computation;\n const movedAt = observers[last + 1] as number;\n observers[at] = moved;\n observers[at + 1] = movedAt;\n moved.sources[movedAt + 1] = at;\n }\n observers.length = last;\n}\n\n/** Drops every edge from `node` to its sources. */\nexport function unlinkSources(node: Computation): void {\n unlinkFrom(node, 0);\n}\n\n/** Drops the edges from `node` to the sources at index `from` of `node.sources` and later, and truncates the list. */\nfunction unlinkFrom(node: Computation, from: number): void {\n const sources = node.sources;\n if (sources.length <= from) return;\n for (let i = sources.length - 2; i >= from; i -= 2) {\n // The index in the source is read each time: removing an edge may move this node's pair in another source.\n removeObserver(sources[i] as Source, sources[i + 1] as number);\n }\n sources.length = from;\n}\n\n/**\n * The array with the pair `first`, `second` appended: a new array of exactly the right size while short (`new Array(n)`\n * allocates the backing store at that size, where `push` on a short array reserves room for sixteen), the same array\n * grown by `push` from sixteen entries on.\n */\nfunction withEdge<T>(array: Array<T | number>, first: T, second: number): Array<T | number> {\n const length = array.length;\n if (length >= 16) {\n array.push(first, second);\n return array;\n }\n const next = new Array<T | number>(length + 2);\n for (let i = 0; i < length; i += 1) next[i] = array[i] as T | number;\n next[length] = first;\n next[length + 1] = second;\n return next;\n}\n\n/**\n * Records that the running computation read `source`, so a later {@link markObservers} on it marks\n * that computation stale. Call it in the reader of a custom source; {@link readSignal} does it for\n * signals. Does nothing when untracked, and a source read again in the same run is recorded once.\n *\n * @param source The source that was read.\n * @example\n * import { markObservers, schedule, type SourceNode, track } from \"@shadow-js/core/extend\";\n *\n * const clock: SourceNode = { kind: 0, value: Date.now(), observers: null, stamp: 0 };\n * export function now(): number {\n * track(clock);\n * return clock.value as number;\n * }\n * setInterval(() => {\n * clock.value = Date.now();\n * markObservers(clock);\n * schedule();\n * }, 1000);\n * @see readSignal\n * @since 1.0.0\n */\nexport function track(source: Source): void {\n const listener = rt.listener;\n if (listener === null) return;\n if (source.stamp === listener.stamp) return;\n source.stamp = listener.stamp;\n // Same dependency at the same position as last run: keep the edge, touch nothing.\n const position = listener.trackIndex;\n if (position < listener.sources.length) {\n if (listener.sources[position] === source) {\n listener.trackIndex = position + 2;\n return;\n }\n unlinkFrom(listener, position);\n }\n // Edge arrays are small: most nodes have one to three edges. `push` on a short array reserves room for about sixteen\n // entries (200 bytes where an exact array takes 64, measured), and a large list pays it for every row. A short array\n // therefore grows into a new exact one; from sixteen entries on `push` amortizes. Nothing iterates an edge array of\n // a node while it tracks, so replacing the array is safe.\n const observers = source.observers;\n const sources = listener.sources;\n const at = observers === null ? 0 : observers.length;\n const index = sources.length;\n source.observers =\n observers === null\n ? [listener, index]\n : (withEdge(observers, listener, index) as Edges<Computation>);\n listener.sources = withEdge(sources, source, at) as Edges<Source>;\n listener.trackIndex = index + 2;\n}\n\n/**\n * The sources the last run of a computation read, in reading order. Use it to inspect the graph (a debugger, a test);\n * it is a snapshot, so changing the returned array changes no edge.\n *\n * @param node The memo or effect.\n * @returns The signals and memos it reads now.\n * @example\n * import { createComputation, createSignalNode, flushSync, readSignal, sourcesOf } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * const effect = createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(sourcesOf(effect).length); // 1\n * @see observersOf\n * @since 1.0.0\n */\nexport function sourcesOf(node: Computation): Source[] {\n return everyOther(node.sources) as Source[];\n}\n\n/**\n * The computations that read a signal or memo in their last run, in the order their edges were made. It is a snapshot,\n * so changing the returned array changes no edge. The node's own `observers` array stores pairs (the observer and an\n * index for the engine), so read it through this function.\n *\n * @param source A signal, a memo or a custom source.\n * @returns The memos and effects that read it now.\n * @example\n * import { createComputation, createSignalNode, flushSync, observersOf, readSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(observersOf(count).length); // 1\n * @see sourcesOf\n * @since 1.0.0\n */\nexport function observersOf(source: Source): Computation[] {\n return source.observers === null ? [] : (everyOther(source.observers) as Computation[]);\n}\n\n/** True when at least one computation read `source` in its last run. */\nexport function hasObservers(source: Source): boolean {\n return source.observers !== null && source.observers.length > 0;\n}\n\n/** The first element of every pair of an edge array. */\nfunction everyOther<T>(edges: Edges<T>): T[] {\n const out: T[] = [];\n for (let i = 0; i < edges.length; i += 2) out.push(edges[i] as T);\n return out;\n}\n\n// Scratch stack for markObservers; never holds data across calls.\nconst markStack: Computation[] = [];\n\nfunction stale(observer: Computation, next: number): void {\n const previous = observer.state;\n if (observer.kind === KIND_EFFECT) {\n if (previous < next) observer.state = next;\n if (previous === CLEAN) enqueue(observer);\n else if (!rt.inTransition) rt.hooks?.promote(observer);\n return;\n }\n if (previous >= next) return;\n observer.state = next;\n if (previous !== CLEAN) return;\n if (observer.observers !== null && observer.observers.length > 0) markStack.push(observer);\n}\n\n/**\n * A suspension (a transition read pending data inside a held boundary) keeps the node's value until the\n * boundary releases it. True when `error` was one, and the node was recorded for that wake-up.\n */\nfunction trySuspend(node: Computation, error: unknown): boolean {\n return rt.hooks?.suspend(node, error) === true;\n}\n\n/**\n * A memo or effect frozen by a pause keeps its last value and does not refresh until it resumes.\n * A memo that never computed is not frozen (it has no value to keep).\n */\nexport function isFrozen(node: Computation): boolean {\n return node.pauses > 0 && (node.flags & FLAG_UNINIT) === 0;\n}\n\n/**\n * Marks the direct observers of a changed source DIRTY and everything downstream CHECK, and queues\n * the effects it reaches. It does not request a flush: call `schedule` afterward, or use `notify`,\n * which does both. Iterative: the graph can be 100,000 nodes deep (G-10).\n *\n * @param source The source whose value changed.\n * @example\n * import { markObservers, schedule, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function push(list: SignalNode<string[]>, item: string): void {\n * list.value.push(item); // same array: writeSignal would see no change\n * markObservers(list);\n * schedule();\n * }\n * @see track\n * @since 1.0.0\n */\nexport function markObservers(source: Source): void {\n staleObservers(source.observers, DIRTY);\n while (markStack.length > 0) {\n const node = markStack.pop();\n if (node !== undefined) staleObservers(node.observers, CHECK);\n }\n}\n\n/** Marks every observer in a list of edge pairs stale at the given level. */\nfunction staleObservers(observers: Edges<Computation> | null, next: number): void {\n if (observers === null) return;\n for (let i = 0; i < observers.length; i += 2) stale(observers[i] as Computation, next);\n}\n\n// Scratch frames for updateIfNecessary; entries above `frameTop` are dead.\nconst frameNodes: Computation[] = [];\nconst frameIndex: number[] = [];\nlet frameTop = 0;\n\n/**\n * Brings `root` up to date: verifies stale sources oldest-first and recomputes only nodes whose\n * sources really changed (equality cut-off, G-2). Iterative so deep chains cannot overflow (G-10).\n * With `eagerSources`, DIRTY nodes also refresh their previous sources first, which keeps the\n * native stack flat for chains where every node reads both a fresh signal and its predecessor.\n */\nexport function updateIfNecessary(root: Computation, eagerSources = false): void {\n if (root.state === CLEAN) return;\n const base = frameTop;\n frameNodes[frameTop] = root;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n root.flags |= FLAG_REFRESHING;\n try {\n while (frameTop > base) {\n const at = frameTop - 1;\n const node = frameNodes[at];\n if (node === undefined) break;\n if (node.state === CHECK || (node.state === DIRTY && eagerSources)) {\n const sources = node.sources;\n let cursor = frameIndex[at] ?? 0;\n let descended = false;\n while (cursor < sources.length) {\n const source = sources[cursor] as Source;\n cursor += 2;\n if (source.kind === KIND_SIGNAL) continue;\n const dependency = source as Computation;\n if (dependency.state === CLEAN || (dependency.flags & FLAG_DISPOSED) !== 0) continue;\n if (isFrozen(dependency)) continue;\n if ((dependency.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n // An owner that is about to re-run would dispose this dependency: update it first.\n refreshAncestors(dependency);\n if (dependency.state === CLEAN || (dependency.flags & FLAG_DISPOSED) !== 0) continue;\n if (isFrozen(dependency)) continue;\n frameIndex[at] = cursor;\n frameNodes[frameTop] = dependency;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n dependency.flags |= FLAG_REFRESHING;\n descended = true;\n break;\n }\n if (descended) continue;\n }\n if (node.state === DIRTY) recompute(node);\n else node.state = CLEAN;\n node.flags &= ~FLAG_REFRESHING;\n frameTop -= 1;\n }\n } finally {\n // An exception leaves frames on the stack: they must not stay marked as being refreshed.\n for (let i = base; i < frameTop; i += 1) {\n const pending = frameNodes[i];\n if (pending !== undefined) pending.flags &= ~FLAG_REFRESHING;\n }\n frameNodes.length = base;\n frameIndex.length = base;\n frameTop = base;\n }\n}\n\n/**\n * Brings stale owners of `node` up to date, topmost first. An owner that is about to re-run will\n * dispose `node`; computing `node` first would run it with state that is already out of date\n * (a zombie, G-17). Iterative: the owner chain depth is user controlled.\n */\nfunction refreshAncestors(node: Computation): void {\n const stale: Computation[] = [];\n for (let owner = node.parent; owner !== null; owner = owner.parent) {\n if (!(owner instanceof Computation)) continue;\n if (\n owner.state !== CLEAN &&\n (owner.flags & (FLAG_RUNNING | FLAG_DISPOSED | FLAG_REFRESHING)) === 0 &&\n !isFrozen(owner)\n ) {\n stale.push(owner);\n }\n }\n for (let i = stale.length - 1; i >= 0; i -= 1) {\n const ancestor = stale[i];\n if (ancestor !== undefined && (ancestor.flags & FLAG_DISPOSED) === 0) {\n updateIfNecessary(ancestor);\n }\n }\n}\n\n/**\n * Reads a signal's value, subscribing the running computation to it when one is listening. The\n * reader of a custom primitive built on `createSignalNode`.\n *\n * @param signal The signal to read.\n * @returns The current value.\n * @example\n * import { createSignalNode, readSignal } from \"@shadow-js/core/extend\";\n *\n * const name = createSignalNode(\"Ada\", Object.is);\n * export const getName = (): string => readSignal(name);\n * @see track\n * @since 1.0.0\n */\nexport function readSignal<T>(signal: Signal<T>): T {\n if (rt.listener !== null) track(signal);\n return signal.value;\n}\n\n/** Reads a memo: refreshes it if stale, tracks it, rethrows its stored error. */\nexport function readMemo<T>(memo: Computation): T {\n if ((memo.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n if (memo.state !== CLEAN && (memo.flags & FLAG_DISPOSED) === 0 && !isFrozen(memo)) {\n refreshAncestors(memo);\n if ((memo.flags & FLAG_DISPOSED) === 0) {\n updateIfNecessary(memo, rt.recomputeDepth >= DEEP_LIMIT);\n }\n }\n if (rt.listener !== null) track(memo);\n if ((memo.flags & FLAG_HAS_ERROR) !== 0) throw memo.error;\n return memo.value as T;\n}\n\n/** Re-runs a memo or effect: disposes the previous run, re-tracks sources, stores the result. */\nexport function recompute(node: Computation): void {\n const fn = node.fn;\n if (fn === null) return;\n disposeChildren(node);\n node.runCleanups();\n // Edges are kept and re-confirmed in order while the function runs (see track()).\n node.trackIndex = 0;\n // Each run starts from a clean slate: handlers, ids and child indices belong to one run.\n node.errorHandlers = null;\n node.idCount = 0;\n node.childCount = 0;\n\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = node;\n rt.running = node;\n rt.recomputeDepth += 1;\n node.state = CLEAN;\n node.flags |= FLAG_RUNNING;\n node.stamp = nextSequence();\n\n let result: unknown;\n let failed = false;\n let failure: unknown;\n const startedAt = __DEV__ ? performance.now() : 0;\n try {\n result = (fn as (previous: unknown) => unknown)(node.value);\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n rt.recomputeDepth -= 1;\n node.flags &= ~FLAG_RUNNING;\n // Sources this run did not read again are no longer dependencies.\n if (node.trackIndex < node.sources.length) unlinkFrom(node, node.trackIndex);\n }\n\n const changed = node.kind === KIND_MEMO ? settleMemo(node, result, failed, failure) : true;\n if (node.kind !== KIND_MEMO) settleEffect(node, result, failed, failure);\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_RUN,\n node,\n startedAt,\n performance.now() - startedAt,\n changed,\n sourcesOf(node),\n );\n }\n}\n\n/** Stores a memo's result; says whether its value changed (observers were told). */\nfunction settleMemo(\n node: Computation,\n result: unknown,\n failed: boolean,\n failure: unknown,\n): boolean {\n // A suspended memo keeps its previous value: its readers see nothing change until it resumes.\n if (failed && trySuspend(node, failure)) return false;\n const first = (node.flags & FLAG_UNINIT) !== 0;\n node.flags &= ~FLAG_UNINIT;\n const hadError = (node.flags & FLAG_HAS_ERROR) !== 0;\n let changed: boolean;\n if (failed && routeToHandler(node, failure)) {\n return false;\n }\n if (failed) {\n node.flags |= FLAG_HAS_ERROR;\n node.error = failure;\n changed = true;\n } else {\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n const equals = node.equals;\n try {\n changed = first || hadError || equals === false || !equals(node.value, result);\n if (changed) node.value = result;\n } catch (comparatorError) {\n // A throwing comparator is a failing memo, not a wedged graph: readers see the error.\n node.flags |= FLAG_HAS_ERROR;\n node.error = comparatorError;\n changed = true;\n }\n }\n if (!changed || first) return changed;\n const observers = node.observers;\n if (observers === null) return changed;\n for (let i = 0; i < observers.length; i += 2) {\n const observer = observers[i] as Computation;\n if (observer.state === CHECK) observer.state = DIRTY;\n }\n return changed;\n}\n\n/**\n * A memo that fails inside a boundary (an ancestor registered catchError()/onError()) reports to it\n * when it fails, and keeps its previous value. Readers then see that value instead of the error:\n * the reader may live outside the boundary (the DOM region that displays the memo's result), where a\n * rethrown error would escape the very boundary meant to catch it. Without a handler the error is\n * stored and rethrown to readers, so it is never silent.\n *\n * The first computation counts too: its value is `undefined`, and it is typically read by a\n * consumer outside the boundary (a DOM region), not by the code that created it.\n */\nfunction routeToHandler(node: Computation, failure: unknown): boolean {\n if (!hasErrorHandler(node)) return false;\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n try {\n handleError(failure, node);\n } catch (unhandled) {\n // The chain ended in a handler that rethrew: readers see it, as for any unhandled failure.\n node.flags |= FLAG_HAS_ERROR;\n node.error = unhandled;\n }\n return true;\n}\n\nfunction settleEffect(node: Computation, result: unknown, failed: boolean, failure: unknown): void {\n if (failed) {\n if (!trySuspend(node, failure)) handleError(failure, node);\n return;\n }\n const apply = node.apply;\n let cleanup: unknown;\n if (apply === null) {\n cleanup = result;\n } else {\n const deferred = (node.flags & FLAG_DEFER) !== 0;\n node.flags &= ~FLAG_DEFER;\n const previousValue = node.value;\n node.value = result;\n if (deferred) return;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = null;\n // Writes from an effect's apply are legal even when the effect was created inside a memo.\n rt.running = node;\n try {\n cleanup = (apply as (value: unknown, previous: unknown) => unknown)(result, previousValue);\n } catch (error) {\n if (!trySuspend(node, error)) handleError(error, node);\n return;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n }\n }\n if (typeof cleanup === \"function\") {\n addCleanup(node, cleanup as Cleanup);\n // The effect disposed its own owner while running: nothing will dispose it again, so run now.\n if ((node.flags & FLAG_DISPOSED) !== 0) node.runCleanups();\n }\n}\n"],"mappings":"A,oPAwBA,MAAMA,EAA4B,OAAO,OAAO,CAAC,CAAC,EAkDlD,IAAaC,EAAb,KAAmD,CAEjD,KAAS,EAKT,MAEA,OAEA,UAAuC,KAEvC,MAAQ,EAKR,KAQA,YAAY,EAAU,EAAmB,EAA0B,CACjE,KAAK,MAAQC,EACb,KAAK,OAASC,EACd,KAAK,KAAOC,CAEd,CACF,EAiBaC,EAAb,cAAiCC,CAAwB,CAEvD,KAEA,MAEA,MA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AiB,EAAwB,CACjG,GAAIH,EAAQ,CACL9B,EAAW1B,EAAMyD,CAAO,GAAGQ,EAAYR,EAASzD,CAAI,EACzD,MACF,CACA,IAAMmE,EAAQnE,EAAK,MACfoE,EACJ,GAAID,IAAU,KACZ,EAAUZ,MACL,CACL,IAAMc,EAAA,GAAYrE,EAAK,MAAA,IACvB,EAAK,OAAS,IACd,IAAMsE,EAAgBtE,EAAK,MAE3B,GADA,EAAK,MAAQuD,EACTc,EAAU,OACd,IAAMjB,EAAgBxC,EAAG,MACnByC,EAAmBzC,EAAG,SACtB0C,EAAkB1C,EAAG,QAC3B,EAAG,MAAQZ,EACX,EAAG,SAAW,KAEd,EAAG,QAAUA,EACb,GAAI,CACF,EAAWmE,EAAyDZ,EAAQe,CAAa,CAC3F,OAAS3C,EAAO,CACTD,EAAW1B,EAAM2B,CAAK,GAAGsC,EAAYtC,EAAO3B,CAAI,EACrD,MACF,QAAU,CACR,EAAG,MAAQoD,EACX,EAAG,SAAWC,EACd,EAAG,QAAUC,CACf,CACF,CACI,OAAOc,GAAY,aACrBG,EAAWvE,EAAMoE,CAAkB,EAE9BpE,EAAK,MAAA,GAA8BA,EAAK,YAAY,EAE7D,C"}
1
+ {"version":3,"file":"graph.js","names":["NO_SOURCES","Signal","value","equals","name","Computation","Owner","parent","kind","flags","fn","nextSequence","unlinkFrom","removeObserver","observers","source","last","at","moved","movedAt","sources","node","from","i","withEdge","length","array","first","second","next","track","listener","rt","position","index","sourcesOf","everyOther","observersOf","hasObservers","out","edges","markStack","stale","previous","observer","enqueue","trySuspend","error","isFrozen","markObservers","staleObservers","frameNodes","frameIndex","frameTop","updateIfNecessary","root","base","eagerSources","cursor","descended","dependency","needsUpdate","ShadowError","refreshAncestors","recompute","owner","ancestor","readSignal","signal","readMemo","memo","disposeChildren","previousOwner","previousListener","previousRunning","result","failed","failure","settleMemo","settleEffect","finishDisposal","isEqual","prev","hadError","changed","routeToHandler","comparatorError","hasErrorHandler","handleError","unhandled","apply","cleanup","deferred","previousValue","addCleanup"],"sources":["../../../src/internal/graph.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport {\n CHECK,\n CLEAN,\n DIRTY,\n FLAG_DEFER,\n FLAG_DISPOSED,\n FLAG_HAS_ERROR,\n FLAG_REFRESHING,\n FLAG_RENDER,\n FLAG_RUNNING,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n KIND_SIGNAL,\n} from \"./flags\";\nimport {\n addCleanup,\n disposeChildren,\n finishDisposal,\n handleError,\n hasErrorHandler,\n Owner,\n} from \"./owner\";\nimport { enqueue } from \"./queue\";\nimport { nextSequence, rt } from \"./state\";\nimport type { Cleanup, Equals } from \"./types\";\n\n// Shared and frozen until a computation reads its first source: most effects and memos in a large\n// tree own few edges, and an empty array per node dominates creation cost.\nconst NO_SOURCES: Edges<Source> = Object.freeze([]) as unknown as Edges<Source>;\n\n/** Memo nesting depth after which pulls switch from recursion to the iterative walk. */\nconst DEEP_LIMIT = 128;\n\n/**\n * Anything that can be read reactively and notify observers: a signal, a memo, or a custom source\n * of a primitive. Exported from `@shadow-js/core/extend` as `SourceNode`. Read one with\n * {@link track}; after changing it, call {@link markObservers} and `schedule` (or `notify`).\n * @since 1.0.0\n */\nexport interface Source {\n /**\n * The node kind: 0 for a signal and for any custom source, which have no sources of their own; a\n * computation has its own kind. A refresh walks only the sources whose kind is not 0.\n */\n readonly kind: number;\n /** The current value. */\n value: unknown;\n /**\n * The computations that read this source in their last run, as pairs: an observer, then the index of this source in\n * that observer's `sources`. Null or empty when none. Read it with `observersOf`, which returns the observers alone.\n */\n observers: Edges<Computation> | null;\n /** Stamp of the last computation run that tracked this source (dedupes repeated reads). */\n stamp: number;\n}\n\n/**\n * The edges of one node, stored as pairs in one array: the node on the other side of the edge, then the index of this\n * node's entry in that node's own edge array. One array per side costs half the memory of two parallel ones, and\n * removing an edge stays O(1): the last pair moves into the vacated place and tells its owner where it went.\n */\nexport type Edges<T> = Array<T | number>;\n\n/**\n * The storage of a signal: its value, its equality and the computations that read it. Exported from\n * `@shadow-js/core/extend` as `SignalNode`; create one with `createSignalNode`, read it with\n * {@link readSignal} and write it with `writeSignal`, which notifies its readers. Build a custom\n * primitive on it the way `useSignal` does.\n *\n * @example\n * import { createSignalNode, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(0, Object.is, \"count\");\n * writeSignal(count, 1);\n * console.log(readSignal(count), count instanceof SignalNode); // 1 true\n * @see createSignalNode\n * @since 1.0.0\n */\nexport class Signal<T = unknown> implements Source {\n /** Always 0, the kind of a signal. */\n readonly kind: number = KIND_SIGNAL;\n // Fields the constructor assigns are `declare`d: a plain field would also emit an empty initializer\n // (`parent;`) that every bundle carries.\n /**\n * The current value. Assigning it directly notifies no one: use `writeSignal`, or call `notify`\n * after the assignment.\n */\n declare value: T;\n /** Decides whether a write is a change; `false` treats every write as one. */\n declare equals: Equals<T>;\n /** The computations that read this signal in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the last computation run that tracked this signal (dedupes repeated reads). */\n stamp = 0;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n declare name: string | undefined;\n\n /**\n * Creates a signal. Prefer `createSignalNode`, which takes the same arguments.\n * @param value Initial value.\n * @param equals Equality that decides whether a write is a change.\n * @param name Devtools label, or undefined for an unnamed signal.\n */\n constructor(value: T, equals: Equals<T>, name?: string) {\n this.value = value;\n this.equals = equals;\n this.name = name;\n if (__DEV__) report(DEVTOOLS_EVENT.SIGNAL_CREATED, this, rt.owner, name, value);\n }\n}\n\n/**\n * A memo or an effect: an owner that reads sources and (for memos) is itself a source. Exported from\n * `@shadow-js/core/extend` as `ComputationNode`; create one with `createComputation` and read a memo\n * with `readComputation`. It owns what its function creates: each run first disposes the children\n * and runs the cleanups of the previous run.\n *\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode(10, Object.is);\n * const total = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 2 });\n * console.log(readComputation<number>(total)); // 20\n * @see createComputation\n * @since 1.0.0\n */\nexport class Computation extends Owner implements Source {\n // Fields the constructor assigns are `declare`d: a plain field would also emit an empty initializer\n // (`parent;`) that every bundle carries.\n /** 1 for a memo, 2 for an effect. */\n declare kind: number;\n /** How stale the node is: 0 (clean), 1 (a transitive source changed), 2 (a direct source changed). */\n declare state: number;\n /** Engine bit flags (queued, running, disposed, render phase, ...). Read-only outside the engine. */\n declare flags: number;\n /** A memo's last value; an effect's last computed value when it has an `apply` stage. */\n declare value: unknown;\n /** The error a memo's last run threw, rethrown to its readers; undefined when it succeeded. */\n error: unknown = undefined;\n /** A memo's equality: readers are notified only when it says the new value differs. */\n declare equals: Equals<unknown>;\n /** The function each run calls with the previous value; null once disposed. */\n fn: ((previous: never) => unknown) | null;\n /**\n * An effect's second stage, run untracked with the computed value and the previous one; null for\n * none and once disposed.\n */\n apply: ((value: never, previous: never) => unknown) | null = null;\n /**\n * The sources the last run read, in reading order, as pairs: a source, then the index of this computation in that\n * source's `observers`. Read it with `sourcesOf`, which returns the sources alone.\n */\n sources: Edges<Source> = NO_SOURCES;\n /** The computations that read this memo in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the current run while it tracks, and of the last run that tracked this memo. */\n stamp = 0;\n /** During a run: how many leading entries of `sources` were confirmed again (they keep their edges). */\n trackIndex = 0;\n /** Creation order; breaks ties between effects at equal depth (G-16). */\n declare seq: number;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the computation is unnamed)\n */\n declare name: string | undefined;\n\n /**\n * Creates a computation that has not run yet. Prefer `createComputation`, which also runs or\n * queues it.\n * @param parent The owner to attach to, or null.\n * @param kind 1 for a memo, 2 for an effect.\n * @param flags Initial engine bit flags.\n * @param fn The function each run calls.\n * @param equals A memo's equality; `false` for an effect.\n * @param name Devtools label, or undefined.\n */\n constructor(\n parent: Owner | null,\n kind: number,\n flags: number,\n fn: (previous: never) => unknown,\n equals: Equals<unknown>,\n name: string | undefined,\n ) {\n super(parent);\n this.kind = kind;\n this.flags = flags;\n this.state = DIRTY;\n this.fn = fn;\n this.equals = equals;\n this.name = name;\n this.value = undefined;\n this.seq = nextSequence();\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_CREATED,\n this,\n parent,\n kind === KIND_MEMO ? \"memo\" : \"effect\",\n name,\n (flags & FLAG_RENDER) !== 0,\n );\n }\n }\n\n protected override release(): void {\n this.flags |= FLAG_DISPOSED;\n unlinkFrom(this, 0);\n this.fn = null;\n this.apply = null;\n }\n}\n\n/**\n * Removes the pair at `at` from `source.observers` in O(1): the last pair moves into its place, and its observer is told\n * where it went.\n */\nfunction removeObserver(source: Source, at: number): void {\n const observers = source.observers;\n if (observers === null) return;\n const last = observers.length - 2;\n if (at !== last) {\n const moved = observers[last] as Computation;\n const movedAt = observers[last + 1] as number;\n observers[at] = moved;\n observers[at + 1] = movedAt;\n moved.sources[movedAt + 1] = at;\n }\n observers.length = last;\n}\n\n/** Drops every edge from `node` to its sources. */\nexport function unlinkSources(node: Computation): void {\n unlinkFrom(node, 0);\n}\n\n/** Drops the edges from `node` to the sources at index `from` of `node.sources` and later, and truncates the list. */\nfunction unlinkFrom(node: Computation, from: number): void {\n const sources = node.sources;\n if (sources.length <= from) return;\n for (let i = sources.length - 2; i >= from; i -= 2) {\n // The index in the source is read each time: removing an edge may move this node's pair in another source.\n removeObserver(sources[i] as Source, sources[i + 1] as number);\n }\n sources.length = from;\n}\n\n/**\n * The array with the pair `first`, `second` appended: a new array of exactly the right size while short (`new Array(n)`\n * allocates the backing store at that size, where `push` on a short array reserves room for sixteen), the same array\n * grown by `push` from sixteen entries on.\n */\nfunction withEdge<T>(array: Array<T | number>, first: T, second: number): Array<T | number> {\n const length = array.length;\n if (length >= 16) {\n array.push(first, second);\n return array;\n }\n const next = new Array<T | number>(length + 2);\n for (let i = 0; i < length; i += 1) next[i] = array[i] as T | number;\n next[length] = first;\n next[length + 1] = second;\n return next;\n}\n\n/**\n * Records that the running computation read `source`, so a later {@link markObservers} on it marks\n * that computation stale. Call it in the reader of a custom source; {@link readSignal} does it for\n * signals. Does nothing when untracked, and a source read again in the same run is recorded once.\n *\n * @param source The source that was read.\n * @example\n * import { markObservers, schedule, type SourceNode, track } from \"@shadow-js/core/extend\";\n *\n * const clock: SourceNode = { kind: 0, value: Date.now(), observers: null, stamp: 0 };\n * export function now(): number {\n * track(clock);\n * return clock.value as number;\n * }\n * setInterval(() => {\n * clock.value = Date.now();\n * markObservers(clock);\n * schedule();\n * }, 1000);\n * @see readSignal\n * @since 1.0.0\n */\nexport function track(source: Source): void {\n const listener = rt.listener;\n if (listener === null) return;\n if (source.stamp === listener.stamp) return;\n source.stamp = listener.stamp;\n // Same dependency at the same position as last run: keep the edge, touch nothing.\n const position = listener.trackIndex;\n if (position < listener.sources.length) {\n if (listener.sources[position] === source) {\n listener.trackIndex = position + 2;\n return;\n }\n unlinkFrom(listener, position);\n }\n // Edge arrays are small: most nodes have one to three edges. `push` on a short array reserves room for about sixteen\n // entries (200 bytes where an exact array takes 64, measured), and a large list pays it for every row. A short array\n // therefore grows into a new exact one; from sixteen entries on `push` amortizes. Nothing iterates an edge array of\n // a node while it tracks, so replacing the array is safe.\n const observers = source.observers;\n const sources = listener.sources;\n const at = observers === null ? 0 : observers.length;\n const index = sources.length;\n source.observers =\n observers === null\n ? [listener, index]\n : (withEdge(observers, listener, index) as Edges<Computation>);\n listener.sources = withEdge(sources, source, at) as Edges<Source>;\n listener.trackIndex = index + 2;\n}\n\n/**\n * The sources the last run of a computation read, in reading order. Use it to inspect the graph (a debugger, a test);\n * it is a snapshot, so changing the returned array changes no edge.\n *\n * @param node The memo or effect.\n * @returns The signals and memos it reads now.\n * @example\n * import { createComputation, createSignalNode, flushSync, readSignal, sourcesOf } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * const effect = createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(sourcesOf(effect).length); // 1\n * @see observersOf\n * @since 1.0.0\n */\nexport function sourcesOf(node: Computation): Source[] {\n return everyOther(node.sources) as Source[];\n}\n\n/**\n * The computations that read a signal or memo in their last run, in the order their edges were made. It is a snapshot,\n * so changing the returned array changes no edge. The node's own `observers` array stores pairs (the observer and an\n * index for the engine), so read it through this function.\n *\n * @param source A signal, a memo or a custom source.\n * @returns The memos and effects that read it now.\n * @example\n * import { createComputation, createSignalNode, flushSync, observersOf, readSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(observersOf(count).length); // 1\n * @see sourcesOf\n * @since 1.0.0\n */\nexport function observersOf(source: Source): Computation[] {\n return source.observers === null ? [] : (everyOther(source.observers) as Computation[]);\n}\n\n/** True when at least one computation read `source` in its last run. */\nexport function hasObservers(source: Source): boolean {\n return source.observers !== null && source.observers.length > 0;\n}\n\n/** The first element of every pair of an edge array. */\nfunction everyOther<T>(edges: Edges<T>): T[] {\n const out: T[] = [];\n for (let i = 0; i < edges.length; i += 2) out.push(edges[i] as T);\n return out;\n}\n\n// Scratch stack for markObservers; never holds data across calls.\nconst markStack: Computation[] = [];\n\nfunction stale(observer: Computation, next: number): void {\n const previous = observer.state;\n if (observer.kind === KIND_EFFECT) {\n if (previous < next) observer.state = next;\n if (previous === CLEAN) enqueue(observer);\n else if (!rt.inTransition) rt.hooks?.promote(observer);\n return;\n }\n if (previous >= next) return;\n observer.state = next;\n if (previous !== CLEAN) return;\n if (observer.observers !== null && observer.observers.length > 0) markStack.push(observer);\n}\n\n/**\n * A suspension (a transition read pending data inside a held boundary) keeps the node's value until the\n * boundary releases it. True when `error` was one, and the node was recorded for that wake-up.\n */\nfunction trySuspend(node: Computation, error: unknown): boolean {\n return rt.hooks?.suspend(node, error) === true;\n}\n\n/**\n * A memo or effect frozen by a pause keeps its last value and does not refresh until it resumes.\n * A memo that never computed is not frozen (it has no value to keep).\n */\nexport function isFrozen(node: Computation): boolean {\n return node.pauses > 0 && (node.flags & FLAG_UNINIT) === 0;\n}\n\n/**\n * Marks the direct observers of a changed source DIRTY and everything downstream CHECK, and queues\n * the effects it reaches. It does not request a flush: call `schedule` afterward, or use `notify`,\n * which does both. Iterative: the graph can be 100,000 nodes deep (G-10).\n *\n * @param source The source whose value changed.\n * @example\n * import { markObservers, schedule, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function push(list: SignalNode<string[]>, item: string): void {\n * list.value.push(item); // same array: writeSignal would see no change\n * markObservers(list);\n * schedule();\n * }\n * @see track\n * @since 1.0.0\n */\nexport function markObservers(source: Source): void {\n staleObservers(source.observers, DIRTY);\n while (markStack.length > 0) {\n staleObservers((markStack.pop() as Computation).observers, CHECK);\n }\n}\n\n/** Marks every observer in a list of edge pairs stale at the given level. */\nfunction staleObservers(observers: Edges<Computation> | null, next: number): void {\n if (observers === null) return;\n for (let i = 0; i < observers.length; i += 2) stale(observers[i] as Computation, next);\n}\n\n// Scratch frames for updateIfNecessary; entries above `frameTop` are dead.\nconst frameNodes: Computation[] = [];\nconst frameIndex: number[] = [];\nlet frameTop = 0;\n\n/**\n * Brings `root` up to date: verifies stale sources oldest-first and recomputes only nodes whose\n * sources really changed (equality cut-off, G-2). Iterative so deep chains cannot overflow (G-10).\n * With `eagerSources`, DIRTY nodes also refresh their previous sources first, which keeps the\n * native stack flat for chains where every node reads both a fresh signal and its predecessor.\n */\nexport function updateIfNecessary(root: Computation, eagerSources = false): void {\n if (root.state === CLEAN) return;\n const base = frameTop;\n frameNodes[frameTop] = root;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n root.flags |= FLAG_REFRESHING;\n try {\n while (frameTop > base) {\n const at = frameTop - 1;\n const node = frameNodes[at] as Computation;\n if (node.state === CHECK || (node.state === DIRTY && eagerSources)) {\n const sources = node.sources;\n let cursor = frameIndex[at] as number;\n let descended = false;\n while (cursor < sources.length) {\n const source = sources[cursor] as Source;\n cursor += 2;\n if (source.kind === KIND_SIGNAL) continue;\n const dependency = source as Computation;\n if (!needsUpdate(dependency)) continue;\n if ((dependency.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n // An owner that is about to re-run would dispose this dependency: update it first.\n if (!refreshAncestors(dependency)) continue;\n frameIndex[at] = cursor;\n frameNodes[frameTop] = dependency;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n dependency.flags |= FLAG_REFRESHING;\n descended = true;\n break;\n }\n if (descended) continue;\n }\n if (node.state === DIRTY) recompute(node);\n else node.state = CLEAN;\n node.flags &= ~FLAG_REFRESHING;\n frameTop -= 1;\n }\n } finally {\n // An exception leaves frames on the stack: they must not stay marked as being refreshed.\n for (let i = base; i < frameTop; i += 1) {\n (frameNodes[i] as Computation).flags &= ~FLAG_REFRESHING;\n }\n frameNodes.length = base;\n frameIndex.length = base;\n frameTop = base;\n }\n}\n\n/** True when `node` is stale, alive and not frozen: running it now is both possible and needed. */\nfunction needsUpdate(node: Computation): boolean {\n return node.state !== CLEAN && (node.flags & FLAG_DISPOSED) === 0 && !isFrozen(node);\n}\n\n/**\n * Brings stale owners of `node` up to date, topmost first. An owner that is about to re-run will\n * dispose `node`; computing `node` first would run it with state that is already out of date\n * (a zombie, G-17). Iterative: the owner chain depth is user controlled.\n *\n * @returns Whether `node` still needs updating afterward (an owner's run may have cleaned or disposed it).\n */\nexport function refreshAncestors(node: Computation): boolean {\n if (!needsUpdate(node)) return false;\n const stale: Computation[] = [];\n for (let owner = node.parent; owner !== null; owner = owner.parent) {\n if (\n owner instanceof Computation &&\n owner.state !== CLEAN &&\n (owner.flags & (FLAG_RUNNING | FLAG_REFRESHING)) === 0\n ) {\n stale.push(owner);\n }\n }\n for (let i = stale.length - 1; i >= 0; i -= 1) {\n const ancestor = stale[i] as Computation;\n if (needsUpdate(ancestor)) updateIfNecessary(ancestor);\n }\n return needsUpdate(node);\n}\n\n/**\n * Reads a signal's value, subscribing the running computation to it when one is listening. The\n * reader of a custom primitive built on `createSignalNode`.\n *\n * @param signal The signal to read.\n * @returns The current value.\n * @example\n * import { createSignalNode, readSignal } from \"@shadow-js/core/extend\";\n *\n * const name = createSignalNode(\"Ada\", Object.is);\n * export const getName = (): string => readSignal(name);\n * @see track\n * @since 1.0.0\n */\nexport function readSignal<T>(signal: Signal<T>): T {\n if (rt.listener !== null) track(signal);\n return signal.value;\n}\n\n/** Reads a memo: refreshes it if stale, tracks it, rethrows its stored error. */\nexport function readMemo<T>(memo: Computation): T {\n if ((memo.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n if (memo.state !== CLEAN && refreshAncestors(memo)) {\n updateIfNecessary(memo, rt.recomputeDepth >= DEEP_LIMIT);\n }\n if (rt.listener !== null) track(memo);\n if ((memo.flags & FLAG_HAS_ERROR) !== 0) throw memo.error;\n return memo.value as T;\n}\n\n/** Re-runs a memo or effect: disposes the previous run, re-tracks sources, stores the result. */\nexport function recompute(node: Computation): void {\n const fn = node.fn;\n if (fn === null) return;\n // One disposal for the children and the cleanups: all of them run even when one throws (the errors\n // are held in rt.uncaught), and the node still re-runs (it would stay dirty otherwise).\n rt.disposing += 1;\n try {\n disposeChildren(node);\n node.runCleanups();\n } finally {\n rt.disposing -= 1;\n }\n // Edges are kept and re-confirmed in order while the function runs (see track()).\n node.trackIndex = 0;\n // Each run starts from a clean slate: handlers, ids and child indices belong to one run.\n node.errorHandlers = null;\n node.idCount = 0;\n node.childCount = 0;\n\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = node;\n rt.running = node;\n rt.recomputeDepth += 1;\n node.state = CLEAN;\n node.flags |= FLAG_RUNNING;\n node.stamp = nextSequence();\n\n let result: unknown;\n let failed = false;\n let failure: unknown;\n const startedAt = __DEV__ ? performance.now() : 0;\n try {\n result = (fn as (previous: unknown) => unknown)(node.value);\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n rt.recomputeDepth -= 1;\n node.flags &= ~FLAG_RUNNING;\n // Sources this run did not read again are no longer dependencies. A node disposed while it ran\n // (it disposed its own owner) keeps none: reads after the disposal must not leave edges that\n // nothing will ever remove.\n unlinkFrom(node, (node.flags & FLAG_DISPOSED) !== 0 ? 0 : node.trackIndex);\n }\n\n let changed = true;\n if (node.kind === KIND_MEMO) changed = settleMemo(node, result, failed, failure);\n else settleEffect(node, result, failed, failure);\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_RUN,\n node,\n startedAt,\n performance.now() - startedAt,\n changed,\n sourcesOf(node),\n );\n }\n // The teardown's errors are thrown once the run is settled (unless a flush or an outer disposal collects them).\n rt.disposing += 1;\n finishDisposal();\n}\n\n/**\n * Calls a comparator untracked. It is a user callback: left tracked, the computation that writes (or the\n * reader that pulled the memo, the listener again once the run is over) would subscribe to whatever it\n * reads. Restored in `finally`, so a throwing comparator leaves the register as it found it.\n */\nexport function isEqual<T>(equals: (prev: T, next: T) => boolean, prev: T, next: T): boolean {\n const listener = rt.listener;\n rt.listener = null;\n try {\n return equals(prev, next);\n } finally {\n rt.listener = listener;\n }\n}\n\n/** Stores a memo's result; says whether its value changed (observers were told). */\nfunction settleMemo(\n node: Computation,\n result: unknown,\n failed: boolean,\n failure: unknown,\n): boolean {\n // A suspended memo keeps its previous value: its readers see nothing change until it resumes.\n if (failed && trySuspend(node, failure)) return false;\n const first = (node.flags & FLAG_UNINIT) !== 0;\n node.flags &= ~FLAG_UNINIT;\n const hadError = (node.flags & FLAG_HAS_ERROR) !== 0;\n let changed: boolean;\n if (failed && routeToHandler(node, failure)) {\n return false;\n }\n if (failed) {\n node.flags |= FLAG_HAS_ERROR;\n node.error = failure;\n changed = true;\n } else {\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n const equals = node.equals;\n try {\n changed = first || hadError || equals === false || !isEqual(equals, node.value, result);\n if (changed) node.value = result;\n } catch (comparatorError) {\n // A throwing comparator is a failing memo, not a wedged graph: readers see the error.\n node.flags |= FLAG_HAS_ERROR;\n node.error = comparatorError;\n changed = true;\n }\n }\n if (!changed || first) return changed;\n const observers = node.observers;\n if (observers === null) return changed;\n for (let i = 0; i < observers.length; i += 2) {\n const observer = observers[i] as Computation;\n if (observer.state === CHECK) observer.state = DIRTY;\n }\n return changed;\n}\n\n/**\n * A memo that fails inside a boundary (an ancestor registered catchError()/onError()) reports to it\n * when it fails, and keeps its previous value. Readers then see that value instead of the error:\n * the reader may live outside the boundary (the DOM region that displays the memo's result), where a\n * rethrown error would escape the very boundary meant to catch it. Without a handler the error is\n * stored and rethrown to readers, so it is never silent.\n *\n * The first computation counts too: its value is `undefined`, and it is typically read by a\n * consumer outside the boundary (a DOM region), not by the code that created it.\n */\nfunction routeToHandler(node: Computation, failure: unknown): boolean {\n if (!hasErrorHandler(node)) return false;\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n try {\n handleError(failure, node);\n } catch (unhandled) {\n // The chain ended in a handler that rethrew: readers see it, as for any unhandled failure.\n node.flags |= FLAG_HAS_ERROR;\n node.error = unhandled;\n }\n return true;\n}\n\nfunction settleEffect(node: Computation, result: unknown, failed: boolean, failure: unknown): void {\n if (failed) {\n if (!trySuspend(node, failure)) handleError(failure, node);\n return;\n }\n const apply = node.apply;\n let cleanup: unknown;\n if (apply === null) {\n cleanup = result;\n } else {\n const deferred = (node.flags & FLAG_DEFER) !== 0;\n node.flags &= ~FLAG_DEFER;\n const previousValue = node.value;\n node.value = result;\n if (deferred) return;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = null;\n // Writes from an effect's apply are legal even when the effect was created inside a memo.\n rt.running = node;\n try {\n cleanup = (apply as (value: unknown, previous: unknown) => unknown)(result, previousValue);\n } catch (error) {\n if (!trySuspend(node, error)) handleError(error, node);\n return;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n }\n }\n if (typeof cleanup === \"function\") {\n addCleanup(node, cleanup as Cleanup);\n // The effect disposed its own owner while running: nothing will dispose it again, so run now.\n if ((node.flags & FLAG_DISPOSED) !== 0) node.runCleanups();\n }\n}\n"],"mappings":"A,wQA+BA,MAAMA,EAA4B,OAAO,OAAO,CAAC,CAAC,EAkDlD,IAAaC,EAAb,KAAmD,CAEjD,KAAS,EAWT,UAAuC,KAEvC,MAAQ,EAaR,YAAY,EAAU,EAAmB,EAAe,CACtD,KAAK,MAAQC,EACb,KAAK,OAASC,EACd,KAAK,KAAOC,CAEd,CACF,EAiBaC,EAAb,cAAiCC,CAAwB,CAYvD,MAAiB,IAAA,GAIjB,GAKA,MAA6D,KAK7D,QAAyBN,EAEzB,UAAuC,KAEvC,MAAQ,EAER,WAAa,EAmBb,YACE,EACA,EACA,EACA,EACA,EACA,EACA,CACA,MAAMO,CAAM,EACZ,KAAK,KAAOC,EACZ,KAAK,MAAQC,EACb,KAAK,MAAA,EACL,KAAK,GAAKC,EACV,KAAK,OAASP,EACd,KAAK,KAAOC,EACZ,KAAK,MAAQ,IAAA,GACb,KAAK,IAAMO,EAAa,CAW1B,CAEA,SAAmC,CACjC,KAAK,OAAA,EACLC,EAAW,KAAM,CAAC,EAClB,KAAK,GAAK,KACV,KAAK,MAAQ,IACf,CACF,EAMA,SAASC,EAAe,EAAgB,EAAkB,CACxD,IAAMC,EAAYC,EAAO,UACzB,GAAID,IAAc,KAAM,OACxB,IAAME,EAAOF,EAAU,OAAS,EAChC,GAAIG,IAAOD,EAAM,CACf,IAAME,EAAQJ,EAAUE,GAClBG,EAAUL,EAAUE,EAAO,GACjC,EAAUC,GAAMC,EAChB,EAAUD,EAAK,GAAKE,EACpB,EAAM,QAAQA,EAAU,GAAKF,CA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K,MAAA,GAA8BA,EAAK,YAAY,EAE7D,C"}
@@ -1,2 +1,2 @@
1
- import{rt as e}from"./state.js";var t=class{parent;lastChild=null;prevSibling=null;nextSibling=null;cleanups=null;context;errorHandlers=null;childCount=0;idCount=0;index;depth;idPrefix;disposed=!1;gate=null;pauses=0;constructor(e){if(this.parent=e,this.context=e===null?null:e.context,this.depth=e===null?0:e.depth+1,this.pauses=e===null?0:e.pauses,e===null)this.index=0;else{this.index=e.childCount,e.childCount+=1;let t=e.lastChild;this.prevSibling=t,t!==null&&(t.nextSibling=this),e.lastChild=this}}reportDisposed(){}release(){}disposeSelf(){if(this.disposed)return;this.disposed=!0;let e=this.parent;if(e!==null){let t=this.prevSibling,n=this.nextSibling;t!==null&&(t.nextSibling=n),n===null?e.lastChild=t:n.prevSibling=t,this.prevSibling=null,this.nextSibling=null}this.release(),this.reportDisposed(),this.runCleanups()}runCleanups(){let t=this.cleanups;if(t===null)return;this.cleanups=null;let r=e.owner,i=e.listener;e.owner=null,e.listener=null;try{if(typeof t==`function`)n(t,this);else for(let e=t.length-1;e>=0;--e){let r=t[e];r!==void 0&&n(r,this)}}finally{e.owner=r,e.listener=i}}};function n(e,t){try{e()}catch(e){s(e,t)}}function r(e,t){let n=e.cleanups;n===null?e.cleanups=t:typeof n==`function`?e.cleanups=[n,t]:n.push(t)}function i(e){for(;;){let t=e.lastChild;if(t===null)return;o(t)}}function a(){if(--e.disposing,e.disposing>0||e.flushing||e.uncaught.length===0)return;let t=e.uncaught;throw e.uncaught=[],t.length===1?t[0]:AggregateError(t,`SHADOW_DISPOSE_ERRORS`)}function o(t){e.disposing+=1;try{let e=t;for(;;){for(;e.lastChild!==null;)e=e.lastChild;let n=e.parent;if(e.disposeSelf(),e===t||n===null)break;e=n}}finally{a()}}function s(t,n){let r=t;for(let t=n;t!==null;t=t.parent){let n=t.errorHandlers;if(n!==null)for(let t=n.length-1;t>=0;--t){let i=n[t];if(i===void 0)continue;let a=e.listener;try{e.listener=null,i(r);return}catch(e){r=e}finally{e.listener=a}}}l(r)}function c(e){for(let t=e;t!==null;t=t.parent){let e=t.errorHandlers;if(e!==null&&e.length>0)return!0}return!1}function l(t){if(e.flushing||e.disposing>0)e.uncaught.push(t);else throw t}export{t as Owner,r as addCleanup,i as disposeChildren,o as disposeTree,s as handleError,c as hasErrorHandler};
1
+ import{rt as e}from"./state.js";var t=class{lastChild=null;prevSibling=null;nextSibling=null;cleanups=null;errorHandlers=null;childCount=0;idCount=0;idPrefix;disposed=!1;gate=null;pauses=0;constructor(e){if(this.parent=e,e===null)this.context=null,this.depth=this.index=0;else{this.context=e.context,this.depth=e.depth+1,this.pauses=e.pauses,this.gate=e.gate,this.index=e.childCount,e.childCount+=1;let t=e.lastChild;this.prevSibling=t,t!==null&&(t.nextSibling=this),e.lastChild=this}}disposeSelf(){if(this.disposed)return;this.disposed=!0;let e=this.parent;if(e!==null){let t=this.prevSibling,n=this.nextSibling;t!==null&&(t.nextSibling=n),n===null?e.lastChild=t:n.prevSibling=t,this.prevSibling=null,this.nextSibling=null}this.release?.(),this.runCleanups()}runCleanups(){let t=this.cleanups;if(t===null)return;this.cleanups=null;let r=e.owner,i=e.listener;e.owner=null,e.listener=null,e.disposing+=1;try{if(typeof t==`function`)n(t,this);else for(let e=t.length-1;e>=0;--e)n(t[e],this)}finally{e.owner=r,e.listener=i,a()}}};function n(e,t){try{e()}catch(e){s(e,t)}}function r(e,t){let n=e.cleanups;n===null?e.cleanups=t:typeof n==`function`?e.cleanups=[n,t]:n.push(t)}function i(e){for(;;){let t=e.lastChild;if(t===null)return;o(t)}}function a(){if(--e.disposing,e.disposing>0||e.flushing||e.uncaught.length===0)return;let t=e.uncaught;throw e.uncaught=[],t.length===1?t[0]:AggregateError(t,`SHADOW_DISPOSE_ERRORS`)}function o(t){e.disposing+=1;try{let e=t;for(;;){for(;e.lastChild!==null;)e=e.lastChild;let n=e.parent;if(e.disposeSelf(),e===t||n===null)break;e=n}}finally{a()}}function s(t,n){let r=t;for(let t=n;t!==null;t=t.parent){let n=t.errorHandlers;if(n!==null)for(let t=n.length-1;t>=0;--t){let i=n[t],a=e.listener;try{e.listener=null,i(r);return}catch(e){r=e}finally{e.listener=a}}}l(r)}function c(e){for(let t=e;t!==null;t=t.parent){let e=t.errorHandlers;if(e!==null&&e.length>0)return!0}return!1}function l(t){if(e.flushing||e.disposing>0)e.uncaught.push(t);else throw t}export{t as Owner,r as addCleanup,i as disposeChildren,o as disposeTree,a as finishDisposal,s as handleError,c as hasErrorHandler};
2
2
  //# sourceMappingURL=owner.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"owner.js","names":["Owner","parent","last","prev","next","cleanups","previousOwner","rt","previousListener","runCleanup","i","cleanup","error","handleError","owner","addCleanup","existing","disposeChildren","child","disposeTree","finishDisposal","errors","node","root","current","from","handlers","handler","reportUncaught","hasErrorHandler"],"sources":["../../../src/internal/owner.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { rt } from \"./state\";\nimport type { Cleanup, ErrorHandler } from \"./types\";\n\n/**\n * The context values an owner sees, keyed by the symbol of each context. A provider creates a map\n * whose prototype is its parent's map, so a lookup is one property read and never walks owners.\n * @since 1.0.0\n */\nexport type ContextMap = Record<symbol, unknown>;\n\n/**\n * A node in the ownership tree: it owns the effects, memos and owners created under it, their\n * cleanups and error handlers, and disposes them together. Create one with `createOwner` and end it\n * with `disposeOwner`; the class is exported for `instanceof` checks and for reading its state.\n * Computations (`ComputationNode`) are owners too. Children are a doubly linked list so detaching one\n * is O(1); disposal walks the tree iteratively because its depth is user controlled (R-CODE-11).\n *\n * @example\n * import { createOwner, disposeOwner, Owner } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * console.log(owner instanceof Owner, owner.depth); // true 0\n * disposeOwner(owner);\n * console.log(owner.disposed); // true\n * @see createOwner\n * @see disposeOwner\n * @since 1.0.0\n */\nexport class Owner {\n /** The owner this node was created under, or null for a root. Kept after disposal. */\n parent: Owner | null;\n /** The newest child that is still alive, or null when there is none. */\n lastChild: Owner | null = null;\n /** The next older sibling that is still alive, or null. */\n prevSibling: Owner | null = null;\n /** The next newer sibling that is still alive, or null. */\n nextSibling: Owner | null = null;\n /**\n * The cleanups registered with `addCleanup` or `onCleanup`: null for none, a function for one, an\n * array (oldest first) for several. Emptied when they run.\n */\n cleanups: Cleanup | Cleanup[] | null = null;\n /** The context values this node sees: inherited from the parent at creation, null for a root. */\n context: ContextMap | null;\n /**\n * The handlers registered with `onError` or `catchError`, oldest first (they are tried newest\n * first), or null for none. A computation clears them before each run.\n */\n errorHandlers: ErrorHandler[] | null = null;\n /** Number of children ever created; gives each child a stable index for useId(). */\n childCount = 0;\n /** Number of ids useId() has handed out from this owner. */\n idCount = 0;\n /** Position among the parent's children, assigned at creation. */\n index: number;\n /** Distance from the root: 0 for a root, the parent's depth plus one otherwise. */\n depth: number;\n /**\n * The hydration-scope prefix of a component's owner, set by the renderer. When present, useId()\n * builds the ids below it from this prefix instead of the owner path.\n * @default undefined\n */\n idPrefix: string | undefined;\n /** True once the node has been disposed. */\n disposed = false;\n /**\n * While this returns true, user effects (and `onMount`) created below this owner wait: they do\n * not run until it returns false for the first time. Suspense sets it so the effects of content\n * that is still loading are held back. The read is tracked.\n */\n gate: (() => boolean) | null = null;\n /**\n * Number of pauses (Activity hidden) that cover this node. Inherited at creation, and changed for a\n * whole subtree by `pauseOwner`/`resumeOwner`. Above zero, effects wait and memos keep their value.\n */\n pauses = 0;\n\n /**\n * Creates an owner and links it as the newest child of `parent`. It inherits the parent's context\n * and pauses.\n * @param parent The owner to attach to, or null for a root.\n */\n constructor(parent: Owner | null) {\n this.parent = parent;\n this.context = parent === null ? null : parent.context;\n this.depth = parent === null ? 0 : parent.depth + 1;\n this.pauses = parent === null ? 0 : parent.pauses;\n if (parent === null) {\n this.index = 0;\n } else {\n this.index = parent.childCount;\n parent.childCount += 1;\n const last = parent.lastChild;\n this.prevSibling = last;\n if (last !== null) last.nextSibling = this;\n parent.lastChild = this;\n }\n // Computations report themselves (with their kind); plain owners and subclasses of it here.\n if (__DEV__ && new.target === Owner) {\n report(DEVTOOLS_EVENT.OWNER_CREATED, this, parent, parent === null ? \"root\" : \"owner\");\n }\n }\n\n /** Tells devtools this node is gone. Computations override it with their own event. */\n protected reportDisposed(): void {\n if (__DEV__) report(DEVTOOLS_EVENT.OWNER_DISPOSED, this);\n }\n\n /** Hook for subclasses: release graph edges before the node is marked disposed. */\n protected release(): void {\n // Plain owners hold no graph edges.\n }\n\n /**\n * Disposes this node only (children must already be gone).\n * @internal\n */\n disposeSelf(): void {\n if (this.disposed) return;\n this.disposed = true;\n // Detach first: a cleanup that throws must never leave a dead node in the tree (R-CODE-5).\n const parent = this.parent;\n if (parent !== null) {\n const prev = this.prevSibling;\n const next = this.nextSibling;\n if (prev !== null) prev.nextSibling = next;\n if (next !== null) next.prevSibling = prev;\n else parent.lastChild = prev;\n this.prevSibling = null;\n this.nextSibling = null;\n }\n this.release();\n this.reportDisposed();\n this.runCleanups();\n }\n\n /**\n * Runs own cleanups newest first, untracked, isolating failures.\n * @internal\n */\n runCleanups(): void {\n const cleanups = this.cleanups;\n if (cleanups === null) return;\n this.cleanups = null;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = null;\n rt.listener = null;\n try {\n if (typeof cleanups === \"function\") {\n runCleanup(cleanups, this);\n } else {\n for (let i = cleanups.length - 1; i >= 0; i -= 1) {\n const cleanup = cleanups[i];\n if (cleanup !== undefined) runCleanup(cleanup, this);\n }\n }\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n }\n}\n\nfunction runCleanup(cleanup: Cleanup, owner: Owner): void {\n try {\n cleanup();\n } catch (error) {\n handleError(error, owner);\n }\n}\n\n/**\n * Registers `cleanup` on an explicit owner. It runs when the owner is disposed or, when the owner is a\n * computation, before its next run. Cleanups run newest first, untracked and with no current owner;\n * one that throws goes to {@link handleError} for that owner and does not stop the others. Use it\n * where `onCleanup` cannot be called: the owner is not the current one, or the code must not warn.\n * Unlike `onCleanup`, nothing checks that the owner is still alive: a cleanup added to a disposed\n * owner never runs.\n *\n * @param owner The owner whose disposal runs the cleanup.\n * @param cleanup The function to run.\n * @example\n * import { addCleanup, currentOwner } from \"@shadow-js/core/extend\";\n *\n * export function useInterval(tick: () => void, ms: number): void {\n * const owner = currentOwner();\n * const timer = setInterval(tick, ms);\n * if (owner !== null) addCleanup(owner, () => clearInterval(timer));\n * }\n * @see disposeOwner\n * @since 1.0.0\n */\nexport function addCleanup(owner: Owner, cleanup: Cleanup): void {\n const existing = owner.cleanups;\n if (existing === null) owner.cleanups = cleanup;\n else if (typeof existing === \"function\") owner.cleanups = [existing, cleanup];\n else existing.push(cleanup);\n}\n\n/**\n * Disposes every child of `owner` (newest first), keeping `owner` itself alive.\n * @internal\n */\nexport function disposeChildren(owner: Owner): void {\n for (;;) {\n const child = owner.lastChild;\n if (child === null) return;\n disposeTree(child);\n }\n}\n\n/** Rethrows what disposal collected once the outermost disposal is finished. */\nfunction finishDisposal(): void {\n rt.disposing -= 1;\n if (rt.disposing > 0 || rt.flushing || rt.uncaught.length === 0) return;\n const errors = rt.uncaught;\n rt.uncaught = [];\n if (errors.length === 1) throw errors[0];\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while disposing.\" : \"SHADOW_DISPOSE_ERRORS\",\n );\n}\n\n/**\n * Disposes `root` and everything below it: children first, then own cleanups, newest first.\n * Iterative post-order walk: a leaf is disposed, which re-links its parent's `lastChild`\n * to the previous sibling, so the loop naturally visits the remaining subtree. The public\n * `disposeOwner` (dispose.ts) wraps it with the flush that follows.\n * @internal\n */\nexport function disposeTree(root: Owner): void {\n rt.disposing += 1;\n try {\n let node: Owner = root;\n for (;;) {\n while (node.lastChild !== null) node = node.lastChild;\n const parent: Owner | null = node.parent;\n node.disposeSelf();\n if (node === root || parent === null) break;\n node = parent;\n }\n } finally {\n finishDisposal();\n }\n}\n\n/**\n * Routes `error` to the nearest handler registered with `catchError` or `onError`, searching `from`\n * and then its ancestors, newest handler first on each owner. Handlers run untracked and restore\n * the caller's tracking even when they rethrow. Use it for errors that happen outside\n * any computation (a rejected promise, an event callback), so they reach the same boundary as errors\n * thrown during rendering. A handler that throws hands its own error to the next handler up the\n * chain. With no handler left the error is uncaught: collected until the running flush or disposal\n * ends (which then throws it), or thrown at once otherwise.\n *\n * @param error The thrown value.\n * @param from The owner where the error happened. Null searches no handler: the error is uncaught.\n * @throws The error (or the last error a handler threw) when no handler catches it and no flush or\n * disposal is running.\n * @example\n * import { currentOwner, handleError } from \"@shadow-js/core/extend\";\n *\n * export function useSaveOnLoad(save: () => Promise<void>): void {\n * const owner = currentOwner();\n * save().catch((error: unknown) => handleError(error, owner));\n * }\n * @since 1.0.0\n */\nexport function handleError(error: unknown, from: Owner | null): void {\n if (__DEV__) report(DEVTOOLS_EVENT.ERROR, from, error, codeOf(error));\n let current = error;\n for (let owner = from; owner !== null; owner = owner.parent) {\n const handlers = owner.errorHandlers;\n if (handlers === null) continue;\n for (let i = handlers.length - 1; i >= 0; i -= 1) {\n const handler = handlers[i];\n if (handler === undefined) continue;\n const previousListener = rt.listener;\n try {\n rt.listener = null;\n return void handler(current);\n } catch (next) {\n current = next;\n } finally {\n rt.listener = previousListener;\n }\n }\n }\n reportUncaught(current);\n}\n\n/**\n * True when `handleError(_, from)` would reach a handler registered by catchError()/onError().\n * @internal\n */\nexport function hasErrorHandler(from: Owner | null): boolean {\n for (let owner = from; owner !== null; owner = owner.parent) {\n const handlers = owner.errorHandlers;\n if (handlers !== null && handlers.length > 0) return true;\n }\n return false;\n}\n\n/**\n * The diagnostic code of a ShadowJS error, for devtools. Reads an own data property only: a getter on a thrown\n * value would run user code inside the error path, and a throw there would replace the error being handled.\n */\nfunction codeOf(error: unknown): unknown {\n if (typeof error !== \"object\" || error === null) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(error, \"code\");\n return descriptor !== undefined && \"value\" in descriptor ? descriptor.value : undefined;\n}\n\nfunction reportUncaught(error: unknown): void {\n if (rt.flushing || rt.disposing > 0) rt.uncaught.push(error);\n else throw error;\n}\n"],"mappings":"A,gCA6BA,IAAaA,EAAb,KAAmB,CAEjB,OAEA,UAA0B,KAE1B,YAA4B,KAE5B,YAA4B,KAK5B,SAAuC,KAEvC,QAKA,cAAuC,KAEvC,WAAa,EAEb,QAAU,EAEV,MAEA,MAMA,SAEA,SAAW,GAMX,KAA+B,KAK/B,OAAS,EAOT,YAAY,EAAsB,CAKhC,GAJA,KAAK,OAASC,EACd,KAAK,QAAUA,IAAW,KAAO,KAAOA,EAAO,QAC/C,KAAK,MAAQA,IAAW,KAAO,EAAIA,EAAO,MAAQ,EAClD,KAAK,OAASA,IAAW,KAAO,EAAIA,EAAO,OACvCA,IAAW,KACb,KAAK,MAAQ,MACR,CACL,KAAK,MAAQA,EAAO,WACpB,EAAO,YAAc,EACrB,IAAMC,EAAOD,EAAO,UACpB,KAAK,YAAcC,EACfA,IAAS,OAAM,EAAK,YAAc,MACtC,EAAO,UAAY,IACrB,CAKF,CAGA,gBAAiC,CAEjC,CAGA,SAA0B,CAE1B,CAMA,aAAoB,CAClB,GAAI,KAAK,SAAU,OACnB,KAAK,SAAW,GAEhB,IAAMD,EAAS,KAAK,OACpB,GAAIA,IAAW,KAAM,CACnB,IAAME,EAAO,KAAK,YACZC,EAAO,KAAK,YACdD,IAAS,OAAM,EAAK,YAAcC,GAClCA,IAAS,KACR,EAAO,UAAYD,EADL,EAAK,YAAcA,EAEtC,KAAK,YAAc,KACnB,KAAK,YAAc,IACrB,CACA,KAAK,QAAQ,EACb,KAAK,eAAe,EACpB,KAAK,YAAY,CACnB,CAMA,aAAoB,CAClB,IAAME,EAAW,KAAK,SACtB,GAAIA,IAAa,KAAM,OACvB,KAAK,SAAW,KAChB,IAAMC,EAAgBC,EAAG,MACnBC,EAAmBD,EAAG,SAC5B,EAAG,MAAQ,KACX,EAAG,SAAW,KACd,GAAI,CACF,GAAI,OAAOF,GAAa,WACtBI,EA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X,IAAU,KAAM,EAAQA,EAAM,OAAQ,CAC3D,IAAMY,EAAWZ,EAAM,cACvB,GAAIY,IAAa,KACjB,IAAK,IAAIhB,EAAIgB,EAAS,OAAS,EAAGhB,GAAK,EAAG,IAAQ,CAChD,IAAMiB,EAAUD,EAAShB,GACzB,GAAIiB,IAAY,IAAA,GAAW,SAC3B,IAAMnB,EAAmBD,EAAG,SAC5B,GAAI,CACF,EAAG,SAAW,KACPoB,EAAaH,CAAO,EAA3B,MACF,OAASpB,EAAM,CACb,EAAUA,CACZ,QAAU,CACR,EAAG,SAAWI,CAChB,CACF,CACF,CACAoB,EAAeJ,CAAO,CACxB,CAMA,SAAgBK,EAAgB,EAA6B,CAC3D,IAAK,IAAIf,EAAQW,EAAMX,IAAU,KAAM,EAAQA,EAAM,OAAQ,CAC3D,IAAMY,EAAWZ,EAAM,cACvB,GAAIY,IAAa,MAAQA,EAAS,OAAS,EAAG,MAAO,EACvD,CACA,MAAO,EACT,CAYA,SAASE,EAAe,EAAsB,CAC5C,GAAIrB,EAAG,UAAYA,EAAG,UAAY,EAAGA,EAAG,SAAS,KAAKK,CAAK,OACtD,MAAMA,CACb,C"}
1
+ {"version":3,"file":"owner.js","names":["Owner","parent","last","prev","next","cleanups","previousOwner","rt","previousListener","runCleanup","i","finishDisposal","cleanup","error","handleError","owner","addCleanup","existing","disposeChildren","child","disposeTree","errors","node","root","current","from","handlers","handler","reportUncaught","hasErrorHandler"],"sources":["../../../src/internal/owner.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { rt } from \"./state\";\nimport type { Cleanup, ErrorHandler } from \"./types\";\n\n/**\n * The context values an owner sees, keyed by the symbol of each context. A provider creates a map\n * whose prototype is its parent's map, so a lookup is one property read and never walks owners.\n * @since 1.0.0\n */\nexport type ContextMap = Record<symbol, unknown>;\n\n/**\n * A node in the ownership tree: it owns the effects, memos and owners created under it, their\n * cleanups and error handlers, and disposes them together. Create one with `createOwner` and end it\n * with `disposeOwner`; the class is exported for `instanceof` checks and for reading its state.\n * Computations (`ComputationNode`) are owners too. Children are a doubly linked list so detaching one\n * is O(1); disposal walks the tree iteratively because its depth is user controlled (R-CODE-11).\n *\n * @example\n * import { createOwner, disposeOwner, Owner } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * console.log(owner instanceof Owner, owner.depth); // true 0\n * disposeOwner(owner);\n * console.log(owner.disposed); // true\n * @see createOwner\n * @see disposeOwner\n * @since 1.0.0\n */\nexport class Owner {\n // Fields the constructor assigns are `declare`d: a plain field would also emit an empty initializer\n // (`parent;`) that every bundle carries.\n /** The owner this node was created under, or null for a root. Kept after disposal. */\n declare parent: Owner | null;\n /** The newest child that is still alive, or null when there is none. */\n lastChild: Owner | null = null;\n /** The next older sibling that is still alive, or null. */\n prevSibling: Owner | null = null;\n /** The next newer sibling that is still alive, or null. */\n nextSibling: Owner | null = null;\n /**\n * The cleanups registered with `addCleanup` or `onCleanup`: null for none, a function for one, an\n * array (oldest first) for several. Emptied when they run.\n */\n cleanups: Cleanup | Cleanup[] | null = null;\n /** The context values this node sees: inherited from the parent at creation, null for a root. */\n declare context: ContextMap | null;\n /**\n * The handlers registered with `onError` or `catchError`, oldest first (they are tried newest\n * first), or null for none. A computation clears them before each run.\n */\n errorHandlers: ErrorHandler[] | null = null;\n /** Number of children ever created; gives each child a stable index for useId(). */\n childCount = 0;\n /** Number of ids useId() has handed out from this owner. */\n idCount = 0;\n /** Position among the parent's children, assigned at creation. */\n declare index: number;\n /** Distance from the root: 0 for a root, the parent's depth plus one otherwise. */\n declare depth: number;\n /**\n * The hydration-scope prefix of a component's owner, set by the renderer. When present, useId()\n * builds the ids below it from this prefix instead of the owner path.\n * @default undefined\n */\n // A real field, not `declare`d: the renderer sets it only on component owners, and an owner shape that\n // already holds it keeps every owner on one hidden class.\n idPrefix: string | undefined;\n /** True once the node has been disposed. */\n disposed = false;\n /**\n * While this returns true, user effects (and `onMount`) created below this owner wait: they do\n * not run until it returns false for the first time. Suspense sets it so the effects of content\n * that is still loading are held back. The read is tracked. A node starts with the gate of its\n * parent, so the nearest gate is the one on the owner an effect is created under.\n */\n gate: (() => boolean) | null = null;\n /**\n * Number of pauses (Activity hidden) that cover this node. Inherited at creation, and changed for a\n * whole subtree by `pauseOwner`/`resumeOwner`. Above zero, effects wait and memos keep their value.\n */\n pauses = 0;\n\n /**\n * Creates an owner and links it as the newest child of `parent`. It inherits the parent's context\n * and pauses.\n * @param parent The owner to attach to, or null for a root.\n */\n constructor(parent: Owner | null) {\n this.parent = parent;\n if (parent === null) {\n this.context = null;\n this.depth = this.index = 0;\n } else {\n this.context = parent.context;\n this.depth = parent.depth + 1;\n this.pauses = parent.pauses;\n // The nearest gate above, copied: a boundary sets its own gate before it creates what lives below it.\n this.gate = parent.gate;\n this.index = parent.childCount;\n parent.childCount += 1;\n const last = parent.lastChild;\n this.prevSibling = last;\n if (last !== null) last.nextSibling = this;\n parent.lastChild = this;\n }\n // Computations report themselves (with their kind); plain owners and subclasses of it here.\n if (__DEV__ && new.target === Owner) {\n report(DEVTOOLS_EVENT.OWNER_CREATED, this, parent, parent === null ? \"root\" : \"owner\");\n }\n }\n\n /**\n * Hook for subclasses: release graph edges before the node is marked disposed. Declared, not\n * defined: a plain owner holds no graph edges, and an empty method would ship in every bundle.\n */\n protected release?(): void;\n\n /**\n * Disposes this node only (children must already be gone).\n * @internal\n */\n disposeSelf(): void {\n if (this.disposed) return;\n this.disposed = true;\n // Detach first: a cleanup that throws must never leave a dead node in the tree (R-CODE-5).\n const parent = this.parent;\n if (parent !== null) {\n const prev = this.prevSibling;\n const next = this.nextSibling;\n if (prev !== null) prev.nextSibling = next;\n if (next !== null) next.prevSibling = prev;\n else parent.lastChild = prev;\n this.prevSibling = null;\n this.nextSibling = null;\n }\n this.release?.();\n // A computation reports itself with its own event (it is the only subclass, and only it has a kind).\n if (__DEV__) {\n report(\n \"kind\" in this ? DEVTOOLS_EVENT.COMPUTATION_DISPOSED : DEVTOOLS_EVENT.OWNER_DISPOSED,\n this,\n );\n }\n this.runCleanups();\n }\n\n /**\n * Runs own cleanups newest first, untracked, isolating failures: every cleanup runs, and the errors\n * nobody handled are thrown together afterward, unless a flush or an outer disposal collects them.\n * @internal\n */\n runCleanups(): void {\n const cleanups = this.cleanups;\n if (cleanups === null) return;\n this.cleanups = null;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = null;\n rt.listener = null;\n // Counted as a disposal: an unhandled error is held until the last cleanup ran (a throw would skip\n // the older ones), and a signal write is no WRITE_IN_MEMO violation (as in disposeTree).\n rt.disposing += 1;\n try {\n if (typeof cleanups === \"function\") {\n runCleanup(cleanups, this);\n } else {\n for (let i = cleanups.length - 1; i >= 0; i -= 1) {\n runCleanup(cleanups[i] as Cleanup, this);\n }\n }\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n finishDisposal();\n }\n }\n}\n\nfunction runCleanup(cleanup: Cleanup, owner: Owner): void {\n try {\n cleanup();\n } catch (error) {\n handleError(error, owner);\n }\n}\n\n/**\n * Registers `cleanup` on an explicit owner. It runs when the owner is disposed or, when the owner is a\n * computation, before its next run. Cleanups run newest first, untracked and with no current owner;\n * one that throws goes to {@link handleError} for that owner and does not stop the others. Use it\n * where `onCleanup` cannot be called: the owner is not the current one, or the code must not warn.\n * Unlike `onCleanup`, nothing checks that the owner is still alive: a cleanup added to a disposed\n * owner never runs.\n *\n * @param owner The owner whose disposal runs the cleanup.\n * @param cleanup The function to run.\n * @example\n * import { addCleanup, currentOwner } from \"@shadow-js/core/extend\";\n *\n * export function useInterval(tick: () => void, ms: number): void {\n * const owner = currentOwner();\n * const timer = setInterval(tick, ms);\n * if (owner !== null) addCleanup(owner, () => clearInterval(timer));\n * }\n * @see disposeOwner\n * @since 1.0.0\n */\nexport function addCleanup(owner: Owner, cleanup: Cleanup): void {\n const existing = owner.cleanups;\n if (existing === null) owner.cleanups = cleanup;\n else if (typeof existing === \"function\") owner.cleanups = [existing, cleanup];\n else existing.push(cleanup);\n}\n\n/**\n * Disposes every child of `owner` (newest first), keeping `owner` itself alive.\n * @internal\n */\nexport function disposeChildren(owner: Owner): void {\n for (;;) {\n const child = owner.lastChild;\n if (child === null) return;\n disposeTree(child);\n }\n}\n\n/**\n * Rethrows what disposal collected once the outermost disposal is finished.\n * @internal\n */\nexport function finishDisposal(): void {\n rt.disposing -= 1;\n if (rt.disposing > 0 || rt.flushing || rt.uncaught.length === 0) return;\n const errors = rt.uncaught;\n rt.uncaught = [];\n if (errors.length === 1) throw errors[0];\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while disposing.\" : \"SHADOW_DISPOSE_ERRORS\",\n );\n}\n\n/**\n * Disposes `root` and everything below it: children first, then own cleanups, newest first.\n * Iterative post-order walk: a leaf is disposed, which re-links its parent's `lastChild`\n * to the previous sibling, so the loop naturally visits the remaining subtree. The public\n * `disposeOwner` (dispose.ts) wraps it with the flush that follows.\n * @internal\n */\nexport function disposeTree(root: Owner): void {\n rt.disposing += 1;\n try {\n let node: Owner = root;\n for (;;) {\n while (node.lastChild !== null) node = node.lastChild;\n const parent: Owner | null = node.parent;\n node.disposeSelf();\n if (node === root || parent === null) break;\n node = parent;\n }\n } finally {\n finishDisposal();\n }\n}\n\n/**\n * Routes `error` to the nearest handler registered with `catchError` or `onError`, searching `from`\n * and then its ancestors, newest handler first on each owner. Handlers run untracked and restore\n * the caller's tracking even when they rethrow. Use it for errors that happen outside\n * any computation (a rejected promise, an event callback), so they reach the same boundary as errors\n * thrown during rendering. A handler that throws hands its own error to the next handler up the\n * chain. With no handler left the error is uncaught: collected until the running flush or disposal\n * ends (which then throws it), or thrown at once otherwise.\n *\n * @param error The thrown value.\n * @param from The owner where the error happened. Null searches no handler: the error is uncaught.\n * @throws The error (or the last error a handler threw) when no handler catches it and no flush or\n * disposal is running.\n * @example\n * import { currentOwner, handleError } from \"@shadow-js/core/extend\";\n *\n * export function useSaveOnLoad(save: () => Promise<void>): void {\n * const owner = currentOwner();\n * save().catch((error: unknown) => handleError(error, owner));\n * }\n * @since 1.0.0\n */\nexport function handleError(error: unknown, from: Owner | null): void {\n if (__DEV__) report(DEVTOOLS_EVENT.ERROR, from, error, codeOf(error));\n let current = error;\n for (let owner = from; owner !== null; owner = owner.parent) {\n const handlers = owner.errorHandlers;\n if (handlers === null) continue;\n for (let i = handlers.length - 1; i >= 0; i -= 1) {\n const handler = handlers[i] as ErrorHandler;\n const previousListener = rt.listener;\n try {\n rt.listener = null;\n return void handler(current);\n } catch (next) {\n current = next;\n } finally {\n rt.listener = previousListener;\n }\n }\n }\n reportUncaught(current);\n}\n\n/**\n * True when `handleError(_, from)` would reach a handler registered by catchError()/onError().\n * @internal\n */\nexport function hasErrorHandler(from: Owner | null): boolean {\n for (let owner = from; owner !== null; owner = owner.parent) {\n const handlers = owner.errorHandlers;\n if (handlers !== null && handlers.length > 0) return true;\n }\n return false;\n}\n\n/**\n * The diagnostic code of a ShadowJS error, for devtools. Reads an own data property only: a getter on a thrown\n * value would run user code inside the error path, and a throw there would replace the error being handled.\n */\nfunction codeOf(error: unknown): unknown {\n if (typeof error !== \"object\" || error === null) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(error, \"code\");\n return descriptor !== undefined && \"value\" in descriptor ? descriptor.value : undefined;\n}\n\nfunction reportUncaught(error: unknown): void {\n if (rt.flushing || rt.disposing > 0) rt.uncaught.push(error);\n else throw error;\n}\n"],"mappings":"A,gCA6BA,IAAaA,EAAb,KAAmB,CAMjB,UAA0B,KAE1B,YAA4B,KAE5B,YAA4B,KAK5B,SAAuC,KAOvC,cAAuC,KAEvC,WAAa,EAEb,QAAU,EAYV,SAEA,SAAW,GAOX,KAA+B,KAK/B,OAAS,EAOT,YAAY,EAAsB,CAEhC,GADA,KAAK,OAASC,EACVA,IAAW,KACb,KAAK,QAAU,KACf,KAAK,MAAQ,KAAK,MAAQ,MACrB,CACL,KAAK,QAAUA,EAAO,QACtB,KAAK,MAAQA,EAAO,MAAQ,EAC5B,KA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EACvD,CACA,MAAO,EACT,CAYA,SAASE,EAAe,EAAsB,CAC5C,GAAIrB,EAAG,UAAYA,EAAG,UAAY,EAAGA,EAAG,SAAS,KAAKM,CAAK,OACtD,MAAMA,CACb,C"}
@@ -1,2 +1,2 @@
1
- import{ShadowError as e}from"./diagnostics.js";import{FLAG_PARKED as t,FLAG_TRANSITION as n}from"./flags.js";import{rt as r}from"./state.js";import{handleError as i}from"./owner.js";import{clearQueues as a,hasPending as o,renderQueue as s,userQueue as c}from"./queue.js";import{recompute as l,updateIfNecessary as u}from"./graph.js";const d=1e3;let f=!1;function p(e,t){return e.depth-t.depth||e.seq-t.seq}function m(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n!==void 0&&r!==void 0&&p(n,r)>0)return!1}return!0}function h(e){let r=e.splice(0,e.length);m(r)||r.sort(p);for(let e of r)if(e.flags&=-3,!(e.flags&4)){if(e.pauses>0)e.flags=e.flags&~n|t;else try{e.state===2?l(e):u(e)}catch(t){i(t,e)}}return r.length}function g(e){let[t]=e;throw e.length===1?t:AggregateError(e,`SHADOW_FLUSH_ERRORS`)}function _(){if(r.flushing)return;r.flushing=!0;let t=0,n=0;try{for(;o();){let i=!1;for(;s.length>0;){if(t+=1,t>1e3){i=!0;break}n+=h(s)}if(!i&&c.length>0&&(t+=1,t>1e3?i=!0:n+=h(c)),i){a(),r.uncaught.push(new e(`INFINITE_LOOP`));break}}}finally{r.flushing=!1}let i=r.uncaught;i.length>0&&(r.uncaught=[],g(i))}function v(e){typeof reportError==`function`?reportError(e):queueMicrotask(()=>Promise.reject(e))}function y(){if(f=!1,o())try{_()}catch(e){v(e)}}function b(){r.inTransition||r.batchDepth>0||r.flushing||f||(f=!0,queueMicrotask(y))}function x(e){r.batchDepth+=1;try{return e()}finally{--r.batchDepth,r.batchDepth===0&&o()&&b()}}function S(e,t){return AggregateError([e,t],`SHADOW_BATCH_ERRORS`)}function C(e){r.batchDepth+=1;let t,n,i=!1;try{t=e()}catch(e){i=!0,n=e}finally{--r.batchDepth}if(r.batchDepth===0&&!r.flushing&&o())try{_()}catch(e){throw i?S(n,e):e}if(i)throw n;return t}function w(e){if(r.flushing)return e===void 0?void 0:e();r.batchDepth+=1;let t,n,i=!1;try{t=e===void 0?void 0:e()}catch(e){i=!0,n=e}finally{--r.batchDepth}try{_()}catch(e){throw i?S(n,e):e}if(i)throw n;return t}export{d as MAX_FLUSH_PASSES,C as batch,p as byCreation,_ as flush,w as flushSync,x as group,m as isOrdered,v as reportUncaught,b as schedule};
1
+ import{ShadowError as e}from"./diagnostics.js";import{FLAG_PARKED as t,FLAG_TRANSITION as n}from"./flags.js";import{rt as r}from"./state.js";import{handleError as i}from"./owner.js";import{clearQueues as a,hasPending as o,renderQueue as s,userQueue as c}from"./queue.js";import{recompute as l,refreshAncestors as u,updateIfNecessary as d}from"./graph.js";const f=1e3;let p=!1;function m(e,t){return e.depth-t.depth||e.seq-t.seq}function h(e){try{if(!u(e))return;e.state===2?l(e):d(e)}catch(t){i(t,e)}}function g(e){let r=e.splice(0,e.length);r.sort(m);for(let e of r)e.flags&=-3,!(e.flags&4)&&(e.pauses>0?e.flags=e.flags&~n|t:h(e));return r.length}function _(e){let[t]=e;throw e.length===1?t:AggregateError(e,`SHADOW_FLUSH_ERRORS`)}function v(){if(r.flushing)return;r.flushing=!0;let t=0,n=0;try{for(;o();){if(t+=1,t>1e3){a(),r.uncaught.push(new e(`INFINITE_LOOP`));break}n+=g(s.length>0?s:c)}}finally{r.flushing=!1}let i=r.uncaught;i.length>0&&(r.uncaught=[],_(i))}function y(e){typeof reportError==`function`?reportError(e):queueMicrotask(()=>Promise.reject(e))}function b(){if(p=!1,o())try{v()}catch(e){y(e)}}function x(){r.inTransition||r.batchDepth>0||r.flushing||p||(p=!0,queueMicrotask(b))}function S(e){r.batchDepth+=1;try{return e()}finally{--r.batchDepth,r.batchDepth===0&&o()&&x()}}function C(e,t){r.batchDepth+=1;let n,i,a=!1;try{n=e===void 0?void 0:e()}catch(e){a=!0,i=e}finally{--r.batchDepth}if(t||r.batchDepth===0&&!r.flushing&&o())try{v()}catch(e){throw a?AggregateError([i,e],`SHADOW_BATCH_ERRORS`):e}if(a)throw i;return n}function w(e){return C(e,!1)}function T(e){return r.flushing?e===void 0?void 0:e():C(e,!0)}export{f as MAX_FLUSH_PASSES,w as batch,m as byCreation,v as flush,T as flushSync,S as group,y as reportUncaught,h as runQueued,x as schedule};
2
2
  //# sourceMappingURL=scheduler.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"scheduler.js","names":["MAX_FLUSH_PASSES","microtaskScheduled","byCreation","a","b","isOrdered","i","list","previous","current","drain","batch","queue","effect","FLAG_TRANSITION","FLAG_PARKED","recompute","updateIfNecessary","error","handleError","raise","first","errors","flush","rt","passes","runs","hasPending","aborted","renderQueue","userQueue","clearQueues","ShadowError","reportUncaught","runScheduled","schedule","group","fn","combine","primary","secondary","result","failure","failed","flushSync"],"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":"A,6UAaA,MAAaA,EAAmB,IAEhC,IAAIC,EAAqB,GAMzB,SAAgBC,EAAW,EAAgB,EAAwB,CACjE,OAAOC,EAAE,MAAQC,EAAE,OAASD,EAAE,IAAMC,EAAE,GACxC,CAMA,SAAgBC,EAAU,EAAuC,CAC/D,IAAK,IAAIC,EAAI,EAAGA,EAAIC,EAAK,OAAQ,G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O,IAAA,GAAY,IAAA,GAAYA,EAAG,CAC7C,OAASnB,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,QAAU,CACR,IAAG,UACL,CACA,GAAI,CACFK,EAAM,CACR,OAASL,EAAO,CAEd,MADIyB,EAAcL,EAAQI,EAASxB,CAAK,EAClCA,CACR,CACA,GAAIyB,EAAQ,MAAMD,EAClB,OAAOD,CACT,C"}
1
+ {"version":3,"file":"scheduler.js","names":["MAX_FLUSH_PASSES","microtaskScheduled","byCreation","a","b","runQueued","refreshAncestors","effect","recompute","updateIfNecessary","error","handleError","drain","batch","queue","FLAG_TRANSITION","FLAG_PARKED","raise","first","errors","flush","rt","passes","runs","hasPending","clearQueues","ShadowError","renderQueue","userQueue","reportUncaught","runScheduled","schedule","group","fn","runBatched","result","failure","failed","sync","flushSync"],"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, refreshAncestors, 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 * Runs one queued effect. Its stale owners come first: an owner that is about to re-run disposes the\n * effect, and running it before (a zombie, G-17) would read state that is already out of date.\n * @internal\n */\nexport function runQueued(effect: Computation): void {\n try {\n if (!refreshAncestors(effect)) return;\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\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 runQueued(effect);\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":"A,mWAaA,MAAaA,EAAmB,IAEhC,IAAIC,EAAqB,GAMzB,SAAgBC,EAAW,EAAgB,EAAwB,CACjE,OAAOC,EAAE,MAAQC,EAAE,OAASD,EAAE,IAAMC,EAAE,GACxC,CAOA,SAAgBC,EAAU,EAA2B,CACnD,GAAI,CACF,GAAI,CAACC,EAAiBC,CAAM,EAAG,OAE3BA,EAAO,QAAA,EAAiBC,EAAUD,CAAM,EACvCE,EAAkBF,CAAM,CAC/B,OAASG,EAAO,CACdC,EAAYD,EAAOH,CAAM,CAC3B,CACF,CAGA,SAASK,EAAM,EAA8B,CAC3C,IAAMC,EAAQC,EAAM,OAAO,EAAGA,EAAM,MAAM,EAE1CD,EAAM,KAAK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pD,CACF,CAOA,SAASG,EAAc,EAA2B,EAAkB,CAClE,EAAG,YAAc,EACjB,IAAIC,EACAC,EACAC,EAAS,GACb,GAAI,CACF,EAASJ,IAAO,IAAA,GAAY,IAAA,GAAYA,EAAG,CAC7C,OAASvB,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,QAAU,CACR,IAAG,UACL,CACA,GAAI4B,GAASjB,EAAG,aAAe,GAAK,CAACA,EAAG,UAAYG,EAAW,EAC7D,GAAI,CACFJ,EAAM,CACR,OAASV,EAAO,CAOd,MANI2B,EACQ,eACR,CAACD,EAAS1B,CAAK,EACsC,qBACvD,EAEIA,CACR,CAEF,GAAI2B,EAAQ,MAAMD,EAClB,OAAOD,CACT,CAwBA,SAAgBtB,EAAS,EAAgB,CACvC,OAAOqB,EAAWD,EAAI,EAAK,CAC7B,CAyBA,SAAgBM,EAAoB,EAAiB,CAKnD,OAJIlB,EAAG,SAEGY,IAAO,IAAA,GAAY,IAAA,GAAYA,EAAG,EAErCC,EAAWD,EAAI,EAAI,CAC5B,C"}
@@ -1,2 +1,2 @@
1
- import"./internal/diagnostics.js";import{Owner as e}from"./internal/owner.js";import{readSignal as t}from"./internal/graph.js";import{createRoot as n,getOwner as r,onCleanup as i,runWithOwner as a,untrack as o}from"./ownership.js";import{disposeTree as s}from"./internal/dispose.js";import{createSignalNode as c,writeSignal as l}from"./extend/index.js";import{useMemo as u}from"./memo.js";var d=class{key;first;item;index;value=void 0;dispose=f;itemNode=null;indexNode=null;constructor(e,t,n,r){this.key=e,this.first=t,this.item=n,this.index=r}readItem(){return this.itemNode??=c(this.item,Object.is),t(this.itemNode)}readIndex(){return this.indexNode??=c(this.index,Object.is),t(this.indexNode)}setItem(e){this.item=e,this.itemNode!==null&&l(this.itemNode,e,{allowInMemo:!0})}setIndex(e){this.index=e,this.indexNode!==null&&l(this.indexNode,e,{allowInMemo:!0})}};function f(){}function p(e,t,n){let r=n?.key;return h(e,r===void 0?{keyOf:e=>e,distinct:!1}:{keyOf:e=>r(e),distinct:!0},(e,n,i)=>t(r===void 0?e:n,i),n?.fallback)}function m(e,t,n){return h(e,{keyOf:(e,t)=>t,distinct:!1},(e,n,r)=>t(n,o(r)),n?.fallback)}function h(t,n,a,c){let l=new e(r());i(()=>{s(l)});let d=[],f;return u(()=>{let e=g(t()),r=Array.isArray(e)?Array.prototype.slice.call(e):e,i=o(()=>_(r,n)),s=b(d,i),u=[],p=[],m;try{i.forEach((e,t)=>{let n=s[t]??-1,r=n===-1?void 0:d[n];if(r!==void 0){p.push({row:r,item:e.item,position:t,fresh:!1});return}let i=x(l,e.key,e.first,e.item,t,a);u.push(i),p.push({row:i,item:e.item,position:t,fresh:!0})}),i.length===0&&c!==void 0&&(m=f??S(l,c))}catch(e){let t=[];for(let e of u)C(e.dispose,t);throw m!==void 0&&m!==f&&C(m.dispose,t),w(e,t)}let h=[],v=d,y=f;d=p.map(e=>e.row),f=m;let E=new Uint8Array(v.length);for(let e of s)e!==-1&&(E[e]=1);v.forEach((e,t)=>{E[t]!==1&&C(e.dispose,h)}),y!==void 0&&y!==m&&C(y.dispose,h);for(let e of p){if(e.fresh)continue;let t=e.row;t.index!==e.position&&t.setIndex(e.position),Object.is(t.item,e.item)||t.setItem(e.item)}return T(h),m===void 0?d.map(e=>e.value):[m.value]},{lazy:!0,allowWrites:!0})}function g(e){return e==null||e===!1?[]:e}function _(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let[i,a]of e.entries()){let e=t.keyOf(a,i),o=!0;t.distinct&&(r.has(e)?o=!1:r.add(e)),n.push({item:a,key:e,first:o})}return n}function v(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function y(e,t){return e!==void 0&&t!==void 0&&e.first&&t.first&&v(e.key,t.key)}function b(e,t){let n=e.length,r=t.length,i=new Int32Array(r).fill(-1),a=0;for(;a<n&&a<r&&y(e[a],t[a]);)i[a]=a,a+=1;let o=n-1,s=r-1;for(;o>=a&&s>=a&&y(e[o],t[s]);)i[s]=o,--o,--s;if(a>o||a>s)return i;let c=/* @__PURE__ */ new Map,l=new Int32Array(n).fill(-1);for(let t=o;t>=a;--t){let n=e[t];n!==void 0&&n.first&&(l[t]=c.get(n.key)??-1,c.set(n.key,t))}for(let e=a;e<=s;e+=1){let n=t[e];if(n===void 0||!n.first)continue;let r=c.get(n.key);r!==void 0&&r!==-1&&(i[e]=r,c.set(n.key,l[r]??-1))}return i}function x(e,t,r,i,s,c){let l=new d(t,r,i,s),u=()=>l.readItem(),f=()=>l.readIndex();return a(e,()=>n(e=>{l.dispose=e,l.value=o(()=>c(i,u,f))})),l}function S(e,t){return a(e,()=>n(e=>({value:o(t),dispose:e})))}function C(e,t){try{e()}catch(e){t.push(e)}}function w(e,t){return t.length===0?e:AggregateError([e,...t],`SHADOW_MAP_ERRORS`)}function T(e){if(e.length!==0)throw e.length===1?e[0]:AggregateError(e,`SHADOW_LIST_DISPOSE_ERRORS`)}export{m as indexArray,p as mapArray};
1
+ import"./internal/diagnostics.js";import{Owner as e}from"./internal/owner.js";import{Signal as t,readSignal as n}from"./internal/graph.js";import{createRoot as r,getOwner as i,onCleanup as a,runWithOwner as o,untrack as s}from"./ownership.js";import{disposeTree as c}from"./internal/dispose.js";import{writeSignal as l}from"./extend/index.js";import{useMemo as u}from"./memo.js";var d=class{value=void 0;dispose=f;itemNode=null;indexNode=null;constructor(e,t,n,r){this.key=e,this.first=t,this.item=n,this.index=r}readItem(){return this.itemNode??=new t(this.item,Object.is),n(this.itemNode)}readIndex(){return this.indexNode??=new t(this.index,Object.is),n(this.indexNode)}setItem(e){this.item=e,this.itemNode!==null&&l(this.itemNode,e,{allowInMemo:!0})}setIndex(e){this.index=e,this.indexNode!==null&&l(this.indexNode,e,{allowInMemo:!0})}};function f(){}function p(e,t,n){let r=n?.key;return h(e,r===void 0?{keyOf:e=>e,distinct:!1}:{keyOf:e=>r(e),distinct:!0},(e,n,i)=>t(r===void 0?e:n,i),n?.fallback)}function m(e,t,n){return h(e,{keyOf:(e,t)=>t,distinct:!1},(e,n,r)=>t(n,s(r)),n?.fallback)}function h(t,n,r,o){let l=new e(i());a(()=>{c(l)});let d=[],f;return u(()=>{let e=g(t()),i=Array.isArray(e)?Array.prototype.slice.call(e):e,a=s(()=>_(i,n)),c=b(d,a),u=[],p=[],m;try{a.forEach((e,t)=>{let n=c[t]??-1,i=n===-1?void 0:d[n];if(i!==void 0){p.push({row:i,item:e.item,position:t,fresh:!1});return}let a=x(l,e.key,e.first,e.item,t,r);u.push(a),p.push({row:a,item:e.item,position:t,fresh:!0})}),a.length===0&&o!==void 0&&(m=f??S(l,o))}catch(e){let t=[];for(let e of u)C(e.dispose,t);throw m!==void 0&&m!==f&&C(m.dispose,t),w(e,t)}let h=[],v=d,y=f;d=p.map(e=>e.row),f=m;let E=new Uint8Array(v.length);for(let e of c)e!==-1&&(E[e]=1);v.forEach((e,t)=>{E[t]!==1&&C(e.dispose,h)}),y!==void 0&&y!==m&&C(y.dispose,h);for(let e of p){if(e.fresh)continue;let t=e.row;t.index!==e.position&&t.setIndex(e.position),Object.is(t.item,e.item)||t.setItem(e.item)}return T(h),m===void 0?d.map(e=>e.value):[m.value]},{lazy:!0,allowWrites:!0})}function g(e){return e==null||e===!1?[]:e}function _(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let[i,a]of e.entries()){let e=t.keyOf(a,i),o=!0;t.distinct&&(r.has(e)?o=!1:r.add(e)),n.push({item:a,key:e,first:o})}return n}function v(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function y(e,t){return e!==void 0&&t!==void 0&&e.first&&t.first&&v(e.key,t.key)}function b(e,t){let n=e.length,r=t.length,i=new Int32Array(r).fill(-1),a=0;for(;a<n&&a<r&&y(e[a],t[a]);)i[a]=a,a+=1;let o=n-1,s=r-1;for(;o>=a&&s>=a&&y(e[o],t[s]);)i[s]=o,--o,--s;if(a>o||a>s)return i;let c=/* @__PURE__ */ new Map,l=new Int32Array(n).fill(-1);for(let t=o;t>=a;--t){let n=e[t];n!==void 0&&n.first&&(l[t]=c.get(n.key)??-1,c.set(n.key,t))}for(let e=a;e<=s;e+=1){let n=t[e];if(n===void 0||!n.first)continue;let r=c.get(n.key);r!==void 0&&r!==-1&&(i[e]=r,c.set(n.key,l[r]??-1))}return i}function x(e,t,n,i,a,c){let l=new d(t,n,i,a),u=()=>l.readItem(),f=()=>l.readIndex();return o(e,()=>r(e=>{l.dispose=e,l.value=s(()=>c(i,u,f))})),l}function S(e,t){return o(e,()=>r(e=>({value:s(t),dispose:e})))}function C(e,t){try{e()}catch(e){t.push(e)}}function w(e,t){return t.length===0?e:AggregateError([e,...t],`SHADOW_MAP_ERRORS`)}function T(e){if(e.length!==0)throw e.length===1?e[0]:AggregateError(e,`SHADOW_LIST_DISPOSE_ERRORS`)}export{m as indexArray,p as mapArray};
2
2
  //# sourceMappingURL=list.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"list.js","names":["Row","noop","key","first","item","index","createSignalNode","readSignal","next","writeSignal","mapArray","keyOf","options","listRows","list","map","readItem","readIndex","indexArray","position","untrack","holder","Owner","getOwner","onCleanup","disposeTree","rows","emptyFallback","useMemo","source","listItems","items","entries","toEntries","keying","reuse","matchRows","created","staged","nextFallback","from","kept","entry","row","openRow","build","fallback","openFallback","error","failures","disposeCollecting","combineFailures","previousRows","previousFallback","stage","throwFailures","value","seen","sameKey","a","b","canReuse","m","old","n","start","oldEnd","newEnd","heads","chain","i","j","head","runWithOwner","createRoot","dispose","primary"],"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":"A,qYAuBA,IAAMA,EAAN,KAAgB,CAEd,IAEA,MAEA,KAEA,MACA,MAAW,IAAA,GACX,QAAsBC,EAEtB,SAAyC,KAEzC,UAA+C,KAE/C,YAAY,EAAc,EAAgB,EAAS,EAAe,CAChE,KAAK,IAAMC,EACX,KAAK,MAAQC,EACb,KAAK,KAAOC,EACZ,KAAK,MAAQC,CACf,CAEA,UAAc,CAEZ,MADA,MAAK,WAAaC,EAAiB,KAAK,KAAM,OAAO,EAAE,EAChDC,EAAW,KAAK,QAAQ,CACjC,CAEA,WAAoB,CAElB,MADA,MAAK,YAAcD,EAAiB,KAAK,MAAO,OAAO,EAAE,EAClDC,EAAW,KAAK,SAAS,CAClC,CAGA,QAAQ,EAAe,CACrB,KAAK,KAAOC,EACR,KAAK,WAAa,MAAMC,EAAY,KAAK,SAAUD,EAAM,CAAE,YAAa,EAAK,CAAC,CACpF,CAEA,SAAS,EAAoB,CAC3B,KAAK,MAAQA,EACT,KAAK,YAAc,MAAMC,EAAY,KAAK,UAAWD,EAAM,CAAE,YAAa,EAAK,CAAC,CACtF,CACF,EAGA,SAASP,GAAa,CAEtB,CA6FA,SAAg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EACvB,eACT,CAACA,EAAS,GAAG3B,CAAQ,EAC0C,mBACjE,CACF,CAGA,SAASM,EAAc,EAAoC,CACzD,GAAIN,EAAS,SAAW,EAExB,MADIA,EAAS,SAAW,EAASA,EAAS,GAChC,eACRA,EAGI,4BACN,CACF,C"}
1
+ {"version":3,"file":"list.js","names":["SignalNode","Row","noop","key","first","item","index","Signal","readSignal","next","writeSignal","mapArray","keyOf","options","listRows","list","map","readItem","readIndex","indexArray","position","untrack","holder","Owner","getOwner","onCleanup","disposeTree","rows","emptyFallback","useMemo","source","listItems","items","entries","toEntries","keying","reuse","matchRows","created","staged","nextFallback","from","kept","entry","row","openRow","build","fallback","openFallback","error","failures","disposeCollecting","combineFailures","previousRows","previousFallback","stage","throwFailures","value","seen","sameKey","a","b","canReuse","m","old","n","start","oldEnd","newEnd","heads","chain","i","j","head","runWithOwner","createRoot","dispose","primary"],"sources":["../../src/list.ts"],"sourcesContent":["import {\n type Accessor,\n disposeOwner,\n Owner,\n readSignal,\n 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 ??= new SignalNode(this.item, Object.is);\n return readSignal(this.itemNode);\n }\n\n readIndex(): number {\n this.indexNode ??= new SignalNode(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":"A,2XAsBA,IAAMC,EAAN,KAAgB,CASd,MAAW,IAAA,GACX,QAAsBC,EAEtB,SAAyC,KAEzC,UAA+C,KAE/C,YAAY,EAAc,EAAgB,EAAS,EAAe,CAChE,KAAK,IAAMC,EACX,KAAK,MAAQC,EACb,KAAK,KAAOC,EACZ,KAAK,MAAQC,CACf,CAEA,UAAc,CAEZ,MADA,MAAK,WAAa,IAAIN,EAAW,KAAK,KAAM,OAAO,EAAE,EAC9CQ,EAAW,KAAK,QAAQ,CACjC,CAEA,WAAoB,CAElB,MADA,MAAK,YAAc,IAAIR,EAAW,KAAK,MAAO,OAAO,EAAE,EAChDQ,EAAW,KAAK,SAAS,CAClC,CAGA,QAAQ,EAAe,CACrB,KAAK,KAAOC,EACR,KAAK,WAAa,MAAMC,EAAY,KAAK,SAAUD,EAAM,CAAE,YAAa,EAAK,CAAC,CACpF,CAEA,SAAS,EAAoB,CAC3B,KAAK,MAAQA,EACT,KAAK,YAAc,MAAMC,EAAY,KAAK,UAAWD,EAAM,CAAE,YAAa,EAAK,CAAC,CACtF,CACF,EAGA,SAASP,GAAa,CAEtB,CA6FA,SAAgBS,EACd,EACA,EACA,EACe,CACf,IAAMC,EAAQC,GAAS,IACvB,OAAOC,EACLC,EACAH,IAAU,IAAA,GACN,CAAE,MAAQ,GAAYP,EAAM,SAAU,EAAM,EAC5C,CAAE,MAAQ,GAAYO,EAAMP,CAAI,EAAG,SAAU,EAAK,GACrD,EAAM,EAAU,IAAcW,EAAIJ,IAAU,IAAA,GAAYP,EAAOY,EAAUC,CAAS,EACnFL,GAAS,QACX,CACF,CAuBA,SAAgBM,EACd,EACA,EACA,EACe,CACf,OAAOL,EACLC,EACA,CAAE,OAAQ,EAAU,IA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,GAAI7B,IAAU,IAAA,IAAa,CAACA,EAAM,MAAO,SACzC,IAAM8B,EAAOJ,EAAM,IAAI1B,EAAM,GAAG,EAC5B8B,IAAS,IAAA,IAAaA,IAAS,KACnC,EAAMD,GAAKC,EACXJ,EAAM,IAAI1B,EAAM,IAAK2B,EAAMG,IAAS,EAAE,EACxC,CACA,OAAOrC,CACT,CAMA,SAASS,EACP,EACA,EACA,EACA,EACA,EACA,EACW,CACX,IAAMD,EAAM,IAAI3C,EAAUE,EAAKC,EAAOC,EAAMC,CAAK,EAC3CW,MAAoB2B,EAAI,SAAS,EACjC1B,MAA0B0B,EAAI,UAAU,EAO9C,OANA8B,EAAapD,MACXqD,EAAY,GAAY,CACtB,EAAI,QAAUC,EACd,EAAI,MAAQvD,MAAcyB,EAAMzC,EAAMY,EAAUC,CAAS,CAAC,CAC5D,CAAC,CACH,EACO0B,CACT,CAGA,SAASI,EAAgB,EAAe,EAAgC,CACtE,OAAO0B,EAAapD,MAClBqD,EAAY,IAAa,CAAE,MAAOtD,EAAQ0B,CAAQ,EAAG,SAAQ,EAAE,CACjE,CACF,CAGA,SAASI,EAAkB,EAAqB,EAA2B,CACzE,GAAI,CACFyB,EAAQ,CACV,OAAS3B,EAAO,CACdC,EAAS,KAAKD,CAAK,CACrB,CACF,CAEA,SAASG,EAAgB,EAAkB,EAAuC,CAEhF,OADIF,EAAS,SAAW,EAAU2B,EACvB,eACT,CAACA,EAAS,GAAG3B,CAAQ,EAC0C,mBACjE,CACF,CAGA,SAASM,EAAc,EAAoC,CACzD,GAAIN,EAAS,SAAW,EAExB,MADIA,EAAS,SAAW,EAASA,EAAS,GAChC,eACRA,EAGI,4BACN,CACF,C"}
@@ -1,2 +1,2 @@
1
- import{createComputation as e,readComputation as t}from"./extend/index.js";function n(n,r){let i=e({kind:`memo`,fn:n,equals:r?.equals===void 0?Object.is:r.equals,lazy:r?.lazy===!0,allowWrites:r?.allowWrites===!0,...r?.name===void 0?{}:{name:r.name}});return()=>t(i)}export{n as useMemo};
1
+ import{createComputation as e,readComputation as t}from"./extend/index.js";function n(n,r){let i=e({kind:`memo`,fn:n,equals:r?.equals,lazy:r?.lazy,allowWrites:r?.allowWrites,name:r?.name});return()=>t(i)}export{n as useMemo};
2
2
  //# sourceMappingURL=memo.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"memo.js","names":["useMemo","node","createComputation","options","readComputation"],"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":"A,2EA0DA,SAAgBA,EACd,EACA,EACa,CACb,IAAMC,EAAOC,EAAkB,CAC7B,KAAM,OACF,KACJ,OAASC,GAAS,SAAW,IAAA,GAAY,OAAO,GAAKA,EAAQ,OAC7D,KAAMA,GAAS,OAAS,GACxB,YAAaA,GAAS,cAAgB,GACtC,GAAIA,GAAS,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAMA,EAAQ,IAAK,CAC9D,CAAC,EACD,UAAaC,EAAmBH,CAAI,CACtC,C"}
1
+ {"version":3,"file":"memo.js","names":["useMemo","node","createComputation","options","readComputation"],"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":"A,2EA2DA,SAAgBA,EACd,EACA,EACa,CACb,IAAMC,EAAOC,EAAkB,CAC7B,KAAM,OACF,KACJ,OAAQC,GAAS,OACjB,KAAMA,GAAS,KACf,YAAaA,GAAS,YACtB,KAAMA,GAAS,IACjB,CAAC,EACD,UAAaC,EAAmBH,CAAI,CACtC,C"}
@@ -1,2 +1,2 @@
1
- import{ShadowError as e}from"./internal/diagnostics.js";import{Owner as t,addCleanup as n,handleError as r}from"./internal/owner.js";import{disposeTree as i}from"./internal/dispose.js";import{currentOwner as a,runInScope as o}from"./extend/index.js";function s(e){return o({listener:null},e)}function c(e,n){let r=n?.detached===!0,s=a(),c=new t(r?null:s);r&&(c.context=s===null?null:s.context);try{return o({owner:c,listener:null},()=>e(()=>i(c)))}catch(e){throw i(c),e}}function l(){return a()}function u(e,t){let n=e;return n?.disposed&&(n=null),o({owner:n,listener:null},t)}function d(e){let t=a();t!==null&&n(t,e)}function f(e){let t=a();t!==null&&(t.errorHandlers===null?t.errorHandlers=[e]:t.errorHandlers.push(e))}function p(e,n){let i=new t(a());i.errorHandlers=[n];try{return u(i,e)}catch(e){r(e,i);return}}function m(){let t=a();if(t===null)throw new e(`NO_OWNER_ID`);for(let e=t;e!==null;e=e.parent){if(e.idPrefix===void 0)continue;let t=e.idCount;return e.idCount+=1,`s${e.idPrefix}${t}`}let n=[];for(let e=t;e!==null;e=e.parent)n.push(e.index);n.reverse();let r=t.idCount;return t.idCount+=1,`s${n.join(`-`)}_${r}`}export{p as catchError,c as createRoot,l as getOwner,d as onCleanup,f as onError,u as runWithOwner,s as untrack,m as useId};
1
+ import{ShadowError as e}from"./internal/diagnostics.js";import{Owner as t,addCleanup as n,handleError as r}from"./internal/owner.js";import{disposeTree as i}from"./internal/dispose.js";import{currentOwner as a,runInScope as o}from"./extend/index.js";function s(e){return o({listener:null},e)}function c(e,n){let r=n?.detached===!0,s=a(),c=new t(r?null:s);r&&(c.context=s===null?null:s.context);try{return o({owner:c,listener:null},()=>e(()=>i(c)))}catch(e){try{i(c)}catch(t){throw AggregateError([e,t],`SHADOW_ROOT_ERRORS`)}throw e}}function l(){return a()}function u(e,t){let n=e;return n?.disposed&&(n=null),o({owner:n,listener:null},t)}function d(e){let t=a();t!==null&&n(t,e)}function f(e){let t=a();t!==null&&(t.errorHandlers===null?t.errorHandlers=[e]:t.errorHandlers.push(e))}function p(e,n){let i=new t(a());i.errorHandlers=[n];try{return u(i,e)}catch(e){r(e,i);return}}function m(){let t=a();if(t===null)throw new e(`NO_OWNER_ID`);for(let e=t;e!==null;e=e.parent){if(e.idPrefix===void 0)continue;let t=e.idCount;return e.idCount+=1,`s${e.idPrefix}${t}`}let n=[];for(let e=t;e!==null;e=e.parent)n.push(e.index);n.reverse();let r=t.idCount;return t.idCount+=1,`s${n.join(`-`)}_${r}`}export{p as catchError,c as createRoot,l as getOwner,d as onCleanup,f as onError,u as runWithOwner,s as untrack,m as useId};
2
2
  //# sourceMappingURL=ownership.js.map