@wcstack/signals 4.1.0 → 4.2.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.
@@ -1 +1 @@
1
- {"version":3,"file":"dom.esm.min.js","sources":["../src/dom.ts"],"sourcesContent":["// Fine-grained hyperscript (v1 design notes). The \"step before JSX\" (docs §4-1).\n//\n// `h(tag, props, ...children)` is the classic JSX factory shape, but it does NOT\n// build a virtual DOM and re-render. It creates a REAL DOM node once; any prop or\n// child given as a function (thunk) or signal is wired to a targeted `effect`, so\n// only that one binding updates when its signals change (Solid-style). This is\n// what keeps the package lightweight: no reconciler is shipped.\n//\n// JSX is intentionally NOT shipped. A consumer who wants it sets, in their own\n// tsconfig, `jsxFactory: \"h\"` + `jsxFragmentFactory: \"Fragment\"` (classic runtime)\n// — opting into a build step is their choice; the buildless path is calling `h`\n// directly. See docs/signals-state-design.md §4-1.\n//\n// OWNERSHIP: effects created here are owned by the enclosing reactive scope.\n// A reactive child's effect owns the prop/child effects of the subtree it builds,\n// so rebuilding that subtree disposes the previous one's effects (no leak). Mount\n// an app under `createRoot` so the whole tree can be torn down on unmount; a\n// dynamic child establishes its own scope automatically (it IS an effect).\n\nimport { signal, effect, onCleanup, createRoot, hasOwner, ReadSignal, WriteSignal } from \"./reactive.js\";\nimport { isDev, warnDev } from \"./dev.js\";\nimport { bindNode } from \"./bindNode.js\";\nimport type { BoundNode, NodeShape, DefaultNodeShape, WcBindableDescriptor } from \"./bindNode.js\";\n\n// `@wcstack/signals/dom` re-exports the headless core (signals, resource,\n// streamResource, bindNode, nodeSource) so UI code can import everything from one\n// module. Both built entries import a single shared `core-*.esm.js` chunk\n// (rollup.config.js `manualChunks`), so importing from BOTH `@wcstack/signals` and\n// `@wcstack/signals/dom` on a buildless page yields ONE reactive instance — the\n// tracking context is shared, not duplicated. `__tests__/packaging.test.ts` pins\n// this (both entries reference the same core chunk; a signal made via one entry is\n// observed by an effect from the other).\nexport {\n signal,\n computed,\n effect,\n createRoot,\n onCleanup,\n flushSync,\n} from \"./reactive.js\";\nexport type { ReadSignal, WriteSignal, EffectHandle, Cleanup, Equals } from \"./reactive.js\";\nexport { resource } from \"./resource.js\";\nexport type { ResourceState, ResourceOptions, ResourceSource } from \"./resource.js\";\nexport { streamResource } from \"./streamResource.js\";\nexport type {\n StreamResourceState,\n StreamResourceOptions,\n StreamSource,\n StreamProducer,\n StreamStatus,\n} from \"./streamResource.js\";\nexport { bindNode, nodeSource, DisposedError, isDisposedError } from \"./bindNode.js\";\nexport type {\n BoundNode,\n NodeShape,\n DefaultNodeShape,\n WcBindableDescriptor,\n WcBindableProperty,\n EventStreamOptions,\n} from \"./bindNode.js\";\n\nexport const Fragment = Symbol(\"signals.Fragment\");\n\nexport type Child = unknown;\nexport type Props = Record<string, unknown> | null;\n// h() always injects `children` into the props object it passes to a component, so\n// the parameter type makes that explicit (a component can declare `{ children }`).\nexport type Component = (\n props: Record<string, unknown> & { children?: Child[] },\n) => Node | Child[];\n\nfunction isReadSignal(value: unknown): value is ReadSignal<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { get?: unknown }).get === \"function\" &&\n typeof (value as { peek?: unknown }).peek === \"function\"\n );\n}\n\nexport function h(\n tag: string | typeof Fragment | Component,\n props?: Props,\n ...children: Child[]\n): Node {\n if (tag === Fragment) {\n const frag = document.createDocumentFragment();\n appendChildren(frag, children);\n return frag;\n }\n\n if (typeof tag === \"function\") {\n const result = tag({ ...(props ?? {}), children });\n return Array.isArray(result) ? wrapFragment(result) : result;\n }\n\n const el = createElement(tag);\n if (props) {\n for (const key in props) {\n bindProp(el, key, props[key]);\n }\n }\n appendChildren(el, children);\n return el;\n}\n\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\n// Tags created in the SVG namespace. Ambiguous names shared with HTML (`a`,\n// `title`, `script`, `style`) are intentionally EXCLUDED so ordinary HTML usage is\n// not broken; an SVG `<a>` / `<title>` must be created in an explicitly-namespaced\n// way by the caller. SVG DOM props are largely read-only, so `setProp`'s\n// settable-property check routes SVG attributes through `setAttribute` for free.\nconst SVG_TAGS = new Set([\n \"svg\", \"g\", \"path\", \"rect\", \"circle\", \"ellipse\", \"line\", \"polyline\", \"polygon\",\n \"text\", \"tspan\", \"defs\", \"use\", \"symbol\", \"marker\", \"linearGradient\",\n \"radialGradient\", \"stop\", \"clipPath\", \"mask\", \"pattern\", \"image\", \"foreignObject\",\n]);\n\nfunction createElement(tag: string): Element {\n return SVG_TAGS.has(tag)\n ? document.createElementNS(SVG_NS, tag)\n : document.createElement(tag);\n}\n\n/** Append `child` into `container`, resolving fragments/arrays. */\nexport function render(child: Child, container: Node): Node {\n appendChild(container, child);\n return container;\n}\n\nfunction wrapFragment(children: Child[]): DocumentFragment {\n const frag = document.createDocumentFragment();\n appendChildren(frag, children);\n return frag;\n}\n\n// --- props ------------------------------------------------------------------\n\n// Attribute names whose corresponding JS DOM property differs. `class` is handled\n// separately (it has reactive-falsy semantics in setProp), so it is not listed here.\nconst ATTR_TO_PROP: Record<string, string> = {\n for: \"htmlFor\",\n tabindex: \"tabIndex\",\n colspan: \"colSpan\",\n rowspan: \"rowSpan\",\n readonly: \"readOnly\",\n maxlength: \"maxLength\",\n minlength: \"minLength\",\n contenteditable: \"contentEditable\",\n};\n\n// True only if `key` resolves to a WRITABLE property on the element or its\n// prototype chain (a data property with `writable !== false`, or an accessor with a\n// setter). `key in el` is not enough: it also matches read-only members like\n// `firstChild` / `childNodes`, whose assignment throws in strict mode. The walk\n// starts at `el` itself so own instance fields (e.g. a custom element's properties)\n// are still matched, exactly as the previous `key in el` did — just without the\n// read-only false positives.\n//\n// MEMOIZATION: the prototype-chain walk runs on every bindProp/setProp. The result\n// depends only on the element's PROTOTYPE (its class) and the key, since DOM props\n// live on the prototype — not on per-instance own fields, which this library never\n// adds dynamically per element. So cache by `(prototype, key)`: a WeakMap keyed by\n// prototype (no leak — entries die with the class) holding a Map of key→result.\nconst settableCache = new WeakMap<object, Map<string, boolean>>();\n\nfunction computeSettable(el: Element, key: string): boolean {\n let obj: object | null = el;\n while (obj !== null) {\n const desc = Object.getOwnPropertyDescriptor(obj, key);\n if (desc) {\n return \"set\" in desc ? typeof desc.set === \"function\" : desc.writable !== false;\n }\n obj = Object.getPrototypeOf(obj);\n }\n return false;\n}\n\nfunction isSettableProperty(el: Element, key: string): boolean {\n // A real Element always has a prototype (HTMLElement.prototype → … → Object), so\n // `getPrototypeOf` is non-null here; use it as the cache key.\n const proto = Object.getPrototypeOf(el) as object;\n let byKey = settableCache.get(proto);\n if (byKey === undefined) {\n byKey = new Map<string, boolean>();\n settableCache.set(proto, byKey);\n }\n let result = byKey.get(key);\n if (result === undefined) {\n result = computeSettable(el, key);\n byKey.set(key, result);\n }\n return result;\n}\n\nfunction bindProp(el: Element, key: string, value: unknown): void {\n // Event handlers are special-cased BEFORE the reactive check: a function here is the\n // listener, not a thunk to track. `onClick` → \"click\" (lowercased); `onclick` /\n // `onadd-to-cart` → the name as written (\"click\", \"add-to-cart\" — data-wcs's `on<event>:`\n // form). A lowercase `onclick` used to fall through to the reactive path, so the handler\n // ran at render and never on click (docs/seam-apps.md, signals-shop).\n if (/^on[A-Za-z-]/.test(key) && typeof value === \"function\") {\n const type = /^on[A-Z]/.test(key) ? key.slice(2).toLowerCase() : key.slice(2);\n const listener = value as EventListener;\n el.addEventListener(type, listener);\n // Remove the listener when the owning scope is torn down (e.g. a dynamic\n // child that rebuilds this subtree), so handlers don't accumulate.\n onCleanup(() => el.removeEventListener(type, listener));\n return;\n }\n\n if (typeof value === \"function\") {\n effect(() => setProp(el, key, (value as () => unknown)()));\n return;\n }\n\n if (isReadSignal(value)) {\n effect(() => setProp(el, key, value.get()));\n return;\n }\n\n setProp(el, key, value);\n}\n\nfunction setProp(el: Element, key: string, value: unknown): void {\n if (key === \"style\") {\n setStyle(el as HTMLElement, value);\n return;\n }\n if (key === \"class\" || key === \"className\") {\n // Set the `class` ATTRIBUTE, not the `className` property. On an SVGElement\n // `className` is a read-only `SVGAnimatedString`, so assigning it throws in\n // strict mode (ESM is always strict) — `setAttribute(\"class\", …)` works for both\n // HTML and SVG. Treat false like null → empty class (consistent with the\n // attribute path's false-removes-it rule), so `() => cond && \"active\"` yields \"\"\n // (not \"false\") when the condition is falsy.\n // STRING-ONLY: a non-null/non-false value is coerced via String(value). Array\n // (`[\"a\", \"b\"]`) and object (`{ active: true }`) class forms are NOT supported —\n // they would stringify to \"a,b\" / \"[object Object]\". Compose the class string in\n // the binding itself (e.g. `() => [a, b].join(\" \")`) and pass a string. This keeps\n // the core free of a class-merging convention.\n el.setAttribute(\"class\", value == null || value === false ? \"\" : String(value));\n return;\n }\n // Remap the handful of attribute names whose JS property differs, so `for` /\n // `tabindex` / `colspan` etc. reach the right property instead of falling through\n // to setAttribute (which works for some but not e.g. `htmlFor`).\n const propKey = ATTR_TO_PROP[key] ?? key;\n if (isSettableProperty(el, propKey)) {\n // Known, WRITABLE DOM property (value, checked, disabled, id, htmlFor, ...).\n // The settability check excludes read-only members (firstChild, childNodes, …)\n // that `key in el` would wrongly accept — assigning to those throws in strict\n // mode; we fall through to the attribute path for them instead.\n //\n // NORMALIZATION: null/undefined are coerced to \"\" before assignment. Without\n // this, a STRING prop (id/title/value/src) given a reactive null/undefined\n // lands as the literal \"null\"/\"undefined\" (e.g. img.src=\"null\" fires a real\n // request) — a correctness footgun. \"\" clears the prop instead. Safe for\n // non-string props too: boolean props coerce \"\"→false (same as null), numeric\n // props coerce \"\"→0 (same as null). We do NOT normalize `false`:\n // `el.disabled = false` is the intended boolean clear.\n (el as unknown as Record<string, unknown>)[propKey] = value == null ? \"\" : value;\n return;\n }\n if (value == null || value === false) {\n el.removeAttribute(key);\n return;\n }\n if (value === true) {\n el.setAttribute(key, \"\");\n return;\n }\n el.setAttribute(key, String(value));\n}\n\nfunction setStyle(el: HTMLElement, value: unknown): void {\n if (value == null) {\n el.removeAttribute(\"style\");\n return;\n }\n if (typeof value === \"string\") {\n el.style.cssText = value;\n return;\n }\n // Object form: the object fully describes the style. Reset first so keys present\n // in a previous run but absent now are removed — otherwise a reactive style that\n // drops a key (e.g. {color,fontWeight} → {color}) would leave the stale property\n // applied. The object is the source of truth, so wiping cssText is correct here.\n el.style.cssText = \"\";\n const style = el.style as CSSStyleDeclaration & Record<string, string>;\n const obj = value as Record<string, string>;\n for (const k in obj) {\n // A key with a hyphen is either kebab-case (`font-weight`) or a CSS custom\n // property (`--accent`). Neither works via property assignment (`style[k]` would\n // just set an inert expando), so route them through setProperty. camelCase keys\n // (`fontWeight`) keep the faster property path.\n if (k.includes(\"-\")) {\n style.setProperty(k, obj[k]);\n } else {\n style[k] = obj[k];\n }\n }\n}\n\n// --- children ---------------------------------------------------------------\n\nfunction appendChildren(parent: Node, children: Child[]): void {\n for (const child of children) {\n appendChild(parent, child);\n }\n}\n\nfunction appendChild(parent: Node, child: Child): void {\n if (child == null || typeof child === \"boolean\") {\n return; // null / undefined / boolean render nothing\n }\n if (Array.isArray(child)) {\n for (const c of child) {\n appendChild(parent, c);\n }\n return;\n }\n if (isListView(child)) {\n // A keyed list (For / Index): it manages its own anchored region with in-place\n // reconciliation, so it does NOT go through the wholesale insertReactive path.\n child.mount(parent);\n return;\n }\n if (child instanceof Node) {\n parent.appendChild(child);\n return;\n }\n if (typeof child === \"function\") {\n insertReactive(parent, child as () => unknown);\n return;\n }\n if (isReadSignal(child)) {\n insertReactive(parent, () => child.get());\n return;\n }\n parent.appendChild(document.createTextNode(String(child)));\n}\n\n/**\n * A reactive insertion point. An anchor comment marks the position; on each run\n * the previous nodes are removed and the freshly-resolved nodes inserted before\n * the anchor. Using `anchor.parentNode` (not the original `parent`) keeps it\n * correct after the subtree is moved/mounted elsewhere.\n *\n * PRECONDITION: the Nodes returned by `accessor` are owned by this insertion point\n * — do not move them to another parent externally. On the next run they are\n * removed from wherever they currently are (`node.parentNode?.removeChild`), so an\n * externally-moved node would be yanked out of its new home without warning.\n *\n * OWNERSHIP: the `effect` below is owned by the enclosing reactive scope at call\n * time (the `currentOwner`). Used under `createRoot` / `SignalsElement` (the module\n * header's mount contract) it is disposed on teardown. Calling `h`/`render` with a\n * reactive child OUTSIDE any owner (no `createRoot`/`SignalsElement`) leaves this\n * effect un-owned and therefore never cleaned up — by design, per that contract.\n */\nfunction insertReactive(parent: Node, accessor: () => unknown): void {\n if (isDev() && !hasOwner()) {\n // A reactive child inserted with no enclosing owner: the effect below is never\n // disposed (the module header documents this as by-design, but it is a frequent\n // accidental leak). Warn once in dev so the un-owned mount is visible.\n warnDev(\n \"UNOWNED_INSERT\",\n \"\",\n \"reactive child inserted with no owner — its update effect will never be \" +\n \"disposed and may leak. Mount under createRoot / SignalsElement.\",\n );\n }\n const anchor = document.createComment(\"\");\n parent.appendChild(anchor);\n let current: Node[] = [];\n\n effect(() => {\n const value = accessor();\n // FAST PATH: a plain text result that replaces a plain text result. The common\n // reactive child is a string/number thunk (`() => \\`count: ${n.get()}\\``); the\n // wholesale path would remove the old Text node, allocate a new one, and re-insert\n // it on every change. When BOTH the previous and next renders are a single Text\n // node, mutate the existing node's `data` in place instead — no allocation, no\n // remove/insert, and the same DOM node identity is preserved across updates.\n if ((typeof value === \"string\" || typeof value === \"number\") && current.length === 1) {\n const node = current[0];\n if (node.nodeType === 3 /* TEXT_NODE */) {\n (node as Text).data = String(value);\n return;\n }\n }\n const next = toNodes(value);\n for (const node of current) {\n node.parentNode?.removeChild(node);\n }\n const host = anchor.parentNode;\n if (host) {\n for (const node of next) {\n host.insertBefore(node, anchor);\n }\n }\n current = next;\n });\n\n // On teardown, drop the references to the inserted Nodes. The disposed effect's\n // closure still captures `current`; if anything retains the effect after disposal\n // (e.g. a parent owner kept alive longer than the subtree), those Nodes would be\n // pinned via that closure even though they have left the DOM. Clearing the array\n // lets them be GC'd as soon as the enclosing owner tears this insertion point down.\n onCleanup(() => {\n current = [];\n });\n}\n\n// --- keyed lists: For / Index (migration-plan §9-3) --------------------------\n//\n// `insertReactive` rebuilds its whole subtree on every change. For lists that is\n// wasteful (and drops per-row state). `For` / `Index` instead keep a stable DOM row\n// per item and reconcile in place. Each row is built under its OWN `createRoot`, so\n// removing a row disposes exactly that row's effects/resources/listeners — the owner\n// tree (§8 (d)) is what makes this leak-free. The reconcile runs in a single\n// `effect` owned by the enclosing scope; an `onCleanup` disposes surviving rows when\n// that scope (e.g. the component) tears down.\n//\n// CONTRACT: `each` must return a SINGLE Node (one row = one node). Keys (For) must\n// be unique. `For` keys by value identity (=== / explicit `key`) and passes the\n// index as an accessor (it changes on move); `Index` keys by position and passes the\n// item as an accessor (the value at a slot changes, the slot does not).\n\nexport type ListAccessor<T> = ReadSignal<readonly T[]> | (() => readonly T[]);\n/**\n * `For`'s row builder. `item` is the item the row was built for — a plain value. A keyed row is\n * kept while its key is (an immutable update hands it a new object under the same key), so read\n * what changes through `current`, an accessor of the item under the row's key now\n * (`() => current().text`). docs/seam-apps.md, signals-shop.\n */\nexport type ForEach<T> = (item: T, index: () => number, current: () => T) => Node;\nexport type IndexEach<T> = (item: () => T, index: number) => Node;\n\n/**\n * The return type of {@link For} / {@link Index}: a keyed list that owns an anchored\n * region and reconciles rows in place. Exported (D4) so consumers can annotate\n * helpers that build or pass around lists. `mount` is called by `h`/`render` when the\n * list is used as a child; `__wcsList` is the brand `appendChild` checks.\n */\nexport interface ListView {\n readonly __wcsList: true;\n mount(parent: Node): void;\n}\n\nfunction isListView(value: unknown): value is ListView {\n return typeof value === \"object\" && value !== null && (value as ListView).__wcsList === true;\n}\n\nfunction readList<T>(list: ListAccessor<T>): () => readonly T[] {\n return isReadSignal(list) ? () => (list as ReadSignal<readonly T[]>).get() : (list as () => readonly T[]);\n}\n\nexport interface ForOptions<T> {\n /** Derive a unique key per item. Default: the item value itself (identity). */\n key?: (item: T, index: number) => unknown;\n}\n\n// --- LIS-based DOM reorder ---------------------------------------------------\n//\n// `reconcileOrder` brings the live DOM under `host` (the contiguous region ending\n// at `anchor`) into `order` — the desired final node sequence — using the FEWEST\n// `insertBefore` moves, while producing EXACTLY the order a naive full re-place\n// would. The naive approach (walk and insert every out-of-place node) does up to\n// O(n) DOM moves on a full reverse or a head insert; here we instead keep the\n// largest set of reused rows that are ALREADY in the right relative order, and\n// move only the others (Solid's reconcileArrays / udomdiff idea).\n//\n// HOW: `prevOrder` is the node sequence the previous run left in the DOM. For each\n// node in the new `order`, a reused row maps to its index in `prevOrder`; a freshly\n// created row has no previous position. The longest increasing subsequence (LIS)\n// of those previous indices marks the reused rows that need NOT move (their pairwise\n// relative order is already correct). Every other node — fresh ones, and reused\n// ones outside the LIS — is inserted before its already-correct successor, walking\n// back-to-front so the \"successor\" reference is always a settled node or the anchor.\n\n/**\n * Indices into `arr` (with value -1 meaning \"no previous position\") whose values\n * form a longest strictly-increasing subsequence. Entries equal to -1 are treated\n * as never part of the subsequence (a fresh node always moves). Classic\n * patience-sorting LIS in O(n log n); returns the chosen indices in ascending order.\n */\nfunction longestIncreasingSubsequence(arr: number[]): number[] {\n const n = arr.length;\n // `tails[k]` = index (into arr) of the smallest tail of an increasing\n // subsequence of length k+1. `prev[i]` = predecessor index, to rebuild the chain.\n const tails: number[] = [];\n const prev: number[] = new Array(n).fill(-1);\n for (let i = 0; i < n; i++) {\n const value = arr[i];\n if (value < 0) {\n continue; // fresh node: not eligible for the stable subsequence\n }\n // Binary search for the first tail whose value is >= this value, and replace it\n // (or extend the tails when this value beats every tail).\n let lo = 0;\n let hi = tails.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (arr[tails[mid]] < value) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n if (lo > 0) {\n prev[i] = tails[lo - 1];\n }\n tails[lo] = i;\n }\n // Rebuild the index chain from the longest tail backwards.\n const result: number[] = [];\n let k = tails.length > 0 ? tails[tails.length - 1] : -1;\n while (k >= 0) {\n result.push(k);\n k = prev[k];\n }\n result.reverse();\n return result;\n}\n\nfunction reconcileOrder(\n host: Node,\n anchor: Node,\n order: Node[],\n prevOrder: Node[],\n): void {\n const n = order.length;\n if (n === 0) {\n return; // nothing to place (removals already happened)\n }\n\n // Map each previous node to its previous position, so a node in `order` can look\n // up where it used to be. A node absent from this map is FRESH (created this run,\n // or the first run where prevOrder is empty) and is encoded as -1 — it always moves.\n const prevIndex = new Map<Node, number>();\n for (let i = 0; i < prevOrder.length; i++) {\n prevIndex.set(prevOrder[i], i);\n }\n\n // previous-position sequence aligned to the new order. -1 marks a fresh node.\n const seq: number[] = new Array(n);\n for (let i = 0; i < n; i++) {\n const p = prevIndex.get(order[i]);\n seq[i] = p === undefined ? -1 : p;\n }\n\n // Rows whose relative order is already correct: leave them in place, move the rest.\n const lis = longestIncreasingSubsequence(seq);\n let lisPtr = lis.length - 1;\n\n // Walk back-to-front. `ref` is the node that must follow the one being placed; it\n // starts at the anchor (the region's tail) and becomes each placed node. A node in\n // the LIS is the maximal already-correctly-ordered set, so it is left untouched\n // (only adopted as the new `ref`). Every OTHER node is, by construction, out of\n // position relative to its settled successor and is inserted before `ref` — no\n // \"is it already in place?\" guard is needed (it never is, unlike the old\n // full-walk reconciler which visited correctly-placed nodes too).\n let ref: Node = anchor;\n for (let i = n - 1; i >= 0; i--) {\n const node = order[i];\n if (lisPtr >= 0 && lis[lisPtr] === i) {\n lisPtr--; // stable: do not move\n } else {\n host.insertBefore(node, ref);\n }\n ref = node;\n }\n}\n\n// Dev-only key sanity check (no effect in production — guarded by `isDev()` at the\n// call site so this is never reached when dev is off). Flags the silent-failure key\n// shapes: a nullish key (NaN / null / undefined collide under SameValueZero, so two\n// such items map to one row and a row is silently dropped), and — when no explicit\n// `key` was given — a non-primitive item used as its own identity key (every render\n// gets a fresh object reference, so the row is rebuilt instead of reused, silently\n// dropping per-row state). Warns once per distinct shape (deduped in warnDev).\nfunction checkKeyDev(key: unknown, item: unknown, hasExplicitKey: boolean): void {\n if (key == null || (typeof key === \"number\" && Number.isNaN(key))) {\n warnDev(\n \"NULLISH_KEY\",\n String(key),\n \"For: a key is null/undefined/NaN. Such keys collide under SameValueZero, \" +\n \"so rows silently merge/drop. Provide a stable unique `key`.\",\n { key },\n );\n return;\n }\n if (!hasExplicitKey && (typeof key === \"object\" || typeof key === \"function\")) {\n warnDev(\n \"NON_PRIMITIVE_KEY\",\n typeof key,\n \"For: a non-primitive item is used as its own key (no `key` option given). \" +\n \"Object identity changes across renders, so every row is rebuilt and per-row \" +\n \"state is lost. Pass `{ key: item => item.id }`.\",\n { item },\n );\n }\n}\n\nexport function For<T>(list: ListAccessor<T>, each: ForEach<T>, options?: ForOptions<T>): ListView {\n const read = readList(list);\n const keyOf = options?.key;\n return {\n __wcsList: true,\n mount(parent: Node): void {\n const anchor = document.createComment(\"for\");\n parent.appendChild(anchor);\n\n interface Row {\n node: Node;\n dispose: () => void;\n idx: WriteSignal<number>;\n /** The item under the row's key now (`each`'s `current`). */\n cur: WriteSignal<T>;\n }\n let rows = new Map<unknown, Row>();\n // The node order placed by the previous reconcile run. Empty on first run.\n // Used to find which reused rows already sit in increasing relative order so\n // only the rest are moved (LIS reorder, see reconcileOrder).\n let prevOrder: Node[] = [];\n\n const make = (item: T, i: number): Row => {\n const idx = signal(i);\n const cur = signal(item);\n let node!: Node;\n const dispose = createRoot((d) => {\n node = each(item, () => idx.get(), () => cur.get());\n return d;\n });\n return { node, dispose, idx, cur };\n };\n\n effect(() => {\n const items = read() ?? [];\n\n // Key-uniqueness PRE-PASS (no side effects): throwing here, before any row is\n // created or moved, keeps a duplicate-key error from leaving half-built rows\n // orphaned (make() runs createRoot) and the DOM mid-reorder. Keys are reused\n // below so keyOf runs once per item.\n const keys: unknown[] = [];\n const seen = new Set<unknown>();\n const dev = isDev();\n for (let i = 0; i < items.length; i++) {\n const k = keyOf ? keyOf(items[i], i) : items[i];\n if (dev) {\n checkKeyDev(k, items[i], keyOf !== undefined);\n }\n if (seen.has(k)) {\n if (dev) {\n // The throw below still halts (production behaviour unchanged); the warn\n // adds the offending key + a pointer to the cause so the silent\n // \"updates stopped\" symptom is diagnosable.\n warnDev(\n \"DUPLICATE_KEY\",\n String(k),\n `For: duplicate key \"${String(k)}\" at index ${i} — keys must be unique. ` +\n \"Rendering throws and the list stops updating until keys are fixed.\",\n { key: k, index: i },\n );\n }\n throw new Error(`For: duplicate key \"${String(k)}\" — keys must be unique.`);\n }\n seen.add(k);\n keys.push(k);\n }\n\n const next = new Map<unknown, Row>();\n const order: Node[] = [];\n\n // Rows freshly created in THIS run (not reused from `rows`). If a later\n // `make()` — i.e. a user `each` — throws mid-loop, the rows already built\n // here are owned by their own detached `createRoot` and are not yet tracked\n // in any surviving map, so they would leak. Dispose them before re-throwing,\n // leaving the old `rows` map untouched (it is recoverable on the next run).\n const fresh: Row[] = [];\n try {\n for (let i = 0; i < items.length; i++) {\n const k = keys[i];\n let row = rows.get(k);\n if (row) {\n if (row.idx.peek() !== i) {\n row.idx.set(i); // position changed — refresh the index accessor\n }\n row.cur.set(items[i]); // the item under the key now (a no-op when it is the same)\n } else {\n row = make(items[i], i);\n fresh.push(row);\n }\n next.set(k, row);\n order.push(row.node);\n }\n } catch (err) {\n for (const row of fresh) {\n row.dispose();\n }\n throw err;\n }\n\n // The LIVE parent (`anchor.parentNode`, not the mount arg) so the region\n // stays correct after being moved (e.g. built inside a Fragment, then\n // appended elsewhere). `host` is null only if the anchor was detached\n // without disposing this scope (a misuse) — then there is nothing to\n // place into. Resolved before the removal phase so the wholesale-removal\n // fast path below can use it.\n const host = anchor.parentNode;\n\n // Dispose rows whose key vanished. `remove()` no-ops if already detached.\n if (rows.size > 0 && next.size === fresh.length) {\n // ZERO-REUSE run: no existing key survives (clear, or a full replacement\n // with disjoint keys), so EVERY current row is removed. When the host\n // contains exactly this list's region — first child is the region's\n // first row, last child is the anchor, and the child count matches\n // rows + anchor — detach them all with a single native\n // `textContent = \"\"` and re-append the anchor, instead of one\n // `remove()` per row (the dominant cost of clearing large lists).\n // Any deviation (foreign sibling, externally detached row, shared\n // host) fails the guard and falls back to the per-row path.\n // Disposal always runs per row; only the DOM detachment is batched.\n if (\n host !== null &&\n host.lastChild === anchor &&\n prevOrder.length > 0 &&\n host.firstChild === prevOrder[0] &&\n host.childNodes.length === rows.size + 1\n ) {\n host.textContent = \"\";\n host.appendChild(anchor);\n for (const row of rows.values()) {\n row.dispose();\n }\n } else {\n for (const row of rows.values()) {\n (row.node as ChildNode).remove();\n row.dispose();\n }\n }\n } else {\n for (const [k, row] of rows) {\n if (!next.has(k)) {\n (row.node as ChildNode).remove();\n row.dispose();\n }\n }\n }\n if (host) {\n reconcileOrder(host, anchor, order, prevOrder);\n }\n\n // Snapshot this run's final order so the NEXT run's reconcile can detect\n // which rows kept their relative position (the LIS basis below). Capturing\n // the array we just placed avoids re-deriving it from the map.\n prevOrder = order;\n rows = next;\n });\n\n onCleanup(() => {\n for (const row of rows.values()) {\n row.dispose();\n }\n rows.clear();\n });\n },\n };\n}\n\nexport function Index<T>(list: ListAccessor<T>, each: IndexEach<T>): ListView {\n const read = readList(list);\n return {\n __wcsList: true,\n mount(parent: Node): void {\n const anchor = document.createComment(\"index\");\n parent.appendChild(anchor);\n\n interface Row {\n node: Node;\n dispose: () => void;\n item: WriteSignal<T>;\n }\n const rows: Row[] = [];\n\n effect(() => {\n const items = read() ?? [];\n // Live parent (see `For`), null only if the anchor was detached undisposed.\n const host = anchor.parentNode;\n\n for (let i = 0; i < items.length; i++) {\n if (i < rows.length) {\n // Slot reused: just push the new value into the row's item signal. The\n // signal's equality guard skips the update when the value is unchanged.\n rows[i].item.set(items[i]);\n } else {\n const item = signal(items[i]);\n let node!: Node;\n const dispose = createRoot((d) => {\n node = each(() => item.get(), i);\n return d;\n });\n rows.push({ node, dispose, item });\n // Positions never move for index keying, so append at the tail (before\n // the anchor) in order. ORDERING CONTRACT (shared with For and the other\n // anchored insertions): the list owns the contiguous region ENDING at its\n // anchor comment. New rows go immediately before the anchor, so the list's\n // own rows always stay correctly ordered and grouped, and static siblings\n // before the anchor (or another list with its own anchor) are never\n // disturbed. Do NOT splice unrelated nodes into the middle of this region.\n host?.insertBefore(node, anchor);\n }\n }\n\n // Trailing slots that no longer exist: dispose and drop.\n if (items.length < rows.length) {\n // WHOLESALE CLEAR (same idea as For's zero-reuse fast path): every slot\n // vanishes and the host holds exactly this list's region (all rows +\n // the anchor), so one native `textContent = \"\"` replaces per-row\n // `remove()`. Guard failures (foreign sibling, detached row, shared\n // host) fall back to the per-row path. Disposal still runs per row.\n if (\n items.length === 0 &&\n host !== null &&\n host.lastChild === anchor &&\n host.firstChild === rows[0].node &&\n host.childNodes.length === rows.length + 1\n ) {\n host.textContent = \"\";\n host.appendChild(anchor);\n for (const row of rows) {\n row.dispose();\n }\n } else {\n for (let i = items.length; i < rows.length; i++) {\n (rows[i].node as ChildNode).remove();\n rows[i].dispose();\n }\n }\n rows.length = items.length;\n }\n });\n\n onCleanup(() => {\n for (const row of rows) {\n row.dispose();\n }\n rows.length = 0;\n });\n },\n };\n}\n\n// --- custom element lifecycle (docs §8 (e)) ---------------------------------\n//\n// The exit point for ownership: a custom element that mounts a signals view under\n// `createRoot` on connect and disposes that root on disconnect. This wires the\n// reactive ownership tree to the real DOM lifecycle — every effect, resource and\n// listener created in `render()` is torn down when the element leaves the DOM, and\n// rebuilt fresh on reconnect. Subclasses only implement `render()`.\n//\n// SCOPE (v1 intentional constraints — drive these reactively, not via this base):\n// - No attribute reactivity. There is no `attributeChangedCallback`/\n// `observedAttributes` wiring: this base does NOT turn HTML attributes into\n// signals. Feed reactive inputs as signals/props from the code that constructs\n// the view (or have a subclass map attributes to signals itself).\n// - Shadow DOM is opt-in and subclass-owned. The default mount point is light DOM\n// (`this`); a subclass that wants encapsulation overrides `getMountPoint()` to\n// return a shadow root it created (e.g. `this.attachShadow(...)` in its\n// constructor). This base never calls attachShadow implicitly.\n// - Mount/unmount only: render() runs once per connect and the whole subtree is\n// disposed on disconnect — there is no partial/incremental re-render hook here\n// (fine-grained updates come from the signals wired inside render()).\n\n// TYPE-ONLY shape of the lifecycle base. `declare abstract class` emits NO runtime\n// code (so it does not reference `HTMLElement` at module-evaluation time — the whole\n// point of the lazy factory below), but it gives the exported `SignalsElement` value\n// and `createSignalsElement()`'s return a precise type that preserves the original\n// contract: `render` is `protected abstract` (a subclass MUST implement it and may\n// only reach it from within), and `getMountPoint` is `protected` (overridable). This\n// is the same surface the previous concrete `abstract class SignalsElement` exposed.\n// (Used only via `typeof` below; the lint rule does not see that as a value use.)\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ndeclare abstract class SignalsElementType extends HTMLElement {\n /** Build the view with `h` + signals. Runs inside an ownership root. */\n protected abstract render(): Node;\n /** Mount target. Override to return a shadow root; default is light DOM. */\n protected getMountPoint(): Node;\n connectedCallback(): void;\n disconnectedCallback(): void;\n}\n\n/**\n * The lifecycle base contract: the abstract constructor type of the `SignalsElement`\n * base. Abstract, so `new SignalsElement()` is rejected (the base has an unimplemented\n * `render`) while `class X extends SignalsElement` is allowed. Returned by\n * {@link createSignalsElement} and the type of the {@link SignalsElement} value.\n */\nexport type SignalsElementClass = typeof SignalsElementType;\n\n// Memoized base class. Built lazily on first access so the `./dom` module can be\n// EVALUATED in a non-DOM environment (SSR pre-pass, a worker without a DOM shim)\n// without a top-level `class … extends HTMLElement` blowing up with\n// `ReferenceError: HTMLElement is not defined`. The class body is only constructed\n// when the consumer actually reaches for the base — at which point a DOM is required\n// and its absence yields a clear, actionable error instead of a raw ReferenceError.\nlet cachedBase: SignalsElementClass | null = null;\n\n/**\n * Build (once, memoized) the `SignalsElement` lifecycle base class. Resolves\n * `HTMLElement` at CALL TIME, so importing `@wcstack/signals/dom` no longer requires\n * a DOM at module-evaluation time — only *calling* this (or subclassing\n * {@link SignalsElement}) does.\n *\n * Contract:\n * - The `.` entry (`@wcstack/signals`) is non-DOM: it evaluates and runs in SSR,\n * Node, and Web Workers with no DOM globals.\n * - The `./dom` entry (`@wcstack/signals/dom`) may now also be *evaluated* without a\n * DOM (so an SSR pre-pass that imports it for the headless re-exports does not\n * crash). The DOM-touching surface — `h`/`render`/`For`/`Index` and this base —\n * still requires DOM globals when actually used.\n *\n * @throws a clear `Error` (not a raw `ReferenceError`) when no `HTMLElement` global is\n * present, naming the offending entry so the failure is self-explanatory.\n */\nexport function createSignalsElement(): SignalsElementClass {\n if (cachedBase !== null) {\n return cachedBase;\n }\n if (typeof HTMLElement === \"undefined\") {\n throw new Error(\n \"@wcstack/signals/dom: SignalsElement requires a DOM (HTMLElement is not defined). \" +\n \"The `./dom` entry's element/render surface is browser-only; in SSR/Node/worker \" +\n \"code import the headless core from `@wcstack/signals` instead, or inject a DOM \" +\n \"(e.g. happy-dom) before constructing custom elements.\",\n );\n }\n\n abstract class SignalsElementBase extends HTMLElement {\n private _dispose: (() => void) | null = null;\n\n /** Build the view with `h` + signals. Runs inside an ownership root. */\n protected abstract render(): Node;\n\n /** Mount target. Override to return a shadow root; default is light DOM. */\n protected getMountPoint(): Node {\n return this;\n }\n\n connectedCallback(): void {\n if (this._dispose !== null) {\n return; // already mounted (defensive against a redundant connect)\n }\n const mount = this.getMountPoint();\n // If render() throws, createRoot disposes any effects it built before the throw,\n // so nothing leaks; _dispose stays null (the element is simply not mounted) and\n // a later disconnectedCallback safely no-ops. The error propagates to the caller.\n this._dispose = createRoot((dispose) => {\n mount.appendChild(this.render());\n return dispose;\n });\n }\n\n disconnectedCallback(): void {\n if (this._dispose === null) {\n return; // not mounted\n }\n this._dispose();\n this._dispose = null;\n const mount = this.getMountPoint();\n while (mount.firstChild) {\n mount.removeChild(mount.firstChild);\n }\n }\n }\n\n cachedBase = SignalsElementBase as unknown as SignalsElementClass;\n return cachedBase;\n}\n\n// `SignalsElement` is the ergonomic name to `extends`. It is a lazily-resolved alias\n// for the class built by `createSignalsElement()`: a Proxy that forwards construct /\n// get / has / getPrototypeOf to the real (memoized) base, building it on first touch.\n// This keeps `class X extends SignalsElement { … }` working exactly as before WHILE\n// deferring the `HTMLElement` reference to subclass-definition time (in a real DOM),\n// instead of `./dom` module-evaluation time (which may be a non-DOM SSR pre-pass).\n//\n// BREAKING note: the value is now a Proxy, not the class object literal. Subclassing,\n// `instanceof`, and static/prototype access all still work; a consumer that relied on\n// `SignalsElement` being a *frozen* concrete class reference (uncommon) should call\n// `createSignalsElement()` to obtain the real class.\n// The Proxy target is a never-called placeholder (every operation is intercepted by a\n// trap below); it only needs to be constructable/callable so `new` / `extends` and the\n// `apply` trap engage. It is intentionally a no-op and never executed.\n/* v8 ignore next */\nconst signalsElementTarget = function (): void {};\nexport const SignalsElement: SignalsElementClass = new Proxy(signalsElementTarget as unknown as SignalsElementClass, {\n construct(_target, args, newTarget): object {\n return Reflect.construct(createSignalsElement(), args, newTarget);\n },\n get(_target, prop, receiver): unknown {\n return Reflect.get(createSignalsElement(), prop, receiver);\n },\n has(_target, prop): boolean {\n return Reflect.has(createSignalsElement(), prop);\n },\n apply(): never {\n throw new TypeError(\"SignalsElement is a class and cannot be invoked without `new`/`extends`.\");\n },\n getPrototypeOf(): object | null {\n return Reflect.getPrototypeOf(createSignalsElement());\n },\n});\n\nfunction toNodes(value: unknown): Node[] {\n const out: Node[] = [];\n const visit = (v: unknown): void => {\n if (v == null || typeof v === \"boolean\") {\n return;\n }\n if (Array.isArray(v)) {\n v.forEach(visit);\n return;\n }\n if (v instanceof Node) {\n out.push(v);\n return;\n }\n out.push(document.createTextNode(String(v)));\n };\n visit(value);\n return out;\n}\n\n// --- mountNode: create + bind + mount a headless wc-bindable node -------------\n//\n// `bindNode` adapts an EXISTING element, which forces its caller to guarantee the\n// custom element class is already registered (the descriptor is read from\n// `el.constructor.wcBindable` at call time — an un-upgraded element has none).\n// `mountNode` closes that gap for the common signals shape where the app OWNS its\n// headless IO nodes: it creates the element AFTER the definition exists (so it is\n// upgraded at construction), binds it, then connects it. The recommended pairing\n// is a side-effect import of the package's `/auto` entry in the same module —\n// module evaluation order then guarantees the definition:\n//\n// import \"@wcstack/fetch/auto\";\n// const fetcher = mountNode(\"wcs-fetch\", { attrs: { url: \"/api/people\" } });\n// fetcher.signals.value.get();\n//\n// The internal order is deliberate: attributes are set BEFORE connect (shells read\n// their config in `connectedCallback`), and the adapter subscribes BEFORE connect,\n// so an event fired from `connectedCallback` is already observed — the missed-event\n// window is structurally zero, not merely closed by bindNode's re-seed. Like\n// `bindNode`, the adapter is NOT auto-registered with a reactive owner; teardown is\n// explicit via `unmount()` — to which `dispose()` is aliased, see MountedNode —\n// (compose with `onCleanup(() => m.unmount())` if the node should die with a\n// scope). See docs/signals-definition-timing.md for the full definition-timing\n// contract (optional packages via dynamic import, the remaining whenDefined /\n// <wcs-defined> territory).\n\nexport interface MountNodeOptions {\n /**\n * Attributes set on the element BEFORE it is connected (declarative pre-connect\n * config, e.g. `{ url: \"/api\", timeout: 5000 }`). HTML boolean-attribute\n * semantics: `true` sets an empty attribute, `false` omits it; other values are\n * stringified.\n */\n attrs?: Record<string, string | number | boolean>;\n /** Parent to append the element to. Default: `document.body`. */\n parent?: Node;\n /**\n * Explicit wc-bindable descriptor forwarded to `bindNode`. When given, the\n * tag-definition check is skipped — the escape hatch for binding a\n * non-custom-element tag, mirroring `bindNode`'s second parameter.\n */\n descriptor?: WcBindableDescriptor;\n}\n\nexport interface MountedNode<S extends NodeShape = DefaultNodeShape> extends BoundNode<S> {\n /** The created element (connected until `unmount()`). */\n readonly el: HTMLElement;\n /**\n * Full teardown: dispose the adapter AND remove the element from the DOM\n * (disconnect stops the shell's IO). Idempotent. On a `MountedNode`,\n * `dispose()` is an alias of this — mountNode owns the element's lifecycle,\n * so the package-wide teardown verb must not leave a connected element with\n * live IO behind (a silent leak for callers habituated to `bindNode`).\n */\n unmount(): void;\n}\n\nexport function mountNode<S extends NodeShape = DefaultNodeShape>(\n tagName: string,\n options: MountNodeOptions = {},\n): MountedNode<S> {\n // Call-time DOM guard (not module-time): `./dom` must evaluate in non-DOM realms\n // (SSR pre-pass / worker) — same contract (and message shape) as `createSignalsElement`.\n if (typeof document === \"undefined\" || typeof customElements === \"undefined\") {\n throw new Error(\n \"@wcstack/signals/dom: mountNode requires a DOM (document/customElements is not defined). \" +\n \"It creates and connects a live element, so it is browser-only; inject a DOM \" +\n \"(e.g. happy-dom) before calling, or keep headless work on `@wcstack/signals`.\",\n );\n }\n const { attrs, parent, descriptor } = options;\n // Custom element names are lowercase; the registry is exact-key while\n // createElement ASCII-lowercases — normalize once so mountNode(el.tagName)\n // (uppercase in HTML documents) hits the same definition the element would.\n const tag = tagName.toLowerCase();\n // Fail loud with the actual cause. Without this, bindNode's generic \"no\n // wc-bindable descriptor\" error hides that the tag simply isn't defined yet.\n if (!descriptor && !customElements.get(tag)) {\n throw new Error(\n `mountNode: \"<${tag}>\" is not defined. Import its defining module first (e.g. a side-effect ` +\n `\\`import \"@wcstack/<pkg>/auto\"\\` in this module — evaluation order then guarantees the definition). ` +\n `For a tag loaded by someone else, await customElements.whenDefined(\"${tag}\") or gate with ` +\n `<wcs-defined> before mounting. Binding a non-custom-element tag requires an explicit \\`descriptor\\`.`,\n );\n }\n\n const el = document.createElement(tag);\n if (attrs) {\n for (const [name, value] of Object.entries(attrs)) {\n if (value === false) {\n continue; // boolean-attribute semantics: false = absent\n }\n el.setAttribute(name, value === true ? \"\" : String(value));\n }\n }\n const bound = bindNode<S>(el, descriptor);\n (parent ?? document.body).appendChild(el);\n const unmount = (): void => {\n bound.dispose();\n el.remove();\n };\n return {\n ...bound,\n el,\n unmount,\n // Override the inherited adapter-only dispose(): on a MountedNode it would be\n // a silent PARTIAL teardown (signals inert, but the created element stays\n // connected with its shell's IO still running). mountNode owns the element,\n // so dispose === unmount.\n dispose: unmount,\n };\n}\n"],"names":["Fragment","Symbol","isReadSignal","value","get","peek","h","tag","props","children","frag","document","createDocumentFragment","appendChildren","result","Array","isArray","wrapFragment","el","SVG_TAGS","has","createElementNS","SVG_NS","createElement","key","bindProp","Set","render","child","container","appendChild","ATTR_TO_PROP","for","tabindex","colspan","rowspan","readonly","maxlength","minlength","contenteditable","settableCache","WeakMap","isSettableProperty","proto","Object","getPrototypeOf","byKey","undefined","Map","set","obj","desc","getOwnPropertyDescriptor","writable","computeSettable","test","type","slice","toLowerCase","listener","addEventListener","onCleanup","removeEventListener","effect","setProp","removeAttribute","style","cssText","k","includes","setProperty","setStyle","setAttribute","String","propKey","parent","c","__wcsList","Node","insertReactive","createTextNode","mount","accessor","isDev","hasOwner","warnDev","anchor","createComment","current","length","node","nodeType","data","next","out","visit","v","forEach","push","toNodes","parentNode","removeChild","host","insertBefore","readList","list","reconcileOrder","order","prevOrder","n","prevIndex","i","seq","p","lis","arr","tails","prev","fill","lo","hi","mid","reverse","longestIncreasingSubsequence","lisPtr","ref","checkKeyDev","item","hasExplicitKey","Number","isNaN","For","each","options","read","keyOf","rows","make","idx","signal","cur","dispose","createRoot","d","items","keys","seen","dev","index","Error","add","fresh","row","err","size","lastChild","firstChild","childNodes","textContent","values","remove","clear","Index","cachedBase","createSignalsElement","HTMLElement","SignalsElementBase","_dispose","getMountPoint","this","connectedCallback","disconnectedCallback","SignalsElement","Proxy","construct","_target","args","newTarget","Reflect","prop","receiver","apply","TypeError","mountNode","tagName","customElements","attrs","descriptor","name","entries","bound","bindNode","body","unmount"],"mappings":"gQA6DaA,EAAWC,OAAO,oBAU/B,SAASC,EAAaC,GACpB,MACmB,iBAAVA,GACG,OAAVA,GAC4C,mBAApCA,EAA4BC,KACU,mBAAtCD,EAA6BE,IAEzC,CAEM,SAAUC,EACdC,EACAC,KACGC,GAEH,GAAIF,IAAQP,EAAU,CACpB,MAAMU,EAAOC,SAASC,yBAEtB,OADAC,EAAeH,EAAMD,GACdC,CACT,CAEA,GAAmB,mBAARH,EAAoB,CAC7B,MAAMO,EAASP,EAAI,IAAMC,GAAS,CAAA,EAAKC,aACvC,OAAOM,MAAMC,QAAQF,GAsCzB,SAAsBL,GACpB,MAAMC,EAAOC,SAASC,yBAEtB,OADAC,EAAeH,EAAMD,GACdC,CACT,CA1CmCO,CAAaH,GAAUA,CACxD,CAEA,MAAMI,EAuBR,SAAuBX,GACrB,OAAOY,EAASC,IAAIb,GAChBI,SAASU,gBAAgBC,EAAQf,G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9H,cAGpB,IAAKiI,IAAeF,eAAerL,IAAIG,GACrC,MAAM,IAAI8I,MACR,gBAAgB9I,oPAEyDA,yHAK7E,MAAMW,EAAKP,SAASY,cAAchB,GAClC,GAAImL,EACF,IAAK,MAAOE,EAAMzL,KAAUyC,OAAOiJ,QAAQH,IAC3B,IAAVvL,GAGJe,EAAGsD,aAAaoH,GAAgB,IAAVzL,EAAiB,GAAKsE,OAAOtE,IAGvD,MAAM2L,EAAQC,EAAY7K,EAAIyK,IAC7BhH,GAAUhE,SAASqL,MAAMlK,YAAYZ,GACtC,MAAM+K,EAAU,KACdH,EAAMjD,UACN3H,EAAG8I,UAEL,MAAO,IACF8B,EACH5K,KACA+K,UAKApD,QAASoD,EAEb"}
1
+ {"version":3,"file":"dom.esm.min.js","sources":["../src/dom.ts"],"sourcesContent":["// Fine-grained hyperscript (v1 design notes). The \"step before JSX\" (docs §4-1).\n//\n// `h(tag, props, ...children)` is the classic JSX factory shape, but it does NOT\n// build a virtual DOM and re-render. It creates a REAL DOM node once; any prop or\n// child given as a function (thunk) or signal is wired to a targeted `effect`, so\n// only that one binding updates when its signals change (Solid-style). This is\n// what keeps the package lightweight: no reconciler is shipped.\n//\n// JSX is intentionally NOT shipped. A consumer who wants it sets, in their own\n// tsconfig, `jsxFactory: \"h\"` + `jsxFragmentFactory: \"Fragment\"` (classic runtime)\n// — opting into a build step is their choice; the buildless path is calling `h`\n// directly. See docs/signals-state-design.md §4-1.\n//\n// OWNERSHIP: effects created here are owned by the enclosing reactive scope.\n// A reactive child's effect owns the prop/child effects of the subtree it builds,\n// so rebuilding that subtree disposes the previous one's effects (no leak). Mount\n// an app under `createRoot` so the whole tree can be torn down on unmount; a\n// dynamic child establishes its own scope automatically (it IS an effect).\n\nimport { signal, innerEffect as effect, onCleanup, createRoot, hasOwner, ReadSignal, WriteSignal } from \"./reactive.js\";\nimport { isDev, warnDev } from \"./dev.js\";\nimport { bindNode } from \"./bindNode.js\";\nimport type { BoundNode, NodeShape, DefaultNodeShape, WcBindableDescriptor } from \"./bindNode.js\";\n\n// `@wcstack/signals/dom` re-exports the headless core (signals, resource,\n// streamResource, bindNode, nodeSource) so UI code can import everything from one\n// module. Both built entries import a single shared `core-*.esm.js` chunk\n// (rollup.config.js `manualChunks`), so importing from BOTH `@wcstack/signals` and\n// `@wcstack/signals/dom` on a buildless page yields ONE reactive instance — the\n// tracking context is shared, not duplicated. `__tests__/packaging.test.ts` pins\n// this (both entries reference the same core chunk; a signal made via one entry is\n// observed by an effect from the other).\nexport {\n signal,\n computed,\n effect,\n createRoot,\n onCleanup,\n flushSync,\n} from \"./reactive.js\";\nexport type { ReadSignal, WriteSignal, EffectHandle, Cleanup, Equals } from \"./reactive.js\";\nexport { resource } from \"./resource.js\";\nexport type { ResourceState, ResourceOptions, ResourceSource } from \"./resource.js\";\nexport { streamResource } from \"./streamResource.js\";\nexport type {\n StreamResourceState,\n StreamResourceOptions,\n StreamSource,\n StreamProducer,\n StreamStatus,\n} from \"./streamResource.js\";\nexport { bindNode, nodeSource, DisposedError, isDisposedError } from \"./bindNode.js\";\nexport type {\n BoundNode,\n NodeShape,\n DefaultNodeShape,\n WcBindableDescriptor,\n WcBindableProperty,\n EventStreamOptions,\n} from \"./bindNode.js\";\n\nexport const Fragment = Symbol(\"signals.Fragment\");\n\nexport type Child = unknown;\nexport type Props = Record<string, unknown> | null;\n// h() always injects `children` into the props object it passes to a component, so\n// the parameter type makes that explicit (a component can declare `{ children }`).\nexport type Component = (\n props: Record<string, unknown> & { children?: Child[] },\n) => Node | Child[];\n\nfunction isReadSignal(value: unknown): value is ReadSignal<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { get?: unknown }).get === \"function\" &&\n typeof (value as { peek?: unknown }).peek === \"function\"\n );\n}\n\nexport function h(\n tag: string | typeof Fragment | Component,\n props?: Props,\n ...children: Child[]\n): Node {\n if (tag === Fragment) {\n const frag = document.createDocumentFragment();\n appendChildren(frag, children);\n return frag;\n }\n\n if (typeof tag === \"function\") {\n const result = tag({ ...(props ?? {}), children });\n return Array.isArray(result) ? wrapFragment(result) : result;\n }\n\n const el = createElement(tag);\n if (props) {\n for (const key in props) {\n bindProp(el, key, props[key]);\n }\n }\n appendChildren(el, children);\n return el;\n}\n\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\n// Tags created in the SVG namespace. Ambiguous names shared with HTML (`a`,\n// `title`, `script`, `style`) are intentionally EXCLUDED so ordinary HTML usage is\n// not broken; an SVG `<a>` / `<title>` must be created in an explicitly-namespaced\n// way by the caller. SVG DOM props are largely read-only, so `setProp`'s\n// settable-property check routes SVG attributes through `setAttribute` for free.\nconst SVG_TAGS = new Set([\n \"svg\", \"g\", \"path\", \"rect\", \"circle\", \"ellipse\", \"line\", \"polyline\", \"polygon\",\n \"text\", \"tspan\", \"defs\", \"use\", \"symbol\", \"marker\", \"linearGradient\",\n \"radialGradient\", \"stop\", \"clipPath\", \"mask\", \"pattern\", \"image\", \"foreignObject\",\n]);\n\nfunction createElement(tag: string): Element {\n return SVG_TAGS.has(tag)\n ? document.createElementNS(SVG_NS, tag)\n : document.createElement(tag);\n}\n\n/** Append `child` into `container`, resolving fragments/arrays. */\nexport function render(child: Child, container: Node): Node {\n appendChild(container, child);\n return container;\n}\n\nfunction wrapFragment(children: Child[]): DocumentFragment {\n const frag = document.createDocumentFragment();\n appendChildren(frag, children);\n return frag;\n}\n\n// --- props ------------------------------------------------------------------\n\n// Attribute names whose corresponding JS DOM property differs. `class` is handled\n// separately (it has reactive-falsy semantics in setProp), so it is not listed here.\nconst ATTR_TO_PROP: Record<string, string> = {\n for: \"htmlFor\",\n tabindex: \"tabIndex\",\n colspan: \"colSpan\",\n rowspan: \"rowSpan\",\n readonly: \"readOnly\",\n maxlength: \"maxLength\",\n minlength: \"minLength\",\n contenteditable: \"contentEditable\",\n};\n\n// True only if `key` resolves to a WRITABLE property on the element or its\n// prototype chain (a data property with `writable !== false`, or an accessor with a\n// setter). `key in el` is not enough: it also matches read-only members like\n// `firstChild` / `childNodes`, whose assignment throws in strict mode. The walk\n// starts at `el` itself so own instance fields (e.g. a custom element's properties)\n// are still matched, exactly as the previous `key in el` did — just without the\n// read-only false positives.\n//\n// MEMOIZATION: the prototype-chain walk runs on every bindProp/setProp. The result\n// depends only on the element's PROTOTYPE (its class) and the key, since DOM props\n// live on the prototype — not on per-instance own fields, which this library never\n// adds dynamically per element. So cache by `(prototype, key)`: a WeakMap keyed by\n// prototype (no leak — entries die with the class) holding a Map of key→result.\nconst settableCache = new WeakMap<object, Map<string, boolean>>();\n\nfunction computeSettable(el: Element, key: string): boolean {\n let obj: object | null = el;\n while (obj !== null) {\n const desc = Object.getOwnPropertyDescriptor(obj, key);\n if (desc) {\n return \"set\" in desc ? typeof desc.set === \"function\" : desc.writable !== false;\n }\n obj = Object.getPrototypeOf(obj);\n }\n return false;\n}\n\nfunction isSettableProperty(el: Element, key: string): boolean {\n // A real Element always has a prototype (HTMLElement.prototype → … → Object), so\n // `getPrototypeOf` is non-null here; use it as the cache key.\n const proto = Object.getPrototypeOf(el) as object;\n let byKey = settableCache.get(proto);\n if (byKey === undefined) {\n byKey = new Map<string, boolean>();\n settableCache.set(proto, byKey);\n }\n let result = byKey.get(key);\n if (result === undefined) {\n result = computeSettable(el, key);\n byKey.set(key, result);\n }\n return result;\n}\n\nfunction bindProp(el: Element, key: string, value: unknown): void {\n // Event handlers are special-cased BEFORE the reactive check: a function here is the\n // listener, not a thunk to track. `onClick` → \"click\" (lowercased); `onclick` /\n // `onadd-to-cart` → the name as written (\"click\", \"add-to-cart\" — data-wcs's `on<event>:`\n // form). A lowercase `onclick` used to fall through to the reactive path, so the handler\n // ran at render and never on click (docs/seam-apps.md, signals-shop).\n if (/^on[A-Za-z-]/.test(key) && typeof value === \"function\") {\n const type = /^on[A-Z]/.test(key) ? key.slice(2).toLowerCase() : key.slice(2);\n const listener = value as EventListener;\n el.addEventListener(type, listener);\n // Remove the listener when the owning scope is torn down (e.g. a dynamic\n // child that rebuilds this subtree), so handlers don't accumulate.\n onCleanup(() => el.removeEventListener(type, listener));\n return;\n }\n\n if (typeof value === \"function\") {\n effect(() => setProp(el, key, (value as () => unknown)()));\n return;\n }\n\n if (isReadSignal(value)) {\n effect(() => setProp(el, key, value.get()));\n return;\n }\n\n setProp(el, key, value);\n}\n\n/**\n * Objects given to a custom element that is not defined yet, by element → property, until it is\n * (docs/seam-apps.md, signals-shop: `h(\"product-card\", { product })` before `product-card.js` ran\n * landed as `product=\"[object Object]\"`). Not set on the element now: an own property set before\n * the upgrade would hide the class's accessor, so its setter would never run. The latest value is\n * assigned once the element is defined — through the setter, as a defined element gets it.\n */\nconst heldUntilDefined = new WeakMap<Element, Map<string, unknown>>();\n\n/** A custom element (a dash in its name) whose definition has not run yet. */\nfunction awaitsDefinition(el: Element): boolean {\n return el.localName.includes(\"-\") && typeof customElements !== \"undefined\" && customElements.get(el.localName) === undefined;\n}\n\nfunction holdUntilDefined(el: Element, key: string, value: unknown): void {\n let held = heldUntilDefined.get(el);\n if (!held) {\n heldUntilDefined.set(el, (held = new Map()));\n const props = held;\n void customElements.whenDefined(el.localName).then(() => {\n heldUntilDefined.delete(el);\n // (an element not in the document is not upgraded by define(): upgrade it before the setter is wanted)\n customElements.upgrade(el);\n for (const [k, v] of props) (el as unknown as Record<string, unknown>)[k] = v;\n });\n }\n held.set(key, value);\n}\n\nfunction setProp(el: Element, key: string, value: unknown): void {\n if (key === \"style\") {\n setStyle(el as HTMLElement, value);\n return;\n }\n if (key === \"class\" || key === \"className\") {\n // Set the `class` ATTRIBUTE, not the `className` property. On an SVGElement\n // `className` is a read-only `SVGAnimatedString`, so assigning it throws in\n // strict mode (ESM is always strict) — `setAttribute(\"class\", …)` works for both\n // HTML and SVG. Treat false like null → empty class (consistent with the\n // attribute path's false-removes-it rule), so `() => cond && \"active\"` yields \"\"\n // (not \"false\") when the condition is falsy.\n // STRING-ONLY: a non-null/non-false value is coerced via String(value). Array\n // (`[\"a\", \"b\"]`) and object (`{ active: true }`) class forms are NOT supported —\n // they would stringify to \"a,b\" / \"[object Object]\". Compose the class string in\n // the binding itself (e.g. `() => [a, b].join(\" \")`) and pass a string. This keeps\n // the core free of a class-merging convention.\n el.setAttribute(\"class\", value == null || value === false ? \"\" : String(value));\n return;\n }\n // Remap the handful of attribute names whose JS property differs, so `for` /\n // `tabindex` / `colspan` etc. reach the right property instead of falling through\n // to setAttribute (which works for some but not e.g. `htmlFor`).\n const propKey = ATTR_TO_PROP[key] ?? key;\n if (isSettableProperty(el, propKey)) {\n // Known, WRITABLE DOM property (value, checked, disabled, id, htmlFor, ...).\n // The settability check excludes read-only members (firstChild, childNodes, …)\n // that `key in el` would wrongly accept — assigning to those throws in strict\n // mode; we fall through to the attribute path for them instead.\n //\n // NORMALIZATION: null/undefined are coerced to \"\" before assignment. Without\n // this, a STRING prop (id/title/value/src) given a reactive null/undefined\n // lands as the literal \"null\"/\"undefined\" (e.g. img.src=\"null\" fires a real\n // request) — a correctness footgun. \"\" clears the prop instead. Safe for\n // non-string props too: boolean props coerce \"\"→false (same as null), numeric\n // props coerce \"\"→0 (same as null). We do NOT normalize `false`:\n // `el.disabled = false` is the intended boolean clear.\n (el as unknown as Record<string, unknown>)[propKey] = value == null ? \"\" : value;\n return;\n }\n // (a value given since replaces a held one: a primitive goes to the attribute, as below)\n heldUntilDefined.get(el)?.delete(propKey);\n if (typeof value === \"object\" && value !== null && awaitsDefinition(el)) {\n holdUntilDefined(el, propKey, value);\n return;\n }\n if (value == null || value === false) {\n el.removeAttribute(key);\n return;\n }\n if (value === true) {\n el.setAttribute(key, \"\");\n return;\n }\n el.setAttribute(key, String(value));\n}\n\nfunction setStyle(el: HTMLElement, value: unknown): void {\n if (value == null) {\n el.removeAttribute(\"style\");\n return;\n }\n if (typeof value === \"string\") {\n el.style.cssText = value;\n return;\n }\n // Object form: the object fully describes the style. Reset first so keys present\n // in a previous run but absent now are removed — otherwise a reactive style that\n // drops a key (e.g. {color,fontWeight} → {color}) would leave the stale property\n // applied. The object is the source of truth, so wiping cssText is correct here.\n el.style.cssText = \"\";\n const style = el.style as CSSStyleDeclaration & Record<string, string>;\n const obj = value as Record<string, string>;\n for (const k in obj) {\n // A key with a hyphen is either kebab-case (`font-weight`) or a CSS custom\n // property (`--accent`). Neither works via property assignment (`style[k]` would\n // just set an inert expando), so route them through setProperty. camelCase keys\n // (`fontWeight`) keep the faster property path.\n if (k.includes(\"-\")) {\n style.setProperty(k, obj[k]);\n } else {\n style[k] = obj[k];\n }\n }\n}\n\n// --- children ---------------------------------------------------------------\n\nfunction appendChildren(parent: Node, children: Child[]): void {\n for (const child of children) {\n appendChild(parent, child);\n }\n}\n\nfunction appendChild(parent: Node, child: Child): void {\n if (child == null || typeof child === \"boolean\") {\n return; // null / undefined / boolean render nothing\n }\n if (Array.isArray(child)) {\n for (const c of child) {\n appendChild(parent, c);\n }\n return;\n }\n if (isListView(child)) {\n // A keyed list (For / Index): it manages its own anchored region with in-place\n // reconciliation, so it does NOT go through the wholesale insertReactive path.\n child.mount(parent);\n return;\n }\n if (child instanceof Node) {\n parent.appendChild(child);\n return;\n }\n if (typeof child === \"function\") {\n insertReactive(parent, child as () => unknown);\n return;\n }\n if (isReadSignal(child)) {\n insertReactive(parent, () => child.get());\n return;\n }\n parent.appendChild(document.createTextNode(String(child)));\n}\n\n/**\n * A reactive insertion point. An anchor comment marks the position; on each run\n * the previous nodes are removed and the freshly-resolved nodes inserted before\n * the anchor. Using `anchor.parentNode` (not the original `parent`) keeps it\n * correct after the subtree is moved/mounted elsewhere.\n *\n * PRECONDITION: the Nodes returned by `accessor` are owned by this insertion point\n * — do not move them to another parent externally. On the next run they are\n * removed from wherever they currently are (`node.parentNode?.removeChild`), so an\n * externally-moved node would be yanked out of its new home without warning.\n *\n * OWNERSHIP: the `effect` below is owned by the enclosing reactive scope at call\n * time (the `currentOwner`). Used under `createRoot` / `SignalsElement` (the module\n * header's mount contract) it is disposed on teardown. Calling `h`/`render` with a\n * reactive child OUTSIDE any owner (no `createRoot`/`SignalsElement`) leaves this\n * effect un-owned and therefore never cleaned up — by design, per that contract.\n */\nfunction insertReactive(parent: Node, accessor: () => unknown): void {\n if (isDev() && !hasOwner()) {\n // A reactive child inserted with no enclosing owner: the effect below is never\n // disposed (the module header documents this as by-design, but it is a frequent\n // accidental leak). Warn once in dev so the un-owned mount is visible.\n warnDev(\n \"UNOWNED_INSERT\",\n \"\",\n \"reactive child inserted with no owner — its update effect will never be \" +\n \"disposed and may leak. Mount under createRoot / SignalsElement.\",\n );\n }\n const anchor = document.createComment(\"\");\n parent.appendChild(anchor);\n let current: Node[] = [];\n\n effect(() => {\n const value = accessor();\n // FAST PATH: a plain text result that replaces a plain text result. The common\n // reactive child is a string/number thunk (`() => \\`count: ${n.get()}\\``); the\n // wholesale path would remove the old Text node, allocate a new one, and re-insert\n // it on every change. When BOTH the previous and next renders are a single Text\n // node, mutate the existing node's `data` in place instead — no allocation, no\n // remove/insert, and the same DOM node identity is preserved across updates.\n if ((typeof value === \"string\" || typeof value === \"number\") && current.length === 1) {\n const node = current[0];\n if (node.nodeType === 3 /* TEXT_NODE */) {\n (node as Text).data = String(value);\n return;\n }\n }\n const next = toNodes(value);\n for (const node of current) {\n node.parentNode?.removeChild(node);\n }\n const host = anchor.parentNode;\n if (host) {\n for (const node of next) {\n host.insertBefore(node, anchor);\n }\n }\n current = next;\n });\n\n // On teardown, drop the references to the inserted Nodes. The disposed effect's\n // closure still captures `current`; if anything retains the effect after disposal\n // (e.g. a parent owner kept alive longer than the subtree), those Nodes would be\n // pinned via that closure even though they have left the DOM. Clearing the array\n // lets them be GC'd as soon as the enclosing owner tears this insertion point down.\n onCleanup(() => {\n current = [];\n });\n}\n\n// --- keyed lists: For / Index (migration-plan §9-3) --------------------------\n//\n// `insertReactive` rebuilds its whole subtree on every change. For lists that is\n// wasteful (and drops per-row state). `For` / `Index` instead keep a stable DOM row\n// per item and reconcile in place. Each row is built under its OWN `createRoot`, so\n// removing a row disposes exactly that row's effects/resources/listeners — the owner\n// tree (§8 (d)) is what makes this leak-free. The reconcile runs in a single\n// `effect` owned by the enclosing scope; an `onCleanup` disposes surviving rows when\n// that scope (e.g. the component) tears down.\n//\n// CONTRACT: `each` must return a SINGLE Node (one row = one node). Keys (For) must\n// be unique. `For` keys by value identity (=== / explicit `key`) and passes the\n// index as an accessor (it changes on move); `Index` keys by position and passes the\n// item as an accessor (the value at a slot changes, the slot does not).\n\nexport type ListAccessor<T> = ReadSignal<readonly T[]> | (() => readonly T[]);\n/**\n * `For`'s row builder. `item` is the item the row was built for — a plain value. A keyed row is\n * kept while its key is (an immutable update hands it a new object under the same key), so read\n * what changes through `current`, an accessor of the item under the row's key now\n * (`() => current().text`). docs/seam-apps.md, signals-shop.\n */\nexport type ForEach<T> = (item: T, index: () => number, current: () => T) => Node;\nexport type IndexEach<T> = (item: () => T, index: number) => Node;\n\n/**\n * The return type of {@link For} / {@link Index}: a keyed list that owns an anchored\n * region and reconciles rows in place. Exported (D4) so consumers can annotate\n * helpers that build or pass around lists. `mount` is called by `h`/`render` when the\n * list is used as a child; `__wcsList` is the brand `appendChild` checks.\n */\nexport interface ListView {\n readonly __wcsList: true;\n mount(parent: Node): void;\n}\n\nfunction isListView(value: unknown): value is ListView {\n return typeof value === \"object\" && value !== null && (value as ListView).__wcsList === true;\n}\n\nfunction readList<T>(list: ListAccessor<T>): () => readonly T[] {\n return isReadSignal(list) ? () => (list as ReadSignal<readonly T[]>).get() : (list as () => readonly T[]);\n}\n\nexport interface ForOptions<T> {\n /** Derive a unique key per item. Default: the item value itself (identity). */\n key?: (item: T, index: number) => unknown;\n}\n\n// --- LIS-based DOM reorder ---------------------------------------------------\n//\n// `reconcileOrder` brings the live DOM under `host` (the contiguous region ending\n// at `anchor`) into `order` — the desired final node sequence — using the FEWEST\n// `insertBefore` moves, while producing EXACTLY the order a naive full re-place\n// would. The naive approach (walk and insert every out-of-place node) does up to\n// O(n) DOM moves on a full reverse or a head insert; here we instead keep the\n// largest set of reused rows that are ALREADY in the right relative order, and\n// move only the others (Solid's reconcileArrays / udomdiff idea).\n//\n// HOW: `prevOrder` is the node sequence the previous run left in the DOM. For each\n// node in the new `order`, a reused row maps to its index in `prevOrder`; a freshly\n// created row has no previous position. The longest increasing subsequence (LIS)\n// of those previous indices marks the reused rows that need NOT move (their pairwise\n// relative order is already correct). Every other node — fresh ones, and reused\n// ones outside the LIS — is inserted before its already-correct successor, walking\n// back-to-front so the \"successor\" reference is always a settled node or the anchor.\n\n/**\n * Indices into `arr` (with value -1 meaning \"no previous position\") whose values\n * form a longest strictly-increasing subsequence. Entries equal to -1 are treated\n * as never part of the subsequence (a fresh node always moves). Classic\n * patience-sorting LIS in O(n log n); returns the chosen indices in ascending order.\n */\nfunction longestIncreasingSubsequence(arr: number[]): number[] {\n const n = arr.length;\n // `tails[k]` = index (into arr) of the smallest tail of an increasing\n // subsequence of length k+1. `prev[i]` = predecessor index, to rebuild the chain.\n const tails: number[] = [];\n const prev: number[] = new Array(n).fill(-1);\n for (let i = 0; i < n; i++) {\n const value = arr[i];\n if (value < 0) {\n continue; // fresh node: not eligible for the stable subsequence\n }\n // Binary search for the first tail whose value is >= this value, and replace it\n // (or extend the tails when this value beats every tail).\n let lo = 0;\n let hi = tails.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (arr[tails[mid]] < value) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n if (lo > 0) {\n prev[i] = tails[lo - 1];\n }\n tails[lo] = i;\n }\n // Rebuild the index chain from the longest tail backwards.\n const result: number[] = [];\n let k = tails.length > 0 ? tails[tails.length - 1] : -1;\n while (k >= 0) {\n result.push(k);\n k = prev[k];\n }\n result.reverse();\n return result;\n}\n\nfunction reconcileOrder(\n host: Node,\n anchor: Node,\n order: Node[],\n prevOrder: Node[],\n): void {\n const n = order.length;\n if (n === 0) {\n return; // nothing to place (removals already happened)\n }\n\n // Map each previous node to its previous position, so a node in `order` can look\n // up where it used to be. A node absent from this map is FRESH (created this run,\n // or the first run where prevOrder is empty) and is encoded as -1 — it always moves.\n const prevIndex = new Map<Node, number>();\n for (let i = 0; i < prevOrder.length; i++) {\n prevIndex.set(prevOrder[i], i);\n }\n\n // previous-position sequence aligned to the new order. -1 marks a fresh node.\n const seq: number[] = new Array(n);\n for (let i = 0; i < n; i++) {\n const p = prevIndex.get(order[i]);\n seq[i] = p === undefined ? -1 : p;\n }\n\n // Rows whose relative order is already correct: leave them in place, move the rest.\n const lis = longestIncreasingSubsequence(seq);\n let lisPtr = lis.length - 1;\n\n // Walk back-to-front. `ref` is the node that must follow the one being placed; it\n // starts at the anchor (the region's tail) and becomes each placed node. A node in\n // the LIS is the maximal already-correctly-ordered set, so it is left untouched\n // (only adopted as the new `ref`). Every OTHER node is, by construction, out of\n // position relative to its settled successor and is inserted before `ref` — no\n // \"is it already in place?\" guard is needed (it never is, unlike the old\n // full-walk reconciler which visited correctly-placed nodes too).\n let ref: Node = anchor;\n for (let i = n - 1; i >= 0; i--) {\n const node = order[i];\n if (lisPtr >= 0 && lis[lisPtr] === i) {\n lisPtr--; // stable: do not move\n } else {\n host.insertBefore(node, ref);\n }\n ref = node;\n }\n}\n\n// Dev-only key sanity check (no effect in production — guarded by `isDev()` at the\n// call site so this is never reached when dev is off). Flags the silent-failure key\n// shapes: a nullish key (NaN / null / undefined collide under SameValueZero, so two\n// such items map to one row and a row is silently dropped), and — when no explicit\n// `key` was given — a non-primitive item used as its own identity key (every render\n// gets a fresh object reference, so the row is rebuilt instead of reused, silently\n// dropping per-row state). Warns once per distinct shape (deduped in warnDev).\nfunction checkKeyDev(key: unknown, item: unknown, hasExplicitKey: boolean): void {\n if (key == null || (typeof key === \"number\" && Number.isNaN(key))) {\n warnDev(\n \"NULLISH_KEY\",\n String(key),\n \"For: a key is null/undefined/NaN. Such keys collide under SameValueZero, \" +\n \"so rows silently merge/drop. Provide a stable unique `key`.\",\n { key },\n );\n return;\n }\n if (!hasExplicitKey && (typeof key === \"object\" || typeof key === \"function\")) {\n warnDev(\n \"NON_PRIMITIVE_KEY\",\n typeof key,\n \"For: a non-primitive item is used as its own key (no `key` option given). \" +\n \"Object identity changes across renders, so every row is rebuilt and per-row \" +\n \"state is lost. Pass `{ key: item => item.id }`, and read the item through current().\",\n { item },\n );\n }\n}\n\nexport function For<T>(list: ListAccessor<T>, each: ForEach<T>, options?: ForOptions<T>): ListView {\n const read = readList(list);\n const keyOf = options?.key;\n return {\n __wcsList: true,\n mount(parent: Node): void {\n const anchor = document.createComment(\"for\");\n parent.appendChild(anchor);\n\n interface Row {\n node: Node;\n dispose: () => void;\n idx: WriteSignal<number>;\n /** The item under the row's key now (`each`'s `current`). */\n cur: WriteSignal<T>;\n }\n let rows = new Map<unknown, Row>();\n // The node order placed by the previous reconcile run. Empty on first run.\n // Used to find which reused rows already sit in increasing relative order so\n // only the rest are moved (LIS reorder, see reconcileOrder).\n let prevOrder: Node[] = [];\n\n const make = (item: T, i: number): Row => {\n const idx = signal(i);\n const cur = signal(item);\n let node!: Node;\n const dispose = createRoot((d) => {\n node = each(item, () => idx.get(), () => cur.get());\n return d;\n });\n return { node, dispose, idx, cur };\n };\n\n effect(() => {\n const items = read() ?? [];\n\n // Key-uniqueness PRE-PASS (no side effects): throwing here, before any row is\n // created or moved, keeps a duplicate-key error from leaving half-built rows\n // orphaned (make() runs createRoot) and the DOM mid-reorder. Keys are reused\n // below so keyOf runs once per item.\n const keys: unknown[] = [];\n const seen = new Set<unknown>();\n const dev = isDev();\n for (let i = 0; i < items.length; i++) {\n const k = keyOf ? keyOf(items[i], i) : items[i];\n if (dev) {\n checkKeyDev(k, items[i], keyOf !== undefined);\n }\n if (seen.has(k)) {\n if (dev) {\n // The throw below still halts (production behaviour unchanged); the warn\n // adds the offending key + a pointer to the cause so the silent\n // \"updates stopped\" symptom is diagnosable.\n warnDev(\n \"DUPLICATE_KEY\",\n String(k),\n `For: duplicate key \"${String(k)}\" at index ${i} — keys must be unique. ` +\n \"Rendering throws and the list stops updating until keys are fixed.\",\n { key: k, index: i },\n );\n }\n throw new Error(`For: duplicate key \"${String(k)}\" — keys must be unique.`);\n }\n seen.add(k);\n keys.push(k);\n }\n\n const next = new Map<unknown, Row>();\n const order: Node[] = [];\n\n // Rows freshly created in THIS run (not reused from `rows`). If a later\n // `make()` — i.e. a user `each` — throws mid-loop, the rows already built\n // here are owned by their own detached `createRoot` and are not yet tracked\n // in any surviving map, so they would leak. Dispose them before re-throwing,\n // leaving the old `rows` map untouched (it is recoverable on the next run).\n const fresh: Row[] = [];\n try {\n for (let i = 0; i < items.length; i++) {\n const k = keys[i];\n let row = rows.get(k);\n if (row) {\n if (row.idx.peek() !== i) {\n row.idx.set(i); // position changed — refresh the index accessor\n }\n row.cur.set(items[i]); // the item under the key now (a no-op when it is the same)\n } else {\n row = make(items[i], i);\n fresh.push(row);\n }\n next.set(k, row);\n order.push(row.node);\n }\n } catch (err) {\n for (const row of fresh) {\n row.dispose();\n }\n throw err;\n }\n\n // The LIVE parent (`anchor.parentNode`, not the mount arg) so the region\n // stays correct after being moved (e.g. built inside a Fragment, then\n // appended elsewhere). `host` is null only if the anchor was detached\n // without disposing this scope (a misuse) — then there is nothing to\n // place into. Resolved before the removal phase so the wholesale-removal\n // fast path below can use it.\n const host = anchor.parentNode;\n\n // Dispose rows whose key vanished. `remove()` no-ops if already detached.\n if (rows.size > 0 && next.size === fresh.length) {\n // ZERO-REUSE run: no existing key survives (clear, or a full replacement\n // with disjoint keys), so EVERY current row is removed. When the host\n // contains exactly this list's region — first child is the region's\n // first row, last child is the anchor, and the child count matches\n // rows + anchor — detach them all with a single native\n // `textContent = \"\"` and re-append the anchor, instead of one\n // `remove()` per row (the dominant cost of clearing large lists).\n // Any deviation (foreign sibling, externally detached row, shared\n // host) fails the guard and falls back to the per-row path.\n // Disposal always runs per row; only the DOM detachment is batched.\n if (\n host !== null &&\n host.lastChild === anchor &&\n prevOrder.length > 0 &&\n host.firstChild === prevOrder[0] &&\n host.childNodes.length === rows.size + 1\n ) {\n host.textContent = \"\";\n host.appendChild(anchor);\n for (const row of rows.values()) {\n row.dispose();\n }\n } else {\n for (const row of rows.values()) {\n (row.node as ChildNode).remove();\n row.dispose();\n }\n }\n } else {\n for (const [k, row] of rows) {\n if (!next.has(k)) {\n (row.node as ChildNode).remove();\n row.dispose();\n }\n }\n }\n if (host) {\n reconcileOrder(host, anchor, order, prevOrder);\n }\n\n // Snapshot this run's final order so the NEXT run's reconcile can detect\n // which rows kept their relative position (the LIS basis below). Capturing\n // the array we just placed avoids re-deriving it from the map.\n prevOrder = order;\n rows = next;\n });\n\n onCleanup(() => {\n for (const row of rows.values()) {\n row.dispose();\n }\n rows.clear();\n });\n },\n };\n}\n\nexport function Index<T>(list: ListAccessor<T>, each: IndexEach<T>): ListView {\n const read = readList(list);\n return {\n __wcsList: true,\n mount(parent: Node): void {\n const anchor = document.createComment(\"index\");\n parent.appendChild(anchor);\n\n interface Row {\n node: Node;\n dispose: () => void;\n item: WriteSignal<T>;\n }\n const rows: Row[] = [];\n\n effect(() => {\n const items = read() ?? [];\n // Live parent (see `For`), null only if the anchor was detached undisposed.\n const host = anchor.parentNode;\n\n for (let i = 0; i < items.length; i++) {\n if (i < rows.length) {\n // Slot reused: just push the new value into the row's item signal. The\n // signal's equality guard skips the update when the value is unchanged.\n rows[i].item.set(items[i]);\n } else {\n const item = signal(items[i]);\n let node!: Node;\n const dispose = createRoot((d) => {\n node = each(() => item.get(), i);\n return d;\n });\n rows.push({ node, dispose, item });\n // Positions never move for index keying, so append at the tail (before\n // the anchor) in order. ORDERING CONTRACT (shared with For and the other\n // anchored insertions): the list owns the contiguous region ENDING at its\n // anchor comment. New rows go immediately before the anchor, so the list's\n // own rows always stay correctly ordered and grouped, and static siblings\n // before the anchor (or another list with its own anchor) are never\n // disturbed. Do NOT splice unrelated nodes into the middle of this region.\n host?.insertBefore(node, anchor);\n }\n }\n\n // Trailing slots that no longer exist: dispose and drop.\n if (items.length < rows.length) {\n // WHOLESALE CLEAR (same idea as For's zero-reuse fast path): every slot\n // vanishes and the host holds exactly this list's region (all rows +\n // the anchor), so one native `textContent = \"\"` replaces per-row\n // `remove()`. Guard failures (foreign sibling, detached row, shared\n // host) fall back to the per-row path. Disposal still runs per row.\n if (\n items.length === 0 &&\n host !== null &&\n host.lastChild === anchor &&\n host.firstChild === rows[0].node &&\n host.childNodes.length === rows.length + 1\n ) {\n host.textContent = \"\";\n host.appendChild(anchor);\n for (const row of rows) {\n row.dispose();\n }\n } else {\n for (let i = items.length; i < rows.length; i++) {\n (rows[i].node as ChildNode).remove();\n rows[i].dispose();\n }\n }\n rows.length = items.length;\n }\n });\n\n onCleanup(() => {\n for (const row of rows) {\n row.dispose();\n }\n rows.length = 0;\n });\n },\n };\n}\n\n// --- custom element lifecycle (docs §8 (e)) ---------------------------------\n//\n// The exit point for ownership: a custom element that mounts a signals view under\n// `createRoot` on connect and disposes that root on disconnect. This wires the\n// reactive ownership tree to the real DOM lifecycle — every effect, resource and\n// listener created in `render()` is torn down when the element leaves the DOM, and\n// rebuilt fresh on reconnect. Subclasses only implement `render()`.\n//\n// SCOPE (v1 intentional constraints — drive these reactively, not via this base):\n// - No attribute reactivity. There is no `attributeChangedCallback`/\n// `observedAttributes` wiring: this base does NOT turn HTML attributes into\n// signals. Feed reactive inputs as signals/props from the code that constructs\n// the view (or have a subclass map attributes to signals itself).\n// - Shadow DOM is opt-in and subclass-owned. The default mount point is light DOM\n// (`this`); a subclass that wants encapsulation overrides `getMountPoint()` to\n// return a shadow root it created (e.g. `this.attachShadow(...)` in its\n// constructor). This base never calls attachShadow implicitly.\n// - Mount/unmount only: render() runs once per connect and the whole subtree is\n// disposed on disconnect — there is no partial/incremental re-render hook here\n// (fine-grained updates come from the signals wired inside render()).\n\n// TYPE-ONLY shape of the lifecycle base. `declare abstract class` emits NO runtime\n// code (so it does not reference `HTMLElement` at module-evaluation time — the whole\n// point of the lazy factory below), but it gives the exported `SignalsElement` value\n// and `createSignalsElement()`'s return a precise type that preserves the original\n// contract: `render` is `protected abstract` (a subclass MUST implement it and may\n// only reach it from within), and `getMountPoint` is `protected` (overridable). This\n// is the same surface the previous concrete `abstract class SignalsElement` exposed.\n// (Used only via `typeof` below; the lint rule does not see that as a value use.)\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ndeclare abstract class SignalsElementType extends HTMLElement {\n /** Build the view with `h` + signals. Runs inside an ownership root. */\n protected abstract render(): Node;\n /** Mount target. Override to return a shadow root; default is light DOM. */\n protected getMountPoint(): Node;\n connectedCallback(): void;\n disconnectedCallback(): void;\n}\n\n/**\n * The lifecycle base contract: the abstract constructor type of the `SignalsElement`\n * base. Abstract, so `new SignalsElement()` is rejected (the base has an unimplemented\n * `render`) while `class X extends SignalsElement` is allowed. Returned by\n * {@link createSignalsElement} and the type of the {@link SignalsElement} value.\n */\nexport type SignalsElementClass = typeof SignalsElementType;\n\n// Memoized base class. Built lazily on first access so the `./dom` module can be\n// EVALUATED in a non-DOM environment (SSR pre-pass, a worker without a DOM shim)\n// without a top-level `class … extends HTMLElement` blowing up with\n// `ReferenceError: HTMLElement is not defined`. The class body is only constructed\n// when the consumer actually reaches for the base — at which point a DOM is required\n// and its absence yields a clear, actionable error instead of a raw ReferenceError.\nlet cachedBase: SignalsElementClass | null = null;\n\n/**\n * Build (once, memoized) the `SignalsElement` lifecycle base class. Resolves\n * `HTMLElement` at CALL TIME, so importing `@wcstack/signals/dom` no longer requires\n * a DOM at module-evaluation time — only *calling* this (or subclassing\n * {@link SignalsElement}) does.\n *\n * Contract:\n * - The `.` entry (`@wcstack/signals`) is non-DOM: it evaluates and runs in SSR,\n * Node, and Web Workers with no DOM globals.\n * - The `./dom` entry (`@wcstack/signals/dom`) may now also be *evaluated* without a\n * DOM (so an SSR pre-pass that imports it for the headless re-exports does not\n * crash). The DOM-touching surface — `h`/`render`/`For`/`Index` and this base —\n * still requires DOM globals when actually used.\n *\n * @throws a clear `Error` (not a raw `ReferenceError`) when no `HTMLElement` global is\n * present, naming the offending entry so the failure is self-explanatory.\n */\nexport function createSignalsElement(): SignalsElementClass {\n if (cachedBase !== null) {\n return cachedBase;\n }\n if (typeof HTMLElement === \"undefined\") {\n throw new Error(\n \"@wcstack/signals/dom: SignalsElement requires a DOM (HTMLElement is not defined). \" +\n \"The `./dom` entry's element/render surface is browser-only; in SSR/Node/worker \" +\n \"code import the headless core from `@wcstack/signals` instead, or inject a DOM \" +\n \"(e.g. happy-dom) before constructing custom elements.\",\n );\n }\n\n abstract class SignalsElementBase extends HTMLElement {\n private _dispose: (() => void) | null = null;\n\n /** Build the view with `h` + signals. Runs inside an ownership root. */\n protected abstract render(): Node;\n\n /** Mount target. Override to return a shadow root; default is light DOM. */\n protected getMountPoint(): Node {\n return this;\n }\n\n connectedCallback(): void {\n if (this._dispose !== null) {\n return; // already mounted (defensive against a redundant connect)\n }\n const mount = this.getMountPoint();\n // If render() throws, createRoot disposes any effects it built before the throw,\n // so nothing leaks; _dispose stays null (the element is simply not mounted) and\n // a later disconnectedCallback safely no-ops. The error propagates to the caller.\n this._dispose = createRoot((dispose) => {\n mount.appendChild(this.render());\n return dispose;\n });\n }\n\n disconnectedCallback(): void {\n if (this._dispose === null) {\n return; // not mounted\n }\n this._dispose();\n this._dispose = null;\n const mount = this.getMountPoint();\n while (mount.firstChild) {\n mount.removeChild(mount.firstChild);\n }\n }\n }\n\n cachedBase = SignalsElementBase as unknown as SignalsElementClass;\n return cachedBase;\n}\n\n// `SignalsElement` is the ergonomic name to `extends`. It is a lazily-resolved alias\n// for the class built by `createSignalsElement()`: a Proxy that forwards construct /\n// get / has / getPrototypeOf to the real (memoized) base, building it on first touch.\n// This keeps `class X extends SignalsElement { … }` working exactly as before WHILE\n// deferring the `HTMLElement` reference to subclass-definition time (in a real DOM),\n// instead of `./dom` module-evaluation time (which may be a non-DOM SSR pre-pass).\n//\n// BREAKING note: the value is now a Proxy, not the class object literal. Subclassing,\n// `instanceof`, and static/prototype access all still work; a consumer that relied on\n// `SignalsElement` being a *frozen* concrete class reference (uncommon) should call\n// `createSignalsElement()` to obtain the real class.\n// The Proxy target is a never-called placeholder (every operation is intercepted by a\n// trap below); it only needs to be constructable/callable so `new` / `extends` and the\n// `apply` trap engage. It is intentionally a no-op and never executed.\n/* v8 ignore next */\nconst signalsElementTarget = function (): void {};\nexport const SignalsElement: SignalsElementClass = new Proxy(signalsElementTarget as unknown as SignalsElementClass, {\n construct(_target, args, newTarget): object {\n return Reflect.construct(createSignalsElement(), args, newTarget);\n },\n get(_target, prop, receiver): unknown {\n return Reflect.get(createSignalsElement(), prop, receiver);\n },\n has(_target, prop): boolean {\n return Reflect.has(createSignalsElement(), prop);\n },\n apply(): never {\n throw new TypeError(\"SignalsElement is a class and cannot be invoked without `new`/`extends`.\");\n },\n getPrototypeOf(): object | null {\n return Reflect.getPrototypeOf(createSignalsElement());\n },\n});\n\nfunction toNodes(value: unknown): Node[] {\n const out: Node[] = [];\n const visit = (v: unknown): void => {\n if (v == null || typeof v === \"boolean\") {\n return;\n }\n if (Array.isArray(v)) {\n v.forEach(visit);\n return;\n }\n if (v instanceof Node) {\n out.push(v);\n return;\n }\n out.push(document.createTextNode(String(v)));\n };\n visit(value);\n return out;\n}\n\n// --- mountNode: create + bind + mount a headless wc-bindable node -------------\n//\n// `bindNode` adapts an EXISTING element, which forces its caller to guarantee the\n// custom element class is already registered (the descriptor is read from\n// `el.constructor.wcBindable` at call time — an un-upgraded element has none).\n// `mountNode` closes that gap for the common signals shape where the app OWNS its\n// headless IO nodes: it creates the element AFTER the definition exists (so it is\n// upgraded at construction), binds it, then connects it. The recommended pairing\n// is a side-effect import of the package's `/auto` entry in the same module —\n// module evaluation order then guarantees the definition:\n//\n// import \"@wcstack/fetch/auto\";\n// const fetcher = mountNode(\"wcs-fetch\", { attrs: { url: \"/api/people\" } });\n// fetcher.signals.value.get();\n//\n// The internal order is deliberate: attributes are set BEFORE connect (shells read\n// their config in `connectedCallback`), and the adapter subscribes BEFORE connect,\n// so an event fired from `connectedCallback` is already observed — the missed-event\n// window is structurally zero, not merely closed by bindNode's re-seed. Like\n// `bindNode`, the adapter is NOT auto-registered with a reactive owner; teardown is\n// explicit via `unmount()` — to which `dispose()` is aliased, see MountedNode —\n// (compose with `onCleanup(() => m.unmount())` if the node should die with a\n// scope). See docs/signals-definition-timing.md for the full definition-timing\n// contract (optional packages via dynamic import, the remaining whenDefined /\n// <wcs-defined> territory).\n\nexport interface MountNodeOptions {\n /**\n * Attributes set on the element BEFORE it is connected (declarative pre-connect\n * config, e.g. `{ url: \"/api\", timeout: 5000 }`). HTML boolean-attribute\n * semantics: `true` sets an empty attribute, `false` omits it; other values are\n * stringified.\n */\n attrs?: Record<string, string | number | boolean>;\n /** Parent to append the element to. Default: `document.body`. */\n parent?: Node;\n /**\n * Explicit wc-bindable descriptor forwarded to `bindNode`. When given, the\n * tag-definition check is skipped — the escape hatch for binding a\n * non-custom-element tag, mirroring `bindNode`'s second parameter.\n */\n descriptor?: WcBindableDescriptor;\n}\n\nexport interface MountedNode<S extends NodeShape = DefaultNodeShape> extends BoundNode<S> {\n /** The created element (connected until `unmount()`). */\n readonly el: HTMLElement;\n /**\n * Full teardown: dispose the adapter AND remove the element from the DOM\n * (disconnect stops the shell's IO). Idempotent. On a `MountedNode`,\n * `dispose()` is an alias of this — mountNode owns the element's lifecycle,\n * so the package-wide teardown verb must not leave a connected element with\n * live IO behind (a silent leak for callers habituated to `bindNode`).\n */\n unmount(): void;\n}\n\nexport function mountNode<S extends NodeShape = DefaultNodeShape>(\n tagName: string,\n options: MountNodeOptions = {},\n): MountedNode<S> {\n // Call-time DOM guard (not module-time): `./dom` must evaluate in non-DOM realms\n // (SSR pre-pass / worker) — same contract (and message shape) as `createSignalsElement`.\n if (typeof document === \"undefined\" || typeof customElements === \"undefined\") {\n throw new Error(\n \"@wcstack/signals/dom: mountNode requires a DOM (document/customElements is not defined). \" +\n \"It creates and connects a live element, so it is browser-only; inject a DOM \" +\n \"(e.g. happy-dom) before calling, or keep headless work on `@wcstack/signals`.\",\n );\n }\n const { attrs, parent, descriptor } = options;\n // Custom element names are lowercase; the registry is exact-key while\n // createElement ASCII-lowercases — normalize once so mountNode(el.tagName)\n // (uppercase in HTML documents) hits the same definition the element would.\n const tag = tagName.toLowerCase();\n // Fail loud with the actual cause. Without this, bindNode's generic \"no\n // wc-bindable descriptor\" error hides that the tag simply isn't defined yet.\n if (!descriptor && !customElements.get(tag)) {\n throw new Error(\n `mountNode: \"<${tag}>\" is not defined. Import its defining module first (e.g. a side-effect ` +\n `\\`import \"@wcstack/<pkg>/auto\"\\` in this module — evaluation order then guarantees the definition). ` +\n `For a tag loaded by someone else, await customElements.whenDefined(\"${tag}\") or gate with ` +\n `<wcs-defined> before mounting. Binding a non-custom-element tag requires an explicit \\`descriptor\\`.`,\n );\n }\n\n const el = document.createElement(tag);\n if (attrs) {\n for (const [name, value] of Object.entries(attrs)) {\n if (value === false) {\n continue; // boolean-attribute semantics: false = absent\n }\n el.setAttribute(name, value === true ? \"\" : String(value));\n }\n }\n const bound = bindNode<S>(el, descriptor);\n (parent ?? document.body).appendChild(el);\n const unmount = (): void => {\n bound.dispose();\n el.remove();\n };\n return {\n ...bound,\n el,\n unmount,\n // Override the inherited adapter-only dispose(): on a MountedNode it would be\n // a silent PARTIAL teardown (signals inert, but the created element stays\n // connected with its shell's IO still running). mountNode owns the element,\n // so dispose === unmount.\n dispose: unmount,\n };\n}\n"],"names":["Fragment","Symbol","isReadSignal","value","get","peek","h","tag","props","children","frag","document","createDocumentFragment","appendChildren","result","Array","isArray","wrapFragment","el","SVG_TAGS","has","createElementNS","SVG_NS","createElement","key","bindProp","Set","render","child","container","appendChild","ATTR_TO_PROP","for","tabindex","colspan","rowspan","readonly","maxlength","minlength","contenteditable","settableCache","WeakMap","isSettableProperty","proto","Object","getPrototypeOf","byKey","undefined","Map","set","obj","desc","getOwnPropertyDescriptor","writable","computeSettable","test","type","slice","toLowerCase","listener","addEventListener","onCleanup","removeEventListener","effect","setProp","heldUntilDefined","removeAttribute","style","cssText","k","includes","setProperty","setStyle","setAttribute","String","propKey","delete","localName","customElements","awaitsDefinition","held","whenDefined","then","upgrade","v","holdUntilDefined","parent","c","__wcsList","Node","insertReactive","createTextNode","mount","accessor","isDev","hasOwner","warnDev","anchor","createComment","current","length","node","nodeType","data","next","out","visit","forEach","push","toNodes","parentNode","removeChild","host","insertBefore","readList","list","reconcileOrder","order","prevOrder","n","prevIndex","i","seq","p","lis","arr","tails","prev","fill","lo","hi","mid","reverse","longestIncreasingSubsequence","lisPtr","ref","checkKeyDev","item","hasExplicitKey","Number","isNaN","For","each","options","read","keyOf","rows","make","idx","signal","cur","dispose","createRoot","d","items","keys","seen","dev","index","Error","add","fresh","row","err","size","lastChild","firstChild","childNodes","textContent","values","remove","clear","Index","cachedBase","createSignalsElement","HTMLElement","SignalsElementBase","_dispose","getMountPoint","this","connectedCallback","disconnectedCallback","SignalsElement","Proxy","construct","_target","args","newTarget","Reflect","prop","receiver","apply","TypeError","mountNode","tagName","attrs","descriptor","name","entries","bound","bindNode","body","unmount"],"mappings":"4QA6DaA,EAAWC,OAAO,oBAU/B,SAASC,EAAaC,GACpB,MACmB,iBAAVA,GACG,OAAVA,GAC4C,mBAApCA,EAA4BC,KACU,mBAAtCD,EAA6BE,IAEzC,CAEM,SAAUC,EACdC,EACAC,KACGC,GAEH,GAAIF,IAAQP,EAAU,CACpB,MAAMU,EAAOC,SAASC,yBAEtB,OADAC,EAAeH,EAAMD,GACdC,CACT,CAEA,GAAmB,mBAARH,EAAoB,CAC7B,MAAMO,EAASP,EAAI,IAAMC,GAAS,CAAA,EAAKC,aACvC,OAAOM,MAAMC,QAAQF,GAsCzB,SAAsBL,GACpB,MAAMC,EAAOC,SAASC,yBAEtB,OADAC,EAAeH,EAAMD,GACdC,CACT,CA1CmCO,CAAaH,GAAUA,CACxD,CAEA,MAAMI,EAuBR,SAAuBX,GACrB,OAAOY,EAASC,IAAIb,GAChBI,SAASU,gBAAgBC,EAAQf,GACjCI,SAASY,cAAchB,EAC7B,CA3BagB,CAA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AOtF,EAAM0E,YACX1E,EAAMmB,YAAYnB,EAAM0E,WAE5B,EAIF,OADAO,EAAaG,EACNH,CACT,CAiBA,MACaS,EAAsC,IAAIC,MAD1B,WAAmB,EACqE,CACnHC,UAAS,CAACC,EAASC,EAAMC,IAChBC,QAAQJ,UAAUV,IAAwBY,EAAMC,GAEzDvL,IAAG,CAACqL,EAASI,EAAMC,IACVF,QAAQxL,IAAI0K,IAAwBe,EAAMC,GAEnD1K,IAAG,CAACqK,EAASI,IACJD,QAAQxK,IAAI0J,IAAwBe,GAE7C,KAAAE,GACE,MAAM,IAAIC,UAAU,2EACtB,EACAnJ,eAAc,IACL+I,QAAQ/I,eAAeiI,gBAiFlBmB,EACdC,EACAnD,EAA4B,IAI5B,GAAwB,oBAAbpI,UAAsD,oBAAnBmE,eAC5C,MAAM,IAAIiF,MACR,sPAKJ,MAAMoC,MAAEA,EAAK7G,OAAEA,EAAM8G,WAAEA,GAAerD,EAIhCxI,EAAM2L,EAAQxI,cAGpB,IAAK0I,IAAetH,eAAe1E,IAAIG,GACrC,MAAM,IAAIwJ,MACR,gBAAgBxJ,oPAEyDA,yHAK7E,MAAMW,EAAKP,SAASY,cAAchB,GAClC,GAAI4L,EACF,IAAK,MAAOE,EAAMlM,KAAUyC,OAAO0J,QAAQH,IAC3B,IAAVhM,GAGJe,EAAGuD,aAAa4H,GAAgB,IAAVlM,EAAiB,GAAKuE,OAAOvE,IAGvD,MAAMoM,EAAQC,EAAYtL,EAAIkL,IAC7B9G,GAAU3E,SAAS8L,MAAM3K,YAAYZ,GACtC,MAAMwL,EAAU,KACdH,EAAMhD,UACNrI,EAAGwJ,UAEL,MAAO,IACF6B,EACHrL,KACAwL,UAKAnD,QAASmD,EAEb"}
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- export { D as DisposedError, b as bindNode, c as computed, a as createRoot, e as effect, f as flushSync, i as isDisposedError, n as nodeSource, o as onCleanup, r as resource, s as signal, d as streamResource } from './core-GLSUraaa.esm.js';
1
+ export { D as DisposedError, b as bindNode, c as computed, a as createRoot, e as effect, f as flushSync, i as isDisposedError, n as nodeSource, o as onCleanup, r as resource, s as signal, d as streamResource } from './core-kS9CKPFP.esm.js';
2
2
  //# sourceMappingURL=index.esm.js.map
@@ -1,2 +1,2 @@
1
- export{D as DisposedError,b as bindNode,c as computed,a as createRoot,e as effect,f as flushSync,i as isDisposedError,n as nodeSource,o as onCleanup,r as resource,s as signal,d as streamResource}from"./core-CUHdCgQ2.esm.min.js";
1
+ export{D as DisposedError,b as bindNode,c as computed,a as createRoot,e as effect,f as flushSync,i as isDisposedError,n as nodeSource,o as onCleanup,r as resource,s as signal,d as streamResource}from"./core-BBzx9zgt.esm.min.js";
2
2
  //# sourceMappingURL=index.esm.min.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wcstack/signals",
3
- "version": "4.1.0",
3
+ "version": "4.2.0",
4
4
  "description": "Signals-based lightweight reactive core with async-IO resource adapters and a wc-bindable → signal bridge for Web Components. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -1,2 +0,0 @@
1
- function e(e){const t=globalThis.reportError;"function"==typeof t?t(e):console.error(e)}function t(){return!0===globalThis.__WCS_DEV__}const n=new Set;function o(e,o,s,...r){if(!t())return;const i=e+"\0"+o;n.has(i)||(n.add(i),console.warn(`[wcstack/signals][${e}] ${s}`,...r))}let s=null;function r(e){null!==s&&(s._sources.add(e),e._observers.add(s))}function i(e){for(const t of e._sources)t._observers.delete(e);e._sources.clear()}let a=null;function c(e){null!==a&&a._owned.push(e)}function d(e){const t=e._owned;for(let e=t.length-1;e>=0;e--)t[e]();t.length=0}let l=new Set,u=!1;const f=[];function h(){return f.pop()??new Set}function _(){u||(u=!0,queueMicrotask(w))}const p=1e3;function v(e){const t=e.filter(e=>!e._disposed),n=t.map((e,t)=>` #${t+1} ${e._devStack?e._devStack.split("\n").slice(1,3).join(" | ").trim():"(no stack)"}`);return`\n[wcstack/signals] dev diagnostics: ${t.length} effect(s) still re-running on the final pass (likely cycle participants):\n${n.join("\n")}`}function w(){u=!1;let n=0,o=null;for(;l.size>0;){if(++n>p)throw l.clear(),new Error("flushEffects: exceeded "+p+" iterations — likely a reactive cycle (an effect writes a signal it depends on with an ever-changing value)."+(o?v(o):""));const s=l;l=h(),t()&&(o=[...s]);for(const t of s)if(!t._disposed)try{y(t)}catch(t){e(t)}s.clear(),f.push(s)}}function b(){w()}function m(e,t){if(e._state<t){const n=0===e._state;e._state=t,n&&e._isEffect&&(l.add(e),_());for(const t of e._observers)m(t,1)}}function y(e){if(0!==e._state){if(1===e._state)for(const t of e._sources)if(t instanceof E&&(y(t),2===e._state))break;try{2===e._state&&e._update()}finally{e._state=0}}}class g{_observers=new Set;_value;_equals;constructor(e,t){this._value=e,this._equals=t}get(){return r(this),this._value}peek(){return this._value}set(e){if(!this._equals(this._value,e)){this._value=e;for(const e of this._observers)m(e,2)}}}class E{_observers=new Set;_sources=new Set;_state=2;_isEffect=!1;_fn;_value=void 0;_initialized=!1;_running=!1;_equals;constructor(e,t){this._fn=e,this._equals=t,c(()=>i(this))}get(){return r(this),y(this),this._value}peek(){return y(this),this._value}_update(){if(this._running)throw new Error("computed: circular dependency — the computed reads itself.");const e=this._value;i(this);const t=s;s=this,this._running=!0;try{this._value=this._fn()}finally{this._running=!1,s=t}if(this._initialized){if(!this._equals(e,this._value))for(const e of this._observers)e._state=2,e._isEffect&&!e._disposed&&(l.add(e),_())}else this._initialized=!0}}class S{_observers=new Set;_sources=new Set;_owned=[];_state=2;_isEffect=!0;_disposed=!1;_devStack=void 0;_fn;_cleanup=void 0;constructor(e){this._fn=e,t()&&(this._devStack=(new Error).stack),c(()=>this.dispose()),y(this)}_update(){this._runCleanup(),d(this),i(this);const e=s,t=a;s=this,a=this;try{this._cleanup=this._fn()}finally{s=e,a=t}}_runCleanup(){"function"==typeof this._cleanup&&(this._cleanup(),this._cleanup=void 0)}dispose(){this._disposed||(this._disposed=!0,this._runCleanup(),d(this),i(this),l.delete(this))}}function k(e,t=Object.is){return new g(e,t)}function $(e,t=Object.is){return new E(e,t)}function C(e){return t()&&null===a&&o("UNOWNED_EFFECT","","effect created with no owner — it will never be disposed and may leak. Wrap it in createRoot(dispose => …) (or a SignalsElement render()) and dispose on teardown."),new S(e)}function N(e){const t={_owned:[]};let n=!1;const o=()=>{n||(n=!0,d(t))},r=a,i=s;a=t,s=null;try{return e(o)}catch(e){throw o(),e}finally{a=r,s=i}}function L(){return null!==a}function q(e){null===a&&o("ORPHAN_CLEANUP","","onCleanup called with no owner — the cleanup will never run. Call it inside an effect, createRoot, or a SignalsElement render()."),c(e)}const R=Symbol("bindNode.disposed");class I extends Error{[R]=!0}function T(e){return"object"==typeof e&&null!==e&&!0===e[R]}function j(e,t){return e[t]}const A=e=>e.detail;function x(e,t){const n=e,o=t??n.constructor.wcBindable;if(!o)throw new Error("bindNode: no wc-bindable descriptor provided and none found on target.constructor.wcBindable");const s=new Map(o.properties.map(e=>[e.name,e])),r=new Set((o.inputs??[]).map(e=>e.name)),i=new Set((o.commands??[]).map(e=>e.name)),a={},c=[];let d=!1;const l=(e,t)=>{if(d)throw new I(`bindNode.${e}: "${t}" called after dispose (the adapter is inert).`)};for(const e of o.properties){const t=k(j(n,e.name));a[e.name]=t;const o=e.getter??A,s=e=>{t.set(o(e))};n.addEventListener(e.event,s),c.push(()=>n.removeEventListener(e.event,s)),t.set(j(n,e.name))}return{signals:a,on(e,t={}){l("on",e);const o=s.get(e);if(!o)throw new Error(`bindNode.on: "${e}" is not a declared property on this node.`);const r=t.fold??((e,t)=>t),i=k(t.initial,()=>!1),a=o.getter??A,d=e=>{const t=a(e);i.set(r(i.peek(),t))};return n.addEventListener(o.event,d),c.push(()=>n.removeEventListener(o.event,d)),i},set(e,t){if(l("set",e),!r.has(e))throw new Error(`bindNode.set: "${e}" is not a declared input on this node.`);n[e]=t},bindInput(e,t){if(l("bindInput",e),!r.has(e))throw new Error(`bindNode.bindInput: "${e}" is not a declared input on this node.`);let o;const s=C(()=>{const s=t.get(),r=o;o=s,void 0===s&&void 0===r||n[e]!==s&&(n[e]=s)});return c.push(()=>s.dispose()),()=>s.dispose()},command(e,...t){if(l("command",e),!i.has(e))throw new Error(`bindNode.command: "${e}" is not a declared command on this node.`);if("function"!=typeof n[e])throw new TypeError(`bindNode.command: "${e}" is declared but not a function on the node.`);return n[e](...t)},bindCommand(e,t,o){if(l("bindCommand",e),!i.has(e))throw new Error(`bindNode.bindCommand: "${e}" is not a declared command on this node.`);if("function"!=typeof n[e])throw new TypeError(`bindNode.bindCommand: "${e}" is declared but not a function on the node.`);let s=!1;const r=C(()=>{const r=t.get();if(!s)return void(s=!0);const i=o?o(r):[r];n[e](...i)});return c.push(()=>r.dispose()),()=>r.dispose()},dispose(){if(!d){d=!0;for(const e of c)e()}}}}function z(t,n,o={}){const s=o.abort??"abort";return(o,r)=>(r.addEventListener("abort",()=>{try{t.command(s)}catch(t){T(t)||e(t)}},{once:!0}),n(t,o))}function O(e,t={}){const n=k(t.initial),o=k(!1),s=k(null);let r=null;const i=C(()=>{const i=t.args?t.args():void 0;r?.abort();const a=new AbortController;let c;r=a,o.set(!0),s.set(null);try{c=e(i,a.signal)}catch(e){return s.set(e),void o.set(!1)}Promise.resolve(c).then(e=>{a.signal.aborted||(n.set(e),o.set(!1))},e=>{a.signal.aborted||(s.set(e),o.set(!1))})}),a=()=>{r?.abort(),i.dispose()};return q(a),{value:n,loading:o,error:s,dispose:a}}function D(e,t={}){const n=t.fold??((e,t)=>t),o=k(t.initial),s=k("idle"),r=k(null);let i=null;const a=C(()=>{const a=t.args?t.args():void 0;i?.abort();const c=new AbortController;i=c,o.set(t.initial),r.set(null),s.set("active"),async function(e,t,n,o,s,r,i){let a=null,c=null;const d=()=>{if(a&&a!==c){c=a;try{a.return?.()?.then?.(void 0,()=>{})}catch{}}};n.addEventListener("abort",d,{once:!0});try{const i=await e(t,n);if(a=function(e,t){if("function"==typeof e?.getReader)return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t);if("function"==typeof e?.[Symbol.asyncIterator])return e;throw new TypeError("streamResource: source must return an AsyncIterable or a ReadableStream (got neither).")}(i,n)[Symbol.asyncIterator](),n.aborted)return void d();for(;;){const e=await a.next();if(e.done)break;if(n.aborted)return;s.set(o(s.peek(),e.value))}if(n.aborted)return;r.set("done")}catch(e){if(n.aborted)return;i.set(e),r.set("error")}finally{n.removeEventListener("abort",d)}}(e,a,c.signal,n,o,s,r)}),c=()=>{i?.abort(),a.dispose()};return q(c),{value:o,status:s,error:r,dispose:c}}export{I as D,N as a,x as b,$ as c,D as d,C as e,b as f,t as g,L as h,T as i,z as n,q as o,O as r,k as s,o as w};
2
- //# sourceMappingURL=core-CUHdCgQ2.esm.min.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"core-CUHdCgQ2.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\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}\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 source._observers.delete(node);\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\ninterface Owner {\n _owned: Disposer[];\n}\n\nlet currentOwner: Owner | null = null;\n\nfunction registerDisposer(disposer: Disposer): 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 owned[i]();\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(() => 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 } 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\nclass EffectNode implements Computation, Owner {\n _observers = new Set<Computation>(); // effects are not observed; kept for the interface\n _sources = new Set<Observable>();\n _owned: Disposer[] = [];\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) {\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.dispose());\n updateIfNecessary(this); // initial run (state starts DIRTY)\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 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 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);\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, 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 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, 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, 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","delete","clear","currentOwner","registerDisposer","disposer","_owned","push","disposeOwned","owner","owned","i","length","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","size","Error","updateIfNecessary","flushSync","markStale","level","_state","wasClean","_isEffect","observer","ComputedNode","_update","SignalNode","_value","_equals","constructor","value","equals","this","get","peek","set","next","_fn","undefined","_initialized","_running","fn","previous","prevObserver","EffectNode","_cleanup","stack","dispose","_runCleanup","prevOwner","signal","initial","Object","is","computed","effect","createRoot","disposed","hasOwner","onCleanup","DISPOSED_ERROR","Symbol","DisposedError","isDisposedError","readProperty","target","name","DEFAULT_GETTER","bindNode","descriptor","desc","wcBindable","propByName","Map","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","a","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,EAElB,UCkBgBK,IACd,OAAiE,IAAzDH,WAAyCI,WACnD,CAKA,MAAMC,EAAU,IAAIC,IAWd,SAAUC,EACdC,EACAC,EACAC,KACGC,GAEH,IAAKR,IACH,OAEF,MAAMS,EAAKJ,EAAO,KAAMC,EACpBJ,EAAQQ,IAAID,KAGhBP,EAAQS,IAAIF,GACZX,QAAQc,KAAK,qBAAqBP,MAASE,OAAcC,GAC3D,CCHA,IAAIK,EAAsC,KAE1C,SAASC,EAAMC,GACW,OAApBF,IACFA,EAAgBG,SAASL,IAAII,GAC7BA,EAAOE,WAAWN,IAAIE,GAE1B,CAEA,SAASK,EAAQC,GACf,IAAK,MAAMJ,KAAUI,EAAKH,SACxBD,EAAOE,WAAWG,OAAOD,GAE3BA,EAAKH,SAASK,OAChB,CAiBA,IAAIC,EAA6B,KAEjC,SAASC,EAAiBC,GACH,OAAjBF,GACFA,EAAaG,OAAOC,KAAKF,EAE7B,CAEA,SAASG,EAAaC,GAEpB,MAAMC,EAAQD,EAAMH,OACpB,IAAK,IAAIK,EAAID,EAAME,OAAS,EAAGD,GAAK,EAAGA,IACrCD,EAAMC,KAERD,EAAME,OAAS,CACjB,CAOA,IAAIC,EAAiB,IAAI7B,IACrB8B,GAAiB,EAQrB,MAAMC,EAAgC,GAEtC,SAASC,IAC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