@shadow-js/core 1.1.0 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +2 -0
- package/dist/dev/action.d.ts +1 -2
- package/dist/dev/cache.d.ts +1 -2
- package/dist/dev/context.d.ts +1 -2
- package/dist/dev/effect.d.ts +1 -2
- package/dist/dev/env.d.ts +1 -2
- package/dist/dev/events.d.ts +1 -2
- package/dist/dev/extend/index.d.ts +1 -2
- package/dist/dev/external-store.d.ts +1 -2
- package/dist/dev/internal/concurrency.d.ts +1 -2
- package/dist/dev/internal/devtools.d.ts +1 -2
- package/dist/dev/internal/diagnostics.d.ts +1 -2
- package/dist/dev/internal/dispose.d.ts +1 -2
- package/dist/dev/internal/dispose.js.map +1 -1
- package/dist/dev/internal/graph.d.ts +1 -2
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/hydration-flag.d.ts +1 -2
- package/dist/dev/internal/messages.d.ts +1 -2
- package/dist/dev/internal/owner.d.ts +1 -2
- package/dist/dev/internal/owner.js.map +1 -1
- package/dist/dev/internal/scheduler.d.ts +1 -2
- package/dist/dev/internal/state.d.ts +1 -2
- package/dist/dev/internal/suspension.d.ts +1 -2
- package/dist/dev/internal/types.d.ts +1 -2
- package/dist/dev/list.d.ts +1 -2
- package/dist/dev/list.js.map +1 -1
- package/dist/dev/memo.d.ts +1 -2
- package/dist/dev/optimistic.d.ts +1 -2
- package/dist/dev/ownership.d.ts +1 -2
- package/dist/dev/ownership.js.map +1 -1
- package/dist/dev/props.d.ts +1 -2
- package/dist/dev/reaction.d.ts +1 -2
- package/dist/dev/reaction.js.map +1 -1
- package/dist/dev/reducer.d.ts +1 -2
- package/dist/dev/refs.d.ts +1 -2
- package/dist/dev/resource.d.ts +1 -2
- package/dist/dev/resource.js.map +1 -1
- package/dist/dev/selector.d.ts +1 -2
- package/dist/dev/selector.js.map +1 -1
- package/dist/dev/signal.d.ts +1 -2
- package/dist/dev/store/nodes.js.map +1 -1
- package/dist/dev/store/proxies.js.map +1 -1
- package/dist/dev/store/read.d.ts +1 -2
- package/dist/dev/store/reconcile.d.ts +1 -2
- package/dist/dev/store/types.d.ts +1 -2
- package/dist/dev/store/use-store.d.ts +1 -2
- package/dist/dev/store/use-store.js.map +1 -1
- package/dist/dev/suspense.d.ts +1 -2
- package/dist/dev/transitions.d.ts +1 -2
- package/dist/prod/action.js.map +1 -1
- package/dist/prod/cache.js.map +1 -1
- package/dist/prod/context.js.map +1 -1
- package/dist/prod/effect.js.map +1 -1
- package/dist/prod/events.js.map +1 -1
- package/dist/prod/extend/index.js.map +1 -1
- package/dist/prod/external-store.js.map +1 -1
- package/dist/prod/internal/concurrency.js.map +1 -1
- package/dist/prod/internal/devtools.js.map +1 -1
- package/dist/prod/internal/diagnostics.js.map +1 -1
- package/dist/prod/internal/dispose.js.map +1 -1
- package/dist/prod/internal/graph.js.map +1 -1
- package/dist/prod/internal/hydration-flag.js.map +1 -1
- package/dist/prod/internal/messages.js.map +1 -1
- package/dist/prod/internal/owner.js.map +1 -1
- package/dist/prod/internal/queue.js.map +1 -1
- package/dist/prod/internal/scheduler.js.map +1 -1
- package/dist/prod/internal/state.js.map +1 -1
- package/dist/prod/internal/suspension.js.map +1 -1
- package/dist/prod/list.js.map +1 -1
- package/dist/prod/memo.js.map +1 -1
- package/dist/prod/optimistic.js.map +1 -1
- package/dist/prod/ownership.js.map +1 -1
- package/dist/prod/props.js.map +1 -1
- package/dist/prod/reaction.js.map +1 -1
- package/dist/prod/reducer.js.map +1 -1
- package/dist/prod/refs.js.map +1 -1
- package/dist/prod/resource.js.map +1 -1
- package/dist/prod/selector.js.map +1 -1
- package/dist/prod/signal.js.map +1 -1
- package/dist/prod/store/nodes.js.map +1 -1
- package/dist/prod/store/proxies.js.map +1 -1
- package/dist/prod/store/read.js.map +1 -1
- package/dist/prod/store/reconcile.js.map +1 -1
- package/dist/prod/store/use-store.js.map +1 -1
- package/dist/prod/suspense.js.map +1 -1
- package/dist/prod/transitions.js.map +1 -1
- package/dist/server/action.js.map +1 -1
- package/dist/server/cache.js.map +1 -1
- package/dist/server/context.js.map +1 -1
- package/dist/server/effect.js.map +1 -1
- package/dist/server/events.js.map +1 -1
- package/dist/server/extend/index.js.map +1 -1
- package/dist/server/external-store.js.map +1 -1
- package/dist/server/internal/concurrency.js.map +1 -1
- package/dist/server/internal/devtools.js.map +1 -1
- package/dist/server/internal/diagnostics.js.map +1 -1
- package/dist/server/internal/dispose.js.map +1 -1
- package/dist/server/internal/graph.js.map +1 -1
- package/dist/server/internal/hydration-flag.js.map +1 -1
- package/dist/server/internal/messages.js.map +1 -1
- package/dist/server/internal/owner.js.map +1 -1
- package/dist/server/internal/queue.js.map +1 -1
- package/dist/server/internal/scheduler.js.map +1 -1
- package/dist/server/internal/state.js.map +1 -1
- package/dist/server/internal/suspension.js.map +1 -1
- package/dist/server/list.js.map +1 -1
- package/dist/server/memo.js.map +1 -1
- package/dist/server/optimistic.js.map +1 -1
- package/dist/server/ownership.js.map +1 -1
- package/dist/server/props.js.map +1 -1
- package/dist/server/reaction.js.map +1 -1
- package/dist/server/reducer.js.map +1 -1
- package/dist/server/refs.js.map +1 -1
- package/dist/server/resource.js.map +1 -1
- package/dist/server/selector.js.map +1 -1
- package/dist/server/signal.js.map +1 -1
- package/dist/server/store/nodes.js.map +1 -1
- package/dist/server/store/proxies.js.map +1 -1
- package/dist/server/store/read.js.map +1 -1
- package/dist/server/store/reconcile.js.map +1 -1
- package/dist/server/store/use-store.js.map +1 -1
- package/dist/server/suspense.js.map +1 -1
- package/dist/server/transitions.js.map +1 -1
- package/dist/server-dev/effect.js.map +1 -1
- package/dist/server-dev/internal/dispose.js.map +1 -1
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/owner.js.map +1 -1
- package/dist/server-dev/list.js.map +1 -1
- package/dist/server-dev/ownership.js.map +1 -1
- package/dist/server-dev/reaction.js.map +1 -1
- package/dist/server-dev/resource.js.map +1 -1
- package/dist/server-dev/selector.js.map +1 -1
- package/dist/server-dev/store/nodes.js.map +1 -1
- package/dist/server-dev/store/proxies.js.map +1 -1
- package/dist/server-dev/store/use-store.js.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-store.js","names":["useExternalStore","
|
|
1
|
+
{"version":3,"file":"external-store.js","names":["untrack","useExternalStore","subscribe","getSnapshot","options","snapshot"],"sources":["../../src/external-store.ts"],"sourcesContent":["import { useEffect } from \"./effect\";\nimport type { Accessor, Equals } from \"./extend\";\nimport { isHydrating } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useExternalStore}. @since 1.0.0 */\nexport interface ExternalStoreOptions<T> {\n /**\n * The snapshot the server renders (there is no subscription there). Without it the server reads\n * `getSnapshot` once. Keep it equal to what the browser reads on its first render: a difference is\n * corrected only after subscribing, and no hydration test covers that case yet. While hydrating,\n * the browser's first render also uses it.\n * @default undefined (the server, and hydration, read `getSnapshot`)\n */\n getServerSnapshot?: () => T;\n /**\n * Decides whether a new snapshot is a change: the accessor updates only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\n/**\n * Reads a value that lives outside ShadowJS (a store, a browser API, an observable) as a reactive\n * accessor. The one bridge for every external source, and the ShadowJS form of React's\n * `useSyncExternalStore` and Solid's `from`.\n *\n * `subscribe(notify)` is called in an effect after the owner is created and returns the\n * unsubscribe function, which runs when the owner is disposed. `getSnapshot()` is read untracked\n * at creation, on every notification, and once after subscribing (so a change made between the\n * first read and the subscription is not lost). The accessor updates only when the snapshot differs\n * by `equals`. On the server nothing is subscribed: the accessor returns `getServerSnapshot()`.\n *\n * @param subscribe Registers `notify`; returns the unsubscribe function.\n * @param getSnapshot Returns the current value. Reads inside it are not tracked.\n * @param options Server snapshot, equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the current snapshot.\n * @example\n * import { useExternalStore } from \"@shadow-js/core\";\n *\n * function subscribe(notify: () => void): () => void {\n * window.addEventListener(\"online\", notify);\n * window.addEventListener(\"offline\", notify);\n * return () => {\n * window.removeEventListener(\"online\", notify);\n * window.removeEventListener(\"offline\", notify);\n * };\n * }\n *\n * function OnlineBadge() {\n * const online = useExternalStore(subscribe, () => navigator.onLine, { getServerSnapshot: () => true });\n * return <span>{online() ? \"online\" : \"offline\"}</span>;\n * }\n * @see useSignal\n * @since 1.0.0\n */\nexport function useExternalStore<T>(\n subscribe: (notify: () => void) => () => void,\n getSnapshot: () => T,\n options?: ExternalStoreOptions<T>,\n): Accessor<T> {\n if (__SERVER__) {\n const snapshot = untrack(options?.getServerSnapshot ?? getSnapshot);\n return () => snapshot;\n }\n // While hydrating, the first render must equal the server markup: the server snapshot, when given.\n // The browser's snapshot is applied by the subscription below.\n const first =\n isHydrating() && options?.getServerSnapshot !== undefined\n ? options.getServerSnapshot\n : getSnapshot;\n const [value, setValue] = useSignal<T>(untrack(first), {\n equals: options?.equals ?? Object.is,\n name: options?.name,\n });\n const sync = (): void => {\n const next = untrack(getSnapshot);\n setValue(() => next);\n };\n useEffect(() => {\n // `subscribe` is a user callback: what it reads must not re-run (and re-subscribe) this effect.\n const unsubscribe = untrack(() => subscribe(sync));\n try {\n // Catch up with changes made between the first read and the subscription.\n sync();\n } catch (error) {\n // The effect fails, so no cleanup is registered: release the subscription here.\n unsubscribe();\n throw error;\n }\n return unsubscribe;\n });\n return value;\n}\n"],"mappings":"A,yCA8DA,SAAgBC,EACdC,EACAC,EACAC,EACa,CACG,CACd,IAAMC,EAAWL,EAAQI,GAAS,mBAAqBD,CAAW,EAClE,UAAaE,CACf,CA6BF,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"concurrency.js","names":["walk","stack","root","node","visit","child","createHooks","laneRender","laneUser","applied","resolveApplied","suspended","holds","scheduled","hasLanePending","laneBusy","drainLane","batch","queue","limit","byCreation","effect","FLAG_TRANSITION","FLAG_PARKED","runQueued","settleLane","resolve","scheduleLane","flushLane","rt","previous","budget","passes","clearQueues","ShadowError","errors","error","reportUncaught","hasPending","schedule","startTransition","listener","fn","shared","parkOrLane","inLane","render","promote","place","renderQueue","userQueue","clear","suspend","SUSPENSION","size","entry","holdReader","tracker","beginHold","endHold","wakeSuspended","woken","markObservers","pause","nodes","owner","i","Computation","finishDisposal","createHold","count","holding","engagedOnce","onSettled","runWithContext","SuspenseContext","pending","holder","Owner","parent","settled","Signal","settle","hasObservers","retireBranch","branch","commit","state","buildPending","owned","choice","hold","previousOwner","previousListener","result","build","isSuspension","marker","addCleanup","disposeTree","readSignal","same","dropped","ready","built","live","ensureHooks","existing","created","registerTransitionLane","inTransition","createTransitionHold","hooks","transitionHooks","pauseOwner","resumeOwner"],"sources":["../../../src/internal/concurrency.ts"],"sourcesContent":["import { runWithContext } from \"../context\";\nimport { SuspenseContext } from \"../suspense\";\nimport { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport { disposeTree } from \"./dispose\";\nimport {\n CLEAN,\n DIRTY,\n FLAG_DISPOSED,\n FLAG_LANE,\n FLAG_PARKED,\n FLAG_QUEUED,\n FLAG_RENDER,\n FLAG_TRANSITION,\n KIND_EFFECT,\n} from \"./flags\";\nimport { Computation, hasObservers, markObservers, readSignal, Signal } from \"./graph\";\nimport { addCleanup, finishDisposal, Owner } from \"./owner\";\nimport { clearQueues, hasPending, place, renderQueue, userQueue } from \"./queue\";\nimport { byCreation, MAX_FLUSH_PASSES, reportUncaught, runQueued, schedule } from \"./scheduler\";\nimport {\n type BoundaryHold,\n type Hooks,\n rt,\n type SlotBranch,\n type SlotChoice,\n type SlotOwned,\n type SlotState,\n type SlotSwap,\n type TransitionHold,\n} from \"./state\";\nimport { isSuspension, SUSPENSION } from \"./suspension\";\n\n/*\n * Transitions, Activity pauses and Suspense holds. Nothing here runs unless an API that needs it is\n * called (startTransition, useTransition, useDeferredValue, pauseOwner, a Suspense hold inside a\n * transition): the first of those creates the hooks (`ensureHooks`), and the engine reaches them only\n * through `rt.hooks`. Module level holds no state of its own: the queues, waiters and holds are\n * closure variables of `createHooks`.\n */\n\n/** Transition-lane effects run per macrotask; between two chunks urgent work and input can run. */\nconst LANE_CHUNK = 64;\n\n/** The length of the suspended list from which the disposed nodes are dropped, at each power of two. */\nconst SUSPENDED_SWEEP_AT = 64;\n\n/** Visits `root` and every node below it. Iterative: the depth is user controlled. */\nfunction walk(root: Owner, visit: (node: Owner) => void): void {\n const stack: Owner[] = [root];\n while (stack.length > 0) {\n const node = stack.pop() as Owner;\n visit(node);\n for (let child = node.lastChild; child !== null; child = child.prevSibling) stack.push(child);\n }\n}\n\n/** Creates the transition machinery. Called once, by the first API that needs it. */\nfunction createHooks(): Hooks {\n const laneRender: Computation[] = [];\n const laneUser: Computation[] = [];\n /**\n * The promise every transition that waits for the lane shares (`waiting` counts the callers, for\n * devtools). One promise instead of one resolver per call: while a hold stays engaged the list of resolvers grew\n * with every `startTransition`, and all of them resolve at the same moment anyway.\n */\n let applied: Promise<void> | null = null;\n let resolveApplied: (() => void) | null = null;\n let waiting = 0;\n /**\n * Memos and effects that caught a suspension; woken all at once when a boundary releases them. A\n * node is listed once (it is a set), and the disposed ones are dropped each time the list\n * length is a power of two from `SUSPENDED_SWEEP_AT` on, so a hold that stays engaged cannot make the list, or the nodes it keeps alive,\n * grow with the number of nodes that came and went.\n */\n const suspended = new Set<Computation>();\n /** Suspense boundaries currently holding a transition (the lane is busy while any holds). */\n let holds = 0;\n let scheduled = false;\n\n const hasLanePending = (): boolean => laneRender.length > 0 || laneUser.length > 0;\n const laneBusy = (): boolean => hasLanePending() || holds > 0;\n\n /**\n * Runs one chunk of a lane queue. An entry without FLAG_TRANSITION was promoted to the urgent queue\n * after it was queued here; it is skipped (the urgent queue owns its FLAG_QUEUED).\n */\n const drainLane = (queue: Computation[], limit: number): number => {\n const batch = queue.splice(0, limit);\n batch.sort(byCreation);\n for (const effect of batch) {\n if ((effect.flags & FLAG_TRANSITION) === 0) continue;\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n effect.flags |= FLAG_PARKED | FLAG_TRANSITION;\n continue;\n }\n runQueued(effect);\n }\n return batch.length;\n };\n\n /** Resolves the transitions that wait for the lane, once the lane is idle. */\n const settleLane = (): void => {\n if (laneBusy() || resolveApplied === null) return;\n const resolve = resolveApplied;\n applied = resolveApplied = null;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.TRANSITION_END, waiting);\n waiting = 0;\n }\n resolve();\n };\n\n /** Asks for one lane macrotask (the timer lets the browser paint and take input first). */\n const scheduleLane = (): void => {\n if (scheduled) return;\n scheduled = true;\n setTimeout(flushLane, 0);\n };\n\n /**\n * Runs the transition lane: one chunk per macrotask, render effects first. Writes made here belong to\n * the lane, so the effects they wake join it. Errors nobody handled are reported, not thrown, because\n * no caller is waiting for this macrotask.\n */\n const flushLane = (): void => {\n scheduled = false;\n if (rt.flushing) {\n scheduleLane();\n return;\n }\n const previous = rt.inTransition;\n rt.inTransition = true;\n rt.flushing = true;\n let budget = LANE_CHUNK;\n let passes = 0;\n try {\n while (budget > 0 && hasLanePending()) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n const queue = laneRender.length > 0 ? laneRender : laneUser;\n budget -= drainLane(queue, budget);\n }\n } finally {\n rt.inTransition = previous;\n rt.flushing = false;\n }\n const errors = rt.uncaught.splice(0, rt.uncaught.length);\n for (const error of errors) reportUncaught(error);\n if (hasLanePending()) scheduleLane();\n else settleLane();\n if (hasPending()) schedule();\n };\n\n const startTransition = (fn: () => void): Promise<void> => {\n // A user callback runs untracked and as a transition: its reads are not subscriptions of the caller.\n const previous = rt.inTransition;\n const listener = rt.listener;\n rt.inTransition = true;\n rt.listener = null;\n try {\n fn();\n } finally {\n rt.inTransition = previous;\n rt.listener = listener;\n }\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_START);\n if (__DEV__) waiting += 1;\n applied ??= new Promise<void>((resolve) => {\n resolveApplied = resolve;\n });\n const shared = applied;\n settleLane();\n return shared;\n };\n\n /** The hook's `place`: parks a paused effect or queues a lane effect. */\n const parkOrLane = (effect: Computation, inLane: boolean): void => {\n if (effect.pauses > 0) {\n // Paused: parked (unqueued) until the owner resumes. A lane effect keeps its lane.\n effect.flags = inLane\n ? effect.flags | FLAG_PARKED | FLAG_TRANSITION\n : (effect.flags | FLAG_PARKED) & ~FLAG_TRANSITION;\n return;\n }\n const render = (effect.flags & FLAG_RENDER) !== 0;\n effect.flags = (effect.flags & ~FLAG_PARKED) | FLAG_QUEUED | FLAG_TRANSITION;\n if (render) laneRender.push(effect);\n else laneUser.push(effect);\n scheduleLane();\n };\n\n const promote = (effect: Computation): void => {\n // Lane-only effects (useDeferredValue's watcher) and paused effects stay where they are.\n if ((effect.flags & FLAG_LANE) !== 0 || effect.pauses > 0) return;\n if ((effect.flags & FLAG_PARKED) !== 0) {\n place(effect, false);\n return;\n }\n if ((effect.flags & (FLAG_QUEUED | FLAG_TRANSITION)) !== (FLAG_QUEUED | FLAG_TRANSITION))\n return;\n // Still listed in the lane array; the lane skips entries that no longer carry FLAG_TRANSITION.\n effect.flags &= ~FLAG_TRANSITION;\n if ((effect.flags & FLAG_RENDER) !== 0) renderQueue.push(effect);\n else userQueue.push(effect);\n };\n\n const clear = (): void => {\n for (const queue of [laneRender, laneUser]) {\n for (const effect of queue) {\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n effect.state = CLEAN;\n }\n queue.length = 0;\n }\n };\n\n const suspend = (node: Computation, error: unknown): boolean => {\n if (error !== SUSPENSION) return false;\n // Listed once: a node that suspends again before the wake-up is already in the set.\n if (!suspended.has(node)) {\n const size = suspended.size;\n if (size >= SUSPENDED_SWEEP_AT && (size & (size - 1)) === 0) {\n // A disposed node never wakes, so keeping it would leak it for as long as the hold lasts.\n for (const entry of suspended) {\n if (entry.disposed) suspended.delete(entry);\n }\n }\n suspended.add(node);\n }\n return true;\n };\n\n const holdReader = (tracker: { hold?(): boolean }): void => {\n if (tracker.hold?.() === true) throw SUSPENSION;\n };\n\n const beginHold = (): void => {\n holds += 1;\n };\n\n const endHold = (): void => {\n if (holds > 0) holds -= 1;\n if (hasLanePending()) scheduleLane();\n settleLane();\n };\n\n const wakeSuspended = (): void => {\n const woken = Array.from(suspended);\n suspended.clear();\n // The woken work is still the transition: it runs in the lane, so a resource it reads again is\n // held the same way, not shown as a fallback by an urgent pass.\n const previous = rt.inTransition;\n rt.inTransition = true;\n try {\n for (const node of woken) {\n if (node.disposed) continue;\n node.state = DIRTY;\n if (node.kind === KIND_EFFECT) place(node, true);\n else markObservers(node);\n }\n } finally {\n rt.inTransition = previous;\n }\n schedule();\n };\n\n const pause = (owner: Owner): void => {\n // Every node is paused before any cleanup runs: a cleanup that throws must not leave the rest\n // unpaused. Preorder reversed is the disposal order: children first, newest first.\n const nodes: Owner[] = [];\n walk(owner, (node) => {\n node.pauses += 1;\n nodes.push(node);\n });\n rt.disposing += 1;\n try {\n for (let i = nodes.length - 1; i >= 0; i -= 1) {\n const node = nodes[i];\n if (\n node instanceof Computation &&\n node.kind === KIND_EFFECT &&\n (node.flags & FLAG_RENDER) === 0 &&\n !node.disposed\n ) {\n node.runCleanups();\n }\n }\n } finally {\n finishDisposal();\n }\n };\n\n const createHold = (onSettled: () => void): TransitionHold => {\n let count = 0;\n let holding = false;\n let engagedOnce = false;\n const tracker = {\n increment(): void {\n count += 1;\n },\n decrement(): void {\n count -= 1;\n if (count !== 0) return;\n if (holding) {\n holding = false;\n // Everything that kept its value for this hold runs again, now that the data arrived.\n wakeSuspended();\n endHold();\n }\n onSettled();\n },\n hold(): boolean {\n engagedOnce = true;\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n };\n return {\n run: (fn) => runWithContext(SuspenseContext, tracker, fn),\n count: () => count,\n engaged: () => engagedOnce,\n drop: () => {\n if (!holding) return;\n holding = false;\n endHold();\n },\n };\n };\n\n const resume = (owner: Owner): void => {\n walk(owner, (node) => {\n if (node.pauses > 0) node.pauses -= 1;\n if (!(node instanceof Computation) || node.pauses !== 0 || node.disposed) return;\n if (node.kind === KIND_EFFECT) {\n // A render effect that was not due while paused keeps its DOM: re-running it would rebuild its\n // subtree (a Provider's children, for one) and lose that state.\n if ((node.flags & FLAG_RENDER) !== 0 && (node.flags & FLAG_PARKED) === 0) return;\n node.state = DIRTY;\n place(node, false);\n } else if (node.state !== CLEAN) {\n // A memo that changed while paused was not recomputed, so its readers outside this owner were\n // not woken either (they read the frozen value). Wake them now that it can be recomputed.\n markObservers(node);\n }\n });\n schedule();\n };\n\n /** A Suspense boundary's hold: engaged by a transition read, released when its data arrived. */\n const boundaryHold = (): BoundaryHold => {\n let holding = false;\n return {\n engage: () => {\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n release: () => {\n if (!holding) return;\n holding = false;\n // Everything that kept its value for this boundary runs again, with the data that arrived.\n wakeSuspended();\n endHold();\n },\n holding: () => holding,\n };\n };\n\n /**\n * The transition layer of one branch slot (Show, Switch). A change made during a transition, while a\n * branch is on screen, builds the new branch under a hold and keeps the shown one until the hold\n * settles; then it commits. The slot's output memo calls `step` first, so the usual path (its own\n * teardown) only runs when no transition is involved. Its state lives in `state`, which the memo\n * reads and writes.\n */\n const slotSwap = <C extends SlotChoice>(\n state: SlotState<C>,\n build: (choice: C, owned: SlotOwned, eager: boolean) => unknown,\n same: (a: C, b: C) => boolean,\n parent: Owner | null,\n ): SlotSwap<C> => {\n /** A transition's branch waiting for its reads; the shown branch stays until it is ready. */\n let pending: SlotBranch<C> | undefined;\n /** Owns the branches built during transitions: they live as long as the slot's owner. */\n const holder = new Owner(parent);\n /** Counts the settled holds; the memo reads it, so it runs again when a pending branch is ready. */\n const settled = new Signal<number>(0, false, undefined);\n\n const settle = (): void => {\n settled.value += 1;\n if (hasObservers(settled)) {\n markObservers(settled);\n schedule();\n }\n };\n\n /** Tears a branch down. Its owner is marked `disposing` first (see the accessors of Show). */\n const retireBranch = (branch: SlotBranch<C>): void => {\n branch.owned.disposing = true;\n try {\n branch.hold?.drop();\n branch.dispose?.();\n } finally {\n branch.owned.disposing = false;\n }\n };\n\n const commit = (branch: SlotBranch<C>): void => {\n const previous = state.live;\n state.live = branch;\n if (previous !== undefined) retireBranch(previous);\n };\n\n /** Builds a transition's branch under the holder. A held read leaves it pending, not shown. */\n const buildPending = (choice: C): SlotBranch<C> => {\n const owned: SlotOwned = { index: choice.index, value: choice.when, disposing: false };\n const hold: TransitionHold = createHold(() => {\n // Only the branch still waiting may commit; a dropped one must not wake the slot.\n if (pending !== undefined && pending.hold === hold) settle();\n });\n const root = new Owner(holder);\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = root;\n rt.listener = null;\n let result: unknown;\n try {\n // The branch's reads report to its own hold (not the boundary), so they do not bring the\n // fallback back. No Provider: its render effect would be re-run by the wake-up, rebuilding\n // the branch and starting its loads again.\n try {\n result = hold.run(() => build(choice, owned, true));\n } catch (error) {\n if (!isSuspension(error)) throw error;\n }\n const marker = new Owner(root);\n addCleanup(marker, () => {\n owned.disposing = true;\n });\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n return {\n choice,\n owned,\n result,\n dispose: () => disposeTree(root),\n hold: hold.engaged() ? hold : null,\n };\n };\n\n return {\n step(choice: C): boolean {\n readSignal(settled);\n if (pending !== undefined) {\n if (!same(pending.choice, choice)) {\n const dropped = pending;\n pending = undefined;\n dropped.hold?.drop();\n dropped.dispose?.();\n } else if ((pending.hold?.count() ?? 0) > 0) {\n // Still waiting for data: the shown branch stays on screen, untouched.\n return true;\n } else {\n const ready = pending;\n pending = undefined;\n commit(ready);\n return true;\n }\n }\n // A transition replacing the shown branch: build it first, keep the shown one until it is ready.\n if (state.live !== undefined && rt.inTransition) {\n const built = buildPending(choice);\n if (built.hold === null) commit(built);\n else pending = built;\n return true;\n }\n // The usual path follows: the branch on screen is retired here (an unmanaged one is torn down).\n const live = state.live;\n state.live = undefined;\n if (live !== undefined) retireBranch(live);\n return false;\n },\n };\n };\n\n return {\n place: parkOrLane,\n promote,\n clear,\n suspend,\n holdReader,\n startTransition,\n beginHold,\n endHold,\n wakeSuspended,\n pause,\n resume,\n createHold,\n slotSwap,\n boundaryHold,\n };\n}\n\n/** Installs the transition machinery on first use; later calls return the same hooks. */\nfunction ensureHooks(): Hooks {\n const existing = rt.hooks;\n if (existing !== null) return existing;\n const created = createHooks();\n rt.hooks = created;\n return created;\n}\n\n/**\n * Installs the transition machinery (the transition lane, Activity pauses and Suspense holds) now\n * instead of at the first `startTransition`. The machinery is created on first use so that an\n * application that never uses transitions does not carry its code; call this from a primitive whose\n * later work needs the lane to exist, as `useDeferredValue` does. Calling it again does nothing.\n *\n * @example\n * import { registerTransitionLane } from \"@shadow-js/core/extend\";\n *\n * export function useBackgroundValue(): void {\n * registerTransitionLane(); // later lane-only effects of this hook find the lane\n * }\n * @see startTransition\n * @since 1.0.0\n */\nexport function registerTransitionLane(): void {\n ensureHooks();\n}\n\n/**\n * Runs `fn` as a transition: the effects its writes wake wait in the transition lane, which runs\n * after urgent work (in a macrotask, one chunk at a time). Reads see the writes at once; the DOM\n * catches up when the lane runs. Use it for an update that may be slow to render or load, so input\n * stays responsive and a Suspense boundary keeps its content instead of showing its fallback. `fn`\n * runs untracked. The returned promise resolves when the lane is idle and no Suspense boundary holds\n * the transition.\n *\n * On the server there are no effects, so `fn` simply runs and the promise is already resolved.\n *\n * @param fn Callback whose writes form the transition.\n * @returns A promise that resolves when the transition has been applied.\n * @throws What `fn` throws, synchronously; no transition is started then.\n * @example\n * import { startTransition, useSignal } from \"@shadow-js/core\";\n *\n * const [page, setPage] = useSignal(\"home\");\n * async function openReports(): Promise<void> {\n * await startTransition(() => setPage(\"reports\"));\n * console.log(`${page()} is on screen`);\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function startTransition(fn: () => void): Promise<void> {\n if (__SERVER__) {\n fn();\n return Promise.resolve();\n }\n return ensureHooks().startTransition(fn);\n}\n\n/**\n * Starts a Suspense hold: the boundary keeps showing its current content while a transition waits\n * for data. Holds are counted, and the running transitions stay pending (`isPending` of\n * `useTransition`, the promise of `startTransition`) until every hold has ended. For renderers that\n * implement Suspense; each call needs one {@link endHold}. Does nothing before the transition\n * machinery exists (no transition has run).\n *\n * @example\n * import { beginHold, endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function holdUntil(data: Promise<unknown>): void {\n * beginHold(); // the boundary keeps its content\n * void data.finally(() => {\n * wakeSuspended();\n * endHold();\n * });\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function beginHold(): void {\n rt.hooks?.beginHold();\n}\n\n/**\n * Ends a Suspense hold started with {@link beginHold}. Call {@link wakeSuspended} first, so the\n * memos and effects that waited are queued; this then schedules the lane for them and, once the lane\n * is idle and no hold remains, resolves the transitions that were waiting. Extra calls never take the\n * count below zero. Does nothing before the transition machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function release(): void {\n * wakeSuspended(); // the held readers run again with the data that arrived\n * endHold();\n * }\n * @see beginHold\n * @since 1.0.0\n */\nexport function endHold(): void {\n rt.hooks?.endHold();\n}\n\n/**\n * Wakes every memo and effect that kept its value for a transition (it caught {@link SUSPENSION}):\n * each runs again in the transition lane, so it reads the data that arrived. A Suspense boundary\n * calls it when it releases its hold, before {@link endHold}. Does nothing before the transition\n * machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function onDataArrived(): void {\n * wakeSuspended();\n * endHold();\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function wakeSuspended(): void {\n rt.hooks?.wakeSuspended();\n}\n\n/**\n * Lets a pending read inside a transition keep the boundary's content: when the tracker's `hold()`\n * returns true (the boundary holds its content for the transition), the reader throws\n * {@link SUSPENSION} and keeps its previous value until the boundary wakes it. Call it from a data\n * primitive's reader when its data is pending, the reader is tracked and {@link inTransition} is\n * true, as `useResource` does. Does nothing before the transition machinery exists, or when the\n * tracker has no `hold`.\n *\n * @param tracker The Suspense tracker of the nearest boundary (`SuspenseContext`).\n * @throws {@link SUSPENSION} (not an error) when the boundary holds its content.\n * @example\n * import { useContext, SuspenseContext } from \"@shadow-js/core\";\n * import { currentListener, holdReader, inTransition } from \"@shadow-js/core/extend\";\n *\n * export function readPending(): void {\n * const tracker = useContext(SuspenseContext);\n * if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n * }\n * @see isSuspension\n * @since 1.0.0\n */\nexport function holdReader(tracker: { hold?(): boolean }): void {\n rt.hooks?.holdReader(tracker);\n}\n\n/**\n * Tells whether a transition callback or a transition-lane run is active, so the writes made now\n * belong to the lane. Use it in a primitive that treats transition reads differently, such as a data\n * reader that holds the boundary only in a transition.\n *\n * @returns True inside `startTransition`'s callback and while the lane runs.\n * @example\n * import { startTransition } from \"@shadow-js/core\";\n * import { inTransition } from \"@shadow-js/core/extend\";\n *\n * void startTransition(() => {\n * console.log(inTransition()); // true in the browser\n * });\n * console.log(inTransition()); // false\n * @see startTransition\n * @since 1.0.0\n */\nexport function inTransition(): boolean {\n return rt.inTransition;\n}\n\n/**\n * Creates the hold of a value a transition builds (see {@link TransitionHold}): the reads that wait\n * for data inside `hold.run(...)` count against this hold instead of the Suspense boundary around the\n * value, so the value on screen stays until the new one is ready. For renderers that build values\n * during a transition.\n *\n * @param onSettled Called each time the number of waiting reads drops back to zero.\n * @returns The hold, or null when the transition machinery does not exist yet (no transition has run,\n * so nothing can be held).\n * @example\n * import { createTransitionHold } from \"@shadow-js/core/extend\";\n *\n * const hold = createTransitionHold(() => console.log(\"ready to commit\"));\n * const built = hold === null ? \"now\" : hold.run(() => \"pending\");\n * @see transitionHooks\n * @since 1.0.0\n */\nexport function createTransitionHold(onSettled: () => void): TransitionHold | null {\n const hooks = rt.hooks;\n return hooks === null ? null : hooks.createHold(onSettled);\n}\n\n/**\n * Returns the transition machinery while a transition is running, otherwise null. Renderers reach\n * the slot and boundary layers (`slotSwap`, `boundaryHold`) only through it: a transition can only be\n * running once the machinery exists, so this never creates it (a static call that did would keep the\n * whole machinery in every bundle that renders a Show).\n *\n * @returns The hooks during a transition callback or lane run, null otherwise.\n * @example\n * import { transitionHooks } from \"@shadow-js/core/extend\";\n *\n * export function boundaryHoldIfTransition() {\n * return transitionHooks()?.boundaryHold() ?? null;\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function transitionHooks(): Hooks | null {\n return rt.inTransition ? rt.hooks : null;\n}\n\n/**\n * Pauses `owner` and everything below it (Activity hidden). User effects run their cleanups and wait.\n * DOM bindings (render effects) wait without a cleanup, so their nodes stay as they are. Memos keep their\n * last value, and effects created below are parked until the owner resumes. Pauses nest: each\n * `pauseOwner` needs one `resumeOwner`. Use it to hide a subtree while keeping its state.\n *\n * @param owner The owner to pause, with its whole subtree.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const hidden = createOwner(null);\n * pauseOwner(hidden); // its effects stop; its memos keep their values\n * resumeOwner(hidden); // its user effects run again with the latest values\n * @see resumeOwner\n * @since 1.0.0\n */\nexport function pauseOwner(owner: Owner): void {\n ensureHooks().pause(owner);\n}\n\n/**\n * Resumes an owner paused with {@link pauseOwner}; the subtree runs again once its last pause ends.\n * User effects below it run once more with the current values (their cleanups ran on pause). DOM\n * bindings run only if something they read changed while paused, so a hidden subtree is not rebuilt\n * on show. Memos that changed while paused wake their readers outside the owner. Call it once per\n * `pauseOwner`, not on an owner that is not paused.\n *\n * @param owner The paused owner.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const panel = createOwner(null);\n * pauseOwner(panel);\n * resumeOwner(panel); // every user effect below runs once with the latest values\n * @see pauseOwner\n * @since 1.0.0\n */\nexport function resumeOwner(owner: Owner): void {\n rt.hooks?.resume(owner);\n}\n"],"mappings":"A,ysBAgDA,SAASA,EAAK,EAAa,EAAoC,CAC7D,IAAMC,EAAiB,CAACC,CAAI,EAC5B,KAAOD,EAAM,OAAS,GAAG,CACvB,IAAME,EAAOF,EAAM,IAAI,EACvBG,EAAMD,CAAI,EACV,IAAK,IAAIE,EAAQF,EAAK,UAAWE,IAAU,KAAM,EAAQA,EAAM,YAAaJ,EAAM,KAAKI,CAAK,CAC9F,CACF,CAGA,SAASC,GAAqB,CAC5B,IAAMC,EAA4B,CAAC,EAC7BC,EAA0B,CAAC,EAM7BC,EAAgC,KAChCC,EAAsC,KAQpCC,kBAAY,IAAI,IAElBC,EAAQ,EACRC,EAAY,GAEVC,MAAgCP,EAAW,OAAS,GAAKC,EAAS,OAAS,EAC3EO,MAA0BD,EAAe,GAAKF,EAAQ,EAMtDI,GAAa,EAAsB,IAA0B,CACjE,IAAMC,EAAQC,EAAM,OAAO,EAAGC,CAAK,EACnCF,EAAM,KAAKG,CAAU,EACrB,IAAK,IAAMC,KAAUJ,EACdI,EAAO,MAAA,OACZ,EAAO,OAAS,EAAA,EAAgBC,GAC3BD,EAAO,MAAA,IACRA,EAAO,OAAS,EAClB,EAAO,OAASE,EAAcD,EAGhCE,EAAUH,CAAM,IAElB,OAAOJ,EAAM,MACf,EAGMQ,MAAyB,CAC7B,GAAIV,EAAS,GAAKL,IAAmB,KAAM,OAC3C,IAAMgB,EAAUhB,EAChB,EAAU,EAAiB,KAK3BgB,EAAQ,CACV,EAGMC,MAA2B,CAC3Bd,IACJ,EAAY,GACZ,WAAWe,EAAW,CAAC,EACzB,EAOMA,MAAwB,CAE5B,GADA,EAAY,GACRC,EAAG,SAAU,CACfF,EAAa,EACb,MACF,CACA,IAAMG,EAAWD,EAAG,aACpB,EAAG,aAAe,GAClB,EAAG,SAAW,GACd,IAAIE,EAAS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9D3B,EAAG,OAAO,WAAW4B,CAAO,CAC9B,CAmBA,SAAgBqD,GAAwB,CACtC,OAAOjF,EAAG,YACZ,CAmBA,SAAgBkF,EAAqB,EAA8C,CACjF,IAAMC,EAAQnF,EAAG,MACjB,OAAOmF,IAAU,KAAO,KAAOA,EAAM,WAAWvC,CAAS,CAC3D,CAkBA,SAAgBwC,GAAgC,CAC9C,OAAOpF,EAAG,aAAeA,EAAG,MAAQ,IACtC,CAkBA,SAAgBqF,EAAW,EAAoB,CAC7CR,EAAY,CAAC,CAAC,MAAMzC,CAAK,CAC3B,CAmBA,SAAgBkD,EAAY,EAAoB,CAC9CtF,EAAG,OAAO,OAAOoC,CAAK,CACxB,C"}
|
|
1
|
+
{"version":3,"file":"concurrency.js","names":["runWithContext","SuspenseContext","ShadowError","disposeTree","FLAG_PARKED","FLAG_TRANSITION","Computation","Signal","hasObservers","markObservers","readSignal","Owner","addCleanup","finishDisposal","clearQueues","hasPending","place","renderQueue","userQueue","byCreation","reportUncaught","runQueued","schedule","rt","SUSPENSION","isSuspension","walk","root","visit","stack","node","child","createHooks","laneRender","laneUser","applied","resolveApplied","suspended","holds","scheduled","hasLanePending","laneBusy","drainLane","queue","limit","batch","effect","settleLane","resolve","scheduleLane","flushLane","previous","budget","passes","errors","error","startTransition","fn","listener","shared","parkOrLane","inLane","render","promote","clear","suspend","size","entry","holdReader","tracker","beginHold","endHold","wakeSuspended","woken","pause","owner","nodes","i","createHold","onSettled","count","holding","engagedOnce","state","build","same","parent","pending","holder","settled","settle","retireBranch","branch","commit","buildPending","choice","owned","hold","previousOwner","previousListener","result","marker","dropped","ready","built","live","ensureHooks","existing","created","registerTransitionLane","inTransition","createTransitionHold","hooks","transitionHooks","pauseOwner","resumeOwner"],"sources":["../../../src/internal/concurrency.ts"],"sourcesContent":["import { runWithContext } from \"../context\";\nimport { SuspenseContext } from \"../suspense\";\nimport { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport { disposeTree } from \"./dispose\";\nimport {\n CLEAN,\n DIRTY,\n FLAG_DISPOSED,\n FLAG_LANE,\n FLAG_PARKED,\n FLAG_QUEUED,\n FLAG_RENDER,\n FLAG_TRANSITION,\n KIND_EFFECT,\n} from \"./flags\";\nimport { Computation, hasObservers, markObservers, readSignal, Signal } from \"./graph\";\nimport { addCleanup, finishDisposal, Owner } from \"./owner\";\nimport { clearQueues, hasPending, place, renderQueue, userQueue } from \"./queue\";\nimport { byCreation, MAX_FLUSH_PASSES, reportUncaught, runQueued, schedule } from \"./scheduler\";\nimport {\n type BoundaryHold,\n type Hooks,\n rt,\n type SlotBranch,\n type SlotChoice,\n type SlotOwned,\n type SlotState,\n type SlotSwap,\n type TransitionHold,\n} from \"./state\";\nimport { isSuspension, SUSPENSION } from \"./suspension\";\n\n/*\n * Transitions, Activity pauses and Suspense holds. Nothing here runs unless an API that needs it is\n * called (startTransition, useTransition, useDeferredValue, pauseOwner, a Suspense hold inside a\n * transition): the first of those creates the hooks (`ensureHooks`), and the engine reaches them only\n * through `rt.hooks`. Module level holds no state of its own: the queues, waiters and holds are\n * closure variables of `createHooks`.\n */\n\n/** Transition-lane effects run per macrotask; between two chunks urgent work and input can run. */\nconst LANE_CHUNK = 64;\n\n/** The length of the suspended list from which the disposed nodes are dropped, at each power of two. */\nconst SUSPENDED_SWEEP_AT = 64;\n\n/** Visits `root` and every node below it. Iterative: the depth is user controlled. */\nfunction walk(root: Owner, visit: (node: Owner) => void): void {\n const stack: Owner[] = [root];\n while (stack.length > 0) {\n const node = stack.pop() as Owner;\n visit(node);\n for (let child = node.lastChild; child !== null; child = child.prevSibling) stack.push(child);\n }\n}\n\n/** Creates the transition machinery. Called once, by the first API that needs it. */\nfunction createHooks(): Hooks {\n const laneRender: Computation[] = [];\n const laneUser: Computation[] = [];\n /**\n * The promise every transition that waits for the lane shares (`waiting` counts the callers, for\n * devtools). One promise instead of one resolver per call: while a hold stays engaged the list of resolvers grew\n * with every `startTransition`, and all of them resolve at the same moment anyway.\n */\n let applied: Promise<void> | null = null;\n let resolveApplied: (() => void) | null = null;\n let waiting = 0;\n /**\n * Memos and effects that caught a suspension; woken all at once when a boundary releases them. A\n * node is listed once (it is a set), and the disposed ones are dropped each time the list\n * length is a power of two from `SUSPENDED_SWEEP_AT` on, so a hold that stays engaged cannot make the list, or the nodes it keeps alive,\n * grow with the number of nodes that came and went.\n */\n const suspended = new Set<Computation>();\n /** Suspense boundaries currently holding a transition (the lane is busy while any holds). */\n let holds = 0;\n let scheduled = false;\n\n const hasLanePending = (): boolean => laneRender.length > 0 || laneUser.length > 0;\n const laneBusy = (): boolean => hasLanePending() || holds > 0;\n\n /**\n * Runs one chunk of a lane queue. An entry without FLAG_TRANSITION was promoted to the urgent queue\n * after it was queued here; it is skipped (the urgent queue owns its FLAG_QUEUED).\n */\n const drainLane = (queue: Computation[], limit: number): number => {\n const batch = queue.splice(0, limit);\n batch.sort(byCreation);\n for (const effect of batch) {\n if ((effect.flags & FLAG_TRANSITION) === 0) continue;\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n effect.flags |= FLAG_PARKED | FLAG_TRANSITION;\n continue;\n }\n runQueued(effect);\n }\n return batch.length;\n };\n\n /** Resolves the transitions that wait for the lane, once the lane is idle. */\n const settleLane = (): void => {\n if (laneBusy() || resolveApplied === null) return;\n const resolve = resolveApplied;\n applied = resolveApplied = null;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.TRANSITION_END, waiting);\n waiting = 0;\n }\n resolve();\n };\n\n /** Asks for one lane macrotask (the timer lets the browser paint and take input first). */\n const scheduleLane = (): void => {\n if (scheduled) return;\n scheduled = true;\n setTimeout(flushLane, 0);\n };\n\n /**\n * Runs the transition lane: one chunk per macrotask, render effects first. Writes made here belong to\n * the lane, so the effects they wake join it. Errors nobody handled are reported, not thrown, because\n * no caller is waiting for this macrotask.\n */\n const flushLane = (): void => {\n scheduled = false;\n if (rt.flushing) {\n scheduleLane();\n return;\n }\n const previous = rt.inTransition;\n rt.inTransition = true;\n rt.flushing = true;\n let budget = LANE_CHUNK;\n let passes = 0;\n try {\n while (budget > 0 && hasLanePending()) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n const queue = laneRender.length > 0 ? laneRender : laneUser;\n budget -= drainLane(queue, budget);\n }\n } finally {\n rt.inTransition = previous;\n rt.flushing = false;\n }\n const errors = rt.uncaught.splice(0, rt.uncaught.length);\n for (const error of errors) reportUncaught(error);\n if (hasLanePending()) scheduleLane();\n else settleLane();\n if (hasPending()) schedule();\n };\n\n const startTransition = (fn: () => void): Promise<void> => {\n // A user callback runs untracked and as a transition: its reads are not subscriptions of the caller.\n const previous = rt.inTransition;\n const listener = rt.listener;\n rt.inTransition = true;\n rt.listener = null;\n try {\n fn();\n } finally {\n rt.inTransition = previous;\n rt.listener = listener;\n }\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_START);\n if (__DEV__) waiting += 1;\n applied ??= new Promise<void>((resolve) => {\n resolveApplied = resolve;\n });\n const shared = applied;\n settleLane();\n return shared;\n };\n\n /** The hook's `place`: parks a paused effect or queues a lane effect. */\n const parkOrLane = (effect: Computation, inLane: boolean): void => {\n if (effect.pauses > 0) {\n // Paused: parked (unqueued) until the owner resumes. A lane effect keeps its lane.\n effect.flags = inLane\n ? effect.flags | FLAG_PARKED | FLAG_TRANSITION\n : (effect.flags | FLAG_PARKED) & ~FLAG_TRANSITION;\n return;\n }\n const render = (effect.flags & FLAG_RENDER) !== 0;\n effect.flags = (effect.flags & ~FLAG_PARKED) | FLAG_QUEUED | FLAG_TRANSITION;\n if (render) laneRender.push(effect);\n else laneUser.push(effect);\n scheduleLane();\n };\n\n const promote = (effect: Computation): void => {\n // Lane-only effects (useDeferredValue's watcher) and paused effects stay where they are.\n if ((effect.flags & FLAG_LANE) !== 0 || effect.pauses > 0) return;\n if ((effect.flags & FLAG_PARKED) !== 0) {\n place(effect, false);\n return;\n }\n if ((effect.flags & (FLAG_QUEUED | FLAG_TRANSITION)) !== (FLAG_QUEUED | FLAG_TRANSITION))\n return;\n // Still listed in the lane array; the lane skips entries that no longer carry FLAG_TRANSITION.\n effect.flags &= ~FLAG_TRANSITION;\n if ((effect.flags & FLAG_RENDER) !== 0) renderQueue.push(effect);\n else userQueue.push(effect);\n };\n\n const clear = (): void => {\n for (const queue of [laneRender, laneUser]) {\n for (const effect of queue) {\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n effect.state = CLEAN;\n }\n queue.length = 0;\n }\n };\n\n const suspend = (node: Computation, error: unknown): boolean => {\n if (error !== SUSPENSION) return false;\n // Listed once: a node that suspends again before the wake-up is already in the set.\n if (!suspended.has(node)) {\n const size = suspended.size;\n if (size >= SUSPENDED_SWEEP_AT && (size & (size - 1)) === 0) {\n // A disposed node never wakes, so keeping it would leak it for as long as the hold lasts.\n for (const entry of suspended) {\n if (entry.disposed) suspended.delete(entry);\n }\n }\n suspended.add(node);\n }\n return true;\n };\n\n const holdReader = (tracker: { hold?(): boolean }): void => {\n if (tracker.hold?.() === true) throw SUSPENSION;\n };\n\n const beginHold = (): void => {\n holds += 1;\n };\n\n const endHold = (): void => {\n if (holds > 0) holds -= 1;\n if (hasLanePending()) scheduleLane();\n settleLane();\n };\n\n const wakeSuspended = (): void => {\n const woken = Array.from(suspended);\n suspended.clear();\n // The woken work is still the transition: it runs in the lane, so a resource it reads again is\n // held the same way, not shown as a fallback by an urgent pass.\n const previous = rt.inTransition;\n rt.inTransition = true;\n try {\n for (const node of woken) {\n if (node.disposed) continue;\n node.state = DIRTY;\n if (node.kind === KIND_EFFECT) place(node, true);\n else markObservers(node);\n }\n } finally {\n rt.inTransition = previous;\n }\n schedule();\n };\n\n const pause = (owner: Owner): void => {\n // Every node is paused before any cleanup runs: a cleanup that throws must not leave the rest\n // unpaused. Preorder reversed is the disposal order: children first, newest first.\n const nodes: Owner[] = [];\n walk(owner, (node) => {\n node.pauses += 1;\n nodes.push(node);\n });\n rt.disposing += 1;\n try {\n for (let i = nodes.length - 1; i >= 0; i -= 1) {\n const node = nodes[i];\n if (\n node instanceof Computation &&\n node.kind === KIND_EFFECT &&\n (node.flags & FLAG_RENDER) === 0 &&\n !node.disposed\n ) {\n node.runCleanups();\n }\n }\n } finally {\n finishDisposal();\n }\n };\n\n const createHold = (onSettled: () => void): TransitionHold => {\n let count = 0;\n let holding = false;\n let engagedOnce = false;\n const tracker = {\n increment(): void {\n count += 1;\n },\n decrement(): void {\n count -= 1;\n if (count !== 0) return;\n if (holding) {\n holding = false;\n // Everything that kept its value for this hold runs again, now that the data arrived.\n wakeSuspended();\n endHold();\n }\n onSettled();\n },\n hold(): boolean {\n engagedOnce = true;\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n };\n return {\n run: (fn) => runWithContext(SuspenseContext, tracker, fn),\n count: () => count,\n engaged: () => engagedOnce,\n drop: () => {\n if (!holding) return;\n holding = false;\n endHold();\n },\n };\n };\n\n const resume = (owner: Owner): void => {\n walk(owner, (node) => {\n if (node.pauses > 0) node.pauses -= 1;\n if (!(node instanceof Computation) || node.pauses !== 0 || node.disposed) return;\n if (node.kind === KIND_EFFECT) {\n // A render effect that was not due while paused keeps its DOM: re-running it would rebuild its\n // subtree (a Provider's children, for one) and lose that state.\n if ((node.flags & FLAG_RENDER) !== 0 && (node.flags & FLAG_PARKED) === 0) return;\n node.state = DIRTY;\n place(node, false);\n } else if (node.state !== CLEAN) {\n // A memo that changed while paused was not recomputed, so its readers outside this owner were\n // not woken either (they read the frozen value). Wake them now that it can be recomputed.\n markObservers(node);\n }\n });\n schedule();\n };\n\n /** A Suspense boundary's hold: engaged by a transition read, released when its data arrived. */\n const boundaryHold = (): BoundaryHold => {\n let holding = false;\n return {\n engage: () => {\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n release: () => {\n if (!holding) return;\n holding = false;\n // Everything that kept its value for this boundary runs again, with the data that arrived.\n wakeSuspended();\n endHold();\n },\n holding: () => holding,\n };\n };\n\n /**\n * The transition layer of one branch slot (Show, Switch). A change made during a transition, while a\n * branch is on screen, builds the new branch under a hold and keeps the shown one until the hold\n * settles; then it commits. The slot's output memo calls `step` first, so the usual path (its own\n * teardown) only runs when no transition is involved. Its state lives in `state`, which the memo\n * reads and writes.\n */\n const slotSwap = <C extends SlotChoice>(\n state: SlotState<C>,\n build: (choice: C, owned: SlotOwned, eager: boolean) => unknown,\n same: (a: C, b: C) => boolean,\n parent: Owner | null,\n ): SlotSwap<C> => {\n /** A transition's branch waiting for its reads; the shown branch stays until it is ready. */\n let pending: SlotBranch<C> | undefined;\n /** Owns the branches built during transitions: they live as long as the slot's owner. */\n const holder = new Owner(parent);\n /** Counts the settled holds; the memo reads it, so it runs again when a pending branch is ready. */\n const settled = new Signal<number>(0, false, undefined);\n\n const settle = (): void => {\n settled.value += 1;\n if (hasObservers(settled)) {\n markObservers(settled);\n schedule();\n }\n };\n\n /** Tears a branch down. Its owner is marked `disposing` first (see the accessors of Show). */\n const retireBranch = (branch: SlotBranch<C>): void => {\n branch.owned.disposing = true;\n try {\n branch.hold?.drop();\n branch.dispose?.();\n } finally {\n branch.owned.disposing = false;\n }\n };\n\n const commit = (branch: SlotBranch<C>): void => {\n const previous = state.live;\n state.live = branch;\n if (previous !== undefined) retireBranch(previous);\n };\n\n /** Builds a transition's branch under the holder. A held read leaves it pending, not shown. */\n const buildPending = (choice: C): SlotBranch<C> => {\n const owned: SlotOwned = { index: choice.index, value: choice.when, disposing: false };\n const hold: TransitionHold = createHold(() => {\n // Only the branch still waiting may commit; a dropped one must not wake the slot.\n if (pending !== undefined && pending.hold === hold) settle();\n });\n const root = new Owner(holder);\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = root;\n rt.listener = null;\n let result: unknown;\n try {\n // The branch's reads report to its own hold (not the boundary), so they do not bring the\n // fallback back. No Provider: its render effect would be re-run by the wake-up, rebuilding\n // the branch and starting its loads again.\n try {\n result = hold.run(() => build(choice, owned, true));\n } catch (error) {\n if (!isSuspension(error)) throw error;\n }\n const marker = new Owner(root);\n addCleanup(marker, () => {\n owned.disposing = true;\n });\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n return {\n choice,\n owned,\n result,\n dispose: () => disposeTree(root),\n hold: hold.engaged() ? hold : null,\n };\n };\n\n return {\n step(choice: C): boolean {\n readSignal(settled);\n if (pending !== undefined) {\n if (!same(pending.choice, choice)) {\n const dropped = pending;\n pending = undefined;\n dropped.hold?.drop();\n dropped.dispose?.();\n } else if ((pending.hold?.count() ?? 0) > 0) {\n // Still waiting for data: the shown branch stays on screen, untouched.\n return true;\n } else {\n const ready = pending;\n pending = undefined;\n commit(ready);\n return true;\n }\n }\n // A transition replacing the shown branch: build it first, keep the shown one until it is ready.\n if (state.live !== undefined && rt.inTransition) {\n const built = buildPending(choice);\n if (built.hold === null) commit(built);\n else pending = built;\n return true;\n }\n // The usual path follows: the branch on screen is retired here (an unmanaged one is torn down).\n const live = state.live;\n state.live = undefined;\n if (live !== undefined) retireBranch(live);\n return false;\n },\n };\n };\n\n return {\n place: parkOrLane,\n promote,\n clear,\n suspend,\n holdReader,\n startTransition,\n beginHold,\n endHold,\n wakeSuspended,\n pause,\n resume,\n createHold,\n slotSwap,\n boundaryHold,\n };\n}\n\n/** Installs the transition machinery on first use; later calls return the same hooks. */\nfunction ensureHooks(): Hooks {\n const existing = rt.hooks;\n if (existing !== null) return existing;\n const created = createHooks();\n rt.hooks = created;\n return created;\n}\n\n/**\n * Installs the transition machinery (the transition lane, Activity pauses and Suspense holds) now\n * instead of at the first `startTransition`. The machinery is created on first use so that an\n * application that never uses transitions does not carry its code; call this from a primitive whose\n * later work needs the lane to exist, as `useDeferredValue` does. Calling it again does nothing.\n *\n * @example\n * import { registerTransitionLane } from \"@shadow-js/core/extend\";\n *\n * export function useBackgroundValue(): void {\n * registerTransitionLane(); // later lane-only effects of this hook find the lane\n * }\n * @see startTransition\n * @since 1.0.0\n */\nexport function registerTransitionLane(): void {\n ensureHooks();\n}\n\n/**\n * Runs `fn` as a transition: the effects its writes wake wait in the transition lane, which runs\n * after urgent work (in a macrotask, one chunk at a time). Reads see the writes at once; the DOM\n * catches up when the lane runs. Use it for an update that may be slow to render or load, so input\n * stays responsive and a Suspense boundary keeps its content instead of showing its fallback. `fn`\n * runs untracked. The returned promise resolves when the lane is idle and no Suspense boundary holds\n * the transition.\n *\n * On the server there are no effects, so `fn` simply runs and the promise is already resolved.\n *\n * @param fn Callback whose writes form the transition.\n * @returns A promise that resolves when the transition has been applied.\n * @throws What `fn` throws, synchronously; no transition is started then.\n * @example\n * import { startTransition, useSignal } from \"@shadow-js/core\";\n *\n * const [page, setPage] = useSignal(\"home\");\n * async function openReports(): Promise<void> {\n * await startTransition(() => setPage(\"reports\"));\n * console.log(`${page()} is on screen`);\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function startTransition(fn: () => void): Promise<void> {\n if (__SERVER__) {\n fn();\n return Promise.resolve();\n }\n return ensureHooks().startTransition(fn);\n}\n\n/**\n * Starts a Suspense hold: the boundary keeps showing its current content while a transition waits\n * for data. Holds are counted, and the running transitions stay pending (`isPending` of\n * `useTransition`, the promise of `startTransition`) until every hold has ended. For renderers that\n * implement Suspense; each call needs one {@link endHold}. Does nothing before the transition\n * machinery exists (no transition has run).\n *\n * @example\n * import { beginHold, endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function holdUntil(data: Promise<unknown>): void {\n * beginHold(); // the boundary keeps its content\n * void data.finally(() => {\n * wakeSuspended();\n * endHold();\n * });\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function beginHold(): void {\n rt.hooks?.beginHold();\n}\n\n/**\n * Ends a Suspense hold started with {@link beginHold}. Call {@link wakeSuspended} first, so the\n * memos and effects that waited are queued; this then schedules the lane for them and, once the lane\n * is idle and no hold remains, resolves the transitions that were waiting. Extra calls never take the\n * count below zero. Does nothing before the transition machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function release(): void {\n * wakeSuspended(); // the held readers run again with the data that arrived\n * endHold();\n * }\n * @see beginHold\n * @since 1.0.0\n */\nexport function endHold(): void {\n rt.hooks?.endHold();\n}\n\n/**\n * Wakes every memo and effect that kept its value for a transition (it caught {@link SUSPENSION}):\n * each runs again in the transition lane, so it reads the data that arrived. A Suspense boundary\n * calls it when it releases its hold, before {@link endHold}. Does nothing before the transition\n * machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function onDataArrived(): void {\n * wakeSuspended();\n * endHold();\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function wakeSuspended(): void {\n rt.hooks?.wakeSuspended();\n}\n\n/**\n * Lets a pending read inside a transition keep the boundary's content: when the tracker's `hold()`\n * returns true (the boundary holds its content for the transition), the reader throws\n * {@link SUSPENSION} and keeps its previous value until the boundary wakes it. Call it from a data\n * primitive's reader when its data is pending, the reader is tracked and {@link inTransition} is\n * true, as `useResource` does. Does nothing before the transition machinery exists, or when the\n * tracker has no `hold`.\n *\n * @param tracker The Suspense tracker of the nearest boundary (`SuspenseContext`).\n * @throws {@link SUSPENSION} (not an error) when the boundary holds its content.\n * @example\n * import { useContext, SuspenseContext } from \"@shadow-js/core\";\n * import { currentListener, holdReader, inTransition } from \"@shadow-js/core/extend\";\n *\n * export function readPending(): void {\n * const tracker = useContext(SuspenseContext);\n * if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n * }\n * @see isSuspension\n * @since 1.0.0\n */\nexport function holdReader(tracker: { hold?(): boolean }): void {\n rt.hooks?.holdReader(tracker);\n}\n\n/**\n * Tells whether a transition callback or a transition-lane run is active, so the writes made now\n * belong to the lane. Use it in a primitive that treats transition reads differently, such as a data\n * reader that holds the boundary only in a transition.\n *\n * @returns True inside `startTransition`'s callback and while the lane runs.\n * @example\n * import { startTransition } from \"@shadow-js/core\";\n * import { inTransition } from \"@shadow-js/core/extend\";\n *\n * void startTransition(() => {\n * console.log(inTransition()); // true in the browser\n * });\n * console.log(inTransition()); // false\n * @see startTransition\n * @since 1.0.0\n */\nexport function inTransition(): boolean {\n return rt.inTransition;\n}\n\n/**\n * Creates the hold of a value a transition builds (see {@link TransitionHold}): the reads that wait\n * for data inside `hold.run(...)` count against this hold instead of the Suspense boundary around the\n * value, so the value on screen stays until the new one is ready. For renderers that build values\n * during a transition.\n *\n * @param onSettled Called each time the number of waiting reads drops back to zero.\n * @returns The hold, or null when the transition machinery does not exist yet (no transition has run,\n * so nothing can be held).\n * @example\n * import { createTransitionHold } from \"@shadow-js/core/extend\";\n *\n * const hold = createTransitionHold(() => console.log(\"ready to commit\"));\n * const built = hold === null ? \"now\" : hold.run(() => \"pending\");\n * @see transitionHooks\n * @since 1.0.0\n */\nexport function createTransitionHold(onSettled: () => void): TransitionHold | null {\n const hooks = rt.hooks;\n return hooks === null ? null : hooks.createHold(onSettled);\n}\n\n/**\n * Returns the transition machinery while a transition is running, otherwise null. Renderers reach\n * the slot and boundary layers (`slotSwap`, `boundaryHold`) only through it: a transition can only be\n * running once the machinery exists, so this never creates it (a static call that did would keep the\n * whole machinery in every bundle that renders a Show).\n *\n * @returns The hooks during a transition callback or lane run, null otherwise.\n * @example\n * import { transitionHooks } from \"@shadow-js/core/extend\";\n *\n * export function boundaryHoldIfTransition() {\n * return transitionHooks()?.boundaryHold() ?? null;\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function transitionHooks(): Hooks | null {\n return rt.inTransition ? rt.hooks : null;\n}\n\n/**\n * Pauses `owner` and everything below it (Activity hidden). User effects run their cleanups and wait.\n * DOM bindings (render effects) wait without a cleanup, so their nodes stay as they are. Memos keep their\n * last value, and effects created below are parked until the owner resumes. Pauses nest: each\n * `pauseOwner` needs one `resumeOwner`. Use it to hide a subtree while keeping its state.\n *\n * @param owner The owner to pause, with its whole subtree.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const hidden = createOwner(null);\n * pauseOwner(hidden); // its effects stop; its memos keep their values\n * resumeOwner(hidden); // its user effects run again with the latest values\n * @see resumeOwner\n * @since 1.0.0\n */\nexport function pauseOwner(owner: Owner): void {\n ensureHooks().pause(owner);\n}\n\n/**\n * Resumes an owner paused with {@link pauseOwner}; the subtree runs again once its last pause ends.\n * User effects below it run once more with the current values (their cleanups ran on pause). DOM\n * bindings run only if something they read changed while paused, so a hidden subtree is not rebuilt\n * on show. Memos that changed while paused wake their readers outside the owner. Call it once per\n * `pauseOwner`, not on an owner that is not paused.\n *\n * @param owner The paused owner.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const panel = createOwner(null);\n * pauseOwner(panel);\n * resumeOwner(panel); // every user effect below runs once with the latest values\n * @see pauseOwner\n * @since 1.0.0\n */\nexport function resumeOwner(owner: Owner): void {\n rt.hooks?.resume(owner);\n}\n"],"mappings":"A,ysBAgDA,SAAS0B,EAAKC,EAAaC,EAAoC,CAC7D,IAAMC,EAAiB,CAACF,CAAI,EAC5B,KAAOE,EAAM,OAAS,GAAG,CACvB,IAAMC,EAAOD,EAAM,IAAI,EACvBD,EAAME,CAAI,EACV,IAAK,IAAIC,EAAQD,EAAK,UAAWC,IAAU,KAAMA,EAAQA,EAAM,YAAaF,EAAM,KAAKE,CAAK,CAC9F,CACF,CAGA,SAASC,GAAqB,CAC5B,IAAMC,EAA4B,CAAC,EAC7BC,EAA0B,CAAC,EAM7BC,EAAgC,KAChCC,EAAsC,KAQpCC,kBAAY,IAAI,IAElBC,EAAQ,EACRC,EAAY,GAEVC,MAAgCP,EAAW,OAAS,GAAKC,EAAS,OAAS,EAC3EO,MAA0BD,EAAe,GAAKF,EAAQ,EAMtDI,GAAaC,EAAsBC,IAA0B,CACjE,IAAMC,EAAQF,EAAM,OAAO,EAAGC,CAAK,EACnCC,EAAM,K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"],"sourcesContent":["/**\n * The runtime's side of the devtools protocol (version 1, see `@shadow-js/devtools`). The runtime\n * does not import that package: it looks up a global hook, in development builds only, and every\n * call site is wrapped as `if (__DEV__) report(...)` so production bundles drop it entirely.\n */\n\n/**\n * The event kinds of the devtools protocol (version 1), numbered as `EVENT` in `@shadow-js/devtools`\n * numbers them. Pass one to {@link devtoolsReport} when a custom primitive shows up in devtools; the\n * meaning of the other arguments of each kind is in the protocol table of the devtools README.\n *\n * Kinds 16 and 17 are the transition events, reported by `internal/concurrency.ts`: `TRANSITION_START`\n * (16) after a `transition()` callback has run, with no arguments; `TRANSITION_END` (17) when the\n * transition lane is idle, with the number of transitions it resolved. The devtools agent does not use\n * them yet.\n *\n * @example\n * import { DEVTOOLS_EVENT } from \"@shadow-js/core/extend\";\n *\n * function describe(kind: number): string {\n * if (kind === DEVTOOLS_EVENT.SIGNAL_WRITTEN) return \"signal written\";\n * if (kind === DEVTOOLS_EVENT.ERROR) return \"error\";\n * return `event ${kind}`;\n * }\n * @see devtoolsReport\n * @since 1.0.0\n */\nexport const DEVTOOLS_EVENT = {\n OWNER_CREATED: 1,\n OWNER_DISPOSED: 2,\n SIGNAL_CREATED: 3,\n SIGNAL_WRITTEN: 4,\n COMPUTATION_CREATED: 5,\n COMPUTATION_RUN: 6,\n COMPUTATION_DISPOSED: 7,\n COMPONENT_MOUNTED: 8,\n COMPONENT_UNMOUNTED: 9,\n RESOURCE_STATE: 10,\n ERROR: 11,\n HYDRATION_MISMATCH: 12,\n FLUSH_START: 13,\n FLUSH_END: 14,\n STORE_CREATED: 15,\n TRANSITION_START: 16,\n TRANSITION_END: 17,\n} as const;\n\nconst KEY = \"__SHADOWJS_DEVTOOLS_HOOK__\";\n\ninterface Hook {\n readonly version: number;\n report(kind: number, a?: unknown, b?: unknown, c?: unknown, d?: unknown, e?: unknown): void;\n}\n\n/**\n * Reports one event to the devtools hook (`globalThis.__SHADOWJS_DEVTOOLS_HOOK__`, protocol version\n * 1) when one is installed. Does nothing without a hook, with a hook of another version, and in\n * production builds. Exported from `@shadow-js/core/extend` as `devtoolsReport`. Pass the runtime's\n * own objects, not copies, so a report allocates nothing.\n *\n * @param kind The event kind, one of {@link DEVTOOLS_EVENT}.\n * @param a First argument of the event (see the protocol table of the devtools README).\n * @param b Second argument of the event, or undefined when the kind has none.\n * @param c Third argument of the event, or undefined when the kind has none.\n * @param d Fourth argument of the event, or undefined when the kind has none.\n * @param e Fifth argument of the event, or undefined when the kind has none.\n * @example\n * import { isDev } from \"@shadow-js/core\";\n * import { currentOwner, DEVTOOLS_EVENT, devtoolsReport } from \"@shadow-js/core/extend\";\n *\n * function reportFailure(error: unknown): void {\n * if (isDev) devtoolsReport(DEVTOOLS_EVENT.ERROR, currentOwner(), error, undefined);\n * }\n * @see DEVTOOLS_EVENT\n * @since 1.0.0\n */\nexport function report(\n kind: number,\n a?: unknown,\n b?: unknown,\n c?: unknown,\n d?: unknown,\n e?: unknown,\n): void {\n if (!__DEV__) return;\n const hook = Reflect.get(globalThis, KEY) as Hook | undefined;\n if (hook !== undefined && hook.version === 1) hook.report(kind, a, b, c, d, e);\n}\n"],"mappings":"AA2BA,MAAaA,EAAiB,CAC5B,cAAe,EACf,eAAgB,EAChB,eAAgB,EAChB,eAAgB,EAChB,oBAAqB,EACrB,gBAAiB,EACjB,qBAAsB,EACtB,kBAAmB,EACnB,oBAAqB,EACrB,eAAgB,GAChB,MAAO,GACP,mBAAoB,GACpB,YAAa,GACb,UAAW,GACX,cAAe,GACf,iBAAkB,GAClB,eAAgB,EAClB,EA+BA,SAAgBC,
|
|
1
|
+
{"version":3,"file":"devtools.js","names":["DEVTOOLS_EVENT","report","kind","a","b","c","d","e"],"sources":["../../../src/internal/devtools.ts"],"sourcesContent":["/**\n * The runtime's side of the devtools protocol (version 1, see `@shadow-js/devtools`). The runtime\n * does not import that package: it looks up a global hook, in development builds only, and every\n * call site is wrapped as `if (__DEV__) report(...)` so production bundles drop it entirely.\n */\n\n/**\n * The event kinds of the devtools protocol (version 1), numbered as `EVENT` in `@shadow-js/devtools`\n * numbers them. Pass one to {@link devtoolsReport} when a custom primitive shows up in devtools; the\n * meaning of the other arguments of each kind is in the protocol table of the devtools README.\n *\n * Kinds 16 and 17 are the transition events, reported by `internal/concurrency.ts`: `TRANSITION_START`\n * (16) after a `transition()` callback has run, with no arguments; `TRANSITION_END` (17) when the\n * transition lane is idle, with the number of transitions it resolved. The devtools agent does not use\n * them yet.\n *\n * @example\n * import { DEVTOOLS_EVENT } from \"@shadow-js/core/extend\";\n *\n * function describe(kind: number): string {\n * if (kind === DEVTOOLS_EVENT.SIGNAL_WRITTEN) return \"signal written\";\n * if (kind === DEVTOOLS_EVENT.ERROR) return \"error\";\n * return `event ${kind}`;\n * }\n * @see devtoolsReport\n * @since 1.0.0\n */\nexport const DEVTOOLS_EVENT = {\n OWNER_CREATED: 1,\n OWNER_DISPOSED: 2,\n SIGNAL_CREATED: 3,\n SIGNAL_WRITTEN: 4,\n COMPUTATION_CREATED: 5,\n COMPUTATION_RUN: 6,\n COMPUTATION_DISPOSED: 7,\n COMPONENT_MOUNTED: 8,\n COMPONENT_UNMOUNTED: 9,\n RESOURCE_STATE: 10,\n ERROR: 11,\n HYDRATION_MISMATCH: 12,\n FLUSH_START: 13,\n FLUSH_END: 14,\n STORE_CREATED: 15,\n TRANSITION_START: 16,\n TRANSITION_END: 17,\n} as const;\n\nconst KEY = \"__SHADOWJS_DEVTOOLS_HOOK__\";\n\ninterface Hook {\n readonly version: number;\n report(kind: number, a?: unknown, b?: unknown, c?: unknown, d?: unknown, e?: unknown): void;\n}\n\n/**\n * Reports one event to the devtools hook (`globalThis.__SHADOWJS_DEVTOOLS_HOOK__`, protocol version\n * 1) when one is installed. Does nothing without a hook, with a hook of another version, and in\n * production builds. Exported from `@shadow-js/core/extend` as `devtoolsReport`. Pass the runtime's\n * own objects, not copies, so a report allocates nothing.\n *\n * @param kind The event kind, one of {@link DEVTOOLS_EVENT}.\n * @param a First argument of the event (see the protocol table of the devtools README).\n * @param b Second argument of the event, or undefined when the kind has none.\n * @param c Third argument of the event, or undefined when the kind has none.\n * @param d Fourth argument of the event, or undefined when the kind has none.\n * @param e Fifth argument of the event, or undefined when the kind has none.\n * @example\n * import { isDev } from \"@shadow-js/core\";\n * import { currentOwner, DEVTOOLS_EVENT, devtoolsReport } from \"@shadow-js/core/extend\";\n *\n * function reportFailure(error: unknown): void {\n * if (isDev) devtoolsReport(DEVTOOLS_EVENT.ERROR, currentOwner(), error, undefined);\n * }\n * @see DEVTOOLS_EVENT\n * @since 1.0.0\n */\nexport function report(\n kind: number,\n a?: unknown,\n b?: unknown,\n c?: unknown,\n d?: unknown,\n e?: unknown,\n): void {\n if (!__DEV__) return;\n const hook = Reflect.get(globalThis, KEY) as Hook | undefined;\n if (hook !== undefined && hook.version === 1) hook.report(kind, a, b, c, d, e);\n}\n"],"mappings":"AA2BA,MAAaA,EAAiB,CAC5B,cAAe,EACf,eAAgB,EAChB,eAAgB,EAChB,eAAgB,EAChB,oBAAqB,EACrB,gBAAiB,EACjB,qBAAsB,EACtB,kBAAmB,EACnB,oBAAqB,EACrB,eAAgB,GAChB,MAAO,GACP,mBAAoB,GACpB,YAAa,GACb,UAAW,GACX,cAAe,GACf,iBAAkB,GAClB,eAAgB,EAClB,EA+BA,SAAgBC,EACdC,EACAC,EACAC,EACAC,EACAC,EACAC,EACM,CAIR,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diagnostics.js","names":["
|
|
1
|
+
{"version":3,"file":"diagnostics.js","names":["formatMessage","ShadowError","code","seen","listener","setWarningListener","next","previous","resetWarningDedupe","warn"],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["import { formatMessage, type MessageCode } from \"./messages\";\n\n/**\n * The error class of every diagnostic the runtime throws, carrying a stable code next to the\n * message. Match on `code` rather than the message: the message is the full text in development\n * builds and only `SHADOW_<CODE>` in production builds. Throw it from a custom primitive to report a\n * core diagnostic the same way the built-in hooks do.\n *\n * @example\n * import { ShadowError } from \"@shadow-js/core/extend\";\n *\n * function isCycle(error: unknown): boolean {\n * return error instanceof ShadowError && error.code === \"CYCLE_DETECTED\";\n * }\n * @see MESSAGES\n * @since 1.0.0\n */\nexport class ShadowError extends Error {\n /** The diagnostic code, a key of {@link MESSAGES}; the same in development and production builds. */\n declare readonly code: MessageCode;\n /**\n * Creates the error with the text of {@link formatMessage} for `code` and the name `\"ShadowError\"`.\n * @param code The diagnostic code.\n */\n constructor(code: MessageCode) {\n super(formatMessage(code));\n this.name = \"ShadowError\";\n this.code = code;\n }\n}\n\n/**\n * A function that receives the warnings of {@link warn} instead of `console.warn`. Install one with\n * {@link setWarningListener}.\n * @param code The diagnostic code of the warning.\n * @param message The text of {@link formatMessage} for that code.\n * @since 1.0.0\n */\nexport type WarningListener = (code: MessageCode, message: string) => void;\n\nconst seen = new Set<MessageCode>();\nlet listener: WarningListener | undefined;\n\n/**\n * Sends every later warning to `next` instead of `console.warn`, for devtools and test helpers\n * (`@shadow-js/testing`) that collect warnings. Deduplication still applies: the listener receives\n * the first warning of each code only. Warnings exist in development builds only.\n *\n * @param next The listener to install. Undefined restores the default, `console.warn`.\n * @returns The listener that was installed before, or undefined when it was the default, so the\n * caller can restore it.\n * @example\n * import { type MessageCode, setWarningListener } from \"@shadow-js/core/extend\";\n *\n * const codes: MessageCode[] = [];\n * const previous = setWarningListener((code) => {\n * codes.push(code);\n * });\n * // ... run the code under test, then:\n * setWarningListener(previous);\n * @see warn\n * @see resetWarningDedupe\n * @since 1.0.0\n */\nexport function setWarningListener(next: WarningListener | undefined): WarningListener | undefined {\n const previous = listener;\n listener = next;\n return previous;\n}\n\n/**\n * Forgets which codes {@link warn} has already reported, so the next warning of each code is\n * reported again. Use it between test cases and after a hot reload.\n *\n * @example\n * import { resetWarningDedupe } from \"@shadow-js/core/extend\";\n *\n * function startTestCase(): void {\n * resetWarningDedupe(); // each case sees its own first warnings\n * }\n * @see warn\n * @since 1.0.0\n */\nexport function resetWarningDedupe(): void {\n seen.clear();\n}\n\n/**\n * Reports a development-only diagnostic. Only the first warning of each code is reported, for the\n * whole program, until {@link resetWarningDedupe}; it goes to the listener of\n * {@link setWarningListener}, or to `console.warn` with the text of {@link formatMessage}. Does\n * nothing in production builds. Use it for a mistake that should not stop the app; throw\n * {@link ShadowError} for one that must.\n *\n * @param code The diagnostic code to report.\n * @example\n * import { currentOwner, warn } from \"@shadow-js/core/extend\";\n *\n * export function useTicker(): void {\n * if (currentOwner() === null) warn(\"NO_OWNER_CLEANUP\");\n * }\n * @see setWarningListener\n * @since 1.0.0\n */\nexport function warn(code: MessageCode): void {\n if (!__DEV__) return;\n if (seen.has(code)) return;\n seen.add(code);\n const message = formatMessage(code);\n if (listener !== undefined) listener(code, message);\n else console.warn(message);\n}\n"],"mappings":"A,8CAiBA,IAAaC,EAAb,cAAiC,KAAM,CAOrC,YAAYC,EAAmB,CAC7B,MAAMF,EAAcE,CAAI,CAAC,EACzB,KAAK,KAAO,cACZ,KAAK,KAAOA,CACd,CACF,EAWA,MAAMC,kBAAO,IAAI,IACjB,IAAIC,EAuBJ,SAAgBC,EAAmBC,EAAgE,CACjG,IAAMC,EAAWH,EAEjB,MADAA,GAAWE,EACJC,CACT,CAeA,SAAgBC,GAA2B,CACzCL,EAAK,MAAM,CACb,CAmBA,SAAgBM,EAAKP,EAAyB,CAO9C,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispose.js","names":["disposeTree$1","
|
|
1
|
+
{"version":3,"file":"dispose.js","names":["disposeSubtree","disposeTree$1","hasPending","flushThenThrow","rt","disposeTree","root","failure","failed","error"],"sources":["../../../src/internal/dispose.ts"],"sourcesContent":["import type { Owner } from \"./owner\";\nimport { disposeTree as disposeSubtree } from \"./owner\";\nimport { hasPending } from \"./queue\";\nimport { flushThenThrow } from \"./scheduler\";\nimport { rt } from \"./state\";\n\n/**\n * Disposes an owner and everything below it: children first, newest first, then each node's\n * cleanups, newest first. Use it to end an owner made with `createOwner`; disposing an owner that is\n * already disposed does nothing. Exported from `@shadow-js/core/extend` as `disposeOwner`.\n *\n * Cleanups run in an implicit batch (O-3): effects that depend on signals a cleanup wrote are\n * flushed before this returns, unless the disposal happens inside a computation, a batch or a flush,\n * whose own exit flushes.\n *\n * @param root The owner to dispose, with its whole subtree.\n * @throws The error of a cleanup that no error handler caught, once the whole tree is disposed\n * (several such errors are thrown together as an `AggregateError`); during a running flush, that\n * flush throws them instead. An error of the flush that\n * follows is thrown as is, or combined with the cleanup errors in an `AggregateError`.\n * @example\n * import { addCleanup, createOwner, disposeOwner } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * addCleanup(owner, () => console.log(\"released\"));\n * disposeOwner(owner); // logs \"released\"\n * @see addCleanup\n * @since 1.0.0\n */\nexport function disposeTree(root: Owner): void {\n let failure: unknown;\n let failed = false;\n try {\n disposeSubtree(root);\n } catch (error) {\n failed = true;\n failure = error;\n }\n // Only the outermost disposal flushes: a nested one (a cleanup disposing another owner) would run\n // effects while the tree it sits in is half torn down.\n flushThenThrow(\n rt.running === null && rt.batches === 0 && rt.disposing === 0 && !rt.flushing && hasPending(),\n failed,\n failure,\n __DEV__ ? \"Disposal and the following flush both threw.\" : \"SHADOW_DISPOSE_FLUSH_ERRORS\",\n );\n}\n"],"mappings":"A,iKA6BA,SAAgBK,EAAYC,EAAmB,CAC7C,IAAIC,EACAC,EAAS,GACb,GAAI,CACFR,EAAeM,CAAI,CACrB,OAASG,EAAO,CACdD,EAAS,GACTD,EAAUE,CACZ,CAGAN,EACEC,EAAG,UAAY,MAAQA,EAAG,UAAY,GAAKA,EAAG,YAAc,GAAK,CAACA,EAAG,UAAYF,EAAW,EAC5FM,EACAD,EAC2D,6BAC7D,CACF,C"}
|
|
@@ -1 +1 @@
|
|
|
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.nesting >= 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.nesting += 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.nesting -= 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 // The body disposed its own owner and kept going: what it created after that (child computations, cleanups) is\n // attached to a node nobody disposes again, so it would live and subscribe for good. It goes with the run.\n if ((node.flags & FLAG_DISPOSED) !== 0) {\n disposeChildren(node);\n node.runCleanups();\n }\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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AID,IAAU,KACZ,EAAUf,MACL,CACL,IAAMiB,EAAA,GAAYvE,EAAK,MAAA,IACvB,EAAK,OAAS,IACd,IAAMwE,EAAgBxE,EAAK,MAE3B,GADA,EAAK,MAAQsD,EACTiB,EAAU,OACd,IAAMpB,EAAgBxC,EAAG,MACnByC,EAAmBzC,EAAG,SACtB0C,EAAkB1C,EAAG,QAC3B,EAAG,MAAQX,EACX,EAAG,SAAW,KAEd,EAAG,QAAUA,EACb,GAAI,CACF,EAAWqE,EAAyDf,EAAQkB,CAAa,CAC3F,OAAS9C,EAAO,CACTD,EAAWzB,EAAM0B,CAAK,GAAGyC,EAAYzC,EAAO1B,CAAI,EACrD,MACF,QAAU,CACR,EAAG,MAAQmD,EACX,EAAG,SAAWC,EACd,EAAG,QAAUC,CACf,CACF,CACI,OAAOiB,GAAY,aACrBG,EAAWzE,EAAMsE,CAAkB,EAE9BtE,EAAK,MAAA,GAA8BA,EAAK,YAAY,EAE7D,C"}
|
|
1
|
+
{"version":3,"file":"graph.js","names":["ShadowError","Owner","addCleanup","disposeChildren","finishDisposal","handleError","hasErrorHandler","enqueue","nextSequence","rt","NO_SOURCES","Signal","value","equals","name","Computation","parent","kind","flags","fn","unlinkFrom","removeObserver","source","at","observers","last","moved","movedAt","node","from","sources","i","withEdge","array","first","second","length","next","track","listener","position","index","sourcesOf","everyOther","observersOf","hasObservers","edges","out","markStack","stale","observer","previous","trySuspend","error","isFrozen","markObservers","staleObservers","frameNodes","frameIndex","frameTop","updateIfNecessary","root","eagerSources","base","cursor","descended","dependency","needsUpdate","refreshAncestors","recompute","owner","ancestor","readSignal","signal","readMemo","memo","previousOwner","previousListener","previousRunning","result","failed","failure","settleMemo","settleEffect","isEqual","prev","hadError","changed","routeToHandler","comparatorError","unhandled","apply","cleanup","deferred","previousValue"],"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.nesting >= 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.nesting += 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.nesting -= 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 // The body disposed its own owner and kept going: what it created after that (child computations, cleanups) is\n // attached to a node nobody disposes again, so it would live and subscribe for good. It goes with the run.\n if ((node.flags & FLAG_DISPOSED) !== 0) {\n disposeChildren(node);\n node.runCleanups();\n }\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,MAAMU,EAA4B,OAAO,OAAO,CAAC,CAAC,EAkDlD,IAAaC,EAAb,KAAmD,CAExC,KAAA,EAWT,UAAuC,KAEvC,MAAQ,EAaR,YAAYC,EAAUC,EAAmBC,EAAe,CACtD,KAAK,MAAQF,EACb,KAAK,OAASC,EACd,KAAK,KAAOC,CAEd,CACF,EAiBaC,EAAb,cAAiCd,CAAwB,CAYvD,MAAiB,IAAA,GAIjB,GAKA,MAA6D,KAK7D,QAAyBS,EAEzB,UAAuC,KAEvC,MAAQ,EAER,WAAa,EAmBb,YACEM,EACAC,EACAC,EACAC,EACAN,EACAC,EACA,CACA,MAAME,CAAM,EACZ,KAAK,KAAOC,EACZ,KAAK,MAAQC,EACb,KAAK,MAAA,EACL,KAAK,GAAKC,EACV,KAAK,OAASN,EACd,KAAK,KAAOC,EACZ,KAAK,MAAQ,IAAA,GACb,KAAK,IAAMN,EAAa,CAW1B,CAEmB,SAAgB,CACjC,KAAK,OAAA,EACLY,EAAW,KAAM,CAAC,EAClB,KAAK,GAAK,KACV,KAAK,MAAQ,IACf,CACF,EAMA,SAASC,EAAeC,EAAgBC,EAAkB,CACxD,IAAMC,EAAYF,EAAO,UACzB,GAAIE,IAAc,KAAM,OACxB,IAAMC,EAAOD,EAAU,OAAS,EAChC,GAAID,IAAOE,EAAM,CACf,IAAMC,EAAQF,EAAUC,GAClBE,EAAUH,EAAUC,EAAO,GACjCD,EAAUD,GAAMG,EAChBF,EAAUD,EAAK,GAAKI,EACpBD,EAAM,QAAQC,EAAU,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W,KAEdA,EAAG,QAAUmB,EACb,GAAI,CACFgE,EAAWD,EAAyDZ,EAAQe,CAAa,CAC3F,OAASzC,EAAO,CACTD,EAAWxB,EAAMyB,CAAK,GAAGhD,EAAYgD,EAAOzB,CAAI,EACrD,MACF,QAAU,CACRnB,EAAG,MAAQmE,EACXnE,EAAG,SAAWoE,EACdpE,EAAG,QAAUqE,CACf,CACF,CACI,OAAOc,GAAY,aACrB1F,EAAW0B,EAAMgE,CAAkB,EAE9BhE,EAAK,MAAA,GAA8BA,EAAK,YAAY,EAE7D,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydration-flag.js","names":["
|
|
1
|
+
{"version":3,"file":"hydration-flag.js","names":["rt","isHydrating","withHydration","fn","previous"],"sources":["../../../src/internal/hydration-flag.ts"],"sourcesContent":["import { rt } from \"./state\";\n\n/**\n * Tells whether the code runs while `hydrate()` claims server markup. Read it at creation in a hook\n * whose first render must match the server, as `useExternalStore` does to read its server snapshot.\n *\n * @returns True inside {@link withHydration}, false otherwise.\n * @example\n * import { isHydrating } from \"@shadow-js/core/extend\";\n *\n * function initialWidth(serverWidth: number): number {\n * return isHydrating() ? serverWidth : window.innerWidth;\n * }\n * @see withHydration\n * @since 1.0.0\n */\nexport function isHydrating(): boolean {\n return rt.hydrating;\n}\n\n/**\n * Runs `fn` with the hydration flag set, so the hooks created inside see {@link isHydrating} return\n * true, and restores the previous flag in `finally`. Renderers wrap their hydration pass in it (the\n * `hydrate()` of `@shadow-js/web` does); application code does not need it.\n *\n * @param fn The hydration pass. A throw is rethrown after the flag is restored.\n * @returns What `fn` returns.\n * @example\n * import { isHydrating, withHydration } from \"@shadow-js/core/extend\";\n *\n * const during = withHydration(() => isHydrating()); // true\n * const after = isHydrating(); // false again\n * @since 1.0.0\n */\nexport function withHydration<T>(fn: () => T): T {\n const previous = rt.hydrating;\n rt.hydrating = true;\n try {\n return fn();\n } finally {\n rt.hydrating = previous;\n }\n}\n"],"mappings":"A,gCAgBA,SAAgBC,GAAuB,CACrC,OAAOD,EAAG,SACZ,CAgBA,SAAgBE,EAAiBC,EAAgB,CAC/C,IAAMC,EAAWJ,EAAG,UACpBA,EAAG,UAAY,GACf,GAAI,CACF,OAAOG,EAAG,CACZ,QAAU,CACRH,EAAG,UAAYI,CACjB,CACF,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.js","names":["MESSAGES","formatMessage","code"],"sources":["../../../src/internal/messages.ts"],"sourcesContent":["/**\n * The diagnostic catalog: every code the runtime throws (as {@link ShadowError}) or warns with\n * (through {@link warn}), mapped to its development text. Read it to show or match a diagnostic by\n * code. {@link formatMessage} reads it only in development builds, so production bundles keep the\n * code (`SHADOW_<CODE>`) and drop the text (R-CODE-8) unless your own code imports this object.\n *\n * @example\n * import { MESSAGES, type MessageCode } from \"@shadow-js/core/extend\";\n *\n * function explain(code: MessageCode): string {\n * return `${code}: ${MESSAGES[code]}`;\n * }\n * @see formatMessage\n * @since 1.0.0\n */\nexport const MESSAGES = {\n NO_OWNER_EFFECT:\n \"An effect was created outside any owner, so it can never be disposed. Create it inside a component or createRoot().\",\n NO_OWNER_CLEANUP: \"onCleanup() was called outside any owner, so the cleanup will never run.\",\n NO_OWNER_ERROR: \"onError() was called outside any owner, so the handler can never be reached.\",\n WRITE_IN_MEMO:\n \"A signal was written inside a useMemo() computation. Derive values from sources instead, or write from an effect.\",\n CYCLE_DETECTED: \"A reactive cycle was detected: a computation read itself while it was running.\",\n INFINITE_LOOP:\n \"Effects kept re-triggering each other for more than 1000 passes; the flush was aborted.\",\n FLUSH_IN_EFFECT:\n \"flushSync() was called while a flush was already running; the call was ignored.\",\n RUN_WITH_DISPOSED_OWNER:\n \"runWithOwner() was called with an owner that is already disposed; the callback ran without an owner.\",\n DUPLICATE_CORE:\n \"More than one copy of @shadow-js/core is loaded. Signals created by one copy are invisible to the other.\",\n CONTEXT_MISSING: \"useContext() found no provider and the context has no default value.\",\n NO_OWNER_ID:\n \"useId() was called outside any owner; the id is not stable across server and client.\",\n EACH_KEY_DUPLICATE: \"Duplicate key in a keyed list; later duplicates get fresh rows each update.\",\n EFFECT_DEPS_IGNORED:\n \"useEffect(fn, [deps]) ignores the array and re-runs on any signal it reads; use useEffect(deps, fn).\",\n} as const;\n\n/**\n * A diagnostic code: one key of {@link MESSAGES}, such as `\"WRITE_IN_MEMO\"`. {@link ShadowError}\n * carries one in its `code` field, and {@link warn} takes one.\n * @since 1.0.0\n */\nexport type MessageCode = keyof typeof MESSAGES;\n\n/**\n * Turns a diagnostic code into the text the runtime throws or logs: the full sentence in development\n * builds and only a stable code in production builds, so message strings never reach user bundles.\n * Use it when a custom primitive reports a core diagnostic in its own way.\n *\n * @param code The diagnostic code.\n * @returns `[shadow <CODE>] <text>` in development builds, `SHADOW_<CODE>` in production builds.\n * @example\n * import { formatMessage } from \"@shadow-js/core/extend\";\n *\n * const text = formatMessage(\"CONTEXT_MISSING\");\n * // development: \"[shadow CONTEXT_MISSING] useContext() found no provider ...\"\n * // production: \"SHADOW_CONTEXT_MISSING\"\n * @see MESSAGES\n * @since 1.0.0\n */\nexport function formatMessage(code: MessageCode): string {\n return __DEV__ ? `[shadow ${code}] ${MESSAGES[code]}` : `SHADOW_${code}`;\n}\n"],"mappings":"AAeA,MAAaA,EAAW,CACtB,gBACE,sHACF,iBAAkB,2EAClB,eAAgB,+EAChB,cACE,oHACF,eAAgB,iFAChB,cACE,0FACF,gBACE,kFACF,wBACE,uGACF,eACE,2GACF,gBAAiB,uEACjB,YACE,uFACF,mBAAoB,8EACpB,oBACE,sGACJ,EAyBA,SAAgBC,
|
|
1
|
+
{"version":3,"file":"messages.js","names":["MESSAGES","formatMessage","code"],"sources":["../../../src/internal/messages.ts"],"sourcesContent":["/**\n * The diagnostic catalog: every code the runtime throws (as {@link ShadowError}) or warns with\n * (through {@link warn}), mapped to its development text. Read it to show or match a diagnostic by\n * code. {@link formatMessage} reads it only in development builds, so production bundles keep the\n * code (`SHADOW_<CODE>`) and drop the text (R-CODE-8) unless your own code imports this object.\n *\n * @example\n * import { MESSAGES, type MessageCode } from \"@shadow-js/core/extend\";\n *\n * function explain(code: MessageCode): string {\n * return `${code}: ${MESSAGES[code]}`;\n * }\n * @see formatMessage\n * @since 1.0.0\n */\nexport const MESSAGES = {\n NO_OWNER_EFFECT:\n \"An effect was created outside any owner, so it can never be disposed. Create it inside a component or createRoot().\",\n NO_OWNER_CLEANUP: \"onCleanup() was called outside any owner, so the cleanup will never run.\",\n NO_OWNER_ERROR: \"onError() was called outside any owner, so the handler can never be reached.\",\n WRITE_IN_MEMO:\n \"A signal was written inside a useMemo() computation. Derive values from sources instead, or write from an effect.\",\n CYCLE_DETECTED: \"A reactive cycle was detected: a computation read itself while it was running.\",\n INFINITE_LOOP:\n \"Effects kept re-triggering each other for more than 1000 passes; the flush was aborted.\",\n FLUSH_IN_EFFECT:\n \"flushSync() was called while a flush was already running; the call was ignored.\",\n RUN_WITH_DISPOSED_OWNER:\n \"runWithOwner() was called with an owner that is already disposed; the callback ran without an owner.\",\n DUPLICATE_CORE:\n \"More than one copy of @shadow-js/core is loaded. Signals created by one copy are invisible to the other.\",\n CONTEXT_MISSING: \"useContext() found no provider and the context has no default value.\",\n NO_OWNER_ID:\n \"useId() was called outside any owner; the id is not stable across server and client.\",\n EACH_KEY_DUPLICATE: \"Duplicate key in a keyed list; later duplicates get fresh rows each update.\",\n EFFECT_DEPS_IGNORED:\n \"useEffect(fn, [deps]) ignores the array and re-runs on any signal it reads; use useEffect(deps, fn).\",\n} as const;\n\n/**\n * A diagnostic code: one key of {@link MESSAGES}, such as `\"WRITE_IN_MEMO\"`. {@link ShadowError}\n * carries one in its `code` field, and {@link warn} takes one.\n * @since 1.0.0\n */\nexport type MessageCode = keyof typeof MESSAGES;\n\n/**\n * Turns a diagnostic code into the text the runtime throws or logs: the full sentence in development\n * builds and only a stable code in production builds, so message strings never reach user bundles.\n * Use it when a custom primitive reports a core diagnostic in its own way.\n *\n * @param code The diagnostic code.\n * @returns `[shadow <CODE>] <text>` in development builds, `SHADOW_<CODE>` in production builds.\n * @example\n * import { formatMessage } from \"@shadow-js/core/extend\";\n *\n * const text = formatMessage(\"CONTEXT_MISSING\");\n * // development: \"[shadow CONTEXT_MISSING] useContext() found no provider ...\"\n * // production: \"SHADOW_CONTEXT_MISSING\"\n * @see MESSAGES\n * @since 1.0.0\n */\nexport function formatMessage(code: MessageCode): string {\n return __DEV__ ? `[shadow ${code}] ${MESSAGES[code]}` : `SHADOW_${code}`;\n}\n"],"mappings":"AAeA,MAAaA,EAAW,CACtB,gBACE,sHACF,iBAAkB,2EAClB,eAAgB,+EAChB,cACE,oHACF,eAAgB,iFAChB,cACE,0FACF,gBACE,kFACF,wBACE,uGACF,eACE,2GACF,gBAAiB,uEACjB,YACE,uFACF,mBAAoB,8EACpB,oBACE,sGACJ,EAyBA,SAAgBC,EAAcC,EAA2B,CACvD,MAAwD,UAAUA,GACpE,C"}
|
|
@@ -1 +1 @@
|
|
|
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,KAAK,OAASA,EAAO,OAErB,KAAK,KAAOA,EAAO,KACnB,KAAK,MAAQA,EAAO,WACpB,EAAO,YAAc,EACrB,IAAMC,EAAOD,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S,KAAKM,CAAK,OACtD,MAAMA,CACb,C"}
|
|
1
|
+
{"version":3,"file":"owner.js","names":["rt","Owner","parent","last","prev","next","cleanups","previousOwner","previousListener","runCleanup","i","finishDisposal","cleanup","owner","error","handleError","addCleanup","existing","disposeChildren","child","disposeTree","errors","root","node","from","current","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,IAAaC,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,YAAYC,EAAsB,CAEhC,GADA,KAAK,OAASA,EACVA,IAAW,KACb,KAAK,QAAU,KACf,KAAK,MAAQ,KAAK,MAAQ,MACrB,CACL,KAAK,QAAUA,EAAO,QACtB,KAAK,MAAQA,EAAO,MAAQ,EAC5B,KAAK,OAASA,EAAO,OAErB,KAAK,KAAOA,EAAO,KACnB,KAAK,MAAQA,EAAO,WACpBA,EAAO,YAAc,EACrB,IAAMC,EAAOD,EAAO,UACpB,KAAK,YAAcC,EACfA,IAAS,OAAMA,EAAK,YAAc,MACtCD,EAAO,UAAY,IACrB,CAKF,CAYA,aAAoB,CAClB,GAAI,KAAK,SAAU,OACnB,KAAK,SAAW,GAEhB,IAAMA,EAAS,KAAK,OACpB,GAAIA,IAAW,KAAM,CACnB,IAAME,EAAO,KAAK,YACZC,EAAO,KAAK,YACdD,IAAS,OAAMA,EAAK,YAAcC,GAClCA,IAAS,KACRH,EAAO,UAAYE,EADLC,EAAK,YAAcD,EAEtC,KAAK,YAAc,KACnB,KAAK,YAAc,IACrB,CACA,KAAK,UAAU,EAQf,KAAK,YAAY,CACnB,CAOA,aAAoB,CAClB,IAAME,EAAW,KAAK,SACtB,GAAIA,IAAa,KAAM,OACvB,KAAK,SAAW,KAChB,IAAMC,EAAgBP,EAAG,MACnBQ,EAAmBR,EAAG,SAC5BA,EAAG,MAAQ,KACXA,EAAG,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