@wcstack/signals 1.22.5 → 1.23.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.
package/README.ja.md CHANGED
@@ -129,6 +129,8 @@ createRoot(() => {
129
129
 
130
130
  動作する完全版は [`examples/signals-live-search`](../../examples/signals-live-search/README.ja.md) にあります。
131
131
 
132
+ > 冒頭の `await customElements.whenDefined(…)` は「**自分がロードしていない**要素に束縛する」ときの形です(パッケージが届かなければ永遠に待ちます)。アプリがノードを自分で持つ場合は、副作用 import + [`mountNode`](#mountnode--ヘッドレスノードの生成から接続まで) を推奨します — await 不要で、ロード失敗は静かなハングではなく明示的なモジュールエラーになります。
133
+
132
134
  ### 6. keyed リスト — `For` / `Index`
133
135
 
134
136
  素のリアクティブ child(`() => items.map(render)`)は変更のたびにサブツリーを丸ごと再生成します。リストには `For`(値/同一性キー)か `Index`(位置キー)を使ってください。各行は安定した DOM 行として保たれ、その場で reconcile されるので、並び替えは行の再生成ではなく移動になります(行ごとの DOM・focus・入力状態を保持)。各行は自身の所有権スコープで走るため、削除された行はその effect だけを破棄します。
@@ -210,6 +212,7 @@ const log = streamResource((args, signal) => openLogStream(signal), {
210
212
  | `Index<T>` | `(list, each) => ListView` | 位置キーのリスト。`each(item: () => T, index: number)` は単一 Node を返す。スロット単位で行を再利用(スロットの値は signal で更新)し、末尾で grow/shrink。 |
211
213
  | `SignalsElement` | `abstract` 基底(遅延 `extends HTMLElement`) | ライフサイクル基底。`render()` を実装、必要なら `getMountPoint()` を上書き。`HTMLElement` は遅延解決され、`./dom` モジュールは非 DOM 環境でも評価可能 — [SSR / 非DOM](#ssr--非dom-dom-エントリは-dom-無しで読み込める)参照。 |
212
214
  | `createSignalsElement` | `() => SignalsElementClass` | `SignalsElement` 基底を(memoize して)呼び出し時に構築。DOM が無ければ分かりやすい Error を投げる。SSR セーフな基底取得手段。 |
215
+ | `mountNode` | `(tagName, { attrs?, parent?, descriptor? }?) => MountedNode` | **定義済み**カスタム要素を生成し、`attrs` を設定、`bindNode` してから接続(既定 `document.body`)。`BoundNode` 全サーフェス + `el` / `unmount()` を返す。タグ未定義なら原因の分かる Error を即 throw — [`mountNode`](#mountnode--ヘッドレスノードの生成から接続まで)参照。 |
213
216
 
214
217
  `setProp` のルール: `style` は文字列またはオブジェクト(camelCase / kebab-case / `--custom` キー)を受け付ける。`class` / `className` は `class` **属性**として設定(SVG でも動く・`null`/`false` でクリア)。書き込み可能な DOM プロパティに解決するキーはプロパティ代入(`null`/`undefined` は `""` に正規化され、`id`/`src` 等の文字列プロパティがリテラル `"null"` ではなくクリアされる)、それ以外は属性(`true` → 空属性、`null`/`false` → 削除)。
215
218
 
@@ -280,6 +283,48 @@ const r = resource(
280
283
  id.set(2); // ノードの abort コマンド経由で進行中の fetch を abort し、再 fetch
281
284
  ```
282
285
 
286
+ #### `mountNode` — ヘッドレスノードの生成から接続まで
287
+
288
+ `bindNode` は**既に存在する**要素を適応します — つまり定義タイミングの保証は呼び出し側の責任です: descriptor は呼び出し時に `el.constructor.wcBindable` から読まれ、upgrade 前の要素はこれを持ちません。アプリがヘッドレス IO ノードを自分で持つ場合、`mountNode` はこの問題系をまるごと消します。定義モジュールを import してから、生成→束縛→接続を1呼び出しで: モジュール評価順が定義を保証するので、`whenDefined` も HTML との順序結合も不要です。
289
+
290
+ ```typescript
291
+ import "@wcstack/fetch/auto"; // <wcs-fetch> を定義 — module graph が順序を保証
292
+ import { mountNode } from "@wcstack/signals/dom";
293
+
294
+ const fetcher = mountNode("wcs-fetch", { attrs: { url: "/api/people" } });
295
+ fetcher.signals.value.get(); // BoundNode 全サーフェス
296
+ fetcher.el; // 生成された要素(接続済み)
297
+ fetcher.unmount(); // dispose() + 要素を除去
298
+ ```
299
+
300
+ 内部の順序が安全契約です: `attrs` は接続**前**に設定され(Shell は `connectedCallback` で設定を読む。`true` → 空属性、`false` → 属性なし、その他は文字列化)、アダプタは接続**前**に購読するので、`connectedCallback` から発火するイベントも取りこぼしません。`parent` の既定は `document.body`。未定義タグは(`whenDefined` の静かな永久保留と違い)**原因の分かる Error を即 throw** します。`descriptor` を明示すると定義チェックはスキップされます(非カスタム要素ターゲット向け・`bindNode` と同じ逃げ道)。**オプショナル**なパッケージは dynamic import と合成します — `whenDefined` と違いロード失敗で *reject* します:
301
+
302
+ ```typescript
303
+ const tilt = signal(null);
304
+ import("@wcstack/tilt/auto")
305
+ .then(() => tilt.set(mountNode("wcs-tilt")))
306
+ .catch(() => {/* 縮退モード — アプリは動き続ける */});
307
+ ```
308
+
309
+ `bindNode` と同様、アダプタはリアクティブオーナーに紐付きません — teardown は明示的(`unmount()` は冪等)で、`onCleanup(() => fetcher.unmount())` と合成できます。`MountedNode` では `dispose()` は **`unmount()` のエイリアス**です: mountNode は要素のライフサイクルを所有するので、パッケージ共通の teardown 動詞が「接続されたまま IO が生きている要素」を残すことはありません。定義タイミングの全体契約(どのロード状況でどのイディオムか)は [`docs/signals-definition-timing.md`](../../docs/signals-definition-timing.md) を参照してください。
310
+
311
+ #### Core を直接束縛する(要素なし)
312
+
313
+ wcstack の I/O ノードはフレームワーク非依存の **Core** とカスタム要素の **Shell** に分層しており、Core 単体で完結した wc-bindable ノードです: `extends EventTarget`・既定で自分自身にイベントを dispatch(`constructor(target?)`・`target ?? this`)・観測プロパティは getter・`static wcBindable` 保持。よって `bindNode` は第2引数なしで `core.constructor` から descriptor を解決します:
314
+
315
+ ```typescript
316
+ import { FetchCore } from "@wcstack/fetch";
317
+
318
+ const core = new FetchCore();
319
+ const bound = bindNode(core); // FetchCore.wcBindable から解決 — 要素は一切関与しない
320
+ core.fetch("/api/user"); // command は素のメソッド
321
+ bound.signals.value.get();
322
+ ```
323
+
324
+ カスタム要素が存在しないので、**定義タイミング問題は丸ごと消滅**します: `customElements` レジストリに一切触れず、`whenDefined` も upgrade 待ちも無く、依存は import だけです。これは本パッケージの建国実証でもあります — アダプタは要素が関与する前に、無改変の実 `FetchCore` で検証されました(`__tests__/integration.fetchCore.test.ts`)。
325
+
326
+ Shell と比べて失うもの: 要素接続ライフサイクル(Core の `observe()`/`dispose()` や start/stop コマンドを自分で駆動 — `onCleanup(() => core.dispose())` と合成)、属性ベース設定、`:state()` CSS 反映(Shell/ElementInternals 専用機能)。向くのは純ロジックノード(fetch・websocket・timer・defined・raf など)で、要素結合ノード(intersection/resize の観測対象・camera プレビュー・fullscreen)では Shell が引き続き価値を持ちます。Core の構造サーフェス — `EventTarget` 継承・自己 dispatch 既定・`static wcBindable`・getter で読める observable・`observe()`/`dispose()`/`ready`・never-throw — は **wcstack I/O ノード横断の規範**([`docs/async-io-node-guidelines.md`](../../docs/async-io-node-guidelines.md) §3.9)で semver 保護されます。コンストラクタの**設定引数**だけはパッケージ個別です — 各パッケージ README のヘッドレス利用節を参照してください。
327
+
283
328
  ## JSX を使う(opt-in)
284
329
 
285
330
  `h` は古典的な JSX ファクトリの形なので、JSX は**使えるが同梱しない** — オプトインは利用者の選択であり、buildless 経路を抜けることを意味します(JSX はトランスパイル必須)。パッケージが出荷するのは土台(`h` + `Fragment`)のみで、`.tsx` も `jsx-runtime` 型も含みません。
@@ -332,7 +377,7 @@ esbuild / tsc / Vite の設定例・検証用 `.tsx` 例・トラブルシュー
332
377
  | **エラー契約** | `DisposedError` / `isDisposedError` | **Stable** — ブランドベース・realm セーフ。 |
333
378
  | **リソース** | `resource` / `streamResource` | **Stable**(概ね)。形は確定済み。ただし `streamResource` の協調キャンセル契約に注意(`source` は `AbortSignal` を必ず honor すること — [注意・制限](#注意制限)参照)。 |
334
379
  | **wc-bindable アダプタ** | `bindNode` / `nodeSource` | **Evolving / experimental** — 実行時挙動は安定だが、**型サーフェス**(`bindNode<NodeShape>`・`NodeShape`)はまだ調整余地あり。 |
335
- | **DOM レイヤ** | `h` / `render` / `Fragment` / `For` / `Index` / `setProp` / `SignalsElement` / `createSignalsElement` / `ListView` | **Evolving / experimental** — 今すぐ使えるが、安定昇格までにシグネチャや要素ファクトリの形が変わりうる。 |
380
+ | **DOM レイヤ** | `h` / `render` / `Fragment` / `For` / `Index` / `setProp` / `SignalsElement` / `createSignalsElement` / `ListView` / `mountNode` | **Evolving / experimental** — 今すぐ使えるが、安定昇格までにシグネチャや要素ファクトリの形が変わりうる。 |
336
381
  | **開発モード** | `globalThis.__WCS_DEV__` と各警告コード | **Experimental** — 診断専用。警告の集合や文言はいつでも変わりうる。本番では一切動かない。 |
337
382
 
338
383
  **deprecation ポリシー。** **1.x** の系列内では、**安定**な API は後方互換を維持します: 非互換な変更は、導入の最低 1 マイナーリリース前に deprecation として告知します。**evolving / experimental** とマークされた API は、マイナーリリースで変わりうる(シグネチャ・型の形・警告文言)ので、現在の形に依存する場合は厳密なバージョンを pin してください。
@@ -349,14 +394,14 @@ esbuild / tsc / Vite の設定例・検証用 `.tsx` 例・トラブルシュー
349
394
 
350
395
  ## ヘッドレス利用
351
396
 
352
- リアクティブコアは DOM 非依存です — `signal` / `computed` / `effect` / `resource` / `streamResource` / `bindNode` / `nodeSource` はすべてプレーンな JS(Node・worker・テスト)で動きます。`document` に触れるのは `/dom` エントリ(`h` / `For` / `Index` / `SignalsElement`)だけです。
397
+ リアクティブコアは DOM 非依存です — `signal` / `computed` / `effect` / `resource` / `streamResource` / `bindNode` / `nodeSource` はすべてプレーンな JS(Node・worker・テスト)で動きます。`document` に触れるのは `/dom` エントリ(`h` / `For` / `Index` / `SignalsElement` / `mountNode`)だけです。I/O ノードパッケージの **Core** クラスはそれ自体が `wcBindable` を持つ `EventTarget` なので、完全に要素なしのパイプラインも組めます — [Core を直接束縛する](#core-を直接束縛する要素なし)参照。
353
398
 
354
399
  ### SSR / 非DOM: `./dom` エントリは DOM 無しで読み込める
355
400
 
356
401
  2 つのエントリは**評価時**の要件が異なります:
357
402
 
358
403
  - **`.` エントリ(`@wcstack/signals`)** — 完全に非 DOM。SSR・Node・Web Worker で DOM グローバル無しに評価・実行できます。
359
- - **`./dom` エントリ(`@wcstack/signals/dom`)** — DOM 無しでも**評価**できます: SSR 前処理(や worker)でヘッドレス再エクスポート目的に import しても `ReferenceError: HTMLElement is not defined` で落ちません。DOM に触れる*サーフェス* — `h` / `render` / `For` / `Index` と `SignalsElement` 基底 — は実際に**使用**する時点で DOM グローバルを**要求**します。
404
+ - **`./dom` エントリ(`@wcstack/signals/dom`)** — DOM 無しでも**評価**できます: SSR 前処理(や worker)でヘッドレス再エクスポート目的に import しても `ReferenceError: HTMLElement is not defined` で落ちません。DOM に触れる*サーフェス* — `h` / `render` / `For` / `Index`・`SignalsElement` 基底・`mountNode`(DOM 無しで呼ぶと分かりやすい Error) — は実際に**使用**する時点で DOM グローバルを**要求**します。
360
405
 
361
406
  `SignalsElement` は `HTMLElement` を遅延解決します: 基底クラスはモジュールロード時ではなく初回のサブクラス化/使用時に構築されます。よってブラウザでは `class X extends SignalsElement {}` が従来どおり動き、非 DOM 文脈での `import "@wcstack/signals/dom"` も安全です。両環境で動くコードでは基底を明示取得する `createSignalsElement()` を使ってください — 呼び出し時に(memoize して)基底を構築し、`HTMLElement` が無ければ生の `ReferenceError` ではなく**分かりやすい Error** を投げます:
362
407
 
@@ -371,7 +416,7 @@ class MyEl extends Base { protected render() { /* … */ } }
371
416
 
372
417
  - **言語ターゲット: ES2022。** 出荷バンドルはモダン構文(private class field・`??`・top-level `const`/`class`)とランタイム機能を使います: `queueMicrotask`(effect スケジューリング)・`AbortController` / `AbortSignal`(`resource` / `streamResource` のキャンセル)・`WeakMap` / `WeakSet`(`bindNode` / DOM キャッシュ)、そして `streamResource` のみ `ReadableStream` + async iteration。
373
418
  - **最低ブラウザ(evergreen):** Chrome / Edge **94+**・Firefox **90+**・**Safari 16.4+**(現実的な下限 — `ReadableStream` の async iteration・Custom Elements・private field 対応がこのあたりで揃う)。Custom Elements(`SignalsElement`)には実 DOM が必要ですが、それ以外は DOM 無しで動きます。
374
- - **2 エントリ・2 環境。** `.` エントリ(`@wcstack/signals`: コア / `resource` / `streamResource` / `bindNode` / `nodeSource`)は**非 DOM** — SSR・Node・Web Worker で動きます。`./dom` エントリ(`@wcstack/signals/dom`: `h` / `render` / `For` / `Index` / `SignalsElement`)も DOM 無しで**評価**できるようになりました(SSR 前処理での import で落ちない)が、DOM に触れるサーフェスは使用時に DOM グローバル(`document`・`HTMLElement`)を要求します。[SSR / 非DOM](#ssr--非dom-dom-エントリは-dom-無しで読み込める)参照。
419
+ - **2 エントリ・2 環境。** `.` エントリ(`@wcstack/signals`: コア / `resource` / `streamResource` / `bindNode` / `nodeSource`)は**非 DOM** — SSR・Node・Web Worker で動きます。`./dom` エントリ(`@wcstack/signals/dom`: `h` / `render` / `For` / `Index` / `SignalsElement` / `mountNode`)も DOM 無しで**評価**できるようになりました(SSR 前処理での import で落ちない)が、DOM に触れるサーフェスは使用時に DOM グローバル(`document`・`HTMLElement`)を要求します。[SSR / 非DOM](#ssr--非dom-dom-エントリは-dom-無しで読み込める)参照。
375
420
 
376
421
  ## バンドルサイズ
377
422
 
@@ -379,8 +424,8 @@ class MyEl extends Base { protected render() { /* … */ } }
379
424
 
380
425
  | エントリ | gzip |
381
426
  |---|---|
382
- | 共有リアクティブコア chunk(`core-*.esm.min.js`) | **≈ 2.5 KB** |
383
- | `./dom` レイヤ chunk(`dom.esm.min.js`・共有コアの上乗せ分) | **≈ 2.1 KB** |
427
+ | 共有リアクティブコア chunk(`core-*.esm.min.js`) | **≈ 3.1 KB** |
428
+ | `./dom` レイヤ chunk(`dom.esm.min.js`・共有コアの上乗せ分) | **≈ 3.8 KB** |
384
429
 
385
430
  公開される両エントリは**1 つ**の共有コア chunk を import する([Buildless](#buildlessimport-map)参照)ので、両方使うページでもコアの分は一度だけです。`package.json` は `"sideEffects": false` を宣言するので、import しないものはバンドラが tree-shake で除去します。
386
431
 
package/README.md CHANGED
@@ -129,6 +129,8 @@ createRoot(() => {
129
129
 
130
130
  A full, runnable version of this lives in [`examples/signals-live-search`](../../examples/signals-live-search/README.md).
131
131
 
132
+ > The `await customElements.whenDefined(…)` above is the shape for binding an element **you did not load** (and it waits forever if the package never arrives). When your app owns the node, prefer a side-effect import plus [`mountNode`](#mountnode--create-bind-and-mount-a-headless-node-wcstacksignalsdom) — no await, and a load failure is a loud module error instead of a silent hang.
133
+
132
134
  ### 6. Keyed lists — `For` / `Index`
133
135
 
134
136
  A bare reactive child (`() => items.map(render)`) rebuilds its whole subtree on every change. For lists, use `For` (keyed by value/identity) or `Index` (keyed by position) — each keeps a stable DOM row per item and reconciles in place, so reordering moves rows instead of rebuilding them (preserving per-row DOM, focus, and input state). Each row runs under its own ownership scope, so a removed row disposes exactly its effects.
@@ -210,6 +212,7 @@ const log = streamResource((args, signal) => openLogStream(signal), {
210
212
  | `Index<T>` | `(list, each) => ListView` | Position-keyed list. `each(item: () => T, index: number)` returns one Node. Rows are reused per slot (the value at a slot updates via a signal); grows/shrinks at the tail. |
211
213
  | `SignalsElement` | `abstract` base (lazy `extends HTMLElement`) | Lifecycle base; implement `render()`, optionally `getMountPoint()`. `HTMLElement` is resolved lazily so the `./dom` module evaluates in non-DOM environments — see [SSR / non-DOM](#ssr--non-dom-the-dom-entry-loads-without-a-dom). |
212
214
  | `createSignalsElement` | `() => SignalsElementClass` | Build (memoized) the `SignalsElement` base at call time. Resolves `HTMLElement` when called; throws a clear error if no DOM. The SSR-safe way to obtain the base. |
215
+ | `mountNode` | `(tagName, { attrs?, parent?, descriptor? }?) => MountedNode` | Create a **defined** custom element, set `attrs`, `bindNode` it, then append (default `document.body`). Returns the full `BoundNode` plus `el` / `unmount()`. Throws a descriptive error if the tag isn't defined yet — see [`mountNode`](#mountnode--create-bind-and-mount-a-headless-node-wcstacksignalsdom). |
213
216
 
214
217
  `setProp` rules: `style` accepts a string or an object (camelCase / kebab-case / `--custom` keys); `class` / `className` are set as the `class` **attribute** (works for SVG too; `null`/`false` clear it); a key that resolves to a writable DOM property is assigned as a property (with `null`/`undefined` normalized to `""` so a string prop like `id`/`src` clears instead of landing the literal `"null"`); otherwise it's an attribute (`true` → empty attr, `null`/`false` → removed).
215
218
 
@@ -282,6 +285,48 @@ const r = resource(
282
285
  id.set(2); // aborts the in-flight fetch via the node's abort command, then refetches
283
286
  ```
284
287
 
288
+ #### `mountNode` — create, bind, and mount a headless node (`@wcstack/signals/dom`)
289
+
290
+ `bindNode` adapts an element that already exists — which makes **you** responsible for definition timing: the descriptor is read from `el.constructor.wcBindable` at call time, and an un-upgraded element has none. When the app owns its headless IO nodes, `mountNode` removes that whole class of problems. Import the defining module, then create-bind-connect in one call: module evaluation order guarantees the definition — no `whenDefined`, no ordering coupling with the HTML.
291
+
292
+ ```typescript
293
+ import "@wcstack/fetch/auto"; // defines <wcs-fetch> — the module graph guarantees the order
294
+ import { mountNode } from "@wcstack/signals/dom";
295
+
296
+ const fetcher = mountNode("wcs-fetch", { attrs: { url: "/api/people" } });
297
+ fetcher.signals.value.get(); // the full BoundNode surface
298
+ fetcher.el; // the created element (connected)
299
+ fetcher.unmount(); // dispose() + remove the element
300
+ ```
301
+
302
+ The internal order is the safety contract: `attrs` are set **before** connect (shells read their config in `connectedCallback`; `true` → empty attribute, `false` → omitted, other values stringified), and the adapter subscribes **before** connect, so an event fired from `connectedCallback` is already observed. `parent` defaults to `document.body`. An undefined tag throws a **descriptive error immediately** (vs. `whenDefined`'s silent forever-pending); an explicit `descriptor` skips the check (non-custom-element targets, mirroring `bindNode`). An **optional** package composes with dynamic import, which — unlike `whenDefined` — *rejects* on load failure:
303
+
304
+ ```typescript
305
+ const tilt = signal(null);
306
+ import("@wcstack/tilt/auto")
307
+ .then(() => tilt.set(mountNode("wcs-tilt")))
308
+ .catch(() => {/* degraded mode — the app keeps running */});
309
+ ```
310
+
311
+ Like `bindNode`, the adapter is not tied to a reactive owner — teardown is explicit (`unmount()` is idempotent), composable with `onCleanup(() => fetcher.unmount())`. On a `MountedNode`, `dispose()` is an **alias of `unmount()`**: mountNode owns the element's lifecycle, so the package-wide teardown verb never leaves a connected element with live IO behind. See [`docs/signals-definition-timing.md`](../../docs/signals-definition-timing.md) for the full definition-timing contract (which idiom for which loading situation).
312
+
313
+ #### Binding a Core directly (no element)
314
+
315
+ Every wcstack IO node splits into a framework-agnostic **Core** and a custom-element **Shell** — and the Core alone is a complete wc-bindable node: it `extends EventTarget`, dispatches its events on itself by default (`constructor(target?)`, `target ?? this`), exposes its observable properties as getters, and carries `static wcBindable` — so `bindNode` resolves the descriptor from `core.constructor` with no second argument:
316
+
317
+ ```typescript
318
+ import { FetchCore } from "@wcstack/fetch";
319
+
320
+ const core = new FetchCore();
321
+ const bound = bindNode(core); // descriptor read from FetchCore.wcBindable — no element involved
322
+ core.fetch("/api/user"); // commands are plain methods
323
+ bound.signals.value.get();
324
+ ```
325
+
326
+ Because no custom element exists, the **definition-timing question disappears entirely**: nothing touches the `customElements` registry — no `whenDefined`, no upgrade to wait for; the import is the only dependency. This is also this package's founding demonstration — the adapter was validated against an unmodified `FetchCore` before any element was involved (`__tests__/integration.fetchCore.test.ts`).
327
+
328
+ Relative to the Shell you give up: element-connected lifecycle (drive the Core's `observe()`/`dispose()` — or its start/stop commands — yourself, e.g. `onCleanup(() => core.dispose())`), attribute-based config, and `:state()` CSS reflection (a Shell/ElementInternals feature). It fits pure-logic nodes (fetch, websocket, timer, defined, raf, …); element-coupled nodes (intersection/resize targets, camera preview, fullscreen) keep earning their Shell. The structural Core surface — `EventTarget` inheritance, self-dispatch default, `static wcBindable`, getter-readable observables, `observe()`/`dispose()`/`ready`, never-throw — is **normative across wcstack IO nodes** ([`docs/async-io-node-guidelines.md`](../../docs/async-io-node-guidelines.md) §3.9) and semver-protected; constructor **config** parameters remain per-package — see each package README's Headless usage section.
329
+
285
330
  ## Using JSX (opt-in)
286
331
 
287
332
  `h` is the classic JSX factory shape, so JSX is **available but not shipped** — opting in is your choice and means leaving the buildless path (JSX must be transpiled). The package ships only the substrate (`h` + `Fragment`); there is no `.tsx` and no `jsx-runtime` types.
@@ -334,7 +379,7 @@ The package version is **1.x**, but the public surface is split into a **stable*
334
379
  | **Error contract** | `DisposedError` / `isDisposedError` | **Stable** — brand-based, realm-safe. |
335
380
  | **Resources** | `resource` / `streamResource` | **Stable** (mostly). The shapes are settled; note the `streamResource` cooperative-cancellation contract (the `source` MUST honor its `AbortSignal` — see [Notes & limitations](#notes--limitations)). |
336
381
  | **wc-bindable adapter** | `bindNode` / `nodeSource` | **Evolving / experimental** — runtime behaviour is stable, but the **typed surface** (`bindNode<NodeShape>`, `NodeShape`) may still be tuned. |
337
- | **DOM layer** | `h` / `render` / `Fragment` / `For` / `Index` / `setProp` / `SignalsElement` / `createSignalsElement` / `ListView` | **Evolving / experimental** — usable today; signatures and the element factory shape may adjust before they are promoted to stable. |
382
+ | **DOM layer** | `h` / `render` / `Fragment` / `For` / `Index` / `setProp` / `SignalsElement` / `createSignalsElement` / `ListView` / `mountNode` | **Evolving / experimental** — usable today; signatures and the element factory shape may adjust before they are promoted to stable. |
338
383
  | **Development mode** | `globalThis.__WCS_DEV__` + the warning codes | **Experimental** — diagnostics only; the set of warnings and their wording may change at any time. It never runs in production. |
339
384
 
340
385
  **Deprecation policy.** Within the **1.x** line, the **stable** APIs keep backward compatibility: any incompatible change is announced as a deprecation at least one minor release before it lands. APIs marked **evolving / experimental** may change in a minor release (signatures, type shapes, or warning wording) — pin an exact version if you depend on their current shape.
@@ -351,14 +396,14 @@ The package version is **1.x**, but the public surface is split into a **stable*
351
396
 
352
397
  ## Headless usage
353
398
 
354
- The reactive core has no DOM dependency — `signal` / `computed` / `effect` / `resource` / `streamResource` / `bindNode` / `nodeSource` all work in plain JS (Node, workers, tests). Only the `/dom` entry (`h` / `For` / `Index` / `SignalsElement`) touches `document`.
399
+ The reactive core has no DOM dependency — `signal` / `computed` / `effect` / `resource` / `streamResource` / `bindNode` / `nodeSource` all work in plain JS (Node, workers, tests). Only the `/dom` entry (`h` / `For` / `Index` / `SignalsElement` / `mountNode`) touches `document`. The IO-node packages' **Core** classes are themselves `EventTarget`s carrying `wcBindable`, so fully element-free pipelines are possible — see [Binding a Core directly](#binding-a-core-directly-no-element).
355
400
 
356
401
  ### SSR / non-DOM: the `./dom` entry loads without a DOM
357
402
 
358
403
  The two entries have distinct **evaluation-time** requirements:
359
404
 
360
405
  - **`.` entry (`@wcstack/signals`)** — fully non-DOM. It evaluates and runs in SSR, Node, and Web Workers with no DOM globals.
361
- - **`./dom` entry (`@wcstack/signals/dom`)** — **evaluates** without a DOM too: importing it for the headless re-exports in an SSR pre-pass (or a worker) no longer throws `ReferenceError: HTMLElement is not defined`. The DOM-touching *surface* — `h` / `render` / `For` / `Index` and the `SignalsElement` base — still **requires** DOM globals when actually **used**.
406
+ - **`./dom` entry (`@wcstack/signals/dom`)** — **evaluates** without a DOM too: importing it for the headless re-exports in an SSR pre-pass (or a worker) no longer throws `ReferenceError: HTMLElement is not defined`. The DOM-touching *surface* — `h` / `render` / `For` / `Index`, the `SignalsElement` base, and `mountNode` (which throws a clear error when called without a DOM) — still **requires** DOM globals when actually **used**.
362
407
 
363
408
  `SignalsElement` resolves `HTMLElement` lazily: the base class is built on first subclass/use, not at module load. So `class X extends SignalsElement {}` still works as before in a browser, while `import "@wcstack/signals/dom"` is safe in a non-DOM context. To obtain the base explicitly (e.g. in code that runs in both), call `createSignalsElement()` — it builds the (memoized) base when called, and **throws a clear error** if there is no `HTMLElement`, instead of a raw `ReferenceError`:
364
409
 
@@ -373,7 +418,7 @@ class MyEl extends Base { protected render() { /* … */ } }
373
418
 
374
419
  - **Language target: ES2022.** The shipped bundles use modern syntax (private class fields, `??`, top-level `const`/`class`) and runtime features: `queueMicrotask` (effect scheduling), `AbortController` / `AbortSignal` (`resource` / `streamResource` cancellation), `WeakMap` / `WeakSet` (`bindNode` / DOM caches), and — for `streamResource` only — `ReadableStream` + async iteration.
375
420
  - **Minimum browsers (evergreen):** Chrome / Edge **94+**, Firefox **90+**, **Safari 16.4+** (the practical floor — `ReadableStream` async iteration and Custom Elements / private-field support all align around there). Custom Elements (`SignalsElement`) require a real DOM; everything else runs without one.
376
- - **Two entries, two environments.** The `.` entry (`@wcstack/signals`: core / `resource` / `streamResource` / `bindNode` / `nodeSource`) is **non-DOM** — it runs in SSR, Node, and Web Workers. The `./dom` entry (`@wcstack/signals/dom`: `h` / `render` / `For` / `Index` / `SignalsElement`) now also **evaluates** without a DOM (so an SSR pre-pass importing it does not crash), but its DOM-touching surface requires DOM globals (`document`, `HTMLElement`) when used. See [SSR / non-DOM](#ssr--non-dom-the-dom-entry-loads-without-a-dom).
421
+ - **Two entries, two environments.** The `.` entry (`@wcstack/signals`: core / `resource` / `streamResource` / `bindNode` / `nodeSource`) is **non-DOM** — it runs in SSR, Node, and Web Workers. The `./dom` entry (`@wcstack/signals/dom`: `h` / `render` / `For` / `Index` / `SignalsElement` / `mountNode`) now also **evaluates** without a DOM (so an SSR pre-pass importing it does not crash), but its DOM-touching surface requires DOM globals (`document`, `HTMLElement`) when used. See [SSR / non-DOM](#ssr--non-dom-the-dom-entry-loads-without-a-dom).
377
422
 
378
423
  ## Bundle size
379
424
 
@@ -381,8 +426,8 @@ Zero runtime dependencies. Measured gzipped sizes of the minified bundles:
381
426
 
382
427
  | Entry | gzip |
383
428
  |---|---|
384
- | Shared reactive core chunk (`core-*.esm.min.js`) | **≈ 2.5 KB** |
385
- | `./dom` layer chunk (`dom.esm.min.js`, on top of the shared core) | **≈ 2.1 KB** |
429
+ | Shared reactive core chunk (`core-*.esm.min.js`) | **≈ 3.1 KB** |
430
+ | `./dom` layer chunk (`dom.esm.min.js`, on top of the shared core) | **≈ 3.8 KB** |
386
431
 
387
432
  Both published entries import the **one** shared core chunk (see [Buildless](#buildless-import-maps)), so a page using both pays for the core only once. `package.json` declares `"sideEffects": false`, so a bundler tree-shakes away anything you don't import.
388
433
 
@@ -0,0 +1,2 @@
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 s(e,s,o,...r){if(!t())return;const i=e+"\0"+s;n.has(i)||(n.add(i),console.warn(`[wcstack/signals][${e}] ${o}`,...r))}let o=null;function r(e){null!==o&&(o._sources.add(e),e._observers.add(o))}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(b))}const p=1e3;function w(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 b(){u=!1;let n=0,s=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)."+(s?w(s):""));const o=l;l=h(),t()&&(s=[...o]);for(const t of o)if(!t._disposed)try{g(t)}catch(t){e(t)}o.clear(),f.push(o)}}function v(){b()}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 g(e){if(0!==e._state){if(1===e._state)for(const t of e._sources)if(t instanceof E&&(g(t),2===e._state))break;try{2===e._state&&e._update()}finally{e._state=0}}}class y{_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),g(this),this._value}peek(){return g(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=o;o=this,this._running=!0;try{this._value=this._fn()}finally{this._running=!1,o=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()),g(this)}_update(){this._runCleanup(),d(this),i(this);const e=o,t=a;o=this,a=this;try{this._cleanup=this._fn()}finally{o=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 y(e,t)}function $(e,t=Object.is){return new E(e,t)}function C(e){return t()&&null===a&&s("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 s=()=>{n||(n=!0,d(t))},r=a,i=o;a=t,o=null;try{return e(s)}catch(e){throw s(),e}finally{a=r,o=i}}function L(){return null!==a}function q(e){null===a&&s("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]}function A(e,t){const n=e,s=t??n.constructor.wcBindable;if(!s)throw new Error("bindNode: no wc-bindable descriptor provided and none found on target.constructor.wcBindable");const o=new Map(s.properties.map(e=>[e.name,e])),r=new Set((s.inputs??[]).map(e=>e.name)),i=new Set((s.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 s.properties){const t=k(j(n,e.name));a[e.name]=t;const s=s=>{t.set(e.getter?e.getter(s):j(n,e.name))};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 s=o.get(e);if(!s)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=t=>{const o=s.getter?s.getter(t):j(n,e);i.set(r(i.peek(),o))};return n.addEventListener(s.event,a),c.push(()=>n.removeEventListener(s.event,a)),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.`);const s=C(()=>{const s=t.get();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,s){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 o=!1;const r=C(()=>{const r=t.get();if(!o)return void(o=!0);const i=s?s(r):[r];n[e](...i)});return c.push(()=>r.dispose()),()=>r.dispose()},dispose(){if(!d){d=!0;for(const e of c)e()}}}}function x(t,n,s={}){const o=s.abort??"abort";return(s,r)=>(r.addEventListener("abort",()=>{try{t.command(o)}catch(t){T(t)||e(t)}},{once:!0}),n(t,s))}function z(e,t={}){const n=k(t.initial),s=k(!1),o=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,s.set(!0),o.set(null);try{c=e(i,a.signal)}catch(e){return o.set(e),void s.set(!1)}Promise.resolve(c).then(e=>{a.signal.aborted||(n.set(e),s.set(!1))},e=>{a.signal.aborted||(o.set(e),s.set(!1))})}),a=()=>{r?.abort(),i.dispose()};return q(a),{value:n,loading:s,error:o,dispose:a}}function O(e,t={}){const n=t.fold??((e,t)=>t),s=k(t.initial),o=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,s.set(t.initial),r.set(null),o.set("active"),async function(e,t,n,s,o,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(),s=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",s,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",s),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;o.set(s(o.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,s,o,r)}),c=()=>{i?.abort(),a.dispose()};return q(c),{value:s,status:o,error:r,dispose:c}}export{I as D,N as a,A as b,$ as c,O as d,C as e,v as f,t as g,L as h,T as i,x as n,q as o,z as r,k as s,s as w};
2
+ //# sourceMappingURL=core-CkLM5R83.esm.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core-CkLM5R83.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)` or the property `name`.\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. Returns a disposer; the effect is also torn down by `dispose()`.\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/**\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 handler = (event: Event): void => {\n cell.set(prop.getter ? prop.getter(event) : readProperty(node, prop.name));\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.\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 handler = (event: Event): void => {\n const chunk = (propDesc.getter ? propDesc.getter(event) : readProperty(node, prop)) 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 const handle = effect(() => {\n const v = source.get();\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","bindNode","descriptor","desc","wcBindable","propByName","Map","properties","p","declaredInputs","inputs","declaredCommands","commands","c","signals","removers","assertLive","op","prop","cell","handler","event","getter","addEventListener","removeEventListener","on","options","propDesc","fold","_acc","chunk","bindInput","handle","v","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","read","releaseLock","readableToAsyncIterable","asyncIterator","iterate","result","consume"],"mappings":"AAOM,SAAUA,EAAYC,GAC1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