@shadow-js/core 0.1.0 → 1.0.1
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 +17 -0
- package/LICENSE +2 -2
- package/README.md +134 -331
- package/dist/dev/action.d.ts +34 -0
- package/dist/dev/action.js +89 -0
- package/dist/dev/action.js.map +1 -0
- package/dist/dev/cache.d.ts +33 -0
- package/dist/dev/cache.js +61 -0
- package/dist/dev/cache.js.map +1 -0
- package/dist/dev/context.d.ts +104 -0
- package/dist/dev/context.js +110 -0
- package/dist/dev/context.js.map +1 -0
- package/dist/dev/effect.d.ts +120 -0
- package/dist/dev/effect.js +110 -0
- package/dist/dev/effect.js.map +1 -0
- package/dist/dev/env.d.ts +27 -0
- package/dist/dev/env.js +30 -0
- package/dist/dev/env.js.map +1 -0
- package/dist/dev/events.d.ts +26 -0
- package/dist/dev/events.js +32 -0
- package/dist/dev/events.js.map +1 -0
- package/dist/dev/extend/index.d.ts +329 -0
- package/dist/dev/extend/index.js +316 -0
- package/dist/dev/extend/index.js.map +1 -0
- package/dist/dev/external-store.d.ts +58 -0
- package/dist/dev/external-store.js +59 -0
- package/dist/dev/external-store.js.map +1 -0
- package/dist/dev/index.d.ts +29 -0
- package/dist/dev/index.js +26 -0
- package/dist/dev/internal/concurrency.d.ts +211 -0
- package/dist/dev/internal/concurrency.js +631 -0
- package/dist/dev/internal/concurrency.js.map +1 -0
- package/dist/dev/internal/devtools.d.ts +69 -0
- package/dist/dev/internal/devtools.js +76 -0
- package/dist/dev/internal/devtools.js.map +1 -0
- package/dist/dev/internal/diagnostics.d.ts +88 -0
- package/dist/dev/internal/diagnostics.js +101 -0
- package/dist/dev/internal/diagnostics.js.map +1 -0
- package/dist/dev/internal/dispose.d.ts +26 -0
- package/dist/dev/internal/dispose.js +48 -0
- package/dist/dev/internal/dispose.js.map +1 -0
- package/dist/dev/internal/flags.js +10 -0
- package/dist/dev/internal/flags.js.map +1 -0
- package/dist/dev/internal/graph.d.ts +231 -0
- package/dist/dev/internal/graph.js +577 -0
- package/dist/dev/internal/graph.js.map +1 -0
- package/dist/dev/internal/hydration-flag.d.ts +31 -0
- package/dist/dev/internal/hydration-flag.js +45 -0
- package/dist/dev/internal/hydration-flag.js.map +1 -0
- package/dist/dev/internal/messages.d.ts +54 -0
- package/dist/dev/internal/messages.js +53 -0
- package/dist/dev/internal/messages.js.map +1 -0
- package/dist/dev/internal/owner.d.ts +140 -0
- package/dist/dev/internal/owner.js +289 -0
- package/dist/dev/internal/owner.js.map +1 -0
- package/dist/dev/internal/queue.js +45 -0
- package/dist/dev/internal/queue.js.map +1 -0
- package/dist/dev/internal/scheduler.d.ts +111 -0
- package/dist/dev/internal/scheduler.js +286 -0
- package/dist/dev/internal/scheduler.js.map +1 -0
- package/dist/dev/internal/state.d.ts +139 -0
- package/dist/dev/internal/state.js +27 -0
- package/dist/dev/internal/state.js.map +1 -0
- package/dist/dev/internal/suspension.d.ts +41 -0
- package/dist/dev/internal/suspension.js +44 -0
- package/dist/dev/internal/suspension.js.map +1 -0
- package/dist/dev/internal/types.d.ts +44 -0
- package/dist/dev/list.d.ts +91 -0
- package/dist/dev/list.js +281 -0
- package/dist/dev/list.js.map +1 -0
- package/dist/dev/memo.d.ts +58 -0
- package/dist/dev/memo.js +40 -0
- package/dist/dev/memo.js.map +1 -0
- package/dist/dev/optimistic.d.ts +24 -0
- package/dist/dev/optimistic.js +44 -0
- package/dist/dev/optimistic.js.map +1 -0
- package/dist/dev/ownership.d.ts +202 -0
- package/dist/dev/ownership.js +260 -0
- package/dist/dev/ownership.js.map +1 -0
- package/dist/dev/props.d.ts +132 -0
- package/dist/dev/props.js +281 -0
- package/dist/dev/props.js.map +1 -0
- package/dist/dev/reaction.d.ts +27 -0
- package/dist/dev/reaction.js +60 -0
- package/dist/dev/reaction.js.map +1 -0
- package/dist/dev/reducer.d.ts +39 -0
- package/dist/dev/reducer.js +38 -0
- package/dist/dev/reducer.js.map +1 -0
- package/dist/dev/refs.d.ts +50 -0
- package/dist/dev/refs.js +57 -0
- package/dist/dev/refs.js.map +1 -0
- package/dist/dev/resource.d.ts +133 -0
- package/dist/dev/resource.js +176 -0
- package/dist/dev/resource.js.map +1 -0
- package/dist/dev/selector.d.ts +32 -0
- package/dist/dev/selector.js +117 -0
- package/dist/dev/selector.js.map +1 -0
- package/dist/dev/signal.d.ts +40 -0
- package/dist/dev/signal.js +38 -0
- package/dist/dev/signal.js.map +1 -0
- package/dist/dev/store/index.d.ts +5 -0
- package/dist/dev/store/index.js +4 -0
- package/dist/dev/store/nodes.js +191 -0
- package/dist/dev/store/nodes.js.map +1 -0
- package/dist/dev/store/proxies.js +159 -0
- package/dist/dev/store/proxies.js.map +1 -0
- package/dist/dev/store/read.d.ts +37 -0
- package/dist/dev/store/read.js +71 -0
- package/dist/dev/store/read.js.map +1 -0
- package/dist/dev/store/reconcile.d.ts +71 -0
- package/dist/dev/store/reconcile.js +185 -0
- package/dist/dev/store/reconcile.js.map +1 -0
- package/dist/dev/store/types.d.ts +104 -0
- package/dist/dev/store/use-store.d.ts +58 -0
- package/dist/dev/store/use-store.js +167 -0
- package/dist/dev/store/use-store.js.map +1 -0
- package/dist/dev/suspense.d.ts +99 -0
- package/dist/dev/suspense.js +44 -0
- package/dist/dev/suspense.js.map +1 -0
- package/dist/dev/transitions.d.ts +75 -0
- package/dist/dev/transitions.js +100 -0
- package/dist/dev/transitions.js.map +1 -0
- package/dist/prod/action.js +2 -0
- package/dist/prod/action.js.map +1 -0
- package/dist/prod/cache.js +2 -0
- package/dist/prod/cache.js.map +1 -0
- package/dist/prod/context.js +2 -0
- package/dist/prod/context.js.map +1 -0
- package/dist/prod/effect.js +2 -0
- package/dist/prod/effect.js.map +1 -0
- package/dist/prod/env.js +2 -0
- package/dist/prod/env.js.map +1 -0
- package/dist/prod/events.js +2 -0
- package/dist/prod/events.js.map +1 -0
- package/dist/prod/extend/index.js +2 -0
- package/dist/prod/extend/index.js.map +1 -0
- package/dist/prod/external-store.js +2 -0
- package/dist/prod/external-store.js.map +1 -0
- package/dist/prod/index.js +1 -0
- package/dist/prod/internal/concurrency.js +2 -0
- package/dist/prod/internal/concurrency.js.map +1 -0
- package/dist/prod/internal/devtools.js +2 -0
- package/dist/prod/internal/devtools.js.map +1 -0
- package/dist/prod/internal/diagnostics.js +2 -0
- package/dist/prod/internal/diagnostics.js.map +1 -0
- package/dist/prod/internal/dispose.js +2 -0
- package/dist/prod/internal/dispose.js.map +1 -0
- package/dist/prod/internal/flags.js +2 -0
- package/dist/prod/internal/flags.js.map +1 -0
- package/dist/prod/internal/graph.js +2 -0
- package/dist/prod/internal/graph.js.map +1 -0
- package/dist/prod/internal/hydration-flag.js +2 -0
- package/dist/prod/internal/hydration-flag.js.map +1 -0
- package/dist/prod/internal/messages.js +2 -0
- package/dist/prod/internal/messages.js.map +1 -0
- package/dist/prod/internal/owner.js +2 -0
- package/dist/prod/internal/owner.js.map +1 -0
- package/dist/prod/internal/queue.js +2 -0
- package/dist/prod/internal/queue.js.map +1 -0
- package/dist/prod/internal/scheduler.js +2 -0
- package/dist/prod/internal/scheduler.js.map +1 -0
- package/dist/prod/internal/state.js +2 -0
- package/dist/prod/internal/state.js.map +1 -0
- package/dist/prod/internal/suspension.js +2 -0
- package/dist/prod/internal/suspension.js.map +1 -0
- package/dist/prod/list.js +2 -0
- package/dist/prod/list.js.map +1 -0
- package/dist/prod/memo.js +2 -0
- package/dist/prod/memo.js.map +1 -0
- package/dist/prod/optimistic.js +2 -0
- package/dist/prod/optimistic.js.map +1 -0
- package/dist/prod/ownership.js +2 -0
- package/dist/prod/ownership.js.map +1 -0
- package/dist/prod/props.js +2 -0
- package/dist/prod/props.js.map +1 -0
- package/dist/prod/reaction.js +2 -0
- package/dist/prod/reaction.js.map +1 -0
- package/dist/prod/reducer.js +2 -0
- package/dist/prod/reducer.js.map +1 -0
- package/dist/prod/refs.js +2 -0
- package/dist/prod/refs.js.map +1 -0
- package/dist/prod/resource.js +2 -0
- package/dist/prod/resource.js.map +1 -0
- package/dist/prod/selector.js +2 -0
- package/dist/prod/selector.js.map +1 -0
- package/dist/prod/signal.js +2 -0
- package/dist/prod/signal.js.map +1 -0
- package/dist/prod/store/index.js +1 -0
- package/dist/prod/store/nodes.js +2 -0
- package/dist/prod/store/nodes.js.map +1 -0
- package/dist/prod/store/proxies.js +2 -0
- package/dist/prod/store/proxies.js.map +1 -0
- package/dist/prod/store/read.js +2 -0
- package/dist/prod/store/read.js.map +1 -0
- package/dist/prod/store/reconcile.js +2 -0
- package/dist/prod/store/reconcile.js.map +1 -0
- package/dist/prod/store/use-store.js +2 -0
- package/dist/prod/store/use-store.js.map +1 -0
- package/dist/prod/suspense.js +2 -0
- package/dist/prod/suspense.js.map +1 -0
- package/dist/prod/transitions.js +2 -0
- package/dist/prod/transitions.js.map +1 -0
- package/dist/server/action.js +2 -0
- package/dist/server/action.js.map +1 -0
- package/dist/server/cache.js +2 -0
- package/dist/server/cache.js.map +1 -0
- package/dist/server/context.js +2 -0
- package/dist/server/context.js.map +1 -0
- package/dist/server/effect.js +2 -0
- package/dist/server/effect.js.map +1 -0
- package/dist/server/env.js +2 -0
- package/dist/server/env.js.map +1 -0
- package/dist/server/events.js +2 -0
- package/dist/server/events.js.map +1 -0
- package/dist/server/extend/index.js +2 -0
- package/dist/server/extend/index.js.map +1 -0
- package/dist/server/external-store.js +2 -0
- package/dist/server/external-store.js.map +1 -0
- package/dist/server/index.js +1 -0
- package/dist/server/internal/concurrency.js +2 -0
- package/dist/server/internal/concurrency.js.map +1 -0
- package/dist/server/internal/devtools.js +2 -0
- package/dist/server/internal/devtools.js.map +1 -0
- package/dist/server/internal/diagnostics.js +2 -0
- package/dist/server/internal/diagnostics.js.map +1 -0
- package/dist/server/internal/dispose.js +2 -0
- package/dist/server/internal/dispose.js.map +1 -0
- package/dist/server/internal/flags.js +2 -0
- package/dist/server/internal/flags.js.map +1 -0
- package/dist/server/internal/graph.js +2 -0
- package/dist/server/internal/graph.js.map +1 -0
- package/dist/server/internal/hydration-flag.js +2 -0
- package/dist/server/internal/hydration-flag.js.map +1 -0
- package/dist/server/internal/messages.js +2 -0
- package/dist/server/internal/messages.js.map +1 -0
- package/dist/server/internal/owner.js +2 -0
- package/dist/server/internal/owner.js.map +1 -0
- package/dist/server/internal/queue.js +2 -0
- package/dist/server/internal/queue.js.map +1 -0
- package/dist/server/internal/scheduler.js +2 -0
- package/dist/server/internal/scheduler.js.map +1 -0
- package/dist/server/internal/state.js +2 -0
- package/dist/server/internal/state.js.map +1 -0
- package/dist/server/internal/suspension.js +2 -0
- package/dist/server/internal/suspension.js.map +1 -0
- package/dist/server/list.js +2 -0
- package/dist/server/list.js.map +1 -0
- package/dist/server/memo.js +2 -0
- package/dist/server/memo.js.map +1 -0
- package/dist/server/optimistic.js +2 -0
- package/dist/server/optimistic.js.map +1 -0
- package/dist/server/ownership.js +2 -0
- package/dist/server/ownership.js.map +1 -0
- package/dist/server/props.js +2 -0
- package/dist/server/props.js.map +1 -0
- package/dist/server/reaction.js +2 -0
- package/dist/server/reaction.js.map +1 -0
- package/dist/server/reducer.js +2 -0
- package/dist/server/reducer.js.map +1 -0
- package/dist/server/refs.js +2 -0
- package/dist/server/refs.js.map +1 -0
- package/dist/server/resource.js +2 -0
- package/dist/server/resource.js.map +1 -0
- package/dist/server/selector.js +2 -0
- package/dist/server/selector.js.map +1 -0
- package/dist/server/signal.js +2 -0
- package/dist/server/signal.js.map +1 -0
- package/dist/server/store/index.js +1 -0
- package/dist/server/store/nodes.js +2 -0
- package/dist/server/store/nodes.js.map +1 -0
- package/dist/server/store/proxies.js +2 -0
- package/dist/server/store/proxies.js.map +1 -0
- package/dist/server/store/read.js +2 -0
- package/dist/server/store/read.js.map +1 -0
- package/dist/server/store/reconcile.js +2 -0
- package/dist/server/store/reconcile.js.map +1 -0
- package/dist/server/store/use-store.js +2 -0
- package/dist/server/store/use-store.js.map +1 -0
- package/dist/server/suspense.js +2 -0
- package/dist/server/suspense.js.map +1 -0
- package/dist/server/transitions.js +2 -0
- package/dist/server/transitions.js.map +1 -0
- package/dist/server-dev/action.js +89 -0
- package/dist/server-dev/action.js.map +1 -0
- package/dist/server-dev/cache.js +61 -0
- package/dist/server-dev/cache.js.map +1 -0
- package/dist/server-dev/context.js +107 -0
- package/dist/server-dev/context.js.map +1 -0
- package/dist/server-dev/effect.js +55 -0
- package/dist/server-dev/effect.js.map +1 -0
- package/dist/server-dev/env.js +30 -0
- package/dist/server-dev/env.js.map +1 -0
- package/dist/server-dev/events.js +32 -0
- package/dist/server-dev/events.js.map +1 -0
- package/dist/server-dev/extend/index.js +316 -0
- package/dist/server-dev/extend/index.js.map +1 -0
- package/dist/server-dev/external-store.js +45 -0
- package/dist/server-dev/external-store.js.map +1 -0
- package/dist/server-dev/index.js +26 -0
- package/dist/server-dev/internal/concurrency.js +632 -0
- package/dist/server-dev/internal/concurrency.js.map +1 -0
- package/dist/server-dev/internal/devtools.js +76 -0
- package/dist/server-dev/internal/devtools.js.map +1 -0
- package/dist/server-dev/internal/diagnostics.js +101 -0
- package/dist/server-dev/internal/diagnostics.js.map +1 -0
- package/dist/server-dev/internal/dispose.js +48 -0
- package/dist/server-dev/internal/dispose.js.map +1 -0
- package/dist/server-dev/internal/flags.js +10 -0
- package/dist/server-dev/internal/flags.js.map +1 -0
- package/dist/server-dev/internal/graph.js +577 -0
- package/dist/server-dev/internal/graph.js.map +1 -0
- package/dist/server-dev/internal/hydration-flag.js +45 -0
- package/dist/server-dev/internal/hydration-flag.js.map +1 -0
- package/dist/server-dev/internal/messages.js +53 -0
- package/dist/server-dev/internal/messages.js.map +1 -0
- package/dist/server-dev/internal/owner.js +289 -0
- package/dist/server-dev/internal/owner.js.map +1 -0
- package/dist/server-dev/internal/queue.js +45 -0
- package/dist/server-dev/internal/queue.js.map +1 -0
- package/dist/server-dev/internal/scheduler.js +286 -0
- package/dist/server-dev/internal/scheduler.js.map +1 -0
- package/dist/server-dev/internal/state.js +27 -0
- package/dist/server-dev/internal/state.js.map +1 -0
- package/dist/server-dev/internal/suspension.js +44 -0
- package/dist/server-dev/internal/suspension.js.map +1 -0
- package/dist/server-dev/list.js +281 -0
- package/dist/server-dev/list.js.map +1 -0
- package/dist/server-dev/memo.js +40 -0
- package/dist/server-dev/memo.js.map +1 -0
- package/dist/server-dev/optimistic.js +44 -0
- package/dist/server-dev/optimistic.js.map +1 -0
- package/dist/server-dev/ownership.js +260 -0
- package/dist/server-dev/ownership.js.map +1 -0
- package/dist/server-dev/props.js +281 -0
- package/dist/server-dev/props.js.map +1 -0
- package/dist/server-dev/reaction.js +60 -0
- package/dist/server-dev/reaction.js.map +1 -0
- package/dist/server-dev/reducer.js +38 -0
- package/dist/server-dev/reducer.js.map +1 -0
- package/dist/server-dev/refs.js +57 -0
- package/dist/server-dev/refs.js.map +1 -0
- package/dist/server-dev/resource.js +175 -0
- package/dist/server-dev/resource.js.map +1 -0
- package/dist/server-dev/selector.js +81 -0
- package/dist/server-dev/selector.js.map +1 -0
- package/dist/server-dev/signal.js +38 -0
- package/dist/server-dev/signal.js.map +1 -0
- package/dist/server-dev/store/index.js +4 -0
- package/dist/server-dev/store/nodes.js +191 -0
- package/dist/server-dev/store/nodes.js.map +1 -0
- package/dist/server-dev/store/proxies.js +159 -0
- package/dist/server-dev/store/proxies.js.map +1 -0
- package/dist/server-dev/store/read.js +71 -0
- package/dist/server-dev/store/read.js.map +1 -0
- package/dist/server-dev/store/reconcile.js +185 -0
- package/dist/server-dev/store/reconcile.js.map +1 -0
- package/dist/server-dev/store/use-store.js +167 -0
- package/dist/server-dev/store/use-store.js.map +1 -0
- package/dist/server-dev/suspense.js +44 -0
- package/dist/server-dev/suspense.js.map +1 -0
- package/dist/server-dev/transitions.js +85 -0
- package/dist/server-dev/transitions.js.map +1 -0
- package/package.json +111 -50
- package/dist/chunk-6Y3CCWOY.js +0 -887
- package/dist/chunk-6Y3CCWOY.js.map +0 -1
- package/dist/chunk-B5FTYDUG.js +0 -3
- package/dist/chunk-B5FTYDUG.js.map +0 -1
- package/dist/index.cjs +0 -2000
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -609
- package/dist/index.d.ts +0 -609
- package/dist/index.js +0 -1094
- package/dist/index.js.map +0 -1
- package/dist/jsx-Bugil6CJ.d.cts +0 -151
- package/dist/jsx-Bugil6CJ.d.ts +0 -151
- package/dist/jsx-dev-runtime.cjs +0 -742
- package/dist/jsx-dev-runtime.cjs.map +0 -1
- package/dist/jsx-dev-runtime.d.cts +0 -2
- package/dist/jsx-dev-runtime.d.ts +0 -2
- package/dist/jsx-dev-runtime.js +0 -4
- package/dist/jsx-dev-runtime.js.map +0 -1
- package/dist/jsx-runtime.cjs +0 -742
- package/dist/jsx-runtime.cjs.map +0 -1
- package/dist/jsx-runtime.d.cts +0 -36
- package/dist/jsx-runtime.d.ts +0 -36
- package/dist/jsx-runtime.js +0 -4
- package/dist/jsx-runtime.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"concurrency.js","names":["walk","stack","root","node","visit","child","createHooks","laneRender","laneUser","waiters","suspended","holds","scheduled","hasLanePending","laneBusy","drainLane","batch","queue","limit","isOrdered","byCreation","effect","FLAG_TRANSITION","FLAG_PARKED","recompute","updateIfNecessary","error","handleError","settleLane","resolved","resolve","scheduleLane","flushLane","rt","previous","budget","passes","clearQueues","ShadowError","errors","reportUncaught","hasPending","schedule","startTransition","listener","fn","applied","parkOrLane","inLane","render","promote","place","renderQueue","userQueue","clear","suspend","SUSPENSION","FLAG_SUSPENDED","holdReader","tracker","beginHold","endHold","wakeSuspended","waiting","markObservers","pause","owner","Computation","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_SUSPENDED,\n FLAG_TRANSITION,\n KIND_EFFECT,\n} from \"./flags\";\nimport {\n Computation,\n hasObservers,\n markObservers,\n readSignal,\n recompute,\n Signal,\n updateIfNecessary,\n} from \"./graph\";\nimport { addCleanup, handleError, Owner } from \"./owner\";\nimport { clearQueues, hasPending, place, renderQueue, userQueue } from \"./queue\";\nimport { byCreation, isOrdered, MAX_FLUSH_PASSES, reportUncaught, 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/** 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();\n if (node === undefined) break;\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 /** Resolvers of the transitions waiting for the lane to go idle. */\n const waiters: Array<() => void> = [];\n /** Memos and effects that caught a suspension; woken all at once when a boundary releases them. */\n const suspended: 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 if (!isOrdered(batch)) 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 try {\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n }\n return batch.length;\n };\n\n /** Resolves the transitions that wait for the lane, once the lane is idle. */\n const settleLane = (): void => {\n if (laneBusy() || waiters.length === 0) return;\n const resolved = waiters.splice(0, waiters.length);\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_END, resolved.length);\n for (const resolve of resolved) 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 const applied = new Promise<void>((resolve) => {\n waiters.push(resolve);\n });\n settleLane();\n return applied;\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 node.flags |= FLAG_SUSPENDED;\n suspended.push(node);\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 waiting = suspended.splice(0, suspended.length);\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 waiting) {\n if ((node.flags & FLAG_SUSPENDED) === 0 || node.disposed) continue;\n node.flags &= ~FLAG_SUSPENDED;\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 walk(owner, (node) => {\n node.pauses += 1;\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 };\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,gwBAsDA,SAASA,EAAK,EAAa,EAAoC,CAC7D,IAAMC,EAAiB,CAACC,CAAI,EAC5B,KAAOD,EAAM,OAAS,GAAG,CACvB,IAAME,EAAOF,EAAM,IAAI,EACvB,GAAIE,IAAS,IAAA,GAAW,MACxBC,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,EAE3BC,EAA6B,CAAC,EAE9BC,EAA2B,CAAC,EAE9BC,EAAQ,EACRC,EAAY,GAEVC,MAAgCN,EAAW,OAAS,GAAKC,EAAS,OAAS,EAC3EM,MAA0BD,EAAe,GAAKF,EAAQ,EAMtDI,GAAa,EAAsB,IAA0B,CACjE,IAAMC,EAAQC,EAAM,OAAO,EAAGC,CAAK,EAC9BC,EAAUH,CAAK,GAAGA,EAAM,KAAKI,CAAU,EAC5C,IAAK,IAAMC,KAAUL,EACnB,GAAKK,EAAO,MAAA,OACZ,EAAO,OAAS,EAAA,EAAgBC,GAC3B,IAAO,MAAA,IACZ,IAAID,EAAO,OAAS,EAClB,EAAO,OAASE,EAAcD,OAGhC,GAAI,CACED,EAAO,QAAA,EAAiBG,EAAUH,CAAM,EACvCI,EAAkBJ,CAAM,CAC/B,OAASK,EAAO,CACdC,EAAYD,EAAOL,CAAM,CAC3B,CANA,CAQF,OAAOL,EAAM,MACf,EAGMY,MAAyB,CAC7B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C9B,CAmBA,SAAgBkD,GAAwB,CACtC,OAAO5E,EAAG,YACZ,CAmBA,SAAgB6E,EAAqB,EAA8C,CACjF,IAAMC,EAAQ9E,EAAG,MACjB,OAAO8E,IAAU,KAAO,KAAOA,EAAM,WAAWvC,CAAS,CAC3D,CAkBA,SAAgBwC,GAAgC,CAC9C,OAAO/E,EAAG,aAAeA,EAAG,MAAQ,IACtC,CAkBA,SAAgBgF,EAAW,EAAoB,CAC7CR,EAAY,CAAC,CAAC,MAAMvC,CAAK,CAC3B,CAmBA,SAAgBgD,EAAY,EAAoB,CAC9CjF,EAAG,OAAO,OAAOiC,CAAK,CACxB,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e={OWNER_CREATED:1,OWNER_DISPOSED:2,SIGNAL_CREATED:3,SIGNAL_WRITTEN:4,COMPUTATION_CREATED:5,COMPUTATION_RUN:6,COMPUTATION_DISPOSED:7,COMPONENT_MOUNTED:8,COMPONENT_UNMOUNTED:9,RESOURCE_STATE:10,ERROR:11,HYDRATION_MISMATCH:12,FLUSH_START:13,FLUSH_END:14,STORE_CREATED:15,TRANSITION_START:16,TRANSITION_END:17};function t(e,t,n,r,i,a){}export{e as DEVTOOLS_EVENT,t as report};
|
|
2
|
+
//# sourceMappingURL=devtools.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"devtools.js","names":["DEVTOOLS_EVENT","report"],"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,EACd,EACA,EACA,EACA,EACA,EACA,EACM,CAIR,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{formatMessage as e}from"./messages.js";var t=class extends Error{code;constructor(t){super(e(t)),this.name=`ShadowError`,this.code=t}};const n=/* @__PURE__ */ new Set;let r;function i(e){let t=r;return r=e,t}function a(){n.clear()}function o(e){}export{t as ShadowError,a as resetWarningDedupe,i as setWarningListener,o as warn};
|
|
2
|
+
//# sourceMappingURL=diagnostics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diagnostics.js","names":["ShadowError","formatMessage","code","seen","listener","setWarningListener","previous","next","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 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,IAAaA,EAAb,cAAiC,KAAM,CAErC,KAKA,YAAY,EAAmB,CAC7B,MAAMC,EAAcC,CAAI,CAAC,EACzB,KAAK,KAAO,cACZ,KAAK,KAAOA,CACd,CACF,EAWA,MAAMC,kBAAO,IAAI,IACjB,IAAIC,EAuBJ,SAAgBC,EAAmB,EAAgE,CACjG,IAAMC,EAAWF,EAEjB,MADA,GAAWG,EACJD,CACT,CAeA,SAAgBE,GAA2B,CACzCL,EAAK,MAAM,CACb,CAmBA,SAAgBM,EAAK,EAAyB,CAO9C,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{rt as e}from"./state.js";import{disposeTree as t}from"./owner.js";import{hasPending as n}from"./queue.js";import{flush as r}from"./scheduler.js";function i(i){let a,o=!1;try{t(i)}catch(e){o=!0,a=e}if(e.running===null&&e.batchDepth===0&&!e.flushing&&n())try{r()}catch(e){throw o?AggregateError([a,e],`SHADOW_DISPOSE_FLUSH_ERRORS`):e}if(o)throw a}export{i as disposeTree};
|
|
2
|
+
//# sourceMappingURL=dispose.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dispose.js","names":["disposeTree$1","disposeTree","failure","failed","root","error","rt","hasPending","flush"],"sources":["../../../src/internal/dispose.ts"],"sourcesContent":["import type { Owner } from \"./owner\";\nimport { disposeTree as disposeSubtree } from \"./owner\";\nimport { hasPending } from \"./queue\";\nimport { flush } 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 if (rt.running === null && rt.batchDepth === 0 && !rt.flushing && hasPending()) {\n try {\n flush();\n } catch (error) {\n if (!failed) throw error;\n throw new AggregateError(\n [failure, error],\n __DEV__ ? \"Disposal and the following flush both threw.\" : \"SHADOW_DISPOSE_FLUSH_ERRORS\",\n );\n }\n }\n if (failed) throw failure;\n}\n"],"mappings":"A,wJA6BA,SAAgBC,EAAY,EAAmB,CAC7C,IAAIC,EACAC,EAAS,GACb,GAAI,CACFH,EAAeI,CAAI,CACrB,OAASC,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,CACA,GAAIC,EAAG,UAAY,MAAQA,EAAG,aAAe,GAAK,CAACA,EAAG,UAAYC,EAAW,EAC3E,GAAI,CACFC,EAAM,CACR,OAASH,EAAO,CAEd,MADKF,EACK,eACR,CAACD,EAASG,CAAK,EAC4C,6BAC7D,EAJmBA,CAKrB,CAEF,GAAIF,EAAQ,MAAMD,CACpB,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flags.js","names":["FLAG_TRANSITION","FLAG_PARKED","FLAG_SUSPENDED"],"sources":["../../../src/internal/flags.ts"],"sourcesContent":["/** Node states: how stale a node is. Monotonic CLEAN < CHECK < DIRTY between two refreshes. */\nexport const CLEAN = 0;\n/** A transitive source changed; verify sources before recomputing. */\nexport const CHECK = 1;\n/** A direct source changed; recompute. */\nexport const DIRTY = 2;\n\n/** Node kinds. */\nexport const KIND_SIGNAL = 0;\nexport const KIND_MEMO = 1;\nexport const KIND_EFFECT = 2;\n\n/** Bit flags on computations. */\nexport const FLAG_RUNNING = 1;\nexport const FLAG_QUEUED = 2;\nexport const FLAG_DISPOSED = 4;\nexport const FLAG_HAS_ERROR = 8;\n/** Effect belongs to the render phase (runs before user effects, synchronously at creation). */\nexport const FLAG_RENDER = 16;\n/** Memo has not produced its first value yet. */\nexport const FLAG_UNINIT = 32;\n/** Explicit-dependency effect whose first apply is skipped. */\nexport const FLAG_DEFER = 64;\n/** Node is on the pull stack of updateIfNecessary (guards re-entrant ancestor refreshes). */\nexport const FLAG_REFRESHING = 128;\n/** Memo that builds components: its body may write signals (component setup does). */\nexport const FLAG_ALLOW_WRITES = 256;\n/** Effect always runs in the transition lane (the watcher behind useDeferredValue). */\nexport const FLAG_LANE = 512;\n/** Effect is queued in (or parked from) the transition lane, not the urgent queues. */\nexport const FLAG_TRANSITION = 1024;\n/** Effect was due while its owner was paused: it waits, unqueued, until the owner resumes. */\nexport const FLAG_PARKED = 2048;\n/** Computation threw a suspension: it keeps its previous value until its boundary releases it. */\nexport const FLAG_SUSPENDED = 4096;\n"],"mappings":"AA8BA,MAAaA,EAAkB,KAElBC,EAAc,KAEdC,EAAiB,K"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ShadowError as e}from"./diagnostics.js";import{nextSequence as t,rt as n}from"./state.js";import{Owner as r,addCleanup as i,disposeChildren as a,handleError as o,hasErrorHandler as s}from"./owner.js";import{enqueue as c}from"./queue.js";const l=Object.freeze([]);var u=class{kind=0;value;equals;observers=null;stamp=0;name;constructor(e,t,n){this.value=e,this.equals=t,this.name=n}},d=class extends r{kind;state;flags;value;error=void 0;equals;fn;apply=null;sources=l;observers=null;stamp=0;trackIndex=0;seq;name;constructor(e,n,r,i,a,o){super(e),this.kind=n,this.flags=r,this.state=2,this.fn=i,this.equals=a,this.name=o,this.value=void 0,this.seq=t()}reportDisposed(){}release(){this.flags|=4,p(this),this.fn=null,this.apply=null}};function f(e,t){let n=e.observers;if(n===null)return;let r=n.length-2;if(t!==r){let e=n[r],i=n[r+1];n[t]=e,n[t+1]=i,e.sources[i+1]=t}n.length=r}function p(e){m(e,0)}function m(e,t){let n=e.sources;if(!(n.length<=t)){for(let e=n.length-2;e>=t;e-=2)f(n[e],n[e+1]);n.length=t}}function h(e,t,n){let r=e.length;if(r>=16)return e.push(t,n),e;let i=Array(r+2);for(let t=0;t<r;t+=1)i[t]=e[t];return i[r]=t,i[r+1]=n,i}function g(e){let t=n.listener;if(t===null||e.stamp===t.stamp)return;e.stamp=t.stamp;let r=t.trackIndex;if(r<t.sources.length){if(t.sources[r]===e){t.trackIndex=r+2;return}m(t,r)}let i=e.observers,a=t.sources,o=i===null?0:i.length,s=a.length;e.observers=i===null?[t,s]:h(i,t,s),t.sources=h(a,e,o),t.trackIndex=s+2}function _(e){return b(e.sources)}function v(e){return e.observers===null?[]:b(e.observers)}function y(e){return e.observers!==null&&e.observers.length>0}function b(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(e[n]);return t}const x=[];function S(e,t){let r=e.state;e.kind===2?(r<t&&(e.state=t),r===0?c(e):n.inTransition||n.hooks?.promote(e)):r>=t||(e.state=t,r===0&&e.observers!==null&&e.observers.length>0&&x.push(e))}function C(e,t){return n.hooks?.suspend(e,t)===!0}function w(e){return e.pauses>0&&!(e.flags&32)}function T(e){for(E(e.observers,2);x.length>0;){let e=x.pop();e!==void 0&&E(e.observers,1)}}function E(e,t){if(e!==null)for(let n=0;n<e.length;n+=2)S(e[n],t)}const D=[],O=[];let k=0;function A(t,n=!1){if(t.state===0)return;let r=k;D[k]=t,O[k]=0,k+=1,t.flags|=128;try{for(;k>r;){let t=k-1,r=D[t];if(r===void 0)break;if(r.state===1||r.state===2&&n){let n=r.sources,i=O[t]??0,a=!1;for(;i<n.length;){let r=n[i];if(i+=2,r.kind===0)continue;let o=r;if(!(o.state===0||o.flags&4)&&!w(o)){if(o.flags&1)throw new e(`CYCLE_DETECTED`);if(j(o),!(o.state===0||o.flags&4)&&!w(o)){O[t]=i,D[k]=o,O[k]=0,k+=1,o.flags|=128,a=!0;break}}}if(a)continue}r.state===2?P(r):r.state=0,r.flags&=-129,--k}}finally{for(let e=r;e<k;e+=1){let t=D[e];t!==void 0&&(t.flags&=-129)}D.length=r,O.length=r,k=r}}function j(e){let t=[];for(let n=e.parent;n!==null;n=n.parent)n instanceof d&&n.state!==0&&!(n.flags&133)&&!w(n)&&t.push(n);for(let e=t.length-1;e>=0;--e){let n=t[e];n!==void 0&&!(n.flags&4)&&A(n)}}function M(e){return n.listener!==null&&g(e),e.value}function N(t){if(t.flags&1)throw new e(`CYCLE_DETECTED`);if(t.state!==0&&!(t.flags&4)&&!w(t)&&(j(t),t.flags&4||A(t,n.recomputeDepth>=128)),n.listener!==null&&g(t),t.flags&8)throw t.error;return t.value}function P(e){let r=e.fn;if(r===null)return;a(e),e.runCleanups(),e.trackIndex=0,e.errorHandlers=null,e.idCount=0,e.childCount=0;let i=n.owner,o=n.listener,s=n.running;n.owner=e,n.listener=e,n.running=e,n.recomputeDepth+=1,e.state=0,e.flags|=1,e.stamp=t();let c,l=!1,u;try{c=r(e.value)}catch(e){l=!0,u=e}finally{n.owner=i,n.listener=o,n.running=s,--n.recomputeDepth,e.flags&=-2,e.trackIndex<e.sources.length&&m(e,e.trackIndex)}e.kind===1&&F(e,c,l,u),e.kind!==1&&L(e,c,l,u)}function F(e,t,n,r){if(n&&C(e,r))return!1;let i=!!(e.flags&32);e.flags&=-33;let a=!!(e.flags&8),o;if(n&&I(e,r))return!1;if(n)e.flags|=8,e.error=r,o=!0;else{e.flags&=-9,e.error=void 0;let n=e.equals;try{o=i||a||n===!1||!n(e.value,t),o&&(e.value=t)}catch(t){e.flags|=8,e.error=t,o=!0}}if(!o||i)return o;let s=e.observers;if(s===null)return o;for(let e=0;e<s.length;e+=2){let t=s[e];t.state===1&&(t.state=2)}return o}function I(e,t){if(!s(e))return!1;e.flags&=-9,e.error=void 0;try{o(t,e)}catch(t){e.flags|=8,e.error=t}return!0}function L(e,t,r,a){if(r){C(e,a)||o(a,e);return}let s=e.apply,c;if(s===null)c=t;else{let r=!!(e.flags&64);e.flags&=-65;let i=e.value;if(e.value=t,r)return;let a=n.owner,l=n.listener,u=n.running;n.owner=e,n.listener=null,n.running=e;try{c=s(t,i)}catch(t){C(e,t)||o(t,e);return}finally{n.owner=a,n.listener=l,n.running=u}}typeof c==`function`&&(i(e,c),e.flags&4&&e.runCleanups())}export{d as Computation,u as Signal,y as hasObservers,w as isFrozen,T as markObservers,v as observersOf,N as readMemo,M as readSignal,P as recompute,_ as sourcesOf,g as track,p as unlinkSources,A as updateIfNecessary};
|
|
2
|
+
//# sourceMappingURL=graph.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph.js","names":["NO_SOURCES","Signal","value","equals","name","Computation","Owner","parent","kind","flags","fn","nextSequence","unlinkSources","removeObserver","observers","source","last","at","moved","movedAt","unlinkFrom","node","sources","from","i","withEdge","length","array","first","second","next","track","listener","rt","position","index","sourcesOf","everyOther","observersOf","hasObservers","out","edges","markStack","stale","previous","observer","enqueue","trySuspend","error","isFrozen","markObservers","staleObservers","frameNodes","frameIndex","frameTop","updateIfNecessary","root","base","eagerSources","cursor","descended","dependency","ShadowError","refreshAncestors","recompute","pending","owner","ancestor","readSignal","signal","readMemo","memo","disposeChildren","previousOwner","previousListener","previousRunning","result","failed","failure","settleMemo","settleEffect","hadError","changed","routeToHandler","comparatorError","hasErrorHandler","handleError","unhandled","apply","cleanup","deferred","previousValue","addCleanup"],"sources":["../../../src/internal/graph.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport {\n CHECK,\n CLEAN,\n DIRTY,\n FLAG_DEFER,\n FLAG_DISPOSED,\n FLAG_HAS_ERROR,\n FLAG_REFRESHING,\n FLAG_RENDER,\n FLAG_RUNNING,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n KIND_SIGNAL,\n} from \"./flags\";\nimport { addCleanup, disposeChildren, handleError, hasErrorHandler, Owner } from \"./owner\";\nimport { enqueue } from \"./queue\";\nimport { nextSequence, rt } from \"./state\";\nimport type { Cleanup, Equals } from \"./types\";\n\n// Shared and frozen until a computation reads its first source: most effects and memos in a large\n// tree own few edges, and an empty array per node dominates creation cost.\nconst NO_SOURCES: Edges<Source> = Object.freeze([]) as unknown as Edges<Source>;\n\n/** Memo nesting depth after which pulls switch from recursion to the iterative walk. */\nconst DEEP_LIMIT = 128;\n\n/**\n * Anything that can be read reactively and notify observers: a signal, a memo, or a custom source\n * of a primitive. Exported from `@shadow-js/core/extend` as `SourceNode`. Read one with\n * {@link track}; after changing it, call {@link markObservers} and `schedule` (or `notify`).\n * @since 1.0.0\n */\nexport interface Source {\n /**\n * The node kind: 0 for a signal and for any custom source, which have no sources of their own; a\n * computation has its own kind. A refresh walks only the sources whose kind is not 0.\n */\n readonly kind: number;\n /** The current value. */\n value: unknown;\n /**\n * The computations that read this source in their last run, as pairs: an observer, then the index of this source in\n * that observer's `sources`. Null or empty when none. Read it with `observersOf`, which returns the observers alone.\n */\n observers: Edges<Computation> | null;\n /** Stamp of the last computation run that tracked this source (dedupes repeated reads). */\n stamp: number;\n}\n\n/**\n * The edges of one node, stored as pairs in one array: the node on the other side of the edge, then the index of this\n * node's entry in that node's own edge array. One array per side costs half the memory of two parallel ones, and\n * removing an edge stays O(1): the last pair moves into the vacated place and tells its owner where it went.\n */\nexport type Edges<T> = Array<T | number>;\n\n/**\n * The storage of a signal: its value, its equality and the computations that read it. Exported from\n * `@shadow-js/core/extend` as `SignalNode`; create one with `createSignalNode`, read it with\n * {@link readSignal} and write it with `writeSignal`, which notifies its readers. Build a custom\n * primitive on it the way `useSignal` does.\n *\n * @example\n * import { createSignalNode, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(0, Object.is, \"count\");\n * writeSignal(count, 1);\n * console.log(readSignal(count), count instanceof SignalNode); // 1 true\n * @see createSignalNode\n * @since 1.0.0\n */\nexport class Signal<T = unknown> implements Source {\n /** Always 0, the kind of a signal. */\n readonly kind: number = KIND_SIGNAL;\n /**\n * The current value. Assigning it directly notifies no one: use `writeSignal`, or call `notify`\n * after the assignment.\n */\n value: T;\n /** Decides whether a write is a change; `false` treats every write as one. */\n equals: Equals<T>;\n /** The computations that read this signal in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the last computation run that tracked this signal (dedupes repeated reads). */\n stamp = 0;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name: string | undefined;\n\n /**\n * Creates a signal. Prefer `createSignalNode`, which takes the same arguments.\n * @param value Initial value.\n * @param equals Equality that decides whether a write is a change.\n * @param name Devtools label, or undefined for an unnamed signal.\n */\n constructor(value: T, equals: Equals<T>, name: string | undefined) {\n this.value = value;\n this.equals = equals;\n this.name = name;\n if (__DEV__) report(DEVTOOLS_EVENT.SIGNAL_CREATED, this, rt.owner, name, value);\n }\n}\n\n/**\n * A memo or an effect: an owner that reads sources and (for memos) is itself a source. Exported from\n * `@shadow-js/core/extend` as `ComputationNode`; create one with `createComputation` and read a memo\n * with `readComputation`. It owns what its function creates: each run first disposes the children\n * and runs the cleanups of the previous run.\n *\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode(10, Object.is);\n * const total = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 2 });\n * console.log(readComputation<number>(total)); // 20\n * @see createComputation\n * @since 1.0.0\n */\nexport class Computation extends Owner implements Source {\n /** 1 for a memo, 2 for an effect. */\n kind: number;\n /** How stale the node is: 0 (clean), 1 (a transitive source changed), 2 (a direct source changed). */\n state: number;\n /** Engine bit flags (queued, running, disposed, render phase, ...). Read-only outside the engine. */\n flags: number;\n /** A memo's last value; an effect's last computed value when it has an `apply` stage. */\n value: unknown;\n /** The error a memo's last run threw, rethrown to its readers; undefined when it succeeded. */\n error: unknown = undefined;\n /** A memo's equality: readers are notified only when it says the new value differs. */\n equals: Equals<unknown>;\n /** The function each run calls with the previous value; null once disposed. */\n fn: ((previous: never) => unknown) | null;\n /**\n * An effect's second stage, run untracked with the computed value and the previous one; null for\n * none and once disposed.\n */\n apply: ((value: never, previous: never) => unknown) | null = null;\n /**\n * The sources the last run read, in reading order, as pairs: a source, then the index of this computation in that\n * source's `observers`. Read it with `sourcesOf`, which returns the sources alone.\n */\n sources: Edges<Source> = NO_SOURCES;\n /** The computations that read this memo in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the current run while it tracks, and of the last run that tracked this memo. */\n stamp = 0;\n /** During a run: how many leading entries of `sources` were confirmed again (they keep their edges). */\n trackIndex = 0;\n /** Creation order; breaks ties between effects at equal depth (G-16). */\n seq: number;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the computation is unnamed)\n */\n name: string | undefined;\n\n /**\n * Creates a computation that has not run yet. Prefer `createComputation`, which also runs or\n * queues it.\n * @param parent The owner to attach to, or null.\n * @param kind 1 for a memo, 2 for an effect.\n * @param flags Initial engine bit flags.\n * @param fn The function each run calls.\n * @param equals A memo's equality; `false` for an effect.\n * @param name Devtools label, or undefined.\n */\n constructor(\n parent: Owner | null,\n kind: number,\n flags: number,\n fn: (previous: never) => unknown,\n equals: Equals<unknown>,\n name: string | undefined,\n ) {\n super(parent);\n this.kind = kind;\n this.flags = flags;\n this.state = DIRTY;\n this.fn = fn;\n this.equals = equals;\n this.name = name;\n this.value = undefined;\n this.seq = nextSequence();\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_CREATED,\n this,\n parent,\n kind === KIND_MEMO ? \"memo\" : \"effect\",\n name,\n (flags & FLAG_RENDER) !== 0,\n );\n }\n }\n\n protected override reportDisposed(): void {\n if (__DEV__) report(DEVTOOLS_EVENT.COMPUTATION_DISPOSED, this);\n }\n\n protected override release(): void {\n this.flags |= FLAG_DISPOSED;\n unlinkSources(this);\n this.fn = null;\n this.apply = null;\n }\n}\n\n/**\n * Removes the pair at `at` from `source.observers` in O(1): the last pair moves into its place, and its observer is told\n * where it went.\n */\nfunction removeObserver(source: Source, at: number): void {\n const observers = source.observers;\n if (observers === null) return;\n const last = observers.length - 2;\n if (at !== last) {\n const moved = observers[last] as Computation;\n const movedAt = observers[last + 1] as number;\n observers[at] = moved;\n observers[at + 1] = movedAt;\n moved.sources[movedAt + 1] = at;\n }\n observers.length = last;\n}\n\n/** Drops every edge from `node` to its sources. */\nexport function unlinkSources(node: Computation): void {\n unlinkFrom(node, 0);\n}\n\n/** Drops the edges from `node` to the sources at index `from` of `node.sources` and later, and truncates the list. */\nfunction unlinkFrom(node: Computation, from: number): void {\n const sources = node.sources;\n if (sources.length <= from) return;\n for (let i = sources.length - 2; i >= from; i -= 2) {\n // The index in the source is read each time: removing an edge may move this node's pair in another source.\n removeObserver(sources[i] as Source, sources[i + 1] as number);\n }\n sources.length = from;\n}\n\n/**\n * The array with the pair `first`, `second` appended: a new array of exactly the right size while short (`new Array(n)`\n * allocates the backing store at that size, where `push` on a short array reserves room for sixteen), the same array\n * grown by `push` from sixteen entries on.\n */\nfunction withEdge<T>(array: Array<T | number>, first: T, second: number): Array<T | number> {\n const length = array.length;\n if (length >= 16) {\n array.push(first, second);\n return array;\n }\n const next = new Array<T | number>(length + 2);\n for (let i = 0; i < length; i += 1) next[i] = array[i] as T | number;\n next[length] = first;\n next[length + 1] = second;\n return next;\n}\n\n/**\n * Records that the running computation read `source`, so a later {@link markObservers} on it marks\n * that computation stale. Call it in the reader of a custom source; {@link readSignal} does it for\n * signals. Does nothing when untracked, and a source read again in the same run is recorded once.\n *\n * @param source The source that was read.\n * @example\n * import { markObservers, schedule, type SourceNode, track } from \"@shadow-js/core/extend\";\n *\n * const clock: SourceNode = { kind: 0, value: Date.now(), observers: null, stamp: 0 };\n * export function now(): number {\n * track(clock);\n * return clock.value as number;\n * }\n * setInterval(() => {\n * clock.value = Date.now();\n * markObservers(clock);\n * schedule();\n * }, 1000);\n * @see readSignal\n * @since 1.0.0\n */\nexport function track(source: Source): void {\n const listener = rt.listener;\n if (listener === null) return;\n if (source.stamp === listener.stamp) return;\n source.stamp = listener.stamp;\n // Same dependency at the same position as last run: keep the edge, touch nothing.\n const position = listener.trackIndex;\n if (position < listener.sources.length) {\n if (listener.sources[position] === source) {\n listener.trackIndex = position + 2;\n return;\n }\n unlinkFrom(listener, position);\n }\n // Edge arrays are small: most nodes have one to three edges. `push` on a short array reserves room for about sixteen\n // entries (200 bytes where an exact array takes 64, measured), and a large list pays it for every row. A short array\n // therefore grows into a new exact one; from sixteen entries on `push` amortizes. Nothing iterates an edge array of\n // a node while it tracks, so replacing the array is safe.\n const observers = source.observers;\n const sources = listener.sources;\n const at = observers === null ? 0 : observers.length;\n const index = sources.length;\n source.observers =\n observers === null\n ? [listener, index]\n : (withEdge(observers, listener, index) as Edges<Computation>);\n listener.sources = withEdge(sources, source, at) as Edges<Source>;\n listener.trackIndex = index + 2;\n}\n\n/**\n * The sources the last run of a computation read, in reading order. Use it to inspect the graph (a debugger, a test);\n * it is a snapshot, so changing the returned array changes no edge.\n *\n * @param node The memo or effect.\n * @returns The signals and memos it reads now.\n * @example\n * import { createComputation, createSignalNode, flushSync, readSignal, sourcesOf } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * const effect = createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(sourcesOf(effect).length); // 1\n * @see observersOf\n * @since 1.0.0\n */\nexport function sourcesOf(node: Computation): Source[] {\n return everyOther(node.sources) as Source[];\n}\n\n/**\n * The computations that read a signal or memo in their last run, in the order their edges were made. It is a snapshot,\n * so changing the returned array changes no edge. The node's own `observers` array stores pairs (the observer and an\n * index for the engine), so read it through this function.\n *\n * @param source A signal, a memo or a custom source.\n * @returns The memos and effects that read it now.\n * @example\n * import { createComputation, createSignalNode, flushSync, observersOf, readSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(observersOf(count).length); // 1\n * @see sourcesOf\n * @since 1.0.0\n */\nexport function observersOf(source: Source): Computation[] {\n return source.observers === null ? [] : (everyOther(source.observers) as Computation[]);\n}\n\n/** True when at least one computation read `source` in its last run. */\nexport function hasObservers(source: Source): boolean {\n return source.observers !== null && source.observers.length > 0;\n}\n\n/** The first element of every pair of an edge array. */\nfunction everyOther<T>(edges: Edges<T>): T[] {\n const out: T[] = [];\n for (let i = 0; i < edges.length; i += 2) out.push(edges[i] as T);\n return out;\n}\n\n// Scratch stack for markObservers; never holds data across calls.\nconst markStack: Computation[] = [];\n\nfunction stale(observer: Computation, next: number): void {\n const previous = observer.state;\n if (observer.kind === KIND_EFFECT) {\n if (previous < next) observer.state = next;\n if (previous === CLEAN) enqueue(observer);\n else if (!rt.inTransition) rt.hooks?.promote(observer);\n return;\n }\n if (previous >= next) return;\n observer.state = next;\n if (previous !== CLEAN) return;\n if (observer.observers !== null && observer.observers.length > 0) markStack.push(observer);\n}\n\n/**\n * A suspension (a transition read pending data inside a held boundary) keeps the node's value until the\n * boundary releases it. True when `error` was one, and the node was recorded for that wake-up.\n */\nfunction trySuspend(node: Computation, error: unknown): boolean {\n return rt.hooks?.suspend(node, error) === true;\n}\n\n/**\n * A memo or effect frozen by a pause keeps its last value and does not refresh until it resumes.\n * A memo that never computed is not frozen (it has no value to keep).\n */\nexport function isFrozen(node: Computation): boolean {\n return node.pauses > 0 && (node.flags & FLAG_UNINIT) === 0;\n}\n\n/**\n * Marks the direct observers of a changed source DIRTY and everything downstream CHECK, and queues\n * the effects it reaches. It does not request a flush: call `schedule` afterward, or use `notify`,\n * which does both. Iterative: the graph can be 100,000 nodes deep (G-10).\n *\n * @param source The source whose value changed.\n * @example\n * import { markObservers, schedule, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function push(list: SignalNode<string[]>, item: string): void {\n * list.value.push(item); // same array: writeSignal would see no change\n * markObservers(list);\n * schedule();\n * }\n * @see track\n * @since 1.0.0\n */\nexport function markObservers(source: Source): void {\n staleObservers(source.observers, DIRTY);\n while (markStack.length > 0) {\n const node = markStack.pop();\n if (node !== undefined) staleObservers(node.observers, CHECK);\n }\n}\n\n/** Marks every observer in a list of edge pairs stale at the given level. */\nfunction staleObservers(observers: Edges<Computation> | null, next: number): void {\n if (observers === null) return;\n for (let i = 0; i < observers.length; i += 2) stale(observers[i] as Computation, next);\n}\n\n// Scratch frames for updateIfNecessary; entries above `frameTop` are dead.\nconst frameNodes: Computation[] = [];\nconst frameIndex: number[] = [];\nlet frameTop = 0;\n\n/**\n * Brings `root` up to date: verifies stale sources oldest-first and recomputes only nodes whose\n * sources really changed (equality cut-off, G-2). Iterative so deep chains cannot overflow (G-10).\n * With `eagerSources`, DIRTY nodes also refresh their previous sources first, which keeps the\n * native stack flat for chains where every node reads both a fresh signal and its predecessor.\n */\nexport function updateIfNecessary(root: Computation, eagerSources = false): void {\n if (root.state === CLEAN) return;\n const base = frameTop;\n frameNodes[frameTop] = root;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n root.flags |= FLAG_REFRESHING;\n try {\n while (frameTop > base) {\n const at = frameTop - 1;\n const node = frameNodes[at];\n if (node === undefined) break;\n if (node.state === CHECK || (node.state === DIRTY && eagerSources)) {\n const sources = node.sources;\n let cursor = frameIndex[at] ?? 0;\n let descended = false;\n while (cursor < sources.length) {\n const source = sources[cursor] as Source;\n cursor += 2;\n if (source.kind === KIND_SIGNAL) continue;\n const dependency = source as Computation;\n if (dependency.state === CLEAN || (dependency.flags & FLAG_DISPOSED) !== 0) continue;\n if (isFrozen(dependency)) continue;\n if ((dependency.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n // An owner that is about to re-run would dispose this dependency: update it first.\n refreshAncestors(dependency);\n if (dependency.state === CLEAN || (dependency.flags & FLAG_DISPOSED) !== 0) continue;\n if (isFrozen(dependency)) continue;\n frameIndex[at] = cursor;\n frameNodes[frameTop] = dependency;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n dependency.flags |= FLAG_REFRESHING;\n descended = true;\n break;\n }\n if (descended) continue;\n }\n if (node.state === DIRTY) recompute(node);\n else node.state = CLEAN;\n node.flags &= ~FLAG_REFRESHING;\n frameTop -= 1;\n }\n } finally {\n // An exception leaves frames on the stack: they must not stay marked as being refreshed.\n for (let i = base; i < frameTop; i += 1) {\n const pending = frameNodes[i];\n if (pending !== undefined) pending.flags &= ~FLAG_REFRESHING;\n }\n frameNodes.length = base;\n frameIndex.length = base;\n frameTop = base;\n }\n}\n\n/**\n * Brings stale owners of `node` up to date, topmost first. An owner that is about to re-run will\n * dispose `node`; computing `node` first would run it with state that is already out of date\n * (a zombie, G-17). Iterative: the owner chain depth is user controlled.\n */\nfunction refreshAncestors(node: Computation): void {\n const stale: Computation[] = [];\n for (let owner = node.parent; owner !== null; owner = owner.parent) {\n if (!(owner instanceof Computation)) continue;\n if (\n owner.state !== CLEAN &&\n (owner.flags & (FLAG_RUNNING | FLAG_DISPOSED | FLAG_REFRESHING)) === 0 &&\n !isFrozen(owner)\n ) {\n stale.push(owner);\n }\n }\n for (let i = stale.length - 1; i >= 0; i -= 1) {\n const ancestor = stale[i];\n if (ancestor !== undefined && (ancestor.flags & FLAG_DISPOSED) === 0) {\n updateIfNecessary(ancestor);\n }\n }\n}\n\n/**\n * Reads a signal's value, subscribing the running computation to it when one is listening. The\n * reader of a custom primitive built on `createSignalNode`.\n *\n * @param signal The signal to read.\n * @returns The current value.\n * @example\n * import { createSignalNode, readSignal } from \"@shadow-js/core/extend\";\n *\n * const name = createSignalNode(\"Ada\", Object.is);\n * export const getName = (): string => readSignal(name);\n * @see track\n * @since 1.0.0\n */\nexport function readSignal<T>(signal: Signal<T>): T {\n if (rt.listener !== null) track(signal);\n return signal.value;\n}\n\n/** Reads a memo: refreshes it if stale, tracks it, rethrows its stored error. */\nexport function readMemo<T>(memo: Computation): T {\n if ((memo.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n if (memo.state !== CLEAN && (memo.flags & FLAG_DISPOSED) === 0 && !isFrozen(memo)) {\n refreshAncestors(memo);\n if ((memo.flags & FLAG_DISPOSED) === 0) {\n updateIfNecessary(memo, rt.recomputeDepth >= DEEP_LIMIT);\n }\n }\n if (rt.listener !== null) track(memo);\n if ((memo.flags & FLAG_HAS_ERROR) !== 0) throw memo.error;\n return memo.value as T;\n}\n\n/** Re-runs a memo or effect: disposes the previous run, re-tracks sources, stores the result. */\nexport function recompute(node: Computation): void {\n const fn = node.fn;\n if (fn === null) return;\n disposeChildren(node);\n node.runCleanups();\n // Edges are kept and re-confirmed in order while the function runs (see track()).\n node.trackIndex = 0;\n // Each run starts from a clean slate: handlers, ids and child indices belong to one run.\n node.errorHandlers = null;\n node.idCount = 0;\n node.childCount = 0;\n\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = node;\n rt.running = node;\n rt.recomputeDepth += 1;\n node.state = CLEAN;\n node.flags |= FLAG_RUNNING;\n node.stamp = nextSequence();\n\n let result: unknown;\n let failed = false;\n let failure: unknown;\n const startedAt = __DEV__ ? performance.now() : 0;\n try {\n result = (fn as (previous: unknown) => unknown)(node.value);\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n rt.recomputeDepth -= 1;\n node.flags &= ~FLAG_RUNNING;\n // Sources this run did not read again are no longer dependencies.\n if (node.trackIndex < node.sources.length) unlinkFrom(node, node.trackIndex);\n }\n\n const changed = node.kind === KIND_MEMO ? settleMemo(node, result, failed, failure) : true;\n if (node.kind !== KIND_MEMO) settleEffect(node, result, failed, failure);\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_RUN,\n node,\n startedAt,\n performance.now() - startedAt,\n changed,\n sourcesOf(node),\n );\n }\n}\n\n/** Stores a memo's result; says whether its value changed (observers were told). */\nfunction settleMemo(\n node: Computation,\n result: unknown,\n failed: boolean,\n failure: unknown,\n): boolean {\n // A suspended memo keeps its previous value: its readers see nothing change until it resumes.\n if (failed && trySuspend(node, failure)) return false;\n const first = (node.flags & FLAG_UNINIT) !== 0;\n node.flags &= ~FLAG_UNINIT;\n const hadError = (node.flags & FLAG_HAS_ERROR) !== 0;\n let changed: boolean;\n if (failed && routeToHandler(node, failure)) {\n return false;\n }\n if (failed) {\n node.flags |= FLAG_HAS_ERROR;\n node.error = failure;\n changed = true;\n } else {\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n const equals = node.equals;\n try {\n changed = first || hadError || equals === false || !equals(node.value, result);\n if (changed) node.value = result;\n } catch (comparatorError) {\n // A throwing comparator is a failing memo, not a wedged graph: readers see the error.\n node.flags |= FLAG_HAS_ERROR;\n node.error = comparatorError;\n changed = true;\n }\n }\n if (!changed || first) return changed;\n const observers = node.observers;\n if (observers === null) return changed;\n for (let i = 0; i < observers.length; i += 2) {\n const observer = observers[i] as Computation;\n if (observer.state === CHECK) observer.state = DIRTY;\n }\n return changed;\n}\n\n/**\n * A memo that fails inside a boundary (an ancestor registered catchError()/onError()) reports to it\n * when it fails, and keeps its previous value. Readers then see that value instead of the error:\n * the reader may live outside the boundary (the DOM region that displays the memo's result), where a\n * rethrown error would escape the very boundary meant to catch it. Without a handler the error is\n * stored and rethrown to readers, so it is never silent.\n *\n * The first computation counts too: its value is `undefined`, and it is typically read by a\n * consumer outside the boundary (a DOM region), not by the code that created it.\n */\nfunction routeToHandler(node: Computation, failure: unknown): boolean {\n if (!hasErrorHandler(node)) return false;\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n try {\n handleError(failure, node);\n } catch (unhandled) {\n // The chain ended in a handler that rethrew: readers see it, as for any unhandled failure.\n node.flags |= FLAG_HAS_ERROR;\n node.error = unhandled;\n }\n return true;\n}\n\nfunction settleEffect(node: Computation, result: unknown, failed: boolean, failure: unknown): void {\n if (failed) {\n if (!trySuspend(node, failure)) handleError(failure, node);\n return;\n }\n const apply = node.apply;\n let cleanup: unknown;\n if (apply === null) {\n cleanup = result;\n } else {\n const deferred = (node.flags & FLAG_DEFER) !== 0;\n node.flags &= ~FLAG_DEFER;\n const previousValue = node.value;\n node.value = result;\n if (deferred) return;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = null;\n // Writes from an effect's apply are legal even when the effect was created inside a memo.\n rt.running = node;\n try {\n cleanup = (apply as (value: unknown, previous: unknown) => unknown)(result, previousValue);\n } catch (error) {\n if (!trySuspend(node, error)) handleError(error, node);\n return;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n }\n }\n if (typeof cleanup === \"function\") {\n addCleanup(node, cleanup as Cleanup);\n // The effect disposed its own owner while running: nothing will dispose it again, so run now.\n if ((node.flags & FLAG_DISPOSED) !== 0)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,IAAiB,EAAS,MAAA,EACzC,CACA,OAAOqC,CACT,CAYA,SAASC,EAAe,EAAmB,EAA2B,CACpE,GAAI,CAACE,EAAgBhE,CAAI,EAAG,MAAO,GACnC,EAAK,OAAS,GACd,EAAK,MAAQ,IAAA,GACb,GAAI,CACFiE,EAAYR,EAASzD,CAAI,CAC3B,OAASkE,EAAW,CAElB,EAAK,OAAA,EACL,EAAK,MAAQA,CACf,CACA,MAAO,EACT,CAEA,SAASP,EAAa,EAAmB,EAAiB,EAAiB,EAAwB,CACjG,GAAIH,EAAQ,CACL9B,EAAW1B,EAAMyD,CAAO,GAAGQ,EAAYR,EAASzD,CAAI,EACzD,MACF,CACA,IAAMmE,EAAQnE,EAAK,MACfoE,EACJ,GAAID,IAAU,KACZ,EAAUZ,MACL,CACL,IAAMc,EAAA,GAAYrE,EAAK,MAAA,IACvB,EAAK,OAAS,IACd,IAAMsE,EAAgBtE,EAAK,MAE3B,GADA,EAAK,MAAQuD,EACTc,EAAU,OACd,IAAMjB,EAAgBxC,EAAG,MACnByC,EAAmBzC,EAAG,SACtB0C,EAAkB1C,EAAG,QAC3B,EAAG,MAAQZ,EACX,EAAG,SAAW,KAEd,EAAG,QAAUA,EACb,GAAI,CACF,EAAWmE,EAAyDZ,EAAQe,CAAa,CAC3F,OAAS3C,EAAO,CACTD,EAAW1B,EAAM2B,CAAK,GAAGsC,EAAYtC,EAAO3B,CAAI,EACrD,MACF,QAAU,CACR,EAAG,MAAQoD,EACX,EAAG,SAAWC,EACd,EAAG,QAAUC,CACf,CACF,CACI,OAAOc,GAAY,aACrBG,EAAWvE,EAAMoE,CAAkB,EAE9BpE,EAAK,MAAA,GAA8BA,EAAK,YAAY,EAE7D,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hydration-flag.js","names":["isHydrating","rt","withHydration","previous","fn"],"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,SAAgBA,GAAuB,CACrC,OAAOC,EAAG,SACZ,CAgBA,SAAgBC,EAAiB,EAAgB,CAC/C,IAAMC,EAAWF,EAAG,UACpB,EAAG,UAAY,GACf,GAAI,CACF,OAAOG,EAAG,CACZ,QAAU,CACR,EAAG,UAAYD,CACjB,CACF,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e={NO_OWNER_EFFECT:`An effect was created outside any owner, so it can never be disposed. Create it inside a component or createRoot().`,NO_OWNER_CLEANUP:`onCleanup() was called outside any owner, so the cleanup will never run.`,NO_OWNER_ERROR:`onError() was called outside any owner, so the handler can never be reached.`,WRITE_IN_MEMO:`A signal was written inside a useMemo() computation. Derive values from sources instead, or write from an effect.`,CYCLE_DETECTED:`A reactive cycle was detected: a computation read itself while it was running.`,INFINITE_LOOP:`Effects kept re-triggering each other for more than 1000 passes; the flush was aborted.`,FLUSH_IN_EFFECT:`flushSync() was called while a flush was already running; the call was ignored.`,RUN_WITH_DISPOSED_OWNER:`runWithOwner() was called with an owner that is already disposed; the callback ran without an owner.`,DUPLICATE_CORE:`More than one copy of @shadow-js/core is loaded. Signals created by one copy are invisible to the other.`,CONTEXT_MISSING:`useContext() found no provider and the context has no default value.`,NO_OWNER_ID:`useId() was called outside any owner; the id is not stable across server and client.`,EACH_KEY_DUPLICATE:`Duplicate key in a keyed list; later duplicates get fresh rows each update.`,EFFECT_DEPS_IGNORED:`useEffect(fn, [deps]) ignores the array and re-runs on any signal it reads; use useEffect(deps, fn).`};function t(e){return`SHADOW_${e}`}export{e as MESSAGES,t as formatMessage};
|
|
2
|
+
//# sourceMappingURL=messages.js.map
|
|
@@ -0,0 +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,EAAc,EAA2B,CACvD,MAAwD,UAAUC,GACpE,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{rt as e}from"./state.js";var t=class{parent;lastChild=null;prevSibling=null;nextSibling=null;cleanups=null;context;errorHandlers=null;childCount=0;idCount=0;index;depth;idPrefix;disposed=!1;gate=null;pauses=0;constructor(e){if(this.parent=e,this.context=e===null?null:e.context,this.depth=e===null?0:e.depth+1,this.pauses=e===null?0:e.pauses,e===null)this.index=0;else{this.index=e.childCount,e.childCount+=1;let t=e.lastChild;this.prevSibling=t,t!==null&&(t.nextSibling=this),e.lastChild=this}}reportDisposed(){}release(){}disposeSelf(){if(this.disposed)return;this.disposed=!0;let e=this.parent;if(e!==null){let t=this.prevSibling,n=this.nextSibling;t!==null&&(t.nextSibling=n),n===null?e.lastChild=t:n.prevSibling=t,this.prevSibling=null,this.nextSibling=null}this.release(),this.reportDisposed(),this.runCleanups()}runCleanups(){let t=this.cleanups;if(t===null)return;this.cleanups=null;let r=e.owner,i=e.listener;e.owner=null,e.listener=null;try{if(typeof t==`function`)n(t,this);else for(let e=t.length-1;e>=0;--e){let r=t[e];r!==void 0&&n(r,this)}}finally{e.owner=r,e.listener=i}}};function n(e,t){try{e()}catch(e){s(e,t)}}function r(e,t){let n=e.cleanups;n===null?e.cleanups=t:typeof n==`function`?e.cleanups=[n,t]:n.push(t)}function i(e){for(;;){let t=e.lastChild;if(t===null)return;o(t)}}function a(){if(--e.disposing,e.disposing>0||e.flushing||e.uncaught.length===0)return;let t=e.uncaught;throw e.uncaught=[],t.length===1?t[0]:AggregateError(t,`SHADOW_DISPOSE_ERRORS`)}function o(t){e.disposing+=1;try{let e=t;for(;;){for(;e.lastChild!==null;)e=e.lastChild;let n=e.parent;if(e.disposeSelf(),e===t||n===null)break;e=n}}finally{a()}}function s(t,n){let r=t;for(let t=n;t!==null;t=t.parent){let n=t.errorHandlers;if(n!==null)for(let t=n.length-1;t>=0;--t){let i=n[t];if(i===void 0)continue;let a=e.listener;try{e.listener=null,i(r);return}catch(e){r=e}finally{e.listener=a}}}l(r)}function c(e){for(let t=e;t!==null;t=t.parent){let e=t.errorHandlers;if(e!==null&&e.length>0)return!0}return!1}function l(t){if(e.flushing||e.disposing>0)e.uncaught.push(t);else throw t}export{t as Owner,r as addCleanup,i as disposeChildren,o as disposeTree,s as handleError,c as hasErrorHandler};
|
|
2
|
+
//# sourceMappingURL=owner.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"owner.js","names":["Owner","parent","last","prev","next","cleanups","previousOwner","rt","previousListener","runCleanup","i","cleanup","error","handleError","owner","addCleanup","existing","disposeChildren","child","disposeTree","finishDisposal","errors","node","root","current","from","handlers","handler","reportUncaught","hasErrorHandler"],"sources":["../../../src/internal/owner.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { rt } from \"./state\";\nimport type { Cleanup, ErrorHandler } from \"./types\";\n\n/**\n * The context values an owner sees, keyed by the symbol of each context. A provider creates a map\n * whose prototype is its parent's map, so a lookup is one property read and never walks owners.\n * @since 1.0.0\n */\nexport type ContextMap = Record<symbol, unknown>;\n\n/**\n * A node in the ownership tree: it owns the effects, memos and owners created under it, their\n * cleanups and error handlers, and disposes them together. Create one with `createOwner` and end it\n * with `disposeOwner`; the class is exported for `instanceof` checks and for reading its state.\n * Computations (`ComputationNode`) are owners too. Children are a doubly linked list so detaching one\n * is O(1); disposal walks the tree iteratively because its depth is user controlled (R-CODE-11).\n *\n * @example\n * import { createOwner, disposeOwner, Owner } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * console.log(owner instanceof Owner, owner.depth); // true 0\n * disposeOwner(owner);\n * console.log(owner.disposed); // true\n * @see createOwner\n * @see disposeOwner\n * @since 1.0.0\n */\nexport class Owner {\n /** The owner this node was created under, or null for a root. Kept after disposal. */\n parent: Owner | null;\n /** The newest child that is still alive, or null when there is none. */\n lastChild: Owner | null = null;\n /** The next older sibling that is still alive, or null. */\n prevSibling: Owner | null = null;\n /** The next newer sibling that is still alive, or null. */\n nextSibling: Owner | null = null;\n /**\n * The cleanups registered with `addCleanup` or `onCleanup`: null for none, a function for one, an\n * array (oldest first) for several. Emptied when they run.\n */\n cleanups: Cleanup | Cleanup[] | null = null;\n /** The context values this node sees: inherited from the parent at creation, null for a root. */\n context: ContextMap | null;\n /**\n * The handlers registered with `onError` or `catchError`, oldest first (they are tried newest\n * first), or null for none. A computation clears them before each run.\n */\n errorHandlers: ErrorHandler[] | null = null;\n /** Number of children ever created; gives each child a stable index for useId(). */\n childCount = 0;\n /** Number of ids useId() has handed out from this owner. */\n idCount = 0;\n /** Position among the parent's children, assigned at creation. */\n index: number;\n /** Distance from the root: 0 for a root, the parent's depth plus one otherwise. */\n depth: number;\n /**\n * The hydration-scope prefix of a component's owner, set by the renderer. When present, useId()\n * builds the ids below it from this prefix instead of the owner path.\n * @default undefined\n */\n idPrefix: string | undefined;\n /** True once the node has been disposed. */\n disposed = false;\n /**\n * While this returns true, user effects (and `onMount`) created below this owner wait: they do\n * not run until it returns false for the first time. Suspense sets it so the effects of content\n * that is still loading are held back. The read is tracked.\n */\n gate: (() => boolean) | null = null;\n /**\n * Number of pauses (Activity hidden) that cover this node. Inherited at creation, and changed for a\n * whole subtree by `pauseOwner`/`resumeOwner`. Above zero, effects wait and memos keep their value.\n */\n pauses = 0;\n\n /**\n * Creates an owner and links it as the newest child of `parent`. It inherits the parent's context\n * and pauses.\n * @param parent The owner to attach to, or null for a root.\n */\n constructor(parent: Owner | null) {\n this.parent = parent;\n this.context = parent === null ? null : parent.context;\n this.depth = parent === null ? 0 : parent.depth + 1;\n this.pauses = parent === null ? 0 : parent.pauses;\n if (parent === null) {\n this.index = 0;\n } else {\n this.index = parent.childCount;\n parent.childCount += 1;\n const last = parent.lastChild;\n this.prevSibling = last;\n if (last !== null) last.nextSibling = this;\n parent.lastChild = this;\n }\n // Computations report themselves (with their kind); plain owners and subclasses of it here.\n if (__DEV__ && new.target === Owner) {\n report(DEVTOOLS_EVENT.OWNER_CREATED, this, parent, parent === null ? \"root\" : \"owner\");\n }\n }\n\n /** Tells devtools this node is gone. Computations override it with their own event. */\n protected reportDisposed(): void {\n if (__DEV__) report(DEVTOOLS_EVENT.OWNER_DISPOSED, this);\n }\n\n /** Hook for subclasses: release graph edges before the node is marked disposed. */\n protected release(): void {\n // Plain owners hold no graph edges.\n }\n\n /**\n * Disposes this node only (children must already be gone).\n * @internal\n */\n disposeSelf(): void {\n if (this.disposed) return;\n this.disposed = true;\n // Detach first: a cleanup that throws must never leave a dead node in the tree (R-CODE-5).\n const parent = this.parent;\n if (parent !== null) {\n const prev = this.prevSibling;\n const next = this.nextSibling;\n if (prev !== null) prev.nextSibling = next;\n if (next !== null) next.prevSibling = prev;\n else parent.lastChild = prev;\n this.prevSibling = null;\n this.nextSibling = null;\n }\n this.release();\n this.reportDisposed();\n this.runCleanups();\n }\n\n /**\n * Runs own cleanups newest first, untracked, isolating failures.\n * @internal\n */\n runCleanups(): void {\n const cleanups = this.cleanups;\n if (cleanups === null) return;\n this.cleanups = null;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = null;\n rt.listener = null;\n try {\n if (typeof cleanups === \"function\") {\n runCleanup(cleanups, this);\n } else {\n for (let i = cleanups.length - 1; i >= 0; i -= 1) {\n const cleanup = cleanups[i];\n if (cleanup !== undefined) runCleanup(cleanup, this);\n }\n }\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n }\n}\n\nfunction runCleanup(cleanup: Cleanup, owner: Owner): void {\n try {\n cleanup();\n } catch (error) {\n handleError(error, owner);\n }\n}\n\n/**\n * Registers `cleanup` on an explicit owner. It runs when the owner is disposed or, when the owner is a\n * computation, before its next run. Cleanups run newest first, untracked and with no current owner;\n * one that throws goes to {@link handleError} for that owner and does not stop the others. Use it\n * where `onCleanup` cannot be called: the owner is not the current one, or the code must not warn.\n * Unlike `onCleanup`, nothing checks that the owner is still alive: a cleanup added to a disposed\n * owner never runs.\n *\n * @param owner The owner whose disposal runs the cleanup.\n * @param cleanup The function to run.\n * @example\n * import { addCleanup, currentOwner } from \"@shadow-js/core/extend\";\n *\n * export function useInterval(tick: () => void, ms: number): void {\n * const owner = currentOwner();\n * const timer = setInterval(tick, ms);\n * if (owner !== null) addCleanup(owner, () => clearInterval(timer));\n * }\n * @see disposeOwner\n * @since 1.0.0\n */\nexport function addCleanup(owner: Owner, cleanup: Cleanup): void {\n const existing = owner.cleanups;\n if (existing === null) owner.cleanups = cleanup;\n else if (typeof existing === \"function\") owner.cleanups = [existing, cleanup];\n else existing.push(cleanup);\n}\n\n/**\n * Disposes every child of `owner` (newest first), keeping `owner` itself alive.\n * @internal\n */\nexport function disposeChildren(owner: Owner): void {\n for (;;) {\n const child = owner.lastChild;\n if (child === null) return;\n disposeTree(child);\n }\n}\n\n/** Rethrows what disposal collected once the outermost disposal is finished. */\nfunction finishDisposal(): void {\n rt.disposing -= 1;\n if (rt.disposing > 0 || rt.flushing || rt.uncaught.length === 0) return;\n const errors = rt.uncaught;\n rt.uncaught = [];\n if (errors.length === 1) throw errors[0];\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while disposing.\" : \"SHADOW_DISPOSE_ERRORS\",\n );\n}\n\n/**\n * Disposes `root` and everything below it: children first, then own cleanups, newest first.\n * Iterative post-order walk: a leaf is disposed, which re-links its parent's `lastChild`\n * to the previous sibling, so the loop naturally visits the remaining subtree. The public\n * `disposeOwner` (dispose.ts) wraps it with the flush that follows.\n * @internal\n */\nexport function disposeTree(root: Owner): void {\n rt.disposing += 1;\n try {\n let node: Owner = root;\n for (;;) {\n while (node.lastChild !== null) node = node.lastChild;\n const parent: Owner | null = node.parent;\n node.disposeSelf();\n if (node === root || parent === null) break;\n node = parent;\n }\n } finally {\n finishDisposal();\n }\n}\n\n/**\n * Routes `error` to the nearest handler registered with `catchError` or `onError`, searching `from`\n * and then its ancestors, newest handler first on each owner. Handlers run untracked and restore\n * the caller's tracking even when they rethrow. Use it for errors that happen outside\n * any computation (a rejected promise, an event callback), so they reach the same boundary as errors\n * thrown during rendering. A handler that throws hands its own error to the next handler up the\n * chain. With no handler left the error is uncaught: collected until the running flush or disposal\n * ends (which then throws it), or thrown at once otherwise.\n *\n * @param error The thrown value.\n * @param from The owner where the error happened. Null searches no handler: the error is uncaught.\n * @throws The error (or the last error a handler threw) when no handler catches it and no flush or\n * disposal is running.\n * @example\n * import { currentOwner, handleError } from \"@shadow-js/core/extend\";\n *\n * export function useSaveOnLoad(save: () => Promise<void>): void {\n * const owner = currentOwner();\n * save().catch((error: unknown) => handleError(error, owner));\n * }\n * @since 1.0.0\n */\nexport function handleError(error: unknown, from: Owner | null): void {\n if (__DEV__) report(DEVTOOLS_EVENT.ERROR, from, error, codeOf(error));\n let current = error;\n for (let owner = from; owner !== null; owner = owner.parent) {\n const handlers = owner.errorHandlers;\n if (handlers === null) continue;\n for (let i = handlers.length - 1; i >= 0; i -= 1) {\n const handler = handlers[i];\n if (handler === undefined) continue;\n const previousListener = rt.listener;\n try {\n rt.listener = null;\n return void handler(current);\n } catch (next) {\n current = next;\n } finally {\n rt.listener = previousListener;\n }\n }\n }\n reportUncaught(current);\n}\n\n/**\n * True when `handleError(_, from)` would reach a handler registered by catchError()/onError().\n * @internal\n */\nexport function hasErrorHandler(from: Owner | null): boolean {\n for (let owner = from; owner !== null; owner = owner.parent) {\n const handlers = owner.errorHandlers;\n if (handlers !== null && handlers.length > 0) return true;\n }\n return false;\n}\n\n/**\n * The diagnostic code of a ShadowJS error, for devtools. Reads an own data property only: a getter on a thrown\n * value would run user code inside the error path, and a throw there would replace the error being handled.\n */\nfunction codeOf(error: unknown): unknown {\n if (typeof error !== \"object\" || error === null) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(error, \"code\");\n return descriptor !== undefined && \"value\" in descriptor ? descriptor.value : undefined;\n}\n\nfunction reportUncaught(error: unknown): void {\n if (rt.flushing || rt.disposing > 0)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IAAMY,EAAWZ,EAAM,cACvB,GAAIY,IAAa,KACjB,IAAK,IAAIhB,EAAIgB,EAAS,OAAS,EAAGhB,GAAK,EAAG,IAAQ,CAChD,IAAMiB,EAAUD,EAAShB,GACzB,GAAIiB,IAAY,IAAA,GAAW,SAC3B,IAAMnB,EAAmBD,EAAG,SAC5B,GAAI,CACF,EAAG,SAAW,KACPoB,EAAaH,CAAO,EAA3B,MACF,OAASpB,EAAM,CACb,EAAUA,CACZ,QAAU,CACR,EAAG,SAAWI,CAChB,CACF,CACF,CACAoB,EAAeJ,CAAO,CACxB,CAMA,SAAgBK,EAAgB,EAA6B,CAC3D,IAAK,IAAIf,EAAQW,EAAMX,IAAU,KAAM,EAAQA,EAAM,OAAQ,CAC3D,IAAMY,EAAWZ,EAAM,cACvB,GAAIY,IAAa,MAAQA,EAAS,OAAS,EAAG,MAAO,EACvD,CACA,MAAO,EACT,CAYA,SAASE,EAAe,EAAsB,CAC5C,GAAIrB,EAAG,UAAYA,EAAG,UAAY,EAAGA,EAAG,SAAS,KAAKK,CAAK,OACtD,MAAMA,CACb,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{FLAG_PARKED as e,FLAG_TRANSITION as t}from"./flags.js";import{rt as n}from"./state.js";const r=[],i=[];function a(a,o){if(a.flags&2)return;let s=o||!!(a.flags&512),c=n.hooks;c!==null&&(s||a.pauses>0)?c.place(a,s):(a.flags=a.flags&~(e|t)|2,a.flags&16?r.push(a):i.push(a))}function o(e){a(e,n.inTransition)}function s(){return r.length>0||i.length>0}function c(){for(let e of[r,i]){for(let n of e)n.flags&=~(2|t),n.state=0;e.length=0}n.hooks?.clear()}export{c as clearQueues,o as enqueue,s as hasPending,a as place,r as renderQueue,i as userQueue};
|
|
2
|
+
//# sourceMappingURL=queue.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queue.js","names":["renderQueue","userQueue","place","effect","inLane","lane","hooks","rt","FLAG_PARKED","FLAG_TRANSITION","enqueue","hasPending","clearQueues","queue"],"sources":["../../../src/internal/queue.ts"],"sourcesContent":["import { CLEAN, FLAG_LANE, FLAG_PARKED, FLAG_QUEUED, FLAG_RENDER, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { rt } from \"./state\";\n\n/** Urgent effects waiting for the next flush, split by phase (render effects run first). */\nexport const renderQueue: Computation[] = [];\nexport const userQueue: Computation[] = [];\n\n/**\n * Puts an effect where it belongs. `lane` says the write that marked it was a transition write;\n * effects with FLAG_LANE always go to the lane. Lane and paused effects are handed to the transition\n * hooks (their queues live there); everything else is queued here, with no hook involved.\n */\nexport function place(effect: Computation, lane: boolean): void {\n if ((effect.flags & FLAG_QUEUED) !== 0) return;\n const inLane = lane || (effect.flags & FLAG_LANE) !== 0;\n const hooks = rt.hooks;\n if (hooks !== null && (inLane || effect.pauses > 0)) {\n hooks.place(effect, inLane);\n return;\n }\n effect.flags = (effect.flags & ~(FLAG_PARKED | FLAG_TRANSITION)) | FLAG_QUEUED;\n if ((effect.flags & FLAG_RENDER) !== 0) renderQueue.push(effect);\n else userQueue.push(effect);\n}\n\n/** Queues an effect for the current write: a transition write joins the lane. */\nexport function enqueue(effect: Computation): void {\n place(effect, rt.inTransition);\n}\n\n/** True when an urgent effect is waiting. */\nexport function hasPending(): boolean {\n return renderQueue.length > 0 || userQueue.length > 0;\n}\n\n/** Drops everything queued (used when a flush is aborted by the loop guard). */\nexport function clearQueues(): void {\n for (const queue of [renderQueue, userQueue]) {\n for (const effect of queue) {\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n // Back to CLEAN so the next write can notify (and re-queue) this effect again.\n effect.state = CLEAN;\n }\n queue.length = 0;\n }\n rt.hooks?.clear();\n}\n"],"mappings":"A,8FAKA,MAAaA,EAA6B,CAAC,EAC9BC,EAA2B,CAAC,EAOzC,SAAgBC,EAAM,EAAqB,EAAqB,CAC9D,GAAKC,EAAO,MAAA,EAA4B,OACxC,IAAMC,EAASC,GAAA,GAASF,EAAO,MAAA,KACzBG,EAAQC,EAAG,MACbD,IAAU,OAASF,GAAUD,EAAO,OAAS,GAC/CG,EAAM,MAAMH,EAAQC,CAAM,GAG5B,EAAO,MAASD,EAAO,MAAQ,EAAEK,EAAcC,GAAA,EAC1CN,EAAO,MAAA,GAA4BH,EAAY,KAAKG,CAAM,EAC1DF,EAAU,KAAKE,CAAM,EAC5B,CAGA,SAAgBO,EAAQ,EAA2B,CACjDR,EAAMC,EAAQI,EAAG,YAAY,CAC/B,CAGA,SAAgBI,GAAsB,CACpC,OAAOX,EAAY,OAAS,GAAKC,EAAU,OAAS,CACtD,CAGA,SAAgBW,GAAoB,CAClC,IAAK,IAAMC,IAAS,CAACb,EAAaC,CAAS,EAAG,CAC5C,IAAK,IAAME,KAAUU,EACnB,EAAO,OAAS,EAAA,EAAgBJ,GAEhC,EAAO,MAAA,EAET,EAAM,OAAS,CACjB,CACAF,EAAG,OAAO,MAAM,CAClB,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ShadowError as e}from"./diagnostics.js";import{FLAG_PARKED as t,FLAG_TRANSITION as n}from"./flags.js";import{rt as r}from"./state.js";import{handleError as i}from"./owner.js";import{clearQueues as a,hasPending as o,renderQueue as s,userQueue as c}from"./queue.js";import{recompute as l,updateIfNecessary as u}from"./graph.js";const d=1e3;let f=!1;function p(e,t){return e.depth-t.depth||e.seq-t.seq}function m(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n!==void 0&&r!==void 0&&p(n,r)>0)return!1}return!0}function h(e){let r=e.splice(0,e.length);m(r)||r.sort(p);for(let e of r)if(e.flags&=-3,!(e.flags&4)){if(e.pauses>0)e.flags=e.flags&~n|t;else try{e.state===2?l(e):u(e)}catch(t){i(t,e)}}return r.length}function g(e){let[t]=e;throw e.length===1?t:AggregateError(e,`SHADOW_FLUSH_ERRORS`)}function _(){if(r.flushing)return;r.flushing=!0;let t=0,n=0;try{for(;o();){let i=!1;for(;s.length>0;){if(t+=1,t>1e3){i=!0;break}n+=h(s)}if(!i&&c.length>0&&(t+=1,t>1e3?i=!0:n+=h(c)),i){a(),r.uncaught.push(new e(`INFINITE_LOOP`));break}}}finally{r.flushing=!1}let i=r.uncaught;i.length>0&&(r.uncaught=[],g(i))}function v(e){typeof reportError==`function`?reportError(e):queueMicrotask(()=>Promise.reject(e))}function y(){if(f=!1,o())try{_()}catch(e){v(e)}}function b(){r.inTransition||r.batchDepth>0||r.flushing||f||(f=!0,queueMicrotask(y))}function x(e){r.batchDepth+=1;try{return e()}finally{--r.batchDepth,r.batchDepth===0&&o()&&b()}}function S(e,t){return AggregateError([e,t],`SHADOW_BATCH_ERRORS`)}function C(e){r.batchDepth+=1;let t,n,i=!1;try{t=e()}catch(e){i=!0,n=e}finally{--r.batchDepth}if(r.batchDepth===0&&!r.flushing&&o())try{_()}catch(e){throw i?S(n,e):e}if(i)throw n;return t}function w(e){if(r.flushing)return e===void 0?void 0:e();r.batchDepth+=1;let t,n,i=!1;try{t=e===void 0?void 0:e()}catch(e){i=!0,n=e}finally{--r.batchDepth}try{_()}catch(e){throw i?S(n,e):e}if(i)throw n;return t}export{d as MAX_FLUSH_PASSES,C as batch,p as byCreation,_ as flush,w as flushSync,x as group,m as isOrdered,v as reportUncaught,b as schedule};
|
|
2
|
+
//# sourceMappingURL=scheduler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scheduler.js","names":["MAX_FLUSH_PASSES","microtaskScheduled","byCreation","a","b","isOrdered","i","list","previous","current","drain","batch","queue","effect","FLAG_TRANSITION","FLAG_PARKED","recompute","updateIfNecessary","error","handleError","raise","first","errors","flush","rt","passes","runs","hasPending","aborted","renderQueue","userQueue","clearQueues","ShadowError","reportUncaught","runScheduled","schedule","group","fn","combine","primary","secondary","result","failure","failed","flushSync"],"sources":["../../../src/internal/scheduler.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError, warn } from \"./diagnostics\";\nimport { DIRTY, FLAG_DISPOSED, FLAG_PARKED, FLAG_QUEUED, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { recompute, updateIfNecessary } from \"./graph\";\nimport { handleError } from \"./owner\";\nimport { clearQueues, hasPending, renderQueue, userQueue } from \"./queue\";\nimport { rt } from \"./state\";\n\n/**\n * Flush passes allowed before the loop guard aborts (R-CODE-12).\n * @internal\n */\nexport const MAX_FLUSH_PASSES = 1000;\n\nlet microtaskScheduled = false;\n\n/**\n * Sort order of queued effects: parents before children (by depth), siblings by creation (G-16).\n * @internal\n */\nexport function byCreation(a: Computation, b: Computation): number {\n return a.depth - b.depth || a.seq - b.seq;\n}\n\n/**\n * Effects mostly arrive in creation order already; checking is O(n), sorting is not.\n * @internal\n */\nexport function isOrdered(list: readonly Computation[]): boolean {\n for (let i = 1; i < list.length; i += 1) {\n const previous = list[i - 1];\n const current = list[i];\n if (previous !== undefined && current !== undefined && byCreation(previous, current) > 0) {\n return false;\n }\n }\n return true;\n}\n\n/** Runs every queued effect of one phase, parents before children, siblings by creation. */\nfunction drain(queue: Computation[]): number {\n const batch = queue.splice(0, queue.length);\n if (!isOrdered(batch)) batch.sort(byCreation);\n for (const effect of batch) {\n effect.flags &= ~FLAG_QUEUED;\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n // Paused after it was queued: wait (unqueued) until the owner resumes.\n effect.flags = (effect.flags & ~FLAG_TRANSITION) | FLAG_PARKED;\n continue;\n }\n try {\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n let aborted = false;\n // Render passes count too: a render effect that keeps writing its own source must abort.\n while (renderQueue.length > 0) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n aborted = true;\n break;\n }\n runs += drain(renderQueue);\n }\n if (!aborted && userQueue.length > 0) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) aborted = true;\n else runs += drain(userQueue);\n }\n if (aborted) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batchDepth > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batchDepth += 1;\n try {\n return fn();\n } finally {\n rt.batchDepth -= 1;\n if (rt.batchDepth === 0 && hasPending()) schedule();\n }\n}\n\nfunction combine(primary: unknown, secondary: unknown): unknown {\n return new AggregateError(\n [primary, secondary],\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n if (rt.batchDepth === 0 && !rt.flushing && hasPending()) {\n try {\n flush();\n } catch (error) {\n if (failed) throw combine(failure, error);\n throw error;\n }\n }\n if (failed) throw failure;\n return result as T;\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.flushing) {\n warn(\"FLUSH_IN_EFFECT\");\n return (fn === undefined ? undefined : fn()) as T;\n }\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n try {\n flush();\n } catch (error) {\n if (failed) throw combine(failure, error);\n throw error;\n }\n if (failed) throw failure;\n return result as T;\n}\n"],"mappings":"A,6UAaA,MAAaA,EAAmB,IAEhC,IAAIC,EAAqB,GAMzB,SAAgBC,EAAW,EAAgB,EAAwB,CACjE,OAAOC,EAAE,MAAQC,EAAE,OAASD,EAAE,IAAMC,EAAE,GACxC,CAMA,SAAgBC,EAAU,EAAuC,CAC/D,IAAK,IAAIC,EAAI,EAAGA,EAAIC,EAAK,OAAQ,GAAK,EAAG,CACvC,IAAMC,EAAWD,EAAKD,EAAI,GACpBG,EAAUF,EAAKD,GACrB,GAAIE,IAAa,IAAA,IAAaC,IAAY,IAAA,IAAaP,EAAWM,EAAUC,CAAO,EAAI,EACrF,MAAO,EAEX,CACA,MAAO,EACT,CAGA,SAASC,EAAM,EAA8B,CAC3C,IAAMC,EAAQC,EAAM,OAAO,EAAGA,EAAM,MAAM,EACrCP,EAAUM,CAAK,GAAGA,EAAM,KAAKT,CAAU,EAC5C,IAAK,IAAMW,KAAUF,EAEnB,GADA,EAAO,OAAS,GACX,IAAO,MAAA,GACZ,IAAIE,EAAO,OAAS,EAElB,EAAO,MAASA,EAAO,MAAQ,CAACC,EAAmBC,OAGrD,GAAI,CAEEF,EAAO,QAAA,EAAiBG,EAAUH,CAAM,EACvCI,EAAkBJ,CAAM,CAC/B,OAASK,EAAO,CACdC,EAAYD,EAAOL,CAAM,CAC3B,CAPA,CASF,OAAOF,EAAM,MACf,CAEA,SAASS,EAAM,EAAyB,CACtC,GAAM,CAACC,GAASC,EAEhB,MADIA,EAAO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,qBACvD,CACF,CAwBA,SAAgB7B,EAAS,EAAgB,CACvC,EAAG,YAAc,EACjB,IAAI8B,EACAC,EACAC,EAAS,GACb,GAAI,CACF,EAASN,EAAG,CACd,OAASnB,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,QAAU,CACR,IAAG,UACL,CACA,GAAIM,EAAG,aAAe,GAAK,CAACA,EAAG,UAAYG,EAAW,EACpD,GAAI,CACFJ,EAAM,CACR,OAASL,EAAO,CAEd,MADIyB,EAAcL,EAAQI,EAASxB,CAAK,EAClCA,CACR,CAEF,GAAIyB,EAAQ,MAAMD,EAClB,OAAOD,CACT,CAyBA,SAAgBG,EAAoB,EAAiB,CACnD,GAAIpB,EAAG,SAEL,OAAQa,IAAO,IAAA,GAAY,IAAA,GAAYA,EAAG,EAE5C,EAAG,YAAc,EACjB,IAAII,EACAC,EACAC,EAAS,GACb,GAAI,CACF,EAASN,IAAO,IAAA,GAAY,IAAA,GAAYA,EAAG,CAC7C,OAASnB,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,QAAU,CACR,IAAG,UACL,CACA,GAAI,CACFK,EAAM,CACR,OAASL,EAAO,CAEd,MADIyB,EAAcL,EAAQI,EAASxB,CAAK,EAClCA,CACR,CACA,GAAIyB,EAAQ,MAAMD,EAClB,OAAOD,CACT,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"state.js","names":["rt","counter","nextSequence"],"sources":["../../../src/internal/state.ts"],"sourcesContent":["import type { Computation } from \"./graph\";\nimport type { Owner } from \"./owner\";\n\n/**\n * A hold for a value a transition builds while its reads wait for data (a `Show` branch built during a\n * transition): the reads that wait count against this hold, not against the Suspense boundary around\n * the value, so the shown value stays until the hold settles. Created by `createTransitionHold`.\n * @since 1.0.0\n */\nexport interface TransitionHold {\n /** Runs `fn` with this hold as the Suspense boundary of the reads inside it. */\n run<T>(fn: () => T): T;\n /** Reads still waiting for data. */\n count(): number;\n /** True once a read in the hold was held (the value is then pending, not ready). */\n engaged(): boolean;\n /** Ends the hold without waking anything (the value is being dropped). */\n drop(): void;\n}\n\n/**\n * The choice a branch slot (Show, Switch) shows: its index, and what decides a rebuild. Renderers\n * extend it with what they need to build the branch.\n * @since 1.0.0\n */\nexport interface SlotChoice {\n /** Which branch is chosen: its position among the slot's branches, or the renderer's fallback index. */\n readonly index: number;\n /** True when the branch is rebuilt whenever `when` changes identity; false when only `index` counts. */\n readonly keyed: boolean;\n /** The condition value that selected the branch. */\n readonly when: unknown;\n}\n\n/**\n * The record of a branch's owner that its accessors read: the value and whether it is being torn down.\n * @since 1.0.0\n */\nexport interface SlotOwned {\n /** The index of the branch this record belongs to (see {@link SlotChoice.index}). */\n index: number;\n /** The latest condition value while the branch is shown; what its accessor returns during teardown. */\n value: unknown;\n /** True while the branch is torn down: its accessor then returns `value` instead of throwing. */\n disposing: boolean;\n}\n\n/**\n * A branch a slot shows, or builds during a transition. A branch without `dispose` is torn down by its memo.\n * @since 1.0.0\n */\nexport interface SlotBranch<C extends SlotChoice> {\n /** The choice the branch was built for. */\n readonly choice: C;\n /** The record its accessors read. */\n readonly owned: SlotOwned;\n /** What the branch produced: the value the slot's output returns while the branch is shown. */\n readonly result: unknown;\n /**\n * Tears the branch down. Set for the branches a transition built: they live under the holder, not\n * under the memo.\n * @default undefined (the slot's memo tears the branch down)\n */\n readonly dispose?: () => void;\n /**\n * The hold a transition built the branch under; null when none of its reads was held.\n * @default undefined (a memo-owned branch has no hold)\n */\n readonly hold?: TransitionHold | null;\n}\n\n/**\n * What a slot's output memo keeps: the branch on screen (its result is the value the output returns).\n * @since 1.0.0\n */\nexport interface SlotState<C extends SlotChoice> {\n /** The branch on screen, or undefined before the first build and while the memo rebuilds it. */\n live: SlotBranch<C> | undefined;\n}\n\n/**\n * The transition layer of one slot, from `transitionHooks()?.slotSwap(...)`: it keeps the shown\n * branch while a transition builds the next one (see `slotSwap` in concurrency.ts).\n * @since 1.0.0\n */\nexport interface SlotSwap<C extends SlotChoice> {\n /**\n * Runs one pass of the slot's memo for `choice`. True when a transition keeps the shown value. False\n * when the usual path follows: the branch on screen has been retired and `state.live` is cleared.\n */\n step(choice: C): boolean;\n}\n\n/**\n * The hold of one Suspense boundary: engaged by a transition read, released when its data arrived.\n * From `transitionHooks()?.boundaryHold()`.\n * @since 1.0.0\n */\nexport interface BoundaryHold {\n /** Engages the hold (a second call changes nothing) so the boundary keeps its content; returns true. */\n engage(): boolean;\n /** When engaged: wakes the readers that waited, then ends the hold. Otherwise does nothing. */\n release(): void;\n /** True while the hold is engaged. */\n holding(): boolean;\n}\n\n/**\n * The transition machinery the engine calls through `rt.hooks`: transition lanes, pauses (Activity)\n * and suspensions (Suspense holds). It is created by the first call of an API that needs it (see\n * concurrency.ts), so an application that never calls one of those APIs carries none of their code.\n * Renderers reach it through `transitionHooks()`.\n * @since 1.0.0\n */\nexport interface Hooks {\n /** The transition layer of one branch slot (see `slotSwap` in concurrency.ts). */\n 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 Suspense boundary's hold (see `boundaryHold` in concurrency.ts). */\n boundaryHold(): BoundaryHold;\n /** Queues an effect that is due in the transition lane, or parks it while its owner is paused. */\n place(effect: Computation, inLane: boolean): void;\n /** An urgent write reached an effect that waits in the lane or is parked: it moves to the urgent queue. */\n promote(effect: Computation): void;\n /** Forgets the lane queues (the flush loop guard). */\n clear(): void;\n /** Keeps `node` for a transition when `error` is a suspension; returns false for any other error. */\n suspend(node: Computation, error: unknown): boolean;\n /** The engine side of `holdReader`: throws the suspension sentinel when `tracker.hold()` is true. */\n holdReader(tracker: { hold?(): boolean }): void;\n /** The engine side of `startTransition` in the browser. */\n startTransition(fn: () => void): Promise<void>;\n /** The engine side of `beginHold`: counts one more Suspense hold. */\n beginHold(): void;\n /** The engine side of `endHold`: counts one hold less and settles the lane. */\n endHold(): void;\n /** The engine side of `wakeSuspended`. */\n wakeSuspended(): void;\n /** The engine side of `pauseOwner`. */\n pause(owner: Owner): void;\n /** The engine side of `resumeOwner`. */\n resume(owner: Owner): void;\n /** The engine side of `createTransitionHold`. */\n createHold(onSettled: () => void): TransitionHold;\n}\n\n/**\n * The runtime registers (R-CODE-4): the only module-level mutable state of core besides\n * monotonic counters. Every write is paired with a `finally` restore (R-CODE-5).\n */\nexport const rt: {\n /** Owner that adopts newly created nodes. */\n owner: Owner | null;\n /** Computation that records the signals it reads; null while untracked. */\n listener: Computation | null;\n /** Computation currently executing, tracked or not (used by the write-in-memo guard). */\n running: Computation | null;\n /** Nesting depth of batch()/flushSync() calls. */\n batchDepth: number;\n /** True while the flush loop is draining the effect queues. */\n flushing: boolean;\n /** Nesting depth of memo recomputation, used to switch to iterative pulls. */\n recomputeDepth: number;\n /** Nesting depth of disposals in progress; errors raised meanwhile are collected, not thrown. */\n disposing: number;\n /** Errors nobody handled during the current flush or disposal; rethrown once it completes. */\n uncaught: unknown[];\n /** True while a transition callback or a transition-lane run is active: writes made now join the lane. */\n inTransition: boolean;\n /** True while `hydrate()` claims server markup (useExternalStore reads its server snapshot). */\n hydrating: boolean;\n /** The transition machinery, or null until an API that needs it is first called. */\n hooks: Hooks | null;\n} = {\n owner: null,\n listener: null,\n running: null,\n batchDepth: 0,\n flushing: false,\n recomputeDepth: 0,\n disposing: 0,\n uncaught: [],\n inTransition: false,\n hydrating: false,\n hooks: null,\n};\n\nlet counter = 0;\n/** Monotonic creation sequence; orders sibling effects (G-16). */\nexport function nextSequence(): number {\n counter += 1;\n return counter;\n}\n"],"mappings":"AA0JA,MAAaA,EAuBT,CACF,MAAO,KACP,SAAU,KACV,QAAS,KACT,WAAY,EACZ,SAAU,GACV,eAAgB,EAChB,UAAW,EACX,SAAU,CAAC,EACX,aAAc,GACd,UAAW,GACX,MAAO,IACT,EAEA,IAAIC,EAAU,EAEd,SAAgBC,GAAuB,CAErC,MADA,IAAW,EACJD,CACT,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"suspension.js","names":["SUSPENSION","isSuspension","value"],"sources":["../../../src/internal/suspension.ts"],"sourcesContent":["/**\n * The value a reader throws when a transition reads data that is still loading inside a Suspense\n * boundary that is showing content. The reader keeps its previous value (a memo keeps its value, an\n * effect leaves the DOM as it is) until the boundary releases it. A single frozen object: identity is\n * the test, so user code cannot forge it. {@link holdReader} throws it for you; a custom primitive\n * that catches errors must let it through, which {@link isSuspension} checks.\n *\n * @example\n * import { SUSPENSION } from \"@shadow-js/core/extend\";\n *\n * function rethrowIfHeld(error: unknown): void {\n * if (error === SUSPENSION) throw error; // not a failure: the boundary resumes the reader later\n * }\n * @see isSuspension\n * @since 1.0.0\n */\nexport const SUSPENSION: { readonly suspended: true } = /* @__PURE__ */ Object.freeze({\n suspended: true as const,\n});\n\n/**\n * Tells whether a caught value is the suspension sentinel rather than an error. Use it in a custom\n * primitive's `catch` so a transition's held read is passed on instead of being reported as a\n * failure.\n *\n * @param value The caught value.\n * @returns True when `value` is {@link SUSPENSION}.\n * @example\n * import { isSuspension } from \"@shadow-js/core/extend\";\n *\n * function attempt(run: () => void, onError: (error: unknown) => void): void {\n * try {\n * run();\n * } catch (error) {\n * if (isSuspension(error)) throw error;\n * onError(error);\n * }\n * }\n * @since 1.0.0\n */\nexport function isSuspension(value: unknown): boolean {\n return value === SUSPENSION;\n}\n"],"mappings":"AAgBA,MAAaA,EAA2D,uBAAO,OAAO,CACpF,UAAW,EACb,CAAC,EAsBD,SAAgBC,EAAa,EAAyB,CACpD,OAAOC,IAAUF,CACnB,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import"./internal/diagnostics.js";import{Owner as e}from"./internal/owner.js";import{readSignal as t}from"./internal/graph.js";import{createRoot as n,getOwner as r,onCleanup as i,runWithOwner as a,untrack as o}from"./ownership.js";import{disposeTree as s}from"./internal/dispose.js";import{createSignalNode as c,writeSignal as l}from"./extend/index.js";import{useMemo as u}from"./memo.js";var d=class{key;first;item;index;value=void 0;dispose=f;itemNode=null;indexNode=null;constructor(e,t,n,r){this.key=e,this.first=t,this.item=n,this.index=r}readItem(){return this.itemNode??=c(this.item,Object.is),t(this.itemNode)}readIndex(){return this.indexNode??=c(this.index,Object.is),t(this.indexNode)}setItem(e){this.item=e,this.itemNode!==null&&l(this.itemNode,e,{allowInMemo:!0})}setIndex(e){this.index=e,this.indexNode!==null&&l(this.indexNode,e,{allowInMemo:!0})}};function f(){}function p(e,t,n){let r=n?.key;return h(e,r===void 0?{keyOf:e=>e,distinct:!1}:{keyOf:e=>r(e),distinct:!0},(e,n,i)=>t(r===void 0?e:n,i),n?.fallback)}function m(e,t,n){return h(e,{keyOf:(e,t)=>t,distinct:!1},(e,n,r)=>t(n,o(r)),n?.fallback)}function h(t,n,a,c){let l=new e(r());i(()=>{s(l)});let d=[],f;return u(()=>{let e=g(t()),r=Array.isArray(e)?Array.prototype.slice.call(e):e,i=o(()=>_(r,n)),s=b(d,i),u=[],p=[],m;try{i.forEach((e,t)=>{let n=s[t]??-1,r=n===-1?void 0:d[n];if(r!==void 0){p.push({row:r,item:e.item,position:t,fresh:!1});return}let i=x(l,e.key,e.first,e.item,t,a);u.push(i),p.push({row:i,item:e.item,position:t,fresh:!0})}),i.length===0&&c!==void 0&&(m=f??S(l,c))}catch(e){let t=[];for(let e of u)C(e.dispose,t);throw m!==void 0&&m!==f&&C(m.dispose,t),w(e,t)}let h=[],v=d,y=f;d=p.map(e=>e.row),f=m;let E=new Uint8Array(v.length);for(let e of s)e!==-1&&(E[e]=1);v.forEach((e,t)=>{E[t]!==1&&C(e.dispose,h)}),y!==void 0&&y!==m&&C(y.dispose,h);for(let e of p){if(e.fresh)continue;let t=e.row;t.index!==e.position&&t.setIndex(e.position),Object.is(t.item,e.item)||t.setItem(e.item)}return T(h),m===void 0?d.map(e=>e.value):[m.value]},{lazy:!0,allowWrites:!0})}function g(e){return e==null||e===!1?[]:e}function _(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let[i,a]of e.entries()){let e=t.keyOf(a,i),o=!0;t.distinct&&(r.has(e)?o=!1:r.add(e)),n.push({item:a,key:e,first:o})}return n}function v(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function y(e,t){return e!==void 0&&t!==void 0&&e.first&&t.first&&v(e.key,t.key)}function b(e,t){let n=e.length,r=t.length,i=new Int32Array(r).fill(-1),a=0;for(;a<n&&a<r&&y(e[a],t[a]);)i[a]=a,a+=1;let o=n-1,s=r-1;for(;o>=a&&s>=a&&y(e[o],t[s]);)i[s]=o,--o,--s;if(a>o||a>s)return i;let c=/* @__PURE__ */ new Map,l=new Int32Array(n).fill(-1);for(let t=o;t>=a;--t){let n=e[t];n!==void 0&&n.first&&(l[t]=c.get(n.key)??-1,c.set(n.key,t))}for(let e=a;e<=s;e+=1){let n=t[e];if(n===void 0||!n.first)continue;let r=c.get(n.key);r!==void 0&&r!==-1&&(i[e]=r,c.set(n.key,l[r]??-1))}return i}function x(e,t,r,i,s,c){let l=new d(t,r,i,s),u=()=>l.readItem(),f=()=>l.readIndex();return a(e,()=>n(e=>{l.dispose=e,l.value=o(()=>c(i,u,f))})),l}function S(e,t){return a(e,()=>n(e=>({value:o(t),dispose:e})))}function C(e,t){try{e()}catch(e){t.push(e)}}function w(e,t){return t.length===0?e:AggregateError([e,...t],`SHADOW_MAP_ERRORS`)}function T(e){if(e.length!==0)throw e.length===1?e[0]:AggregateError(e,`SHADOW_LIST_DISPOSE_ERRORS`)}export{m as indexArray,p as mapArray};
|
|
2
|
+
//# sourceMappingURL=list.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"list.js","names":["Row","noop","key","first","item","index","createSignalNode","readSignal","next","writeSignal","mapArray","keyOf","options","listRows","list","map","readItem","readIndex","indexArray","position","untrack","holder","Owner","getOwner","onCleanup","disposeTree","rows","emptyFallback","useMemo","source","listItems","items","entries","toEntries","keying","reuse","matchRows","created","staged","nextFallback","from","kept","entry","row","openRow","build","fallback","openFallback","error","failures","disposeCollecting","combineFailures","previousRows","previousFallback","stage","throwFailures","value","seen","sameKey","a","b","canReuse","m","old","n","start","oldEnd","newEnd","heads","chain","i","j","head","runWithOwner","createRoot","dispose","primary"],"sources":["../../src/list.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n disposeOwner,\n Owner,\n readSignal,\n type SignalNode,\n warn,\n writeSignal,\n} from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { createRoot, getOwner, onCleanup, runWithOwner, untrack } from \"./ownership\";\n\n/**\n * A list as the list primitives read it. `null`, `undefined` and `false` count as an empty list.\n * @since 1.0.0\n */\nexport type ListSource<T> = () => readonly T[] | null | undefined | false;\n\n/**\n * One mapped row: its own root, its mapped value, and the signals behind `item()` and `index()`. The signals are created\n * by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.\n */\nclass Row<T, U> {\n /** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */\n readonly key: unknown;\n /** False for a later copy of a key in a keyed list. Such a row is never reused. */\n readonly first: boolean;\n /** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */\n item: T;\n /** Index last written to the row. */\n index: number;\n value: U = undefined as U;\n dispose: () => void = noop;\n /** Created by the first `item()` read; null until then. */\n private itemNode: SignalNode<T> | null = null;\n /** Created by the first `index()` read; null until then. */\n private indexNode: SignalNode<number> | null = null;\n\n constructor(key: unknown, first: boolean, item: T, index: number) {\n this.key = key;\n this.first = first;\n this.item = item;\n this.index = index;\n }\n\n readItem(): T {\n this.itemNode ??= createSignalNode(this.item, Object.is);\n return readSignal(this.itemNode);\n }\n\n readIndex(): number {\n this.indexNode ??= createSignalNode(this.index, Object.is);\n return readSignal(this.indexNode);\n }\n\n /** List bookkeeping, not a user write: allowed while the list memo computes. */\n setItem(next: T): void {\n this.item = next;\n if (this.itemNode !== null) writeSignal(this.itemNode, next, { allowInMemo: true });\n }\n\n setIndex(next: number): void {\n this.index = next;\n if (this.indexNode !== null) writeSignal(this.indexNode, next, { allowInMemo: true });\n }\n}\n\n/** The dispose of a row whose root has not been made yet. */\nfunction noop(): void {\n // Replaced by the root's own dispose before the row is used.\n}\n\n/** One incoming item of a list update, with the key it is matched by. */\ninterface Entry<T> {\n readonly item: T;\n readonly key: unknown;\n readonly first: boolean;\n}\n\n/** How incoming items are matched against the rows of the previous update. */\ninterface Keying<T> {\n /** Reuse key of the item at `position`. User code, so it runs untracked. */\n readonly keyOf: (item: T, position: number) => unknown;\n /** Keyed lists: only the first copy of a key may reuse a row. Otherwise copies pair up in order. */\n readonly distinct: boolean;\n}\n\n/** The row shown while the list is empty, in its own root. */\ninterface Fallback<U> {\n readonly value: U;\n readonly dispose: () => void;\n}\n\n/** A row chosen by one update, in output order. */\ninterface Staged<T, U> {\n readonly row: Row<T, U>;\n readonly item: T;\n readonly position: number;\n readonly fresh: boolean;\n}\n\n/**\n * Maps each item of a list to a row that lives as long as the item does. Rows whose key survives\n * an update keep their mapped value; new items get new rows; removed items have their rows disposed.\n *\n * Unkeyed: rows are matched by item reference, and `map` receives the item value. Equal primitives\n * pair up in order of occurrence. The returned accessor is lazy and memoized: rows are created and\n * disposed when it is read, so a list nobody reads keeps removed rows alive until the next read.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `index()` follows the row.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [users] = useSignal([{ name: \"Ada\" }, { name: \"Linus\" }]);\n * const names = mapArray(users, (user, index) => `${index() + 1}. ${user.name}`);\n * console.log(names()); // [\"1. Ada\", \"2. Linus\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T, index: () => number) => U,\n options?: { key?: undefined; fallback?: () => U },\n): Accessor<U[]>;\n/**\n * Keyed form: rows are matched by `key(item)`. `map` receives an accessor, so a new object under\n * the same key updates `item()` without re-creating the row. A duplicate key warns in dev and its\n * later copies get fresh rows on every update (dev warning `EACH_KEY_DUPLICATE`, once). Keys\n * compare like `Map` keys, so `NaN` matches `NaN`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `item()` and `index()` follow\n * the row.\n * @param options `key` identifies each item and runs untracked; `fallback` is shown while the list\n * is empty.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map`, `key` or a row cleanup threw;\n * several errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * const rows = mapArray(todos, (todo) => `#${todo().id} ${todo().title}`, {\n * key: (todo) => todo.id,\n * });\n * console.log(rows()); // [\"#1 Write docs\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: () => number) => U,\n options: { key: (item: T) => unknown; fallback?: () => U },\n): Accessor<U[]>;\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T | (() => T), index: () => number) => U,\n options?: { key?: ((item: T) => unknown) | undefined; fallback?: (() => U) | undefined },\n): Accessor<U[]> {\n const keyOf = options?.key;\n return listRows(\n list,\n keyOf === undefined\n ? { keyOf: (item: T) => item, distinct: false }\n : { keyOf: (item: T) => keyOf(item), distinct: true },\n (item, readItem, readIndex) => map(keyOf === undefined ? item : readItem, readIndex),\n options?.fallback,\n );\n}\n\n/**\n * Maps each position of a list to a row. Rows are created and removed only when the length\n * changes; the row at position `i` stays, and its `item()` accessor follows the value at `i`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per position, untracked, in the row's own root.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, indexArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [values] = useSignal([\"a\", \"b\"]);\n * const cells = indexArray(values, (value, index) => `${index}: ${value()}`);\n * console.log(cells()); // [\"0: a\", \"1: b\"]\n * });\n * @see mapArray\n * @since 1.0.0\n */\nexport function indexArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: number) => U,\n options?: { fallback?: () => U },\n): Accessor<U[]> {\n return listRows(\n list,\n { keyOf: (_item: T, position: number) => position, distinct: false },\n (_item, readItem, readIndex) => map(readItem, untrack(readIndex)),\n options?.fallback,\n );\n}\n\n/**\n * The shared engine. The memo tracks `list()` and reconciles the previous rows against the new\n * items; each row is a child of a private holder owner, so the memo's own recomputation never\n * disposes rows, and disposing the list's owner disposes the holder with every row in it.\n */\nfunction listRows<T, U>(\n list: ListSource<T>,\n keying: Keying<T>,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n fallback: (() => U) | undefined,\n): Accessor<U[]> {\n const holder = new Owner(getOwner());\n onCleanup(() => {\n disposeOwner(holder);\n });\n let rows: Row<T, U>[] = [];\n let emptyFallback: Fallback<U> | undefined;\n return useMemo<U[]>(\n () => {\n // Reading the list's contents is tracked, so a store array (proxy) updates the list when an\n // item is pushed, removed or replaced; user key functions then run untracked.\n const source = listItems(list());\n const items: readonly unknown[] = Array.isArray(source)\n ? Array.prototype.slice.call(source)\n : source;\n const entries = untrack(() => toEntries(items as readonly never[], keying));\n const reuse = matchRows(rows, entries);\n const created: Row<T, U>[] = [];\n const staged: Staged<T, U>[] = [];\n let nextFallback: Fallback<U> | undefined;\n try {\n entries.forEach((entry, position) => {\n const from = reuse[position] ?? -1;\n const kept = from === -1 ? undefined : rows[from];\n if (kept !== undefined) {\n staged.push({ row: kept, item: entry.item, position, fresh: false });\n return;\n }\n const row = openRow(holder, entry.key, entry.first, entry.item, position, build);\n created.push(row);\n staged.push({ row, item: entry.item, position, fresh: true });\n });\n if (entries.length === 0 && fallback !== undefined) {\n nextFallback = emptyFallback ?? openFallback(holder, fallback);\n }\n } catch (error) {\n // Nothing above touched the previous state, so only the rows made in this pass go.\n const failures: unknown[] = [];\n for (const row of created) disposeCollecting(row.dispose, failures);\n if (nextFallback !== undefined && nextFallback !== emptyFallback) {\n disposeCollecting(nextFallback.dispose, failures);\n }\n throw combineFailures(error, failures);\n }\n\n // Commit. Writes to retained rows come last, after every creation has succeeded.\n const failures: unknown[] = [];\n const previousRows = rows;\n const previousFallback = emptyFallback;\n rows = staged.map((stage) => stage.row);\n emptyFallback = nextFallback;\n const kept = new Uint8Array(previousRows.length);\n for (const from of reuse) {\n if (from !== -1) kept[from] = 1;\n }\n previousRows.forEach((row, from) => {\n if (kept[from] !== 1) disposeCollecting(row.dispose, failures);\n });\n if (previousFallback !== undefined && previousFallback !== nextFallback) {\n disposeCollecting(previousFallback.dispose, failures);\n }\n for (const stage of staged) {\n if (stage.fresh) continue;\n const row = stage.row;\n if (row.index !== stage.position) row.setIndex(stage.position);\n if (!Object.is(row.item, stage.item)) row.setItem(stage.item);\n }\n throwFailures(failures);\n if (nextFallback !== undefined) return [nextFallback.value];\n return rows.map((row) => row.value);\n },\n // The row callbacks build children (components, refs, directives): setup may write signals.\n { lazy: true, allowWrites: true },\n );\n}\n\n/** Treats `null`, `undefined` and `false` as an empty list. */\nfunction listItems<T>(value: readonly T[] | null | undefined | false): readonly T[] {\n return value === null || value === undefined || value === false ? [] : value;\n}\n\n/** Computes each item's reuse key. Keyed lists flag later copies of a key and warn once. */\nfunction toEntries<T>(items: readonly T[], keying: Keying<T>): Entry<T>[] {\n const entries: Entry<T>[] = [];\n const seen = new Set<unknown>();\n let duplicate = false;\n for (const [position, item] of items.entries()) {\n const key = keying.keyOf(item, position);\n let first = true;\n if (keying.distinct) {\n if (seen.has(key)) {\n first = false;\n duplicate = true;\n } else {\n seen.add(key);\n }\n }\n entries.push({ item, key, first });\n }\n if (duplicate) warn(\"EACH_KEY_DUPLICATE\");\n return entries;\n}\n\n/** Keys compare like `Map` keys: `NaN` matches `NaN`. */\nfunction sameKey(a: unknown, b: unknown): boolean {\n return a === b || (Number.isNaN(a) && Number.isNaN(b));\n}\n\nfunction canReuse<T, U>(row: Row<T, U> | undefined, entry: Entry<T> | undefined): boolean {\n return (\n row !== undefined &&\n entry !== undefined &&\n row.first &&\n entry.first &&\n sameKey(row.key, entry.key)\n );\n}\n\n/**\n * Pairs each new position with the old row it reuses; -1 means a fresh row is needed. The prefix\n * and suffix runs settle append, prepend, remove and swap at the ends in one step each. The middle\n * is matched through a Map from key to the chain of old positions with that key (earliest first),\n * so the whole pass is linear on average. Iterative throughout.\n */\nfunction matchRows<T, U>(old: readonly Row<T, U>[], next: readonly Entry<T>[]): Int32Array {\n const m = old.length;\n const n = next.length;\n const reuse = new Int32Array(n).fill(-1);\n let start = 0;\n while (start < m && start < n && canReuse(old[start], next[start])) {\n reuse[start] = start;\n start += 1;\n }\n let oldEnd = m - 1;\n let newEnd = n - 1;\n while (oldEnd >= start && newEnd >= start && canReuse(old[oldEnd], next[newEnd])) {\n reuse[newEnd] = oldEnd;\n oldEnd -= 1;\n newEnd -= 1;\n }\n if (start > oldEnd || start > newEnd) return reuse;\n\n const heads = new Map<unknown, number>();\n const chain = new Int32Array(m).fill(-1);\n for (let i = oldEnd; i >= start; i -= 1) {\n const row = old[i];\n if (row === undefined || !row.first) continue;\n chain[i] = heads.get(row.key) ?? -1;\n heads.set(row.key, i);\n }\n for (let j = start; j <= newEnd; j += 1) {\n const entry = next[j];\n if (entry === undefined || !entry.first) continue;\n const head = heads.get(entry.key);\n if (head === undefined || head === -1) continue;\n reuse[j] = head;\n heads.set(entry.key, chain[head] ?? -1);\n }\n return reuse;\n}\n\n/**\n * Creates one row in its own root under the holder. The row exists before `build` runs, so a read of `item()` or\n * `index()` during the build sees the final values. The root is detached from the memo on purpose.\n */\nfunction openRow<T, U>(\n holder: Owner,\n key: unknown,\n first: boolean,\n item: T,\n index: number,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n): Row<T, U> {\n const row = new Row<T, U>(key, first, item, index);\n const readItem = (): T => row.readItem();\n const readIndex = (): number => row.readIndex();\n runWithOwner(holder, () =>\n createRoot((dispose) => {\n row.dispose = dispose;\n row.value = untrack(() => build(item, readItem, readIndex));\n }),\n );\n return row;\n}\n\n/** Creates the empty-list row in its own root under the holder. */\nfunction openFallback<U>(holder: Owner, fallback: () => U): Fallback<U> {\n return runWithOwner(holder, () =>\n createRoot((dispose) => ({ value: untrack(fallback), dispose })),\n );\n}\n\n/** Disposes one row root. A throwing cleanup is collected so that the other rows still go. */\nfunction disposeCollecting(dispose: () => void, failures: unknown[]): void {\n try {\n dispose();\n } catch (error) {\n failures.push(error);\n }\n}\n\nfunction combineFailures(primary: unknown, failures: readonly unknown[]): unknown {\n if (failures.length === 0) return primary;\n return new AggregateError(\n [primary, ...failures],\n __DEV__ ? \"Several errors were thrown while mapping a list.\" : \"SHADOW_MAP_ERRORS\",\n );\n}\n\n/** Rethrows the one disposal failure, or all of them together. */\nfunction throwFailures(failures: readonly unknown[]): void {\n if (failures.length === 0) return;\n if (failures.length === 1) throw failures[0];\n throw new AggregateError(\n failures,\n __DEV__\n ? \"Several errors were thrown while disposing list rows.\"\n : \"SHADOW_LIST_DISPOSE_ERRORS\",\n );\n}\n"],"mappings":"A,qYAuBA,IAAMA,EAAN,KAAgB,CAEd,IAEA,MAEA,KAEA,MACA,MAAW,IAAA,GACX,QAAsBC,EAEtB,SAAyC,KAEzC,UAA+C,KAE/C,YAAY,EAAc,EAAgB,EAAS,EAAe,CAChE,KAAK,IAAMC,EACX,KAAK,MAAQC,EACb,KAAK,KAAOC,EACZ,KAAK,MAAQC,CACf,CAEA,U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,EAO9C,OANA8B,EAAapD,MACXqD,EAAY,GAAY,CACtB,EAAI,QAAUC,EACd,EAAI,MAAQvD,MAAcyB,EAAMzC,EAAMY,EAAUC,CAAS,CAAC,CAC5D,CAAC,CACH,EACO0B,CACT,CAGA,SAASI,EAAgB,EAAe,EAAgC,CACtE,OAAO0B,EAAapD,MAClBqD,EAAY,IAAa,CAAE,MAAOtD,EAAQ0B,CAAQ,EAAG,SAAQ,EAAE,CACjE,CACF,CAGA,SAASI,EAAkB,EAAqB,EAA2B,CACzE,GAAI,CACFyB,EAAQ,CACV,OAAS3B,EAAO,CACdC,EAAS,KAAKD,CAAK,CACrB,CACF,CAEA,SAASG,EAAgB,EAAkB,EAAuC,CAEhF,OADIF,EAAS,SAAW,EAAU2B,EACvB,eACT,CAACA,EAAS,GAAG3B,CAAQ,EAC0C,mBACjE,CACF,CAGA,SAASM,EAAc,EAAoC,CACzD,GAAIN,EAAS,SAAW,EAExB,MADIA,EAAS,SAAW,EAASA,EAAS,GAChC,eACRA,EAGI,4BACN,CACF,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createComputation as e,readComputation as t}from"./extend/index.js";function n(n,r){let i=e({kind:`memo`,fn:n,equals:r?.equals===void 0?Object.is:r.equals,lazy:r?.lazy===!0,allowWrites:r?.allowWrites===!0,...r?.name===void 0?{}:{name:r.name}});return()=>t(i)}export{n as useMemo};
|
|
2
|
+
//# sourceMappingURL=memo.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memo.js","names":["useMemo","node","createComputation","options","readComputation"],"sources":["../../src/memo.ts"],"sourcesContent":["import { type Accessor, createComputation, type Equals, readComputation } from \"./extend\";\n\n/**\n * Options of {@link useMemo}.\n * @since 1.0.0\n */\nexport interface MemoOptions<T> {\n /**\n * Decides whether a recomputation changed the value: readers are notified only when it returns\n * `false`. `false` always propagates.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Skip the initial computation until the first read. Without it the memo computes once when it\n * is created.\n * @default false\n */\n lazy?: boolean;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the memo is unnamed)\n */\n name?: string;\n /**\n * Turn off the development check that rejects signal writes while this memo computes. Set it for\n * a memo that builds children (components, `ref` callbacks, directives), where the code that runs\n * is setup and may write a counter or a registry; the control-flow components do. A memo that\n * derives a value must leave it off.\n * @default false\n */\n allowWrites?: boolean;\n}\n\n/**\n * Creates a cached derivation that recomputes only when a dependency actually changed.\n * Dependencies are discovered on every run, so branches that are not taken are not tracked.\n * A memo that throws inside an error boundary (an ancestor `onError` or `catchError`) reports the\n * error there and keeps its previous value; without a boundary it stores the error and rethrows it\n * to every reader.\n *\n * @param fn Computation; receives the previous value (`undefined` on the first run).\n * @param options Equality override, `lazy`, `allowWrites` and a devtools name. Undefined uses the\n * defaults.\n * @returns An accessor returning the current, always fresh value.\n * @throws ShadowError `CYCLE_DETECTED` from the accessor when the memo reads itself while it\n * computes. Outside an error boundary the accessor also rethrows the error `fn` threw on its last\n * run.\n * @example\n * import { useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(2);\n * const doubled = useMemo(() => count() * 2);\n * setCount(5);\n * console.log(doubled()); // 10\n * @see useSignal\n * @since 1.0.0\n */\nexport function useMemo<T>(\n fn: (previous: T | undefined) => T,\n options?: MemoOptions<T>,\n): Accessor<T> {\n const node = createComputation({\n kind: \"memo\",\n fn: fn as (previous: never) => unknown,\n equals: (options?.equals === undefined ? Object.is : options.equals) as Equals<unknown>,\n lazy: options?.lazy === true,\n allowWrites: options?.allowWrites === true,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n return () => readComputation<T>(node);\n}\n"],"mappings":"A,2EA0DA,SAAgBA,EACd,EACA,EACa,CACb,IAAMC,EAAOC,EAAkB,CAC7B,KAAM,OACF,KACJ,OAASC,GAAS,SAAW,IAAA,GAAY,OAAO,GAAKA,EAAQ,OAC7D,KAAMA,GAAS,OAAS,GACxB,YAAaA,GAAS,cAAgB,GACtC,GAAIA,GAAS,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAMA,EAAQ,IAAK,CAC9D,CAAC,EACD,UAAaC,EAAmBH,CAAI,CACtC,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{useSignal as e}from"./signal.js";import{useMemo as t}from"./memo.js";function n(n,r){let[i,a]=e([]);return[t(()=>{let e=n();for(let t of i())e=r(e,t.action);return e}),(e,t)=>{let n={action:e};a(e=>[...e,n]);let r=()=>{a(e=>e.filter(e=>e!==n))};t.then(r,r)}]}export{n as useOptimistic};
|
|
2
|
+
//# sourceMappingURL=optimistic.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"optimistic.js","names":["useOptimistic","pending","setPending","useSignal","useMemo","current","source","entry","reducer","list","drop","item","settled"],"sources":["../../src/optimistic.ts"],"sourcesContent":["import type { Accessor } from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { useSignal } from \"./signal\";\n\n/**\n * Optimistic state: shows `reducer` applied over the real value for every action whose\n * `settled` promise is still pending. When the promise settles (either way) the action is\n * dropped and the view falls back to the real source, which is where the confirmed result lives.\n *\n * @param source The authoritative value, tracked.\n * @param reducer Pure function combining the current state with one pending action. It runs for\n * every pending action, in the order they were applied, each time the state recomputes.\n * @returns `[state, apply]`. `state` is a memo; `apply(action, settled)` adds the action at once\n * and drops it when `settled` resolves or rejects. Pass the mutation's promise as `settled`.\n * @example\n * import { useOptimistic, useSignal } from \"@shadow-js/core\";\n *\n * const [todos, setTodos] = useSignal<string[]>([]);\n * const [shown, addTodo] = useOptimistic(todos, (list, text: string) => [...list, text]);\n * const save = (text: string) =>\n * fetch(\"/api/todos\", { method: \"POST\", body: text }).then(() => setTodos((l) => [...l, text]));\n * addTodo(\"milk\", save(\"milk\")); // shown() includes \"milk\" at once\n * @see useAction\n * @since 1.0.0\n */\nexport function useOptimistic<T, A>(\n source: Accessor<T>,\n reducer: (state: T, action: A) => T,\n): [Accessor<T>, (action: A, settled: Promise<unknown>) => void] {\n const [pending, setPending] = useSignal<ReadonlyArray<{ action: A }>>([]);\n const state = useMemo(() => {\n let current = source();\n for (const entry of pending()) current = reducer(current, entry.action);\n return current;\n });\n const apply = (action: A, settled: Promise<unknown>): void => {\n const entry = { action };\n setPending((list) => [...list, entry]);\n const drop = (): void => {\n setPending((list) => list.filter((item) => item !== entry));\n };\n settled.then(drop, drop);\n };\n return [state, apply];\n}\n"],"mappings":"A,4EAyBA,SAAgBA,EACd,EACA,EAC+D,CAC/D,GAAM,CAACC,EAASC,GAAcC,EAAwC,CAAC,CAAC,EAcxE,MAAO,CAbOC,MAAc,CAC1B,IAAIC,EAAUC,EAAO,EACrB,IAAK,IAAMC,KAASN,EAAQ,EAAG,EAAUO,EAAQH,EAASE,EAAM,MAAM,EACtE,OAAOF,CACT,CASQ,GARO,EAAW,IAAoC,CAC5D,IAAME,EAAQ,CAAE,QAAO,EACvBL,EAAY,GAAS,CAAC,GAAGO,EAAMF,CAAK,CAAC,EACrC,IAAMG,MAAmB,CACvBR,EAAY,GAASO,EAAK,OAAQ,GAASE,IAASJ,CAAK,CAAC,CAC5D,EACAK,EAAQ,KAAKF,EAAMA,CAAI,CACzB,CACoB,CACtB,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ShadowError as e}from"./internal/diagnostics.js";import{Owner as t,addCleanup as n,handleError as r}from"./internal/owner.js";import{disposeTree as i}from"./internal/dispose.js";import{currentOwner as a,runInScope as o}from"./extend/index.js";function s(e){return o({listener:null},e)}function c(e,n){let r=n?.detached===!0,s=a(),c=new t(r?null:s);r&&(c.context=s===null?null:s.context);try{return o({owner:c,listener:null},()=>e(()=>i(c)))}catch(e){throw i(c),e}}function l(){return a()}function u(e,t){let n=e;return n?.disposed&&(n=null),o({owner:n,listener:null},t)}function d(e){let t=a();t!==null&&n(t,e)}function f(e){let t=a();t!==null&&(t.errorHandlers===null?t.errorHandlers=[e]:t.errorHandlers.push(e))}function p(e,n){let i=new t(a());i.errorHandlers=[n];try{return u(i,e)}catch(e){r(e,i);return}}function m(){let t=a();if(t===null)throw new e(`NO_OWNER_ID`);for(let e=t;e!==null;e=e.parent){if(e.idPrefix===void 0)continue;let t=e.idCount;return e.idCount+=1,`s${e.idPrefix}${t}`}let n=[];for(let e=t;e!==null;e=e.parent)n.push(e.index);n.reverse();let r=t.idCount;return t.idCount+=1,`s${n.join(`-`)}_${r}`}export{p as catchError,c as createRoot,l as getOwner,d as onCleanup,f as onError,u as runWithOwner,s as untrack,m as useId};
|
|
2
|
+
//# sourceMappingURL=ownership.js.map
|