@wcstack/signals 4.17.0 → 4.19.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core-C5Booev-.esm.min.js","sources":["../src/reportError.ts","../src/dev.ts","../src/reactive.ts","../src/bindNode.ts","../src/resource.ts","../src/streamResource.ts"],"sourcesContent":["// Internal error-reporting policy (NOT part of the public API; not re-exported\n// from exports.ts). Single source of truth for \"surface an error without crashing\".\n//\n// Delegates to the platform `reportError` when present — it dispatches a window\n// \"error\" event / logs to the console without aborting the current task — and falls\n// back to `console.error` otherwise. It NEVER re-throws (re-throwing would abort the\n// caller's drain / abort handler) and NEVER swallows silently (that would hide bugs).\nexport function reportError(err: unknown): void {\n const r = (globalThis as { reportError?: (e: unknown) => void }).reportError;\n if (typeof r === \"function\") {\n r(err);\n } else {\n console.error(err);\n }\n}\n","// Opt-in development diagnostics (NOT part of the public API; not re-exported from\n// exports.ts). Surfaces \"silent failure\" modes — duplicate/unkeyed list rows,\n// un-owned effects that leak, no-op onCleanup, reactive cycles — that production\n// otherwise swallows.\n//\n// DEFAULT OFF. Nothing here runs unless the consumer flips `globalThis.__WCS_DEV__`\n// to `true` BEFORE the failing operation. `isDev()` reads the flag at CALL TIME (not\n// module-load time), so a page can toggle it on for a debugging session without a\n// rebuild. See README \"Development mode\".\n//\n// TREE-SHAKING: the package sets `\"sideEffects\": false`, and every export here is a\n// pure function with no module-top-level side effects (the dedupe cache is a lazily-\n// populated Set, not eager work). A production bundler that never references warnDev\n// can drop this module entirely; a bundler that does keep it still pays nothing at\n// runtime because `warnDev` short-circuits on the `isDev()` guard before touching the\n// dedupe Set or formatting a message.\n\n/** Stable warning codes, so docs/tests can reference a warning without matching prose. */\nexport type DevWarningCode =\n | \"DUPLICATE_KEY\"\n | \"NON_PRIMITIVE_KEY\"\n | \"NULLISH_KEY\"\n | \"UNOWNED_EFFECT\"\n | \"UNOWNED_INSERT\"\n | \"ORPHAN_CLEANUP\"\n | \"REACTIVE_CYCLE\"\n | \"UNTRACKED_COMPUTED\"\n | \"UNTRACKED_EFFECT\";\n\n/**\n * True only when the consumer has opted in via `globalThis.__WCS_DEV__ === true`.\n * Read at call time so the flag can be toggled at runtime. Kept tiny and pure so a\n * production bundle that strips dev branches pays nothing.\n */\nexport function isDev(): boolean {\n return (globalThis as { __WCS_DEV__?: boolean }).__WCS_DEV__ === true;\n}\n\n// Dedupe set: a given (code + dedupe-key) warning is emitted at most once, so a\n// per-row or per-flush failure does not flood the console. Lazily populated; empty\n// and inert until the first dev warning actually fires.\nconst emitted = new Set<string>();\n\n/**\n * Emit a development warning ONCE per `(code, dedupeKey)`, only when dev mode is on.\n * In production (`isDev()` false) this is a no-op that returns before any work.\n *\n * @param code stable warning code (see DevWarningCode)\n * @param dedupeKey extra discriminator folded into the dedupe identity (e.g. the\n * duplicate key value). Same code + same dedupeKey warns once.\n * @param message human-readable explanation; `detail` is appended for context.\n */\nexport function warnDev(\n code: DevWarningCode,\n dedupeKey: string,\n message: string,\n ...detail: unknown[]\n): void {\n if (!isDev()) {\n return;\n }\n const id = code + \"\\u0000\" + dedupeKey;\n if (emitted.has(id)) {\n return;\n }\n emitted.add(id);\n console.warn(`[wcstack/signals][${code}] ${message}`, ...detail);\n}\n\n/**\n * Clear the dedupe cache. Test-only seam so each test can re-exercise a warning that\n * is otherwise emitted once per process. Not meant for application use.\n */\nexport function __resetDevWarnings(): void {\n emitted.clear();\n}\n","// Minimal signal core (v1 design notes).\n//\n// A self-contained, zero-dependency reactive primitive whose public API is\n// shaped after the TC39 Signals proposal (State / Computed / effect). The intent\n// is NOT to ship signal-polyfill as a runtime dependency, but to keep an in-house\n// implementation that can later be swapped for the native one without changing\n// call sites. See docs/signals-state-design.md §2 (the \"case C\" decision).\n//\n// Reactivity model: three-color marking (CLEAN / CHECK / DIRTY), pull-validated\n// (after Reactively / Solid). docs §8 (c).\n// - A signal write marks its direct observers DIRTY and their transitive\n// observers CHECK. Effects scheduled on the CLEAN→stale transition run on a\n// coalesced microtask (docs §5-3).\n// - On read/run, `updateIfNecessary` validates a CHECK node by refreshing its\n// computed sources first; it recomputes only if a source actually changed.\n// - EQUALITY SHORT-CIRCUIT: when a computed recomputes to an equal value it does\n// NOT mark its observers DIRTY, so downstream effects/computeds skip work.\n// - dependencies are re-tracked on every run, so conditional deps are pruned.\n\nimport { reportError } from \"./reportError.js\";\nimport { isDev, warnDev } from \"./dev.js\";\n\nexport type Cleanup = () => void;\nexport type Equals<T> = (a: T, b: T) => boolean;\n\nexport interface ReadSignal<T> {\n /** Read the value AND register the current observer as a dependent. */\n get(): T;\n /** Read the value WITHOUT tracking (no dependency edge created). */\n peek(): T;\n}\n\nexport interface WriteSignal<T> extends ReadSignal<T> {\n set(value: T): void;\n}\n\nexport interface EffectHandle {\n dispose(): void;\n}\n\n// Node freshness. CLEAN: up to date. CHECK: a transitive source may have changed\n// — must validate before use. DIRTY: a direct source changed — must recompute.\n// Typed as `number` (not literals) on purpose: `_state` is mutated through\n// aliasing during `updateIfNecessary`, so literal narrowing would wrongly flag\n// the `=== DIRTY` re-check after a source update.\nconst CLEAN: number = 0;\nconst CHECK: number = 1;\nconst DIRTY: number = 2;\n\ninterface Observable {\n _observers: Set<Computation>;\n /** Called when the last observer leaves (selector's per-key nodes forget their key). */\n _unobserved?: () => void;\n}\n\ninterface Computation extends Observable {\n _state: number;\n _sources: Set<Observable>;\n _isEffect: boolean;\n _update(): void;\n}\n\n// --- tracking context -------------------------------------------------------\n\nlet currentObserver: Computation | null = null;\n\nfunction track(source: Observable): void {\n if (currentObserver !== null) {\n currentObserver._sources.add(source);\n source._observers.add(currentObserver);\n }\n}\n\nfunction untrack(node: Computation): void {\n for (const source of node._sources) {\n const observers = source._observers;\n observers.delete(node);\n if (observers.size === 0 && source._unobserved !== undefined) {\n source._unobserved();\n }\n }\n node._sources.clear();\n}\n\n// --- ownership (disposal tree) ----------------------------------------------\n//\n// Orthogonal to dependency tracking. An \"owner\" collects the disposers of the\n// computations (effects, nested cleanups, child roots) created during its run.\n// An effect IS an owner: it owns whatever was created while it ran, and disposes\n// those children before it re-runs or is disposed. This is what lets the DOM\n// layer rebuild a subtree without leaking the previous subtree's effects\n// (docs §8 (d)). Modeled after Solid's reactive ownership.\n\ntype Disposer = () => void;\n\n/** An owned child: a disposer function, or a node disposed through its own method (no closure per node). */\ntype Owned = Disposer | { _disposeOwned(): void };\n\ninterface Owner {\n _owned: Owned[];\n}\n\nlet currentOwner: Owner | null = null;\n\nfunction registerDisposer(disposer: Owned): void {\n if (currentOwner !== null) {\n currentOwner._owned.push(disposer);\n }\n}\n\nfunction disposeOwned(owner: Owner): void {\n // Dispose in reverse creation order (children before parents, last-in-first-out).\n const owned = owner._owned;\n for (let i = owned.length - 1; i >= 0; i--) {\n const o = owned[i];\n if (typeof o === \"function\") o();\n else o._disposeOwned();\n }\n owned.length = 0;\n}\n\n// --- effect scheduling (microtask coalesce) ---------------------------------\n\n// The queue NEW work accumulates into (markStale / a computed's DIRTY promotion add\n// here). Each drain pass takes the current queue to iterate and installs a fresh\n// empty one in its place, so effects queued WHILE draining land in the next pass.\nlet pendingEffects = new Set<EffectNode>();\nlet flushScheduled = false;\n\n// Double-buffer free list: rather than `[...pendingEffects]` (a Set→Array copy) per\n// pass, a drain SWAPS the live queue with a recycled empty Set and iterates that Set\n// directly. The swapped-out Set must be a fresh buffer that re-entrancy cannot\n// clobber — a nested flushSync swaps `pendingEffects` again, so the outer pass keeps\n// iterating its OWN buffer (the same isolation the old local-array copy gave). After\n// draining, the buffer is cleared and returned to the pool for reuse.\nconst bufferPool: Set<EffectNode>[] = [];\n\nfunction takeBuffer(): Set<EffectNode> {\n return bufferPool.pop() ?? new Set<EffectNode>();\n}\n\nfunction schedule(): void {\n if (flushScheduled) {\n return;\n }\n flushScheduled = true;\n queueMicrotask(flushEffects);\n}\n\n// Upper bound on drain iterations. A well-behaved graph settles in a handful of\n// passes; exceeding this means an effect keeps dirtying its own dependency with a\n// changing value (a reactive cycle), which would otherwise hang the page. We bail\n// loudly instead of spinning forever (docs §5-3).\nconst MAX_FLUSH_ITERATIONS = 1000;\n\n// Dev-only: build a \"what was still running\" appendix for the cycle bail. Uses the\n// creation stack captured per effect (dev only) so the message points at WHERE the\n// looping effects were defined. Production never calls this (guarded by the dev\n// `lastBatch`), so the stack-capture cost never lands on shipped code.\nfunction describeCycle(batch: EffectNode[]): string {\n const live = batch.filter((e) => !e._disposed);\n const lines = live.map((e, i) => {\n const where = e._devStack ? e._devStack.split(\"\\n\").slice(1, 3).join(\" | \").trim() : \"(no stack)\";\n return ` #${i + 1} ${where}`;\n });\n return (\n `\\n[wcstack/signals] dev diagnostics: ${live.length} effect(s) still re-running on the ` +\n `final pass (likely cycle participants):\\n${lines.join(\"\\n\")}`\n );\n}\n\nfunction flushEffects(): void {\n flushScheduled = false;\n // Drain in a loop: an effect may, while running, dirty a signal that queues\n // further effects. Coalescing collapses multiple writes in one tick into a\n // single run per effect (docs §5-3).\n let iterations = 0;\n // Dev-only: the effects run on the most recent pass, so a cycle bail can point at\n // the culprits. Lazily allocated only in dev (no cost in production).\n let lastBatch: EffectNode[] | null = null;\n while (pendingEffects.size > 0) {\n if (++iterations > MAX_FLUSH_ITERATIONS) {\n // Drop the runaway queue so a single bad effect cannot wedge every later\n // flush, then surface the bug.\n pendingEffects.clear();\n throw new Error(\n \"flushEffects: exceeded \" +\n MAX_FLUSH_ITERATIONS +\n \" iterations — likely a reactive cycle (an effect writes a signal it depends on with an ever-changing value).\" +\n (lastBatch ? describeCycle(lastBatch) : \"\"),\n );\n }\n // Swap the live queue out for a fresh empty buffer, then iterate the swapped-out\n // Set directly (no array copy). New work queued by an effect's body lands in the\n // new `pendingEffects` and is picked up on the next pass — same coalescing as\n // before. `batch` is a local reference, so a re-entrant flushSync (which swaps\n // `pendingEffects` again) cannot clobber this pass's iteration.\n const batch = pendingEffects;\n pendingEffects = takeBuffer();\n if (isDev()) {\n // Record the effects on this pass; on the FINAL (overflowing) pass these are\n // the ones still re-queuing themselves — the cycle participants.\n lastBatch = [...batch];\n }\n for (const node of batch) {\n if (!node._disposed) {\n // Isolate each effect: a throw from one effect's body must NOT abort the\n // batch and silently strand its already-dequeued siblings. We hand the\n // error to reportError (which does not re-throw, so the drain continues)\n // and move on. updateIfNecessary guarantees the node is settled to CLEAN\n // even on throw, so it is not left stuck DIRTY.\n try {\n updateIfNecessary(node);\n } catch (err) {\n reportError(err);\n }\n }\n }\n // Recycle this pass's buffer. Clear AFTER iterating so a node is never dropped\n // mid-walk; the Set is now free for a later takeBuffer().\n batch.clear();\n bufferPool.push(batch);\n }\n}\n\n// Effect/computed errors are surfaced via the shared `reportError` policy\n// (./reportError.ts), called synchronously from the drain loop. It does NOT\n// re-throw (that would abort the drain) and does NOT swallow (that would hide the\n// bug). Re-entrancy is safe: the only re-scheduling path (markStale) defers to a\n// microtask, so reporting here cannot recurse into the running flush.\n\n/**\n * Synchronously flush queued effects. Provided for tests and for callers that\n * need DOM updates applied before reading the DOM back. In normal use effects\n * settle on their own microtask.\n */\nexport function flushSync(): void {\n // Do NOT touch flushScheduled here: a microtask may already be queued. Just\n // drain. flushEffects resets the flag itself; if a queued microtask still fires\n // afterwards it finds an empty queue and is a no-op. Touching the flag from here\n // would let a second flushSync race the queued microtask into a double drain.\n flushEffects();\n}\n\n// --- marking & validation ---------------------------------------------------\n\nfunction markStale(node: Computation, level: number): void {\n if (node._state < level) {\n const wasClean = node._state === CLEAN;\n node._state = level;\n if (wasClean && node._isEffect) {\n pendingEffects.add(node as EffectNode);\n schedule();\n }\n // Observers can only become CHECK from us: they need to re-validate, but\n // whether they truly changed depends on our recomputed value.\n for (const observer of node._observers) {\n markStale(observer, CHECK);\n }\n }\n}\n\nfunction updateIfNecessary(node: Computation): void {\n if (node._state === CLEAN) {\n return;\n }\n if (node._state === CHECK) {\n // A transitive source might have changed. Refresh computed sources; one of\n // them may set us DIRTY (via the equality check in its _update).\n // NOTE: this scans ALL sources each validation (O(sources)); the standard\n // pull-based scheme (Reactively/Solid) does the same. Intentional for v1 —\n // a future optimization could track per-source dirtiness to scan less.\n for (const source of node._sources) {\n if (source instanceof ComputedNode) {\n updateIfNecessary(source);\n if (node._state === DIRTY) {\n break;\n }\n }\n }\n }\n // Settle to CLEAN in a finally: if _update() (a user fn / equals) throws, the\n // node must NOT be left stuck DIRTY, otherwise every later peek/get would\n // re-run the throwing fn forever. The error propagates to the caller (a flush\n // isolates it per-effect; a direct get/peek surfaces it to that caller).\n try {\n if (node._state === DIRTY) {\n node._update();\n }\n } finally {\n node._state = CLEAN;\n }\n}\n\n// --- signal -----------------------------------------------------------------\n\nclass SignalNode<T> implements Observable, WriteSignal<T> {\n _observers = new Set<Computation>();\n private _value: T;\n private _equals: Equals<T>;\n\n constructor(value: T, equals: Equals<T>) {\n this._value = value;\n this._equals = equals;\n }\n\n get(): T {\n track(this);\n return this._value;\n }\n\n peek(): T {\n return this._value;\n }\n\n set(next: T): void {\n if (this._equals(this._value, next)) {\n return;\n }\n this._value = next;\n // No copy needed: markStale only schedules effects (on a microtask) and marks\n // observers — it never runs user code synchronously, so this set is not\n // mutated during the walk. Iterating it directly avoids a per-write allocation.\n for (const observer of this._observers) {\n markStale(observer, DIRTY);\n }\n }\n}\n\n// --- computed ---------------------------------------------------------------\n\nclass ComputedNode<T> implements Computation, ReadSignal<T> {\n _observers = new Set<Computation>();\n _sources = new Set<Observable>();\n _state = DIRTY; // never computed yet\n _isEffect = false;\n private _fn: () => T;\n private _value: T | undefined = undefined;\n private _initialized = false;\n private _running = false;\n private _equals: Equals<T>;\n\n constructor(fn: () => T, equals: Equals<T>) {\n this._fn = fn;\n this._equals = equals;\n // Be owned by the enclosing scope (a parent effect or createRoot). When that\n // scope tears down, untrack this computed so it is removed from its sources'\n // observer sets — otherwise a computed created inside an effect that re-runs\n // would leak a stale ComputedNode into each source on every run (docs §8 (d)).\n // Lazy + no children: teardown is just untrack, no cleanup/owned to dispose.\n registerDisposer(this);\n }\n\n _disposeOwned(): void {\n untrack(this);\n }\n\n get(): T {\n // Order matters: track BEFORE updateIfNecessary. The current observer must be\n // registered against THIS computed regardless of whether validation recomputes —\n // and recomputation swaps currentObserver to this node, so tracking first records\n // the edge under the OUTER observer (the caller), not this computed's own run.\n track(this);\n updateIfNecessary(this);\n return this._value as T;\n }\n\n peek(): T {\n updateIfNecessary(this);\n return this._value as T;\n }\n\n _update(): void {\n // Cycle guard: if _fn (directly or transitively) reads this computed, get()\n // would recurse into _update and blow the stack with an opaque RangeError.\n // Detect the self-reference and throw a clear error instead. (The effect-level\n // MAX_FLUSH_ITERATIONS guard does not cover this synchronous self-recursion.)\n if (this._running) {\n throw new Error(\"computed: circular dependency — the computed reads itself.\");\n }\n const previous = this._value;\n untrack(this);\n const prevObserver = currentObserver;\n currentObserver = this;\n this._running = true;\n try {\n this._value = this._fn();\n } finally {\n this._running = false;\n currentObserver = prevObserver;\n }\n // Equality short-circuit: only propagate when the value actually changed.\n // Our observers are already CHECK (from the originating markStale); promote\n // them to DIRTY so they recompute, otherwise leave them to settle CLEAN. Skip\n // on the first computation: there is no prior value to compare, and a custom\n // `equals` must not be invoked with the undefined sentinel.\n if (!this._initialized) {\n this._initialized = true;\n // A first run that read no signal never recomputes: a value read outside the function,\n // or with peek(), was fixed when it ran (docs/seam-apps.md, signals-shop). Dev-only.\n if (isDev() && this._sources.size === 0) {\n warnDev(\n \"UNTRACKED_COMPUTED\",\n String(this._fn).slice(0, 120),\n \"computed read no signal, so it never recomputes: read signals with get() inside it.\",\n this._fn,\n );\n }\n } else if (!this._equals(previous as T, this._value as T)) {\n for (const observer of this._observers) {\n observer._state = DIRTY;\n // Normally this computed is refreshed from inside flushEffects while\n // validating an already-scheduled effect, so the observer is in the queue\n // already. But if it is refreshed out-of-band (e.g. a `peek()` outside a\n // flush) an effect observer could otherwise be promoted to DIRTY without\n // being queued, and never re-run. Re-schedule defensively to keep the\n // \"DIRTY effect always runs\" invariant regardless of refresh path.\n if (observer._isEffect && !(observer as EffectNode)._disposed) {\n pendingEffects.add(observer as EffectNode);\n schedule();\n }\n }\n }\n }\n}\n\n// --- effect -----------------------------------------------------------------\n\n/** The observers of every effect: effects are not read, so this stays empty. */\nconst NO_OBSERVERS: Set<Computation> = new Set();\n\nclass EffectNode implements Computation, Owner {\n _observers: Set<Computation> = NO_OBSERVERS; // effects are never read, so nothing is ever added\n _sources = new Set<Observable>();\n _owned: Owned[] = [];\n _state = DIRTY;\n _isEffect = true;\n _disposed = false;\n // Dev-only creation stack, used to point a reactive-cycle bail at where the looping\n // effect was defined. Captured only when dev mode is on at construction time, so\n // production effects pay nothing for it.\n _devStack: string | undefined = undefined;\n private _fn: () => Cleanup | void;\n private _cleanup: Cleanup | void = undefined;\n\n constructor(fn: () => Cleanup | void, checkTracked = false) {\n this._fn = fn;\n if (isDev()) {\n this._devStack = new Error().stack;\n }\n // Be owned by the enclosing owner (a parent effect or a createRoot), so a\n // parent teardown disposes this effect.\n registerDisposer(this);\n updateIfNecessary(this); // initial run (state starts DIRTY)\n // An author's effect whose first run read no signal never runs again (docs/seam-apps.md,\n // signals-shop). One that returned a cleanup, registered onCleanup or built children is a\n // setup effect, run once on purpose. The effects dom.ts and the adapters build for an\n // author's values are not checked (checkTracked false): the author did not write them.\n if (checkTracked && isDev() && !this._disposed && this._sources.size === 0 &&\n typeof this._cleanup !== \"function\" && this._owned.length === 0) {\n warnDev(\n \"UNTRACKED_EFFECT\",\n String(fn).slice(0, 120),\n \"effect read no signal, so it never runs again: read signals with get() inside it.\",\n fn,\n );\n }\n }\n\n _update(): void {\n this._runCleanup();\n disposeOwned(this); // tear down children created in the previous run\n untrack(this);\n const prevObserver = currentObserver;\n const prevOwner = currentOwner;\n currentObserver = this;\n currentOwner = this; // children created during the run are owned by this effect\n try {\n this._cleanup = this._fn();\n } finally {\n currentObserver = prevObserver;\n currentOwner = prevOwner;\n }\n }\n\n private _runCleanup(): void {\n if (typeof this._cleanup === \"function\") {\n this._cleanup();\n this._cleanup = undefined;\n }\n }\n\n _disposeOwned(): void {\n this.dispose();\n }\n\n dispose(): void {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n this._runCleanup();\n disposeOwned(this);\n untrack(this);\n pendingEffects.delete(this);\n }\n}\n\n// --- public API -------------------------------------------------------------\n\nexport function signal<T>(initial: T, equals: Equals<T> = Object.is): WriteSignal<T> {\n return new SignalNode(initial, equals);\n}\n\nexport function computed<T>(fn: () => T, equals: Equals<T> = Object.is): ReadSignal<T> {\n return new ComputedNode(fn, equals);\n}\n\nexport function effect(fn: () => Cleanup | void): EffectHandle {\n // (an effect built by dom.ts or an adapter for the author's value — innerEffect — is not checked for tracking)\n const checkTracked = !innerNext;\n innerNext = false;\n if (isDev() && currentOwner === null) {\n // No enclosing owner: nothing will ever dispose this effect, so it (and the\n // subscriptions it builds) leak. Legitimate top-level effects should be mounted\n // under createRoot / SignalsElement and disposed on teardown. Dev-only warn.\n warnDev(\n \"UNOWNED_EFFECT\",\n \"\",\n \"effect created with no owner — it will never be disposed and may leak. \" +\n \"Wrap it in createRoot(dispose => …) (or a SignalsElement render()) and \" +\n \"dispose on teardown.\",\n );\n }\n return new EffectNode(fn, checkTracked);\n}\n\n/**\n * One boolean per key over one source: `isSelected(key)` is true while the source equals `key`.\n * A change of the source re-runs only the readers of the key it left and the key it took, not\n * every reader — a row per item that compares `selected.get() === id` itself re-runs every row on\n * each change. Solid's createSelector.\n *\n * A key is compared with the source as a Map compares keys (`===`, and NaN equals NaN): to select an\n * object, select its id — `selector(computed(() => selected.get()?.id))`. The readers are told when\n * effects run (a microtask, or `flushSync`); a call itself reads the source as it is now. A key no\n * reader reads any more is forgotten. Create it under an owner (`createRoot` / a `SignalsElement`\n * render): its subscription to the source is an effect.\n */\nexport function selector<T>(source: ReadSignal<T>): (key: T) => boolean {\n const byKey = new Map<T, Observable>();\n let value = source.peek();\n const dirty = (key: T): void => {\n const node = byKey.get(key);\n if (node !== undefined) {\n for (const observer of node._observers) {\n markStale(observer, DIRTY);\n }\n }\n };\n innerEffect(() => {\n const next = source.get();\n if (!sameKey(next, value)) {\n const prev = value;\n value = next;\n dirty(prev);\n dirty(next);\n }\n });\n return (key: T): boolean => {\n if (currentObserver !== null) {\n let node = byKey.get(key);\n if (node === undefined) {\n node = {\n _observers: new Set(),\n // tracked only right after it is read from the map, it is the map's node until this runs\n _unobserved: () => byKey.delete(key),\n };\n byKey.set(key, node);\n }\n track(node);\n }\n return sameKey(key, source.peek());\n };\n}\n\n/** SameValueZero, the comparison of a Map's keys. */\nfunction sameKey(a: unknown, b: unknown): boolean {\n return a === b || (a !== a && b !== b);\n}\n\n/** The next effect() is one the package builds for an author's value (not checked for tracking). */\nlet innerNext = false;\n\n/**\n * Internal (dom.ts, bindNode, the resource adapters): an effect the package builds around an\n * author's value — a function child or prop, a bound node, a fetcher. Behaves as effect(); only\n * the dev-mode UNTRACKED_EFFECT check, which is about effects the author wrote, is skipped.\n */\nexport function innerEffect(fn: () => Cleanup | void): EffectHandle {\n innerNext = true;\n return effect(fn);\n}\n\n/**\n * Run `fn` inside a fresh ownership scope and return its result. Every effect (or\n * nested cleanup) created during `fn` — directly or transitively — is owned by\n * this root; calling the `dispose` passed to `fn` tears them all down.\n *\n * The root is detached: it is NOT auto-disposed by an enclosing owner. The caller\n * holds `dispose` (e.g. a custom element disposes it in disconnectedCallback).\n *\n * If `fn` throws, any effects/cleanups it created BEFORE the throw are disposed\n * before the error propagates — a caller that never received `dispose` (because the\n * call threw) cannot leak the half-built scope.\n */\nexport function createRoot<T>(fn: (dispose: () => void) => T): T {\n const owner: Owner = { _owned: [] };\n let disposed = false;\n const dispose = (): void => {\n if (disposed) {\n return;\n }\n disposed = true;\n disposeOwned(owner);\n };\n const prevOwner = currentOwner;\n const prevObserver = currentObserver;\n currentOwner = owner;\n // Detach the dependency-tracking context too, not just ownership. A root is a\n // fresh reactive boundary: signals read SYNCHRONOUSLY while `fn` builds the scope\n // must not register the OUTER observer as their dependent (Solid's createRoot\n // clears both owner and listener). Without this, a For/Index `each` that reads\n // `index()`/`item()` synchronously in its body would track the outer reconcile\n // effect against the row's idx/item signal, so reordering re-dirties the reconcile\n // effect — a self-loop the equality/MAX_FLUSH guards only paper over.\n currentObserver = null;\n try {\n return fn(dispose);\n } catch (err) {\n dispose(); // tear down whatever fn built before it threw\n throw err;\n } finally {\n currentOwner = prevOwner;\n currentObserver = prevObserver;\n }\n}\n\n/**\n * True when there is a current ownership scope (an enclosing effect or createRoot).\n * Dev-diagnostics seam for the DOM layer to flag un-owned reactive insertions\n * without re-implementing owner tracking. NOT part of the public API.\n */\nexport function hasOwner(): boolean {\n return currentOwner !== null;\n}\n\n/**\n * Register a teardown callback with the current owner. Runs when the owning effect\n * re-runs or is disposed, or when the enclosing root is disposed. A no-op when\n * there is no current owner.\n */\nexport function onCleanup(fn: () => void): void {\n if (currentOwner === null) {\n // No owner → registerDisposer drops `fn` on the floor: the cleanup never runs.\n // Silent in production; flag it in dev so the missing teardown is visible.\n warnDev(\n \"ORPHAN_CLEANUP\",\n \"\",\n \"onCleanup called with no owner — the cleanup will never run. \" +\n \"Call it inside an effect, createRoot, or a SignalsElement render().\",\n );\n }\n registerDisposer(fn);\n}\n","// wc-bindable → signal adapter. The crux of the design.\n//\n// Any async-IO node in wcstack speaks the wc-bindable protocol:\n// - properties: outputs — the node dispatches `event` on change; the value is\n// read via `getter(event)`, defaulting to `e.detail` (wc-bindable\n// SPEC § Default Getter). The property `name` is read only for the\n// initial seed, where no event exists yet (SPEC § Initial Sync).\n// - inputs: settable surface — write `node[name] = value`.\n// - commands: invocable methods — call `node[name](...args)`.\n// The node has NO idea whether the observer behind the binding is a proxy (state)\n// or a signal. So a single adapter that maps these surfaces onto signals makes every\n// existing node plug into the signal core unchanged. See docs/signals-state-design.md\n// §3, and the four mappings of §3-1:\n//\n// element → signal | property (latest snapshot) → read signal [`signals`]\n// element → signal | event-token (per-emit stream) → folded signal [`on`]\n// signal → element | input (write-back) → effect → prop [`bindInput`]\n// signal → element | command-token (start/cancel) → emit on change [`bindCommand`]\n//\n// `signals` is the STATE view of a property (equality-guarded — same value = no\n// update). `on` is the OCCURRENCE view of the same event (a stream — every emit\n// updates, even with an equal value), folded latest-by-default.\n\nimport { signal, innerEffect as effect, WriteSignal, ReadSignal } from \"./reactive.js\";\nimport { reportError } from \"./reportError.js\";\nimport type { ResourceSource } from \"./resource.js\";\n\nexport interface WcBindableProperty<V = unknown> {\n readonly name: string;\n readonly event: string;\n readonly getter?: (event: Event) => V;\n}\n\n// Structurally a SUBSET of the real `IWcBindable` (which additionally carries\n// `protocol` / `version`, and richer input/command entries). A real descriptor is\n// therefore assignable to this type — see __tests__/bindNode.compat.test.ts.\nexport interface WcBindableDescriptor {\n readonly properties: readonly WcBindableProperty[];\n readonly inputs?: readonly { readonly name: string }[];\n readonly commands?: readonly { readonly name: string }[];\n}\n\n// --- typed node shape (D1) ---------------------------------------------------\n//\n// `bindNode` is the package's centerpiece, yet without a type argument every output\n// was `ReadSignal<unknown>` and every `set`/`command` took `unknown` — the feature\n// was effectively untyped in consumer code. `NodeShape` is an OPT-IN description of a\n// node's reactive surface that drives the return type: declare the property value\n// types, the input value types, and the command signatures ONCE, and `bound.signals`,\n// `on`, `set`, `bindInput`, `command`, and `bindCommand` are all typed from it.\n//\n// interface FetchShape extends NodeShape {\n// signals: { value: Person[]; loading: boolean };\n// inputs: { url: string };\n// commands: { fetch: (url: string) => Promise<Person[]>; abort: () => void };\n// }\n// const bound = bindNode<FetchShape>(el, desc);\n// bound.signals.value.get(); // ReadSignal<Person[]> — key & type checked\n// bound.set(\"url\", \"/api/people\"); // string enforced\n// bound.command(\"fetch\", \"/api\"); // arg/return inferred\n//\n// The runtime is UNCHANGED — these types are erased; the adapter still validates names\n// against the descriptor at runtime. The default shape below keeps every existing\n// untyped call site compiling exactly as before (all-`unknown`, string keys).\n// Open command map: a command name → any call signature. `(...args: any[])` (NOT\n// `never[]`) is the constraint a USER shape's commands must satisfy — and, crucially,\n// the OPEN fallback used when a shape omits `commands`. `Parameters<(...args: any[])\n// => unknown>` is `any[]`, so an untyped `command(\"run\", \"/api\")` accepts any args,\n// preserving the pre-generic behaviour (symmetric with `inputs` → `unknown`). A shape\n// that DECLARES a precise signature (e.g. `(url: string) => Promise<X>`) still gets\n// exact arg/return checking on the typed path — the loose constraint only widens the\n// DEFAULT, never a declared command. (`no-explicit-any` is disabled for this package.)\ntype OpenCommandMap = Record<string, (...args: any[]) => unknown>;\n\nexport interface NodeShape {\n /** propertyName → latest-snapshot value type (what `signals[name]` / `on(name)` carry). */\n signals?: Record<string, unknown>;\n /** inputName → settable value type (what `set` / `bindInput` accept). */\n inputs?: Record<string, unknown>;\n /** commandName → its call signature (what `command` / `bindCommand` invoke). */\n commands?: OpenCommandMap;\n}\n\n// Back-compat default: a fully-open shape so `bindNode(target, desc)` with no type\n// argument behaves as before (signals keyed by arbitrary string → unknown; any\n// input/command name; unknown values; any command args). Stronger typing is opt-in\n// via the type arg.\nexport interface DefaultNodeShape extends NodeShape {\n signals: Record<string, unknown>;\n inputs: Record<string, unknown>;\n commands: OpenCommandMap;\n}\n\n// Resolve the three sub-maps with sane fallbacks when a shape omits one of them.\ntype SignalsOf<S extends NodeShape> = S[\"signals\"] extends Record<string, unknown>\n ? S[\"signals\"]\n : Record<string, unknown>;\ntype InputsOf<S extends NodeShape> = S[\"inputs\"] extends Record<string, unknown>\n ? S[\"inputs\"]\n : Record<string, unknown>;\ntype CommandsOf<S extends NodeShape> = S[\"commands\"] extends OpenCommandMap ? S[\"commands\"] : OpenCommandMap;\n\n/** Options for `on` — how each event emission folds into the stream signal. */\nexport interface EventStreamOptions<T, C> {\n /** Combine the running value with each emission. Default: latest (replace). */\n fold?: (acc: T | undefined, chunk: C) => T;\n /** Seed value before the first emission. */\n initial?: T;\n}\n\nexport interface BoundNode<S extends NodeShape = DefaultNodeShape> {\n /**\n * Output properties as read-only signals (latest value), keyed by property name and\n * typed from the node shape: `bound.signals.value.get()` carries the declared value\n * type (no longer `unknown`). Keys are the declared property names.\n */\n readonly signals: { readonly [K in keyof SignalsOf<S>]: ReadSignal<SignalsOf<S>[K]> };\n /**\n * An event-token STREAM for a declared property's event: a read signal that folds\n * every emission (latest by default). Unlike `signals[prop]`, it updates on EVERY\n * emit — even when the derived value is equal — because it models occurrences, not\n * state. The chunk per emit is `getter(event)` if the property declares one, else\n * the property's current value.\n *\n * With no fold the value type defaults to the property's declared snapshot type; a\n * `fold` may reshape it (explicit `T`/`C` type args override).\n */\n on<K extends keyof SignalsOf<S>>(prop: K): ReadSignal<SignalsOf<S>[K] | undefined>;\n on<T, C = SignalsOf<S>[keyof SignalsOf<S>]>(\n prop: keyof SignalsOf<S>,\n options: EventStreamOptions<T, C>,\n ): ReadSignal<T | undefined>;\n /** Write a declared input on the node (imperative); value type checked against the shape. */\n set<K extends keyof InputsOf<S>>(name: K, value: InputsOf<S>[K]): void;\n /**\n * Reactively write a declared input from a signal: an effect mirrors `source` into\n * `node[name]`. A same-value guard (`node[name] !== v`) skips redundant writes, so\n * a property whose write re-dispatches an event cannot feed back into an infinite\n * loop. `undefined` follows the wc-bindable applier profile (A2): it is not written\n * while the source has had no other value (the first evaluation, or after another\n * `undefined`), so the element keeps its own initial state; after a value it is\n * written, so the element restores that state. Returns a disposer; the effect is\n * also torn down by `dispose()` (neither writes anything).\n */\n bindInput<K extends keyof InputsOf<S>>(name: K, source: ReadSignal<InputsOf<S>[K]>): () => void;\n /** Invoke a declared command on the node (imperative); args/return typed from the shape. */\n command<K extends keyof CommandsOf<S>>(name: K, ...args: Parameters<CommandsOf<S>[K]>): ReturnType<CommandsOf<S>[K]>;\n /**\n * Command-token: invoke a declared command whenever `trigger` CHANGES. The initial\n * value does not fire (subscribe-without-firing), so a command like `abort` is not\n * triggered on mount. `mapArgs` shapes the call arguments from the trigger value\n * (default: the value itself as a single argument). Returns a disposer; also torn\n * down by `dispose()`.\n */\n bindCommand<K extends keyof CommandsOf<S>, V = unknown>(\n name: K,\n trigger: ReadSignal<V>,\n mapArgs?: (value: V) => Parameters<CommandsOf<S>[K]>,\n ): () => void;\n /**\n * Detach all listeners/effects and make the adapter inert. After dispose the output\n * signals/streams stop updating and `set`/`command`/`bindInput`/`bindCommand`/`on`\n * throw (use-after-dispose). Idempotent.\n */\n dispose(): void;\n}\n\n// Internal target type. `Record<string, any>` is needed to index arbitrary declared\n// members (target[name]) inside the adapter, but it is DELIBERATELY NOT in the public\n// `bindNode` signature — exposing it there erased the caller's element type and let any\n// stray member access type-check. Kept private; the public entry takes `EventTarget`.\ntype NodeTarget = EventTarget & Record<string, any>;\n\n// Internal, fully-loose surface the adapter object is built against (string keys,\n// `unknown` values). The public `BoundNode<S>` is a stricter projection of this same\n// runtime object; `bindNode` casts the built `UntypedBoundNode` to `BoundNode<S>` at\n// return. Kept private so the loose `unknown`-typed methods never leak to callers.\ninterface UntypedBoundNode {\n readonly signals: Record<string, ReadSignal<unknown>>;\n on<T = unknown, C = unknown>(prop: string, options?: EventStreamOptions<T, C>): ReadSignal<T | undefined>;\n set(name: string, value: unknown): void;\n bindInput(name: string, source: ReadSignal<unknown>): () => void;\n command(name: string, ...args: unknown[]): unknown;\n bindCommand(name: string, trigger: ReadSignal<unknown>, mapArgs?: (value: unknown) => unknown[]): () => void;\n dispose(): void;\n}\n\n// The error thrown by `assertLive` when an adapter method is called after dispose.\n// Carries a brand symbol so callers that need to distinguish a post-dispose throw\n// (e.g. nodeSource's abort bridge) can test it structurally instead of matching the\n// message string — the message is free to change without silently breaking the\n// guard. The brand survives even if a consumer's bundler duplicates the class (e.g.\n// `instanceof` across realms), since it's a Symbol on the instance, not a class\n// identity check.\nconst DISPOSED_ERROR = Symbol(\"bindNode.disposed\");\n\n/**\n * Error thrown when a {@link BoundNode} method is invoked after the adapter has been\n * disposed. Every surface that mutates or subscribes — `on` / `set` / `bindInput` /\n * `command` / `bindCommand` — throws this once `dispose()` has run, so a\n * use-after-dispose is loud instead of silently writing/invoking on an inert adapter.\n *\n * Prefer {@link isDisposedError} over `instanceof` for the check: the brand survives a\n * bundler that duplicates the class across realms, where `instanceof` would not. Use it\n * to make teardown-order races robust — e.g. swallow a post-dispose throw while letting\n * any other error surface:\n *\n * ```ts\n * try {\n * bound.command(\"abort\");\n * } catch (err) {\n * if (!isDisposedError(err)) throw err; // expected during teardown; ignore\n * }\n * ```\n */\nexport class DisposedError extends Error {\n readonly [DISPOSED_ERROR] = true;\n}\n\n/**\n * True if `err` is a {@link DisposedError} — i.e. a use-after-dispose error thrown by a\n * {@link BoundNode} method after `dispose()`. Brand-based (checks a Symbol on the\n * instance), so it stays correct even if a consumer's bundler duplicates the\n * `DisposedError` class across module realms, where `err instanceof DisposedError`\n * could be false.\n */\nexport function isDisposedError(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && (err as Record<symbol, unknown>)[DISPOSED_ERROR] === true;\n}\n\nfunction readProperty(target: NodeTarget, name: string): unknown {\n return target[name];\n}\n\n// wc-bindable SPEC § Default Getter: when a property omits `getter`, an adapter MUST\n// read `e.detail`. This adapter used to read the property instead (#238), which\n// diverged from `@wcstack/state` and `@wc-bindable/core` — the same element could\n// bind correctly in one adapter and not the other. Only the initial seed reads the\n// property (SPEC § Initial Sync: there is no event to derive from at bind time).\nconst DEFAULT_GETTER = (e: Event): unknown => (e as CustomEvent).detail;\n\n/**\n * Adapt a wc-bindable node into signals. The public `target` parameter is a plain\n * `EventTarget` (the internal `Record<string, any>` indexing is cast away here, not\n * leaked to callers — see {@link NodeTarget}). Pass an optional {@link NodeShape} type\n * argument to type the result; omit it for the back-compat all-`unknown` shape.\n *\n * @example typed\n * interface FetchShape extends NodeShape {\n * signals: { value: Person[]; loading: boolean };\n * inputs: { url: string };\n * commands: { fetch: (url: string) => Promise<Person[]>; abort: () => void };\n * }\n * const bound = bindNode<FetchShape>(fetchEl, FetchCore.wcBindable);\n * bound.signals.value.get(); // ReadSignal<Person[]>\n * bound.set(\"url\", \"/api/people\"); // string enforced\n */\nexport function bindNode<S extends NodeShape = DefaultNodeShape>(\n target: EventTarget,\n descriptor?: WcBindableDescriptor,\n): BoundNode<S> {\n // The Record<string, any> indexing surface is needed internally to read/write/invoke\n // declared members by name; keep it private to this body.\n const node = target as NodeTarget;\n const desc = descriptor ?? (node.constructor as { wcBindable?: WcBindableDescriptor }).wcBindable;\n if (!desc) {\n // A custom element whose definition has not run yet has no descriptor yet: say so\n // (docs/signals-definition-timing.md §5.3; docs/seam-apps.md, signals-shop)\n const tag = (target as { localName?: unknown }).localName;\n if (typeof tag === \"string\" && tag.includes(\"-\") && typeof customElements !== \"undefined\" && customElements.get(tag) === undefined) {\n throw new Error(\n `bindNode: <${tag}> is not defined yet: load it before this code, or await customElements.whenDefined(\"${tag}\").`,\n );\n }\n throw new Error(\"bindNode: no wc-bindable descriptor provided and none found on target.constructor.wcBindable\");\n }\n\n // Name → declared-entry lookups so set/command/on reject names the node never\n // declared, instead of silently writing/invoking/listening on an arbitrary member.\n const propByName = new Map(desc.properties.map((p) => [p.name, p]));\n const declaredInputs = new Set((desc.inputs ?? []).map((i) => i.name));\n const declaredCommands = new Set((desc.commands ?? []).map((c) => c.name));\n\n const signals: Record<string, WriteSignal<unknown>> = {};\n const removers: Array<() => void> = [];\n let disposed = false;\n\n const assertLive = (op: string, name: string): void => {\n if (disposed) {\n throw new DisposedError(`bindNode.${op}: \"${name}\" called after dispose (the adapter is inert).`);\n }\n };\n\n for (const prop of desc.properties) {\n // Seed with the node's current value so the signal is valid before the first\n // event fires (e.g. FetchCore.value === null at rest).\n const cell = signal<unknown>(readProperty(node, prop.name));\n signals[prop.name] = cell;\n\n const read = prop.getter ?? DEFAULT_GETTER;\n const handler = (event: Event): void => {\n cell.set(read(event));\n };\n node.addEventListener(prop.event, handler);\n removers.push(() => node.removeEventListener(prop.event, handler));\n // Re-seed AFTER subscribing: the initial read above is a snapshot taken before\n // the listener was attached, so a value change in that gap would be missed.\n // Reading the property once more now closes the race (the equality guard makes\n // it a no-op when nothing changed). Note this is the property snapshot, not a\n // getter(event) — there is no event to derive from at bind time, and the SPEC's\n // default getter (`e.detail`) applies to events only.\n cell.set(readProperty(node, prop.name));\n }\n\n // Implemented against a string-keyed, all-`unknown` surface (`UntypedBoundNode`); the\n // generic typing in `BoundNode<S>` is a compile-time projection over the SAME\n // runtime, so the object is built once and cast to `BoundNode<S>` at return. Runtime\n // name validation against the descriptor is unchanged.\n const bound: UntypedBoundNode = {\n signals,\n\n on<T = unknown, C = unknown>(prop: string, options: EventStreamOptions<T, C> = {}): ReadSignal<T | undefined> {\n assertLive(\"on\", prop);\n const propDesc = propByName.get(prop);\n if (!propDesc) {\n throw new Error(`bindNode.on: \"${prop}\" is not a declared property on this node.`);\n }\n const fold = options.fold ?? ((_acc: T | undefined, chunk: C) => chunk as unknown as T);\n // equals: () => false — a stream notifies on EVERY emit, even an equal value.\n const cell = signal<T | undefined>(options.initial, () => false);\n const read = propDesc.getter ?? DEFAULT_GETTER;\n const handler = (event: Event): void => {\n const chunk = read(event) as C;\n cell.set(fold(cell.peek(), chunk));\n };\n node.addEventListener(propDesc.event, handler);\n removers.push(() => node.removeEventListener(propDesc.event, handler));\n return cell;\n },\n\n set(name: string, value: unknown): void {\n assertLive(\"set\", name);\n if (!declaredInputs.has(name)) {\n throw new Error(`bindNode.set: \"${name}\" is not a declared input on this node.`);\n }\n node[name] = value;\n },\n\n bindInput(name: string, source: ReadSignal<unknown>): () => void {\n assertLive(\"bindInput\", name);\n if (!declaredInputs.has(name)) {\n throw new Error(`bindNode.bindInput: \"${name}\" is not a declared input on this node.`);\n }\n // The previous evaluation, written or not. Its initial `undefined` stands for \"no\n // previous evaluation\", which A2 treats the same as a previous `undefined`.\n let previous: unknown = undefined;\n const handle = effect(() => {\n const v = source.get();\n const before = previous;\n previous = v;\n // A2: an `undefined` that follows no value means \"no value yet\" — writing it\n // would overwrite the element's own initial state (its default, or the markup)\n if (v === undefined && before === undefined) return;\n if (node[name] !== v) {\n node[name] = v; // same-value guard above breaks write→event→write loops\n }\n });\n removers.push(() => handle.dispose());\n return () => handle.dispose();\n },\n\n command(name: string, ...args: unknown[]): unknown {\n assertLive(\"command\", name);\n if (!declaredCommands.has(name)) {\n throw new Error(`bindNode.command: \"${name}\" is not a declared command on this node.`);\n }\n if (typeof node[name] !== \"function\") {\n throw new TypeError(`bindNode.command: \"${name}\" is declared but not a function on the node.`);\n }\n return node[name](...args);\n },\n\n bindCommand(name: string, trigger: ReadSignal<unknown>, mapArgs?: (value: unknown) => unknown[]): () => void {\n assertLive(\"bindCommand\", name);\n if (!declaredCommands.has(name)) {\n throw new Error(`bindNode.bindCommand: \"${name}\" is not a declared command on this node.`);\n }\n // Fail fast at bind time (not on first change), so a wrong name surfaces when\n // the subscription is set up rather than silently later inside a flush.\n if (typeof node[name] !== \"function\") {\n throw new TypeError(`bindNode.bindCommand: \"${name}\" is declared but not a function on the node.`);\n }\n let primed = false;\n const handle = effect(() => {\n const v = trigger.get();\n if (!primed) {\n primed = true; // subscribe on mount without firing (emit on CHANGE only)\n return;\n }\n const args = mapArgs ? mapArgs(v) : [v];\n node[name](...args);\n });\n removers.push(() => handle.dispose());\n return () => handle.dispose();\n },\n\n dispose(): void {\n if (disposed) {\n return; // idempotent\n }\n disposed = true;\n for (const remove of removers) {\n remove();\n }\n },\n };\n\n return bound as unknown as BoundNode<S>;\n}\n\n/**\n * Build a `resource` source from a wc-bindable node, bridging the resource's\n * AbortSignal to the node's cancel command (default `\"abort\"`) before delegating to\n * `run`. This generalizes the earlier hand-wired `sig → core.abort()` bridge (docs §8\n * (e), §5-2): wrap the result in `resource({ args })` and any node that declares an\n * abort command gets switchMap-style cancel/restart for free — an `args` change\n * aborts the in-flight call (firing the node's abort command, which cancels its real\n * AbortController) and starts the next.\n *\n * The node's own value/loading/error stay available via `bound.signals`; `resource`\n * here is used for the cancel/restart lifecycle, not to re-derive that triad.\n *\n * @example\n * const bound = bindNode(fetchEl);\n * const r = resource(\n * nodeSource(bound, (b, id) => b.command(\"fetch\", `/api/${id}`)),\n * { args: () => id.get() },\n * );\n */\nexport function nodeSource<T, A = void, S extends NodeShape = DefaultNodeShape>(\n bound: BoundNode<S>,\n run: (node: BoundNode<S>, args: A) => Promise<T> | T,\n options: { abort?: string } = {},\n): ResourceSource<T, A> {\n const abortName = options.abort ?? \"abort\";\n return (args, signal) => {\n // Honor the resource's cancel by invoking the node's abort command. `once`:\n // each resource run gets a fresh AbortSignal, so the listener fires at most once.\n //\n // GUARD: the abort listener runs SYNCHRONOUSLY inside AbortController.abort().\n // If `bound` was already disposed (e.g. the adapter and the resource share an\n // owner and the adapter's disposer ran first), `command` throws assertLive —\n // and a throw out of an abort listener surfaces as an unhandled exception during\n // the synchronous abort() call. Swallow a post-dispose throw so teardown order is\n // robust; report any OTHER error via the platform reporter without breaking abort.\n signal.addEventListener(\n \"abort\",\n () => {\n try {\n // `abortName` is a runtime string (validated by the adapter); the cast lets\n // it reach `command` regardless of the typed command-name union of `S`.\n (bound.command as (name: string, ...args: unknown[]) => unknown)(abortName);\n } catch (err) {\n // Brand-based check (not a message regex): a post-dispose throw is\n // expected here and swallowed; any OTHER error is reported.\n if (!isDisposedError(err)) {\n reportError(err);\n }\n }\n },\n { once: true },\n );\n return run(bound, args);\n };\n}\n","// Async resource (v1 design notes).\n//\n// Adapts an async producer into a reactive `{ value, loading, error }` triad —\n// the same shape FetchCore exposes (value/loading/error). When the resource's\n// `args` (a reactive getter) change, the in-flight request is aborted and a fresh\n// one starts: dependency-driven cancel/restart, i.e. RxJS switchMap.\n//\n// This is the signals-side counterpart of the state-side `$streams` adapter\n// (docs/state-stream-type-design.md §4-1). The hard part — making sure a stale\n// response from a superseded request never lands on the new state — is handled\n// here by checking `signal.aborted` before committing any result.\n\nimport { signal, innerEffect as effect, onCleanup, ReadSignal } from \"./reactive.js\";\n\nexport interface ResourceState<T> {\n value: ReadSignal<T | undefined>;\n // Progress is a BOOLEAN here, intentionally different from streamResource's\n // `status` enum. A resource is single-shot (one request → resolve/reject), so\n // its progress is binary: in-flight or not. A stream is continuous (idle →\n // active → done/error), so it needs the enum. The \"shared contract\" with the\n // state-side `$streams` adapter covers the cancel/restart SEMANTICS, not this\n // progress representation. (docs §8 (a)).\n loading: ReadSignal<boolean>;\n /** Last error, or `null` when there is none. Initial value is `null`; a (re)start resets it to `null`. */\n error: ReadSignal<unknown>;\n /** Abort any in-flight request and stop reacting to `args` changes. */\n dispose(): void;\n}\n\nexport interface ResourceOptions<T, A> {\n /** Reactive inputs. Reading signals here wires restart-on-change. */\n args?: () => A;\n /** Seed value before the first resolution. */\n initial?: T;\n}\n\nexport type ResourceSource<T, A> = (args: A, signal: AbortSignal) => Promise<T> | T;\n\nexport function resource<T, A = void>(\n source: ResourceSource<T, A>,\n options: ResourceOptions<T, A> = {},\n): ResourceState<T> {\n const value = signal<T | undefined>(options.initial);\n const loading = signal<boolean>(false);\n const error = signal<unknown>(null);\n\n let controller: AbortController | null = null;\n\n const runner = effect(() => {\n // Reading args() inside the effect is what subscribes us to its signals, so a\n // change re-runs this body — that IS the restart trigger.\n //\n // NOTE (effect-internal writes): this effect writes loading/error/value, which\n // are signals OTHER effects may observe. A write that actually CHANGES the value\n // marks those observers stale and queues them on the same flush; the drain loop\n // then runs them in the same tick. (A same-value write — e.g. error.set(null)\n // when error is already null — is a no-op via the equality guard and notifies\n // nothing.) We never read these signals inside THIS effect, so we don't dirty\n // our own dependency — no cycle. (docs §8 (a)).\n const a = (options.args ? options.args() : undefined) as A;\n\n // Abort the previous request before starting the next (switchMap).\n controller?.abort();\n const ac = new AbortController();\n controller = ac;\n\n loading.set(true);\n error.set(null);\n\n // Call the source SYNCHRONOUSLY (so it receives ac.signal immediately and can\n // wire its abort listener before any teardown), but guard it with try/catch so\n // a synchronous throw is normalized into the same error/loading state as a\n // rejected promise. Without the guard a sync throw would escape the effect body\n // (and, on the initial run, the resource() call itself), leaving loading stuck\n // true and error unset.\n let produced: Promise<T> | T;\n try {\n produced = source(a, ac.signal);\n } catch (err) {\n error.set(err);\n loading.set(false);\n return;\n }\n\n // Settle via two-arm `.then` rather than `await` + try/catch (streamResource's\n // shape): a resource is SINGLE-SHOT — one resolve/reject lands once — so a flat\n // resolved/rejected pair maps cleanly. A stream is a CONTINUOUS loop whose chunks\n // and termination must share one error path, which an `await` loop in try/catch\n // expresses; that structure would be needless here.\n Promise.resolve(produced).then(\n (resolved) => {\n // Drop the result if this request was superseded/disposed: committing it\n // would let a stale response overwrite the newer request's state.\n if (ac.signal.aborted) {\n return;\n }\n value.set(resolved);\n loading.set(false);\n },\n (err) => {\n if (ac.signal.aborted) {\n return;\n }\n error.set(err);\n loading.set(false);\n },\n );\n });\n\n const dispose = (): void => {\n controller?.abort();\n runner.dispose();\n };\n\n // Auto-dispose with the enclosing owner (createRoot / parent effect), so a\n // resource created inside a component is aborted on unmount. No-op when there\n // is no owner — the caller then disposes manually.\n onCleanup(dispose);\n\n return { value, loading, error, dispose };\n}\n","// Stream resource (docs §8 (a)). The signals-side counterpart of the state-side\n// `$streams` adapter (docs/state-stream-type-design.md).\n//\n// Adapts a continuous async flow (async iterable / ReadableStream / async\n// generator) into a single reactive value by FOLDING each chunk:\n// - latest (default): replace — value becomes the last chunk.\n// - reduce: accumulate — value = fold(acc, chunk), needs `initial`.\n// When the resource's `args` change, the in-flight stream is aborted and a fresh\n// one starts (switchMap), with `value` reset to `initial`.\n//\n// Deliberate non-goal: backpressure. The fold result IS the buffer; demand does\n// not flow back to the producer. Unbounded accumulation of an infinite stream is\n// a footgun — bound the fold (latest / count / last-N / window) for live streams.\n// This mirrors the state `$streams` norm and is what lets the impedance mismatch\n// be resolved honestly (state-stream §0, §4-3).\n//\n// Shared contract with state `$streams` (settled in v1):\n// - source(args, signal) receives an AbortSignal; honoring it drives restart.\n// - restart RESETS value to `initial`; error KEEPS the last value.\n// - status companion: \"idle\" | \"active\" | \"done\" | \"error\".\n// - async iterable is the lingua franca; anything getReader-bearing\n// (ReadableStream) is read via getReader() — see rescue levels below.\n//\n// CONTRACT (cooperative cancellation — STRONG REQUIREMENT): the `source` MUST honor\n// the `AbortSignal` it is given. Honoring it is what drives switchMap restart/dispose;\n// a source that ignores it cannot be reliably cancelled.\n//\n// Rescue levels on abort:\n// - ReadableStream: FULLY rescued. A parked read() is force-unwound via\n// reader.cancel(), which both releases the underlying source and settles the\n// pending read() so the loop unwinds. Anything getReader-bearing is routed\n// through this path even when it is ALSO natively async-iterable (Node 18+ /\n// Chrome 124+ / Firefox): the spec serializes asyncIterator.return() behind\n// the pending next() ([[ongoingPromise]]), so the AsyncIterable rescue below\n// cannot force-unwind a parked read on a native ReadableStream.\n// - AsyncIterable / async generator: PARTIALLY rescued. On abort we call\n// iterator.return() to trigger the generator's finally/cleanup. But a parked\n// `await` (the producer stalling before its next yield while IGNORING `signal`)\n// cannot be force-unwound from outside — return() only takes effect when the\n// generator next resumes. So a source that parks forever and never observes\n// `signal` still leaks its consume() task. Honor `signal` to bound this.\n// The `if (signal.aborted) return` check only runs after a chunk arrives, not while\n// parked — it drops stale chunks but is not, by itself, a cancellation mechanism.\n\nimport { signal, innerEffect as effect, onCleanup, ReadSignal, WriteSignal } from \"./reactive.js\";\n\nexport type StreamStatus = \"idle\" | \"active\" | \"done\" | \"error\";\n\nexport interface StreamResourceState<T> {\n value: ReadSignal<T | undefined>;\n // Progress is an ENUM here, intentionally different from resource's `loading`\n // boolean: a continuous stream moves idle → active → done/error, which a boolean\n // cannot express. The cancel/restart contract is shared with `resource` and the\n // state-side `$streams` adapter; the progress representation is not.\n status: ReadSignal<StreamStatus>;\n /** Last error, or `null` when there is none. Initial value is `null`; a (re)start resets it to `null`. */\n error: ReadSignal<unknown>;\n /** Abort the in-flight stream and stop reacting to `args`. */\n dispose(): void;\n}\n\nexport interface StreamResourceOptions<T, C, A> {\n /** Reactive inputs. Reading signals here wires restart-on-change. */\n args?: () => A;\n /** Combine the running value with each chunk. Default: latest (replace). */\n fold?: (acc: T | undefined, chunk: C) => T;\n /** Seed value, and the value `value` is reset to on each (re)start. */\n initial?: T;\n}\n\nexport type StreamProducer<C> = AsyncIterable<C> | ReadableStream<C>;\n\n/**\n * Produce a stream for the current `args`. The `signal` aborts on restart/dispose —\n * the source **MUST honor it** (this is a hard contract, not a suggestion): a\n * `ReadableStream` is fully cancelled via `reader.cancel()`, and an async generator\n * should observe `signal` (e.g. reject/break on `signal.aborted`) so a parked `await`\n * can unwind. On abort the adapter also calls the iterator's `return()` to run a\n * generator's `finally`, but a generator that parks forever while ignoring `signal`\n * cannot be force-unwound and will leak. See the module header's CONTRACT.\n */\nexport type StreamSource<C, A> = (\n args: A,\n signal: AbortSignal,\n) => StreamProducer<C> | Promise<StreamProducer<C>>;\n\nexport function streamResource<T, C = T, A = void>(\n source: StreamSource<C, A>,\n options: StreamResourceOptions<T, C, A> = {},\n): StreamResourceState<T> {\n const fold = options.fold ?? ((_acc: T | undefined, chunk: C) => chunk as unknown as T);\n const value = signal<T | undefined>(options.initial);\n const status = signal<StreamStatus>(\"idle\");\n const error = signal<unknown>(null);\n\n let controller: AbortController | null = null;\n\n const runner = effect(() => {\n // NOTE (effect-internal writes): like `resource`, this effect writes\n // value/status/error — signals other effects may observe. Those observers are\n // queued on the same flush and run in the same tick. This effect never reads\n // those signals, so it does not dirty its own dependency (no cycle). The async\n // `consume` writes them later from microtasks/timers, outside this flush.\n const a = (options.args ? options.args() : undefined) as A;\n\n controller?.abort();\n const ac = new AbortController();\n controller = ac;\n\n // Reset for the new run: a restart starts the fold from `initial`.\n value.set(options.initial);\n error.set(null);\n status.set(\"active\");\n\n void consume(source, a, ac.signal, fold, value, status, error);\n });\n\n const dispose = (): void => {\n controller?.abort();\n runner.dispose();\n };\n onCleanup(dispose);\n\n return { value, status, error, dispose };\n}\n\nasync function consume<T, C, A>(\n source: StreamSource<C, A>,\n args: A,\n signal: AbortSignal,\n fold: (acc: T | undefined, chunk: C) => T,\n // Use the public WriteSignal type instead of re-declaring an inline subset, so\n // these stay in lockstep with the signal API (no structural drift).\n value: WriteSignal<T | undefined>,\n status: WriteSignal<StreamStatus>,\n error: WriteSignal<unknown>,\n): Promise<void> {\n // Obtain the iterator EXPLICITLY (not via `for await`'s implicit one) so abort can\n // call `iterator.return()` to trigger an AsyncIterable / async generator's\n // `finally`/cleanup. A `for await` only calls `.return()` when the loop itself exits;\n // if the producer is PARKED (awaiting before the next yield while ignoring `signal`),\n // the loop never advances, so the implicit `.return()` never runs and the task leaks\n // past restart/dispose. Calling `.return()` on abort is the PARTIAL rescue: the\n // parked `await` cannot be force-unwound from outside, but once the generator resumes\n // (its next tick), `.return()` makes it run its `finally` and stop — recovering the\n // common \"generator wakes up after abort\" case. The ReadableStream path is fully\n // rescued via `reader.cancel()` (see `readableToAsyncIterable`).\n let iterator: AsyncIterator<C> | null = null;\n // Guard against returning the SAME iterator twice. `onAbort` is reachable two ways:\n // the abort listener, and the explicit call on line ~163 when abort raced the\n // `await source(...)`. The guard keys on the iterator instance (not a plain \"ran\"\n // flag): the listener firing with iterator still null must NOT consume the single\n // real cleanup that the explicit call performs once the iterator exists. So we only\n // mark an iterator returned once we have actually called `.return()` on it.\n let returned: AsyncIterator<C> | null = null;\n const onAbort = (): void => {\n if (!iterator || iterator === returned) {\n return; // nothing to release yet, or already released this iterator\n }\n returned = iterator;\n // Fire the iterator's cleanup. Swallow any throw/rejection from `.return()` — we\n // are tearing down; a producer that rejects on return must not surface here.\n try {\n void iterator.return?.()?.then?.(undefined, () => {});\n } catch {\n // `.return()` threw synchronously while tearing down — ignore.\n }\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n try {\n const produced = await source(args, signal);\n iterator = iterate(produced, signal)[Symbol.asyncIterator]();\n if (signal.aborted) {\n // Aborted while awaiting the source: the abort listener already ran (iterator\n // was still null then), so explicitly release the just-produced iterator now —\n // this fires a generator's finally / a ReadableStream's cancel for the\n // resource we created but will never iterate.\n onAbort();\n return;\n }\n for (;;) {\n const result = await iterator.next();\n if (result.done) {\n break;\n }\n if (signal.aborted) {\n return; // stale chunk from a superseded/disposed run — drop it\n }\n value.set(fold(value.peek(), result.value));\n }\n if (signal.aborted) {\n return; // stream ended but this run was aborted — don't mark done\n }\n status.set(\"done\");\n } catch (e) {\n if (signal.aborted) {\n return; // an abort that surfaced as a throw is not an error\n }\n error.set(e); // keep the last folded value (do not reset)\n status.set(\"error\");\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction iterate<C>(produced: StreamProducer<C>, signal: AbortSignal): AsyncIterable<C> {\n // Anything ReadableStream-shaped (has getReader) takes the reader path FIRST —\n // even when it is also async-iterable. On runtimes where ReadableStream\n // implements native async iteration (Node 18+ / Chrome 124+ / Firefox), the\n // spec serializes `iterator.return()` behind the pending `next()`\n // ([[ongoingPromise]]), so the AsyncIterable rescue cannot force-unwind a\n // parked read: abort would hang the consume task until the producer's next\n // chunk (or forever on a silent stream), leaking the underlying source.\n // `reader.cancel()` has no such ordering — routing every getReader-bearing\n // source through it keeps the FULL rescue promised for ReadableStream.\n if (typeof (produced as ReadableStream<C>)?.getReader === \"function\") {\n return readableToAsyncIterable(produced as ReadableStream<C>, signal);\n }\n if (typeof (produced as AsyncIterable<C>)?.[Symbol.asyncIterator] === \"function\") {\n return produced as AsyncIterable<C>;\n }\n throw new TypeError(\n \"streamResource: source must return an AsyncIterable or a ReadableStream (got neither).\",\n );\n}\n\nasync function* readableToAsyncIterable<C>(\n stream: ReadableStream<C>,\n signal: AbortSignal,\n): AsyncGenerator<C> {\n const reader = stream.getReader();\n // A ReadableStream read() does NOT observe an AbortSignal on its own. Without\n // this, a switchMap restart / dispose leaves the previous reader parked in a\n // pending read() forever, leaking the underlying source. Cancelling on abort\n // both releases the source AND settles the pending read() so the for-await\n // unwinds and the finally below can release the lock. Abort is the only\n // early-exit path for this generator (the consumer never calls .return()\n // without aborting), so this is the sole place a non-drained stream is cancelled.\n const onAbort = (): void => {\n void reader.cancel().catch(() => {}); // tearing down; swallow a rejected cancel\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n yield value as C;\n }\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n reader.releaseLock();\n }\n}\n"],"names":["reportError","err","r","globalThis","console","error","isDev","__WCS_DEV__","emitted","Set","warnDev","code","dedupeKey","message","detail","id","has","add","warn","currentObserver","track","source","_sources","_observers","untrack","node","observers","delete","size","undefined","_unobserved","clear","currentOwner","registerDisposer","disposer","_owned","push","disposeOwned","owner","owned","i","length","o","_disposeOwned","pendingEffects","flushScheduled","bufferPool","takeBuffer","pop","schedule","queueMicrotask","flushEffects","MAX_FLUSH_ITERATIONS","describeCycle","batch","live","filter","e","_disposed","lines","map","_devStack","split","slice","join","trim","iterations","lastBatch","Error","updateIfNecessary","flushSync","markStale","level","_state","wasClean","_isEffect","observer","ComputedNode","_update","SignalNode","_value","_equals","constructor","value","equals","this","get","peek","set","next","_fn","_initialized","_running","fn","previous","prevObserver","String","NO_OBSERVERS","EffectNode","_cleanup","checkTracked","stack","_runCleanup","prevOwner","dispose","signal","initial","Object","is","computed","effect","innerNext","selector","byKey","Map","dirty","key","innerEffect","sameKey","prev","a","b","createRoot","disposed","hasOwner","onCleanup","DISPOSED_ERROR","Symbol","DisposedError","isDisposedError","readProperty","target","name","DEFAULT_GETTER","bindNode","descriptor","desc","wcBindable","tag","localName","includes","customElements","propByName","properties","p","declaredInputs","inputs","declaredCommands","commands","c","signals","removers","assertLive","op","prop","cell","read","getter","handler","event","addEventListener","removeEventListener","on","options","propDesc","fold","_acc","chunk","bindInput","handle","v","before","command","args","TypeError","bindCommand","trigger","mapArgs","primed","remove","nodeSource","bound","run","abortName","abort","once","resource","loading","controller","runner","ac","AbortController","produced","Promise","resolve","then","resolved","aborted","streamResource","status","async","iterator","returned","onAbort","return","getReader","stream","reader","cancel","catch","done","releaseLock","readableToAsyncIterable","asyncIterator","iterate","result","consume"],"mappings":"AAOM,SAAUA,EAAYC,GAC1B,MAAMC,EAAKC,WAAsDH,YAChD,mBAANE,EACTA,EAAED,GAEFG,QAAQC,MAAMJ,EAEl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ts CHANGED
@@ -21,6 +21,19 @@ declare function flushSync(): void;
21
21
  declare function signal<T>(initial: T, equals?: Equals<T>): WriteSignal<T>;
22
22
  declare function computed<T>(fn: () => T, equals?: Equals<T>): ReadSignal<T>;
23
23
  declare function effect(fn: () => Cleanup | void): EffectHandle;
24
+ /**
25
+ * One boolean per key over one source: `isSelected(key)` is true while the source equals `key`.
26
+ * A change of the source re-runs only the readers of the key it left and the key it took, not
27
+ * every reader — a row per item that compares `selected.get() === id` itself re-runs every row on
28
+ * each change. Solid's createSelector.
29
+ *
30
+ * A key is compared with the source as a Map compares keys (`===`, and NaN equals NaN): to select an
31
+ * object, select its id — `selector(computed(() => selected.get()?.id))`. The readers are told when
32
+ * effects run (a microtask, or `flushSync`); a call itself reads the source as it is now. A key no
33
+ * reader reads any more is forgotten. Create it under an owner (`createRoot` / a `SignalsElement`
34
+ * render): its subscription to the source is an effect.
35
+ */
36
+ declare function selector<T>(source: ReadSignal<T>): (key: T) => boolean;
24
37
  /**
25
38
  * Run `fn` inside a fresh ownership scope and return its result. Every effect (or
26
39
  * nested cleanup) created during `fn` — directly or transitively — is owned by
@@ -257,6 +270,19 @@ type Component = (props: Record<string, unknown> & {
257
270
  declare function h(tag: string | typeof Fragment | Component, props?: Props, ...children: Child[]): Node;
258
271
  /** Append `child` into `container`, resolving fragments/arrays. */
259
272
  declare function render(child: Child, container: Node): Node;
273
+ /**
274
+ * Delegate the `on…` handlers `h()` gives elements from now on, for these event types, to one listener per type
275
+ * on `root` (default: the document). Each handler still sees its element as `currentTarget` and `this`, and
276
+ * `stopPropagation()` stops the handlers of the elements around it. A handler then lives as long as its element.
277
+ *
278
+ * Only events that bubble and are composed can be delegated (the default is all of them); others throw. Call it
279
+ * before building the view: elements made earlier keep their listeners. For a closed shadow root, pass the root.
280
+ * Differences from a listener on the element: the handlers run when the event reaches the root (after listeners on
281
+ * the elements between), not at all if one of those stops it, and not for an element outside the document.
282
+ *
283
+ * @returns a function that stops delegating at this root.
284
+ */
285
+ declare function delegateEvents(types?: readonly string[], root?: EventTarget): () => void;
260
286
  type ListAccessor<T> = ReadSignal<readonly T[]> | (() => readonly T[]);
261
287
  /**
262
288
  * `For`'s row builder. `item` is the item the row was built for — a plain value. A keyed row is
@@ -347,5 +373,5 @@ interface MountedNode<S extends NodeShape = DefaultNodeShape> extends BoundNode<
347
373
  }
348
374
  declare function mountNode<S extends NodeShape = DefaultNodeShape>(tagName: string, options?: MountNodeOptions): MountedNode<S>;
349
375
 
350
- export { DisposedError, For, Fragment, Index, SignalsElement, bindNode, computed, createRoot, createSignalsElement, effect, flushSync, h, isDisposedError, mountNode, nodeSource, onCleanup, render, resource, signal, streamResource };
376
+ export { DisposedError, For, Fragment, Index, SignalsElement, bindNode, computed, createRoot, createSignalsElement, delegateEvents, effect, flushSync, h, isDisposedError, mountNode, nodeSource, onCleanup, render, resource, selector, signal, streamResource };
351
377
  export type { BoundNode, Child, Cleanup, Component, DefaultNodeShape, EffectHandle, Equals, EventStreamOptions, ForEach, ForOptions, IndexEach, ListAccessor, ListView, MountNodeOptions, MountedNode, NodeShape, Props, ReadSignal, ResourceOptions, ResourceSource, ResourceState, SignalsElementClass, StreamProducer, StreamResourceOptions, StreamResourceState, StreamSource, StreamStatus, WcBindableDescriptor, WcBindableProperty, WriteSignal };
package/dist/dom.esm.js CHANGED
@@ -1,5 +1,5 @@
1
- import { g as innerEffect, o as onCleanup, b as bindNode, h as isDev, j as hasOwner, w as warnDev, s as signal, a as createRoot } from './core-kS9CKPFP.esm.js';
2
- export { D as DisposedError, c as computed, e as effect, f as flushSync, i as isDisposedError, n as nodeSource, r as resource, d as streamResource } from './core-kS9CKPFP.esm.js';
1
+ import { h as innerEffect, o as onCleanup, b as bindNode, j as reportError, k as isDev, l as hasOwner, w as warnDev, d as signal, a as createRoot } from './core-BreHgNBK.esm.js';
2
+ export { D as DisposedError, c as computed, e as effect, f as flushSync, i as isDisposedError, n as nodeSource, r as resource, s as selector, g as streamResource } from './core-BreHgNBK.esm.js';
3
3
 
4
4
  // Fine-grained hyperscript (v1 design notes). The "step before JSX" (docs §4-1).
5
5
  //
@@ -131,13 +131,28 @@ function bindProp(el, key, value) {
131
131
  // `onadd-to-cart` → the name as written ("click", "add-to-cart" — data-wcs's `on<event>:`
132
132
  // form). A lowercase `onclick` used to fall through to the reactive path, so the handler
133
133
  // ran at render and never on click (docs/seam-apps.md, signals-shop).
134
- if (/^on[A-Za-z-]/.test(key) && typeof value === "function") {
135
- const type = /^on[A-Z]/.test(key) ? key.slice(2).toLowerCase() : key.slice(2);
134
+ // `on` and a letter or `-` (no regex per prop: it ran twice for every prop of every element).
135
+ // `| 32` folds A-Z onto a-z and leaves "-" (45) as it is.
136
+ const c2 = key.charCodeAt(2) | 32;
137
+ if (key[0] === "o" && key[1] === "n" && ((c2 >= 97 && c2 <= 122) || c2 === 45) && typeof value === "function") {
138
+ const type = key.charCodeAt(2) < 91 ? key.slice(2).toLowerCase() : key.slice(2);
136
139
  const listener = value;
140
+ if (delegatedRoots.has(type)) {
141
+ // Delegated (delegateEvents): the handler waits in the element's slot for the root's one listener. No
142
+ // listener and no cleanup per element — it goes with the element.
143
+ el[handlerKey(type)] = listener;
144
+ return;
145
+ }
137
146
  el.addEventListener(type, listener);
138
- // Remove the listener when the owning scope is torn down (e.g. a dynamic
139
- // child that rebuilds this subtree), so handlers don't accumulate.
140
- onCleanup(() => el.removeEventListener(type, listener));
147
+ // Remove the listener when the owning scope is torn down while the element is still in the
148
+ // document (e.g. a reactive child of a kept element, or a SignalsElement re-render), so handlers
149
+ // don't accumulate on an element that lives on. A detached element (a removed row, a replaced
150
+ // subtree) is not touched: its listeners go with it, and removing them one by one was a fifth
151
+ // of clearing a list.
152
+ onCleanup(() => {
153
+ if (el.isConnected)
154
+ el.removeEventListener(type, listener);
155
+ });
141
156
  return;
142
157
  }
143
158
  if (typeof value === "function") {
@@ -150,6 +165,94 @@ function bindProp(el, key, value) {
150
165
  }
151
166
  setProp(el, key, value);
152
167
  }
168
+ // --- event delegation (opt-in) ---------------------------------------------
169
+ //
170
+ // `delegateEvents()` makes `h()` keep an `on…` handler of a delegated type in a slot of its element instead of
171
+ // adding a listener, and puts ONE listener per type on the root (the document, or a shadow root). An event that
172
+ // reaches the root is walked along its composed path from the target outwards, calling each slot it finds — what
173
+ // the fastest fine-grained libraries do: no listener to add per row on create, none to remove on clear. Opt-in,
174
+ // because the order and reach differ from a listener on the element (README, "Event delegation").
175
+ /** Events that bubble and are composed (cross shadow roots): the ones a root can see for any element under it. */
176
+ const DELEGABLE = ("beforeinput click contextmenu dblclick focusin focusout input keydown keyup " +
177
+ "mousedown mousemove mouseout mouseover mouseup pointerdown pointermove pointerout pointerover pointerup").split(" ");
178
+ /** A delegated type → the roots that listen for it. */
179
+ const delegatedRoots = new Map();
180
+ /** A type → the symbol under which an element keeps its delegated handler. */
181
+ const handlerKeys = new Map();
182
+ function handlerKey(type) {
183
+ let key = handlerKeys.get(type);
184
+ if (key === undefined)
185
+ handlerKeys.set(type, (key = Symbol(type)));
186
+ return key;
187
+ }
188
+ /** Events already walked: a composed event reaches a shadow root and the document; the first walks it all. */
189
+ const walked = new WeakSet();
190
+ function dispatchDelegated(event) {
191
+ if (walked.has(event))
192
+ return;
193
+ walked.add(event);
194
+ const key = handlerKey(event.type);
195
+ try {
196
+ for (const node of event.composedPath()) {
197
+ const handler = node[key];
198
+ if (handler === undefined)
199
+ continue;
200
+ // What a listener on the element would see: the element as `currentTarget` and `this`.
201
+ Object.defineProperty(event, "currentTarget", { configurable: true, value: node });
202
+ try {
203
+ handler.call(node, event);
204
+ }
205
+ catch (err) {
206
+ reportError(err); // as a listener's throw: reported, and the walk goes on
207
+ }
208
+ if (event.cancelBubble)
209
+ break; // stopPropagation() / stopImmediatePropagation()
210
+ }
211
+ }
212
+ finally {
213
+ delete event.currentTarget;
214
+ }
215
+ }
216
+ /**
217
+ * Delegate the `on…` handlers `h()` gives elements from now on, for these event types, to one listener per type
218
+ * on `root` (default: the document). Each handler still sees its element as `currentTarget` and `this`, and
219
+ * `stopPropagation()` stops the handlers of the elements around it. A handler then lives as long as its element.
220
+ *
221
+ * Only events that bubble and are composed can be delegated (the default is all of them); others throw. Call it
222
+ * before building the view: elements made earlier keep their listeners. For a closed shadow root, pass the root.
223
+ * Differences from a listener on the element: the handlers run when the event reaches the root (after listeners on
224
+ * the elements between), not at all if one of those stops it, and not for an element outside the document.
225
+ *
226
+ * @returns a function that stops delegating at this root.
227
+ */
228
+ function delegateEvents(types = DELEGABLE, root = document) {
229
+ for (const type of types) {
230
+ if (!DELEGABLE.includes(type)) {
231
+ // (touch / wheel bubble, but a root's listener for them is passive: preventDefault() would be ignored)
232
+ throw new Error(`delegateEvents: "${type}" cannot be delegated (it does not bubble, cross shadow roots, or allow preventDefault at a root). Delegable: ${DELEGABLE.join(", ")}.`);
233
+ }
234
+ }
235
+ const added = [];
236
+ for (const type of types) {
237
+ let roots = delegatedRoots.get(type);
238
+ if (roots === undefined)
239
+ delegatedRoots.set(type, (roots = new Set()));
240
+ if (roots.has(root))
241
+ continue;
242
+ roots.add(root);
243
+ root.addEventListener(type, dispatchDelegated);
244
+ added.push(type);
245
+ }
246
+ return () => {
247
+ for (const type of added.splice(0)) {
248
+ root.removeEventListener(type, dispatchDelegated);
249
+ const roots = delegatedRoots.get(type);
250
+ roots.delete(root);
251
+ if (roots.size === 0)
252
+ delegatedRoots.delete(type);
253
+ }
254
+ };
255
+ }
153
256
  /**
154
257
  * Objects given to a custom element that is not defined yet, by element → property, until it is
155
258
  * (docs/seam-apps.md, signals-shop: `h("product-card", { product })` before `product-card.js` ran
@@ -323,23 +426,38 @@ function insertReactive(parent, accessor) {
323
426
  warnDev("UNOWNED_INSERT", "", "reactive child inserted with no owner — its update effect will never be " +
324
427
  "disposed and may leak. Mount under createRoot / SignalsElement.");
325
428
  }
326
- const anchor = document.createComment("");
327
- parent.appendChild(anchor);
429
+ // The position: the first render's Text node while the value stays text (no anchor comment per text
430
+ // child — most reactive children are text); an anchor comment from the first render of nodes on.
431
+ // Until the anchor exists, `current` is empty (before the first run) or that one Text node.
432
+ let anchor = null;
328
433
  let current = [];
329
434
  innerEffect(() => {
330
435
  const value = accessor();
331
- // FAST PATH: a plain text result that replaces a plain text result. The common
332
- // reactive child is a string/number thunk (`() => \`count: ${n.get()}\``); the
333
- // wholesale path would remove the old Text node, allocate a new one, and re-insert
334
- // it on every change. When BOTH the previous and next renders are a single Text
335
- // node, mutate the existing node's `data` in place instead — no allocation, no
336
- // remove/insert, and the same DOM node identity is preserved across updates.
337
- if ((typeof value === "string" || typeof value === "number") && current.length === 1) {
338
- const node = current[0];
339
- if (node.nodeType === 3 /* TEXT_NODE */) {
340
- node.data = String(value);
436
+ if (typeof value === "string" || typeof value === "number") {
437
+ if (anchor === null && current.length === 0) {
438
+ current = [parent.appendChild(document.createTextNode(String(value)))];
341
439
  return;
342
440
  }
441
+ // FAST PATH: a plain text result that replaces a plain text result. The common
442
+ // reactive child is a string/number thunk (`() => \`count: ${n.get()}\``); the
443
+ // wholesale path would remove the old Text node, allocate a new one, and re-insert
444
+ // it on every change. When BOTH the previous and next renders are a single Text
445
+ // node, mutate the existing node's `data` in place instead — no allocation, no
446
+ // remove/insert, and the same DOM node identity is preserved across updates.
447
+ if (current.length === 1 && current[0].nodeType === 3 /* TEXT_NODE */) {
448
+ current[0].data = String(value);
449
+ return;
450
+ }
451
+ }
452
+ if (anchor === null) {
453
+ // the first render of nodes: at the end, or right after the text rendered until now
454
+ anchor = document.createComment("");
455
+ if (current.length === 0) {
456
+ parent.appendChild(anchor);
457
+ }
458
+ else {
459
+ current[0].after(anchor);
460
+ }
343
461
  }
344
462
  const next = toNodes(value);
345
463
  for (const node of current) {
@@ -502,15 +620,16 @@ function For(list, each, options) {
502
620
  // Used to find which reused rows already sit in increasing relative order so
503
621
  // only the rest are moved (LIS reorder, see reconcileOrder).
504
622
  let prevOrder = [];
623
+ // A row's index and current-item signals are made the first time `each`'s accessor is read: a row
624
+ // that never reads them (most rows) owns two signals fewer. Until then the reconcile keeps the plain
625
+ // values on the row, and the signal starts from them.
505
626
  const make = (item, i) => {
506
- const idx = signal(i);
507
- const cur = signal(item);
508
- let node;
509
- const dispose = createRoot((d) => {
510
- node = each(item, () => idx.get(), () => cur.get());
627
+ const row = { node: null, dispose: null, i, idx: null, item, cur: null };
628
+ row.dispose = createRoot((d) => {
629
+ row.node = each(item, () => (row.idx ??= signal(row.i)).get(), () => (row.cur ??= signal(row.item)).get());
511
630
  return d;
512
631
  });
513
- return { node, dispose, idx, cur };
632
+ return row;
514
633
  };
515
634
  innerEffect(() => {
516
635
  const items = read() ?? [];
@@ -552,10 +671,12 @@ function For(list, each, options) {
552
671
  const k = keys[i];
553
672
  let row = rows.get(k);
554
673
  if (row) {
555
- if (row.idx.peek() !== i) {
556
- row.idx.set(i); // position changed — refresh the index accessor
674
+ if (row.i !== i) {
675
+ row.i = i;
676
+ row.idx?.set(i); // position changed — refresh the index accessor
557
677
  }
558
- row.cur.set(items[i]); // the item under the key now (a no-op when it is the same)
678
+ row.item = items[i];
679
+ row.cur?.set(items[i]); // the item under the key now (a no-op when it is the same)
559
680
  }
560
681
  else {
561
682
  row = make(items[i], i);
@@ -874,5 +995,5 @@ function mountNode(tagName, options = {}) {
874
995
  };
875
996
  }
876
997
 
877
- export { For, Fragment, Index, SignalsElement, bindNode, createRoot, createSignalsElement, h, mountNode, onCleanup, render, signal };
998
+ export { For, Fragment, Index, SignalsElement, bindNode, createRoot, createSignalsElement, delegateEvents, h, mountNode, onCleanup, render, signal };
878
999
  //# sourceMappingURL=dom.esm.js.map