@wcstack/signals 4.1.0 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +5 -3
- package/README.md +6 -4
- package/dist/core-BBzx9zgt.esm.min.js +2 -0
- package/dist/core-BBzx9zgt.esm.min.js.map +1 -0
- package/dist/{core-GLSUraaa.esm.js → core-kS9CKPFP.esm.js} +0 -0
- package/dist/core-kS9CKPFP.esm.js.map +1 -0
- package/dist/dom.esm.js +42 -9
- package/dist/dom.esm.js.map +1 -1
- package/dist/dom.esm.min.js +1 -1
- package/dist/dom.esm.min.js.map +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.min.js +1 -1
- package/package.json +1 -1
- package/dist/core-CUHdCgQ2.esm.min.js +0 -2
- package/dist/core-CUHdCgQ2.esm.min.js.map +0 -1
- package/dist/core-GLSUraaa.esm.js.map +0 -1
package/README.ja.md
CHANGED
|
@@ -328,7 +328,7 @@ id.set(2); // ノードの abort コマンド経由で進行中の fetch を abo
|
|
|
328
328
|
|
|
329
329
|
#### `mountNode` — ヘッドレスノードの生成から接続まで
|
|
330
330
|
|
|
331
|
-
`bindNode` は**既に存在する**要素を適応します — つまり定義タイミングの保証は呼び出し側の責任です: descriptor は呼び出し時に `el.constructor.wcBindable` から読まれ、upgrade
|
|
331
|
+
`bindNode` は**既に存在する**要素を適応します — つまり定義タイミングの保証は呼び出し側の責任です: descriptor は呼び出し時に `el.constructor.wcBindable` から読まれ、upgrade 前の要素はこれを持ちません — そのとき `bindNode` は、タグがまだ定義されていないことと、読み込み方・待ち方を言います。アプリがヘッドレス IO ノードを自分で持つ場合、`mountNode` はこの問題系をまるごと消します。定義モジュールを import してから、生成→束縛→接続を1呼び出しで: モジュール評価順が定義を保証するので、`whenDefined` も HTML との順序結合も不要です。
|
|
332
332
|
|
|
333
333
|
```typescript
|
|
334
334
|
import "@wcstack/fetch/auto"; // <wcs-fetch> を定義 — module graph が順序を保証
|
|
@@ -431,7 +431,7 @@ esbuild / tsc / Vite の設定例・検証用 `.tsx` 例・トラブルシュー
|
|
|
431
431
|
- **リストは素のリアクティブ child でなく `For`/`Index` を。** 関数/signal の child は*挿入点*で、実行のたびに以前生成した全ノードを除去し新ノードを挿入します。条件描画や小さい動的領域には十分ですが、リスト(`() => items.map(render)`)では任意の変更でサブツリー全体を再生成し、DOM 再生成コストはサイズに比例、行ごとの状態(focus・編集中の `<input>`/`<select>`・scroll・selection)が失われます。keyed 再利用には [`For`/`Index`](#6-keyed-リスト--for--index)を使ってください。各行は単一 Node です。
|
|
432
432
|
- **backpressure なし(stream)。** fold の結果が*そのまま*バッファです — 需要はプロデューサに伝わりません。無限ストリームには fold を有界に(latest / count / window)してください。無制限の蓄積は罠です。
|
|
433
433
|
- **協調的キャンセル — `source` は `AbortSignal` を必ず honor すること(強い契約)。** これが switchMap の restart/dispose を駆動します。`ReadableStream` は abort 時に `reader.cancel()` で**完全に**巻き戻されます(park した `read()` も強制解決)。プレーンな `AsyncIterable` / async generator は**部分的に**救済されます: abort 時にアダプタが iterator の `return()` を呼び `finally`/クリーンアップを起動しますが、park した `await`(`signal` を*無視*して次の `yield` 前で停止)は外から強制巻き戻しできず、`return()` は generator が次に再開したときに初めて効きます。永久に park して `signal` を一切観測しない generator は `consume()` タスクをリークさせます。**必ず `source` 内で `signal` を観測**してください(例: `signal.aborted` で reject/break)。
|
|
434
|
-
- **`setProp` は主要な属性↔プロパティのケースをカバー(全てではない)。** 小さなリマップ表で `for`→`htmlFor`・`tabindex`→`tabIndex`・`colspan`/`rowspan` 等を処理し、read-only な DOM メンバーは `setAttribute` に退避、SVG タグは SVG 名前空間で生成し `class` は常に属性として設定(SVG でも動く)します。`style` オブジェクトは camelCase・kebab-case・CSS カスタムプロパティ(`--x`)を受け付けます。DOM プロパティへの `null`/`undefined` は `""` に正規化(`id`/`src` 等が `"null"` でなくクリア)されますが、`false` はそのまま据え置きます — boolean プロパティ(`disabled = false`)では正しいので、*文字列*プロパティにリアクティブな `false` が流れると `"false"` になります。この `""` 正規化は**オブジェクト/配列を取るカスタム要素プロパティ**にも及びます — リアクティブな `null` は `null` でなく `""` になるので、クリアするには空配列/空オブジェクトを渡してください。`""` を渡すか thunk でガードを。`class` は特別扱い済み(`false` → `""`)
|
|
434
|
+
- **`setProp` は主要な属性↔プロパティのケースをカバー(全てではない)。** 小さなリマップ表で `for`→`htmlFor`・`tabindex`→`tabIndex`・`colspan`/`rowspan` 等を処理し、read-only な DOM メンバーは `setAttribute` に退避、SVG タグは SVG 名前空間で生成し `class` は常に属性として設定(SVG でも動く)します。`style` オブジェクトは camelCase・kebab-case・CSS カスタムプロパティ(`--x`)を受け付けます。DOM プロパティへの `null`/`undefined` は `""` に正規化(`id`/`src` 等が `"null"` でなくクリア)されますが、`false` はそのまま据え置きます — boolean プロパティ(`disabled = false`)では正しいので、*文字列*プロパティにリアクティブな `false` が流れると `"false"` になります。この `""` 正規化は**オブジェクト/配列を取るカスタム要素プロパティ**にも及びます — リアクティブな `null` は `null` でなく `""` になるので、クリアするには空配列/空オブジェクトを渡してください。`""` を渡すか thunk でガードを。`class` は特別扱い済み(`false` → `""`)。**まだ定義されていない**カスタム要素(`h()` が作った後でモジュールが動く)へのオブジェクト・配列は属性(`"[object Object]"`)にせず、手元に持って、要素が定義されたらその setter で渡します(その間に変われば最後の値)。プリミティブは今までどおり属性です。
|
|
435
435
|
- **依存する値を(毎回変えながら)書き込む effect はループする。** 暴走フラッシュは反復回数の上限で打ち切られ、ハングせずに throw します。
|
|
436
436
|
- **v1 スコープ外。** SSR/hydration(マークアップでなく JS から初期化)・深い/proxy リアクティビティ(パスベースの深い追跡は `@wcstack/state` を使用)・ストリーム backpressure は意図的に非対応です — 設計ドキュメント参照。
|
|
437
437
|
|
|
@@ -489,11 +489,13 @@ class MyEl extends Base { protected render() { /* … */ } }
|
|
|
489
489
|
| コード | 発生条件 | 意味 |
|
|
490
490
|
| --- | --- | --- |
|
|
491
491
|
| `DUPLICATE_KEY` | `For` に同一キーの item が 2 つ。 | レンダリングが**throw**し(本番挙動は不変)リストが更新停止。dev 警告は重複キーと index を示し、静かな「更新停止」症状を診断可能にします。 |
|
|
492
|
-
| `NON_PRIMITIVE_KEY` | `For` を `key` 未指定で使い、item がオブジェクト/関数。 | item の参照同一性がキーになるがレンダ毎に変わる — 全行が作り直され行ごとの状態が失われます。`{ key: item => item.id }`
|
|
492
|
+
| `NON_PRIMITIVE_KEY` | `For` を `key` 未指定で使い、item がオブジェクト/関数。 | item の参照同一性がキーになるがレンダ毎に変わる — 全行が作り直され行ごとの状態が失われます。`{ key: item => item.id }` を渡し、行の item は `each` の第 3 引数 `current()` で読んでください(使い回す行は item が置き換わっても作り直されません)。 |
|
|
493
493
|
| `NULLISH_KEY` | `For` のキーが `null` / `undefined` / `NaN`。 | `SameValueZero` で衝突し、該当行が静かにマージ/脱落します。安定した一意キーを与えてください。 |
|
|
494
494
|
| `UNOWNED_EFFECT` | owner なしで `effect(...)` を生成。 | 誰にも dispose されず、購読ごとリークします。`createRoot(dispose => …)` か `SignalsElement` の `render()` 配下で使ってください。 |
|
|
495
495
|
| `UNOWNED_INSERT` | owner なしで reactive child(`h("div", null, () => …)`)を挿入。 | 更新 effect が dispose されずリークしうる。`createRoot` / `SignalsElement` 配下でマウントしてください。 |
|
|
496
496
|
| `ORPHAN_CLEANUP` | owner 外で `onCleanup(...)` を呼ぶ。 | no-op になり cleanup が実行されません。effect / `createRoot` / `SignalsElement` の `render()` 内で呼んでください。 |
|
|
497
|
+
| `UNTRACKED_COMPUTED` | `computed` の最初の実行が signal を 1 つも読まなかった。 | 二度と再計算されません: 関数の外で読んだ値や `peek()` で読んだ値は、実行したときに固定されます。signal は関数の中で `get()` で読んでください。 |
|
|
498
|
+
| `UNTRACKED_EFFECT` | 自分で書いた `effect` の最初の実行が signal を 1 つも読まず、cleanup も返さず、`onCleanup` も登録せず、何も作らなかった。 | 二度と実行されません。signal は中で `get()` で読んでください(`peek()` は追跡しない)。一度だけ動かす effect は cleanup を返すか `onCleanup` を登録します(`h()`・`For`・アダプタが値のために作る effect は見ません)。 |
|
|
497
499
|
| `REACTIVE_CYCLE` | 暴走サイクルガード(`MAX_FLUSH_ITERATIONS`)が発火。 | dev 時は throw する `Error` メッセージに、最終パスで再実行され続けた effect 群とその生成スタックを付加し、サイクルの原因 effect を特定できます。 |
|
|
498
500
|
|
|
499
501
|
## エラーハンドリング契約
|
package/README.md
CHANGED
|
@@ -331,7 +331,7 @@ id.set(2); // aborts the in-flight fetch via the node's abort command, then refe
|
|
|
331
331
|
|
|
332
332
|
#### `mountNode` — create, bind, and mount a headless node (`@wcstack/signals/dom`)
|
|
333
333
|
|
|
334
|
-
`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.
|
|
334
|
+
`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 — `bindNode` then says the tag is not defined yet and how to load or wait for it. 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.
|
|
335
335
|
|
|
336
336
|
```typescript
|
|
337
337
|
import "@wcstack/fetch/auto"; // defines <wcs-fetch> — the module graph guarantees the order
|
|
@@ -414,7 +414,7 @@ A step-by-step guide (esbuild / tsc / Vite setups, a verifying `.tsx` example, t
|
|
|
414
414
|
Both entries ship as production code-split bundles that import **one shared reactive-core chunk** — but that chunk is imported by **relative path** (`./core-*.esm.js`), so whether a buildless page ends up with one reactive instance depends on how the files are served.
|
|
415
415
|
|
|
416
416
|
- **Map the single `/dom` entry (the recommended CDN form).** `@wcstack/signals/dom` re-exports the entire headless core (`signal` / `computed` / `effect` / `createRoot` / `onCleanup` / `flushSync` / `resource` / `streamResource` / `bindNode` / `nodeSource`) alongside the DOM helpers, so one specifier covers everything and the single instance is structural — nothing depends on chunk sharing. The signals demos in this repo all import from this one entry.
|
|
417
|
-
- **Mapping both specifiers only works from a path-preserving origin.** `.` and `./dom` keep sharing the core only if their relative `./core-*.esm.js` import resolves to the **same URL** — i.e. the whole `dist/` is served as files (self-hosted, or version-pinned path URLs such as `https://cdn.jsdelivr.net/npm/@wcstack/signals@4.
|
|
417
|
+
- **Mapping both specifiers only works from a path-preserving origin.** `.` and `./dom` keep sharing the core only if their relative `./core-*.esm.js` import resolves to the **same URL** — i.e. the whole `dist/` is served as files (self-hosted, or version-pinned path URLs such as `https://cdn.jsdelivr.net/npm/@wcstack/signals@4.2.0/dist/index.esm.js` + `…/dist/dom.esm.js`, both pinned to the same version). A *transforming* ESM endpoint like `https://esm.run/@wcstack/signals` bundles each entry into its own self-contained file, so mapping both esm.run entries ships **two** reactive cores: a signal created through one is invisible to an effect from the other.
|
|
418
418
|
|
|
419
419
|
Bundler users dedupe via the module graph and may use either entry.
|
|
420
420
|
|
|
@@ -439,7 +439,7 @@ The package is versioned with the rest of wcstack (**4.x**: every package is rel
|
|
|
439
439
|
- **Use `For`/`Index` for lists, not a bare reactive child.** A function/signal child is an *insertion point*: on each run every node it produced before is removed and the freshly-resolved nodes inserted. That is fine for conditional/small dynamic regions, but for a list (`() => items.map(render)`) the whole subtree regenerates on any change — DOM-regen cost grows with size and per-row state (focus, an inline `<input>`/`<select>` being edited, scroll, selection) is lost. Use [`For`/`Index`](#6-keyed-lists--for--index) for keyed reuse. Each row must be a single Node.
|
|
440
440
|
- **No backpressure (stream).** The fold result *is* the buffer — demand does not flow back to the producer. Bound the fold (latest / count / window) for infinite streams; unbounded accumulation is a footgun.
|
|
441
441
|
- **Cooperative cancellation — the `source` MUST honor its `AbortSignal` (hard contract).** This is what drives switchMap restart/dispose. A `ReadableStream` is **fully** rescued on abort via `reader.cancel()` (the parked `read()` is force-unwound). A plain `AsyncIterable` / async generator is **partially** rescued: on abort the adapter calls the iterator's `return()` to fire your `finally`/cleanup, but a parked `await` (the producer stalling before its next `yield` while *ignoring* `signal`) cannot be force-unwound from outside — `return()` only takes effect when the generator next resumes. A generator that parks forever and never observes `signal` still leaks its `consume()` task. **Always observe `signal` in your `source`** (e.g. reject/break on `signal.aborted`).
|
|
442
|
-
- **`setProp` covers the common attribute↔property cases, not all.** A small remap table handles `for`→`htmlFor`, `tabindex`→`tabIndex`, `colspan`/`rowspan`, etc.; read-only DOM members fall through to `setAttribute`; SVG tags are created in the SVG namespace and `class` is always set as an attribute (so SVG works). `style` objects accept camelCase, kebab-case, and CSS custom properties (`--x`). `null`/`undefined` on a DOM property are normalized to `""` (so a string prop like `id`/`src` clears, not `"null"`), but `false` is left as-is — correct for boolean props (`disabled = false`), so a reactive `false` on a *string* prop still lands as `"false"`. The same `""` normalization also hits **object/array-valued custom-element props** — a reactive `null` lands as `""`, not `null`; pass an empty array/object to clear such a prop. Pass `""` or guard in the thunk; `class` is special-cased (`false` → `""`).
|
|
442
|
+
- **`setProp` covers the common attribute↔property cases, not all.** A small remap table handles `for`→`htmlFor`, `tabindex`→`tabIndex`, `colspan`/`rowspan`, etc.; read-only DOM members fall through to `setAttribute`; SVG tags are created in the SVG namespace and `class` is always set as an attribute (so SVG works). `style` objects accept camelCase, kebab-case, and CSS custom properties (`--x`). `null`/`undefined` on a DOM property are normalized to `""` (so a string prop like `id`/`src` clears, not `"null"`), but `false` is left as-is — correct for boolean props (`disabled = false`), so a reactive `false` on a *string* prop still lands as `"false"`. The same `""` normalization also hits **object/array-valued custom-element props** — a reactive `null` lands as `""`, not `null`; pass an empty array/object to clear such a prop. Pass `""` or guard in the thunk; `class` is special-cased (`false` → `""`). An object or array given to a custom element that is **not defined yet** (its module runs after `h()` made it) is not written as an attribute (`"[object Object]"`): it is held and assigned through the element's setter once the element is defined — the latest value, if it changed in between. Primitives still go to the attribute.
|
|
443
443
|
- **An effect that writes a value it depends on (mutating each run) loops.** A runaway flush is bounded by a hard iteration cap and throws rather than hanging.
|
|
444
444
|
- **Out of scope for v1.** SSR/hydration (initialize from JS, not markup), deep/proxy reactivity (use `@wcstack/state` for path-based deep tracking), and stream backpressure are deliberately not provided — see the design doc.
|
|
445
445
|
|
|
@@ -497,11 +497,13 @@ Warnings:
|
|
|
497
497
|
| Code | When | Why it matters |
|
|
498
498
|
| --- | --- | --- |
|
|
499
499
|
| `DUPLICATE_KEY` | `For` is given two items with the same key. | Rendering **throws** (production behaviour unchanged) and the list stops updating. The dev warning names the offending key + index so the silent "updates stopped" symptom is diagnosable. |
|
|
500
|
-
| `NON_PRIMITIVE_KEY` | `For` is used **without** a `key` option and the items are objects/functions. | The item's object identity is the key, but it changes across renders — every row is rebuilt and per-row state is lost. Pass `{ key: item => item.id }
|
|
500
|
+
| `NON_PRIMITIVE_KEY` | `For` is used **without** a `key` option and the items are objects/functions. | The item's object identity is the key, but it changes across renders — every row is rebuilt and per-row state is lost. Pass `{ key: item => item.id }`, and read a row's item through `each`'s third argument, `current()`: a kept row is not rebuilt when its item is replaced. |
|
|
501
501
|
| `NULLISH_KEY` | A `For` key resolves to `null` / `undefined` / `NaN`. | These collide under `SameValueZero`, so two such rows silently merge/drop. Provide a stable unique key. |
|
|
502
502
|
| `UNOWNED_EFFECT` | `effect(...)` is created with no enclosing owner. | Nothing will ever dispose it — it (and its subscriptions) leak. Wrap it in `createRoot(dispose => …)` or a `SignalsElement` `render()`. |
|
|
503
503
|
| `UNOWNED_INSERT` | A reactive child (`h("div", null, () => …)`) is inserted with no owner. | Its update effect is never disposed and may leak. Mount under `createRoot` / `SignalsElement`. |
|
|
504
504
|
| `ORPHAN_CLEANUP` | `onCleanup(...)` is called outside any owner. | It is a no-op — the cleanup never runs. Call it inside an effect, `createRoot`, or a `SignalsElement` `render()`. |
|
|
505
|
+
| `UNTRACKED_COMPUTED` | A `computed`'s first run read no signal. | It never recomputes: a value read outside the function, or with `peek()`, was fixed when it ran. Read each signal with `get()` inside it. |
|
|
506
|
+
| `UNTRACKED_EFFECT` | An `effect` you wrote read no signal on its first run, and returned no cleanup, registered no `onCleanup` and built nothing. | It never runs again. Read each signal with `get()` inside it; an effect meant to run once can return its cleanup or register `onCleanup`. (The effects `h()`, `For` and the adapters build for your values are not checked.) |
|
|
505
507
|
| `REACTIVE_CYCLE` | The runaway-cycle guard (`MAX_FLUSH_ITERATIONS`) trips. | In dev the thrown `Error` message is enriched with the effects still re-running on the final pass and the stacks of where they were created, so you can find the cycle's participants. |
|
|
506
508
|
|
|
507
509
|
## Error-handling contract
|
|
@@ -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,...i){if(!t())return;const r=e+"\0"+s;n.has(r)||(n.add(r),console.warn(`[wcstack/signals][${e}] ${o}`,...i))}let o=null;function i(e){null!==o&&(o._sources.add(e),e._observers.add(o))}function r(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(v))}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 v(){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 b(){v()}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 i(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(()=>r(this))}get(){return i(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;r(this);const n=o;o=this,this._running=!0;try{this._value=this._fn()}finally{this._running=!1,o=n}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,t()&&0===this._sources.size&&s("UNTRACKED_COMPUTED",String(this._fn).slice(0,120),"computed read no signal, so it never recomputes: read signals with get() inside it.",this._fn)}}class S{_observers=new Set;_sources=new Set;_owned=[];_state=2;_isEffect=!0;_disposed=!1;_devStack=void 0;_fn;_cleanup=void 0;constructor(e,n=!1){this._fn=e,t()&&(this._devStack=(new Error).stack),c(()=>this.dispose()),g(this),n&&t()&&!this._disposed&&0===this._sources.size&&"function"!=typeof this._cleanup&&0===this._owned.length&&s("UNTRACKED_EFFECT",String(e).slice(0,120),"effect read no signal, so it never runs again: read signals with get() inside it.",e)}_update(){this._runCleanup(),d(this),r(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),r(this),l.delete(this))}}function k(e,t=Object.is){return new y(e,t)}function C(e,t=Object.is){return new E(e,t)}function N(e){const n=!$;return $=!1,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,n)}let $=!1;function L(e){return $=!0,N(e)}function T(e){const t={_owned:[]};let n=!1;const s=()=>{n||(n=!0,d(t))},i=a,r=o;a=t,o=null;try{return e(s)}catch(e){throw s(),e}finally{a=i,o=r}}function R(){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 A=Symbol("bindNode.disposed");class D extends Error{[A]=!0}function j(e){return"object"==typeof e&&null!==e&&!0===e[A]}function z(e,t){return e[t]}const I=e=>e.detail;function O(e,t){const n=e,s=t??n.constructor.wcBindable;if(!s){const t=e.localName;if("string"==typeof t&&t.includes("-")&&"undefined"!=typeof customElements&&void 0===customElements.get(t))throw new Error(`bindNode: <${t}> is not defined yet: load it before this code, or await customElements.whenDefined("${t}").`);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])),i=new Set((s.inputs??[]).map(e=>e.name)),r=new Set((s.commands??[]).map(e=>e.name)),a={},c=[];let d=!1;const l=(e,t)=>{if(d)throw new D(`bindNode.${e}: "${t}" called after dispose (the adapter is inert).`)};for(const e of s.properties){const t=k(z(n,e.name));a[e.name]=t;const s=e.getter??I,o=e=>{t.set(s(e))};n.addEventListener(e.event,o),c.push(()=>n.removeEventListener(e.event,o)),t.set(z(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 i=t.fold??((e,t)=>t),r=k(t.initial,()=>!1),a=s.getter??I,d=e=>{const t=a(e);r.set(i(r.peek(),t))};return n.addEventListener(s.event,d),c.push(()=>n.removeEventListener(s.event,d)),r},set(e,t){if(l("set",e),!i.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),!i.has(e))throw new Error(`bindNode.bindInput: "${e}" is not a declared input on this node.`);let s;const o=L(()=>{const o=t.get(),i=s;s=o,void 0===o&&void 0===i||n[e]!==o&&(n[e]=o)});return c.push(()=>o.dispose()),()=>o.dispose()},command(e,...t){if(l("command",e),!r.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),!r.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 i=L(()=>{const i=t.get();if(!o)return void(o=!0);const r=s?s(i):[i];n[e](...r)});return c.push(()=>i.dispose()),()=>i.dispose()},dispose(){if(!d){d=!0;for(const e of c)e()}}}}function U(t,n,s={}){const o=s.abort??"abort";return(s,i)=>(i.addEventListener("abort",()=>{try{t.command(o)}catch(t){j(t)||e(t)}},{once:!0}),n(t,s))}function x(e,t={}){const n=k(t.initial),s=k(!1),o=k(null);let i=null;const r=L(()=>{const r=t.args?t.args():void 0;i?.abort();const a=new AbortController;let c;i=a,s.set(!0),o.set(null);try{c=e(r,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=()=>{i?.abort(),r.dispose()};return q(a),{value:n,loading:s,error:o,dispose:a}}function F(e,t={}){const n=t.fold??((e,t)=>t),s=k(t.initial),o=k("idle"),i=k(null);let r=null;const a=L(()=>{const a=t.args?t.args():void 0;r?.abort();const c=new AbortController;r=c,s.set(t.initial),i.set(null),o.set("active"),async function(e,t,n,s,o,i,r){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 r=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).")}(r,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;i.set("done")}catch(e){if(n.aborted)return;r.set(e),i.set("error")}finally{n.removeEventListener("abort",d)}}(e,a,c.signal,n,s,o,i)}),c=()=>{r?.abort(),a.dispose()};return q(c),{value:s,status:o,error:i,dispose:c}}export{D,T as a,O as b,C as c,F as d,N as e,b as f,L as g,t as h,j as i,R as j,U as n,q as o,x as r,k as s,s as w};
|
|
2
|
+
//# sourceMappingURL=core-BBzx9zgt.esm.min.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core-BBzx9zgt.esm.min.js","sources":["../src/reportError.ts","../src/dev.ts","../src/reactive.ts","../src/bindNode.ts","../src/resource.ts","../src/streamResource.ts"],"sourcesContent":["// Internal error-reporting policy (NOT part of the public API; not re-exported\n// from exports.ts). Single source of truth for \"surface an error without crashing\".\n//\n// Delegates to the platform `reportError` when present — it dispatches a window\n// \"error\" event / logs to the console without aborting the current task — and falls\n// back to `console.error` otherwise. It NEVER re-throws (re-throwing would abort the\n// caller's drain / abort handler) and NEVER swallows silently (that would hide bugs).\nexport function reportError(err: unknown): void {\n const r = (globalThis as { reportError?: (e: unknown) => void }).reportError;\n if (typeof r === \"function\") {\n r(err);\n } else {\n console.error(err);\n }\n}\n","// Opt-in development diagnostics (NOT part of the public API; not re-exported from\n// exports.ts). Surfaces \"silent failure\" modes — duplicate/unkeyed list rows,\n// un-owned effects that leak, no-op onCleanup, reactive cycles — that production\n// otherwise swallows.\n//\n// DEFAULT OFF. Nothing here runs unless the consumer flips `globalThis.__WCS_DEV__`\n// to `true` BEFORE the failing operation. `isDev()` reads the flag at CALL TIME (not\n// module-load time), so a page can toggle it on for a debugging session without a\n// rebuild. See README \"Development mode\".\n//\n// TREE-SHAKING: the package sets `\"sideEffects\": false`, and every export here is a\n// pure function with no module-top-level side effects (the dedupe cache is a lazily-\n// populated Set, not eager work). A production bundler that never references warnDev\n// can drop this module entirely; a bundler that does keep it still pays nothing at\n// runtime because `warnDev` short-circuits on the `isDev()` guard before touching the\n// dedupe Set or formatting a message.\n\n/** Stable warning codes, so docs/tests can reference a warning without matching prose. */\nexport type DevWarningCode =\n | \"DUPLICATE_KEY\"\n | \"NON_PRIMITIVE_KEY\"\n | \"NULLISH_KEY\"\n | \"UNOWNED_EFFECT\"\n | \"UNOWNED_INSERT\"\n | \"ORPHAN_CLEANUP\"\n | \"REACTIVE_CYCLE\"\n | \"UNTRACKED_COMPUTED\"\n | \"UNTRACKED_EFFECT\";\n\n/**\n * True only when the consumer has opted in via `globalThis.__WCS_DEV__ === true`.\n * Read at call time so the flag can be toggled at runtime. Kept tiny and pure so a\n * production bundle that strips dev branches pays nothing.\n */\nexport function isDev(): boolean {\n return (globalThis as { __WCS_DEV__?: boolean }).__WCS_DEV__ === true;\n}\n\n// Dedupe set: a given (code + dedupe-key) warning is emitted at most once, so a\n// per-row or per-flush failure does not flood the console. Lazily populated; empty\n// and inert until the first dev warning actually fires.\nconst emitted = new Set<string>();\n\n/**\n * Emit a development warning ONCE per `(code, dedupeKey)`, only when dev mode is on.\n * In production (`isDev()` false) this is a no-op that returns before any work.\n *\n * @param code stable warning code (see DevWarningCode)\n * @param dedupeKey extra discriminator folded into the dedupe identity (e.g. the\n * duplicate key value). Same code + same dedupeKey warns once.\n * @param message human-readable explanation; `detail` is appended for context.\n */\nexport function warnDev(\n code: DevWarningCode,\n dedupeKey: string,\n message: string,\n ...detail: unknown[]\n): void {\n if (!isDev()) {\n return;\n }\n const id = code + \"\u0000\" + dedupeKey;\n if (emitted.has(id)) {\n return;\n }\n emitted.add(id);\n console.warn(`[wcstack/signals][${code}] ${message}`, ...detail);\n}\n\n/**\n * Clear the dedupe cache. Test-only seam so each test can re-exercise a warning that\n * is otherwise emitted once per process. Not meant for application use.\n */\nexport function __resetDevWarnings(): void {\n emitted.clear();\n}\n","// Minimal signal core (v1 design notes).\n//\n// A self-contained, zero-dependency reactive primitive whose public API is\n// shaped after the TC39 Signals proposal (State / Computed / effect). The intent\n// is NOT to ship signal-polyfill as a runtime dependency, but to keep an in-house\n// implementation that can later be swapped for the native one without changing\n// call sites. See docs/signals-state-design.md §2 (the \"case C\" decision).\n//\n// Reactivity model: three-color marking (CLEAN / CHECK / DIRTY), pull-validated\n// (after Reactively / Solid). docs §8 (c).\n// - A signal write marks its direct observers DIRTY and their transitive\n// observers CHECK. Effects scheduled on the CLEAN→stale transition run on a\n// coalesced microtask (docs §5-3).\n// - On read/run, `updateIfNecessary` validates a CHECK node by refreshing its\n// computed sources first; it recomputes only if a source actually changed.\n// - EQUALITY SHORT-CIRCUIT: when a computed recomputes to an equal value it does\n// NOT mark its observers DIRTY, so downstream effects/computeds skip work.\n// - dependencies are re-tracked on every run, so conditional deps are pruned.\n\nimport { reportError } from \"./reportError.js\";\nimport { isDev, warnDev } from \"./dev.js\";\n\nexport type Cleanup = () => void;\nexport type Equals<T> = (a: T, b: T) => boolean;\n\nexport interface ReadSignal<T> {\n /** Read the value AND register the current observer as a dependent. */\n get(): T;\n /** Read the value WITHOUT tracking (no dependency edge created). */\n peek(): T;\n}\n\nexport interface WriteSignal<T> extends ReadSignal<T> {\n set(value: T): void;\n}\n\nexport interface EffectHandle {\n dispose(): void;\n}\n\n// Node freshness. CLEAN: up to date. CHECK: a transitive source may have changed\n// — must validate before use. DIRTY: a direct source changed — must recompute.\n// Typed as `number` (not literals) on purpose: `_state` is mutated through\n// aliasing during `updateIfNecessary`, so literal narrowing would wrongly flag\n// the `=== DIRTY` re-check after a source update.\nconst CLEAN: number = 0;\nconst CHECK: number = 1;\nconst DIRTY: number = 2;\n\ninterface Observable {\n _observers: Set<Computation>;\n}\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 // A first run that read no signal never recomputes: a value read outside the function,\n // or with peek(), was fixed when it ran (docs/seam-apps.md, signals-shop). Dev-only.\n if (isDev() && this._sources.size === 0) {\n warnDev(\n \"UNTRACKED_COMPUTED\",\n String(this._fn).slice(0, 120),\n \"computed read no signal, so it never recomputes: read signals with get() inside it.\",\n this._fn,\n );\n }\n } else if (!this._equals(previous as T, this._value as T)) {\n for (const observer of this._observers) {\n observer._state = DIRTY;\n // Normally this computed is refreshed from inside flushEffects while\n // validating an already-scheduled effect, so the observer is in the queue\n // already. But if it is refreshed out-of-band (e.g. a `peek()` outside a\n // flush) an effect observer could otherwise be promoted to DIRTY without\n // being queued, and never re-run. Re-schedule defensively to keep the\n // \"DIRTY effect always runs\" invariant regardless of refresh path.\n if (observer._isEffect && !(observer as EffectNode)._disposed) {\n pendingEffects.add(observer as EffectNode);\n schedule();\n }\n }\n }\n }\n}\n\n// --- effect -----------------------------------------------------------------\n\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, checkTracked = false) {\n this._fn = fn;\n if (isDev()) {\n this._devStack = new Error().stack;\n }\n // Be owned by the enclosing owner (a parent effect or a createRoot), so a\n // parent teardown disposes this effect.\n registerDisposer(() => this.dispose());\n updateIfNecessary(this); // initial run (state starts DIRTY)\n // An author's effect whose first run read no signal never runs again (docs/seam-apps.md,\n // signals-shop). One that returned a cleanup, registered onCleanup or built children is a\n // setup effect, run once on purpose. The effects dom.ts and the adapters build for an\n // author's values are not checked (checkTracked false): the author did not write them.\n if (checkTracked && isDev() && !this._disposed && this._sources.size === 0 &&\n typeof this._cleanup !== \"function\" && this._owned.length === 0) {\n warnDev(\n \"UNTRACKED_EFFECT\",\n String(fn).slice(0, 120),\n \"effect read no signal, so it never runs again: read signals with get() inside it.\",\n fn,\n );\n }\n }\n\n _update(): void {\n this._runCleanup();\n disposeOwned(this); // tear down children created in the previous run\n untrack(this);\n const prevObserver = currentObserver;\n const prevOwner = currentOwner;\n currentObserver = this;\n currentOwner = this; // children created during the run are owned by this effect\n try {\n this._cleanup = this._fn();\n } finally {\n currentObserver = prevObserver;\n currentOwner = prevOwner;\n }\n }\n\n private _runCleanup(): void {\n if (typeof this._cleanup === \"function\") {\n this._cleanup();\n this._cleanup = undefined;\n }\n }\n\n dispose(): void {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n this._runCleanup();\n disposeOwned(this);\n untrack(this);\n pendingEffects.delete(this);\n }\n}\n\n// --- public API -------------------------------------------------------------\n\nexport function signal<T>(initial: T, equals: Equals<T> = Object.is): WriteSignal<T> {\n return new SignalNode(initial, equals);\n}\n\nexport function computed<T>(fn: () => T, equals: Equals<T> = Object.is): ReadSignal<T> {\n return new ComputedNode(fn, equals);\n}\n\nexport function effect(fn: () => Cleanup | void): EffectHandle {\n // (an effect built by dom.ts or an adapter for the author's value — innerEffect — is not checked for tracking)\n const checkTracked = !innerNext;\n innerNext = false;\n if (isDev() && currentOwner === null) {\n // No enclosing owner: nothing will ever dispose this effect, so it (and the\n // subscriptions it builds) leak. Legitimate top-level effects should be mounted\n // under createRoot / SignalsElement and disposed on teardown. Dev-only warn.\n warnDev(\n \"UNOWNED_EFFECT\",\n \"\",\n \"effect created with no owner — it will never be disposed and may leak. \" +\n \"Wrap it in createRoot(dispose => …) (or a SignalsElement render()) and \" +\n \"dispose on teardown.\",\n );\n }\n return new EffectNode(fn, checkTracked);\n}\n\n/** The next effect() is one the package builds for an author's value (not checked for tracking). */\nlet innerNext = false;\n\n/**\n * Internal (dom.ts, bindNode, the resource adapters): an effect the package builds around an\n * author's value — a function child or prop, a bound node, a fetcher. Behaves as effect(); only\n * the dev-mode UNTRACKED_EFFECT check, which is about effects the author wrote, is skipped.\n */\nexport function innerEffect(fn: () => Cleanup | void): EffectHandle {\n innerNext = true;\n return effect(fn);\n}\n\n/**\n * Run `fn` inside a fresh ownership scope and return its result. Every effect (or\n * nested cleanup) created during `fn` — directly or transitively — is owned by\n * this root; calling the `dispose` passed to `fn` tears them all down.\n *\n * The root is detached: it is NOT auto-disposed by an enclosing owner. The caller\n * holds `dispose` (e.g. a custom element disposes it in disconnectedCallback).\n *\n * If `fn` throws, any effects/cleanups it created BEFORE the throw are disposed\n * before the error propagates — a caller that never received `dispose` (because the\n * call threw) cannot leak the half-built scope.\n */\nexport function createRoot<T>(fn: (dispose: () => void) => T): T {\n const owner: Owner = { _owned: [] };\n let disposed = false;\n const dispose = (): void => {\n if (disposed) {\n return;\n }\n disposed = true;\n disposeOwned(owner);\n };\n const prevOwner = currentOwner;\n const prevObserver = currentObserver;\n currentOwner = owner;\n // Detach the dependency-tracking context too, not just ownership. A root is a\n // fresh reactive boundary: signals read SYNCHRONOUSLY while `fn` builds the scope\n // must not register the OUTER observer as their dependent (Solid's createRoot\n // clears both owner and listener). Without this, a For/Index `each` that reads\n // `index()`/`item()` synchronously in its body would track the outer reconcile\n // effect against the row's idx/item signal, so reordering re-dirties the reconcile\n // effect — a self-loop the equality/MAX_FLUSH guards only paper over.\n currentObserver = null;\n try {\n return fn(dispose);\n } catch (err) {\n dispose(); // tear down whatever fn built before it threw\n throw err;\n } finally {\n currentOwner = prevOwner;\n currentObserver = prevObserver;\n }\n}\n\n/**\n * True when there is a current ownership scope (an enclosing effect or createRoot).\n * Dev-diagnostics seam for the DOM layer to flag un-owned reactive insertions\n * without re-implementing owner tracking. NOT part of the public API.\n */\nexport function hasOwner(): boolean {\n return currentOwner !== null;\n}\n\n/**\n * Register a teardown callback with the current owner. Runs when the owning effect\n * re-runs or is disposed, or when the enclosing root is disposed. A no-op when\n * there is no current owner.\n */\nexport function onCleanup(fn: () => void): void {\n if (currentOwner === null) {\n // No owner → registerDisposer drops `fn` on the floor: the cleanup never runs.\n // Silent in production; flag it in dev so the missing teardown is visible.\n warnDev(\n \"ORPHAN_CLEANUP\",\n \"\",\n \"onCleanup called with no owner — the cleanup will never run. \" +\n \"Call it inside an effect, createRoot, or a SignalsElement render().\",\n );\n }\n registerDisposer(fn);\n}\n","// wc-bindable → signal adapter. The crux of the design.\n//\n// Any async-IO node in wcstack speaks the wc-bindable protocol:\n// - properties: outputs — the node dispatches `event` on change; the value is\n// read via `getter(event)`, defaulting to `e.detail` (wc-bindable\n// SPEC § Default Getter). The property `name` is read only for the\n// initial seed, where no event exists yet (SPEC § Initial Sync).\n// - inputs: settable surface — write `node[name] = value`.\n// - commands: invocable methods — call `node[name](...args)`.\n// The node has NO idea whether the observer behind the binding is a proxy (state)\n// or a signal. So a single adapter that maps these surfaces onto signals makes every\n// existing node plug into the signal core unchanged. See docs/signals-state-design.md\n// §3, and the four mappings of §3-1:\n//\n// element → signal | property (latest snapshot) → read signal [`signals`]\n// element → signal | event-token (per-emit stream) → folded signal [`on`]\n// signal → element | input (write-back) → effect → prop [`bindInput`]\n// signal → element | command-token (start/cancel) → emit on change [`bindCommand`]\n//\n// `signals` is the STATE view of a property (equality-guarded — same value = no\n// update). `on` is the OCCURRENCE view of the same event (a stream — every emit\n// updates, even with an equal value), folded latest-by-default.\n\nimport { signal, innerEffect as effect, WriteSignal, ReadSignal } from \"./reactive.js\";\nimport { reportError } from \"./reportError.js\";\nimport type { ResourceSource } from \"./resource.js\";\n\nexport interface WcBindableProperty<V = unknown> {\n readonly name: string;\n readonly event: string;\n readonly getter?: (event: Event) => V;\n}\n\n// Structurally a SUBSET of the real `IWcBindable` (which additionally carries\n// `protocol` / `version`, and richer input/command entries). A real descriptor is\n// therefore assignable to this type — see __tests__/bindNode.compat.test.ts.\nexport interface WcBindableDescriptor {\n readonly properties: readonly WcBindableProperty[];\n readonly inputs?: readonly { readonly name: string }[];\n readonly commands?: readonly { readonly name: string }[];\n}\n\n// --- typed node shape (D1) ---------------------------------------------------\n//\n// `bindNode` is the package's centerpiece, yet without a type argument every output\n// was `ReadSignal<unknown>` and every `set`/`command` took `unknown` — the feature\n// was effectively untyped in consumer code. `NodeShape` is an OPT-IN description of a\n// node's reactive surface that drives the return type: declare the property value\n// types, the input value types, and the command signatures ONCE, and `bound.signals`,\n// `on`, `set`, `bindInput`, `command`, and `bindCommand` are all typed from it.\n//\n// interface FetchShape extends NodeShape {\n// signals: { value: Person[]; loading: boolean };\n// inputs: { url: string };\n// commands: { fetch: (url: string) => Promise<Person[]>; abort: () => void };\n// }\n// const bound = bindNode<FetchShape>(el, desc);\n// bound.signals.value.get(); // ReadSignal<Person[]> — key & type checked\n// bound.set(\"url\", \"/api/people\"); // string enforced\n// bound.command(\"fetch\", \"/api\"); // arg/return inferred\n//\n// The runtime is UNCHANGED — these types are erased; the adapter still validates names\n// against the descriptor at runtime. The default shape below keeps every existing\n// untyped call site compiling exactly as before (all-`unknown`, string keys).\n// Open command map: a command name → any call signature. `(...args: any[])` (NOT\n// `never[]`) is the constraint a USER shape's commands must satisfy — and, crucially,\n// the OPEN fallback used when a shape omits `commands`. `Parameters<(...args: any[])\n// => unknown>` is `any[]`, so an untyped `command(\"run\", \"/api\")` accepts any args,\n// preserving the pre-generic behaviour (symmetric with `inputs` → `unknown`). A shape\n// that DECLARES a precise signature (e.g. `(url: string) => Promise<X>`) still gets\n// exact arg/return checking on the typed path — the loose constraint only widens the\n// DEFAULT, never a declared command. (`no-explicit-any` is disabled for this package.)\ntype OpenCommandMap = Record<string, (...args: any[]) => unknown>;\n\nexport interface NodeShape {\n /** propertyName → latest-snapshot value type (what `signals[name]` / `on(name)` carry). */\n signals?: Record<string, unknown>;\n /** inputName → settable value type (what `set` / `bindInput` accept). */\n inputs?: Record<string, unknown>;\n /** commandName → its call signature (what `command` / `bindCommand` invoke). */\n commands?: OpenCommandMap;\n}\n\n// Back-compat default: a fully-open shape so `bindNode(target, desc)` with no type\n// argument behaves as before (signals keyed by arbitrary string → unknown; any\n// input/command name; unknown values; any command args). Stronger typing is opt-in\n// via the type arg.\nexport interface DefaultNodeShape extends NodeShape {\n signals: Record<string, unknown>;\n inputs: Record<string, unknown>;\n commands: OpenCommandMap;\n}\n\n// Resolve the three sub-maps with sane fallbacks when a shape omits one of them.\ntype SignalsOf<S extends NodeShape> = S[\"signals\"] extends Record<string, unknown>\n ? S[\"signals\"]\n : Record<string, unknown>;\ntype InputsOf<S extends NodeShape> = S[\"inputs\"] extends Record<string, unknown>\n ? S[\"inputs\"]\n : Record<string, unknown>;\ntype CommandsOf<S extends NodeShape> = S[\"commands\"] extends OpenCommandMap ? S[\"commands\"] : OpenCommandMap;\n\n/** Options for `on` — how each event emission folds into the stream signal. */\nexport interface EventStreamOptions<T, C> {\n /** Combine the running value with each emission. Default: latest (replace). */\n fold?: (acc: T | undefined, chunk: C) => T;\n /** Seed value before the first emission. */\n initial?: T;\n}\n\nexport interface BoundNode<S extends NodeShape = DefaultNodeShape> {\n /**\n * Output properties as read-only signals (latest value), keyed by property name and\n * typed from the node shape: `bound.signals.value.get()` carries the declared value\n * type (no longer `unknown`). Keys are the declared property names.\n */\n readonly signals: { readonly [K in keyof SignalsOf<S>]: ReadSignal<SignalsOf<S>[K]> };\n /**\n * An event-token STREAM for a declared property's event: a read signal that folds\n * every emission (latest by default). Unlike `signals[prop]`, it updates on EVERY\n * emit — even when the derived value is equal — because it models occurrences, not\n * state. The chunk per emit is `getter(event)` if the property declares one, else\n * the property's current value.\n *\n * With no fold the value type defaults to the property's declared snapshot type; a\n * `fold` may reshape it (explicit `T`/`C` type args override).\n */\n on<K extends keyof SignalsOf<S>>(prop: K): ReadSignal<SignalsOf<S>[K] | undefined>;\n on<T, C = SignalsOf<S>[keyof SignalsOf<S>]>(\n prop: keyof SignalsOf<S>,\n options: EventStreamOptions<T, C>,\n ): ReadSignal<T | undefined>;\n /** Write a declared input on the node (imperative); value type checked against the shape. */\n set<K extends keyof InputsOf<S>>(name: K, value: InputsOf<S>[K]): void;\n /**\n * Reactively write a declared input from a signal: an effect mirrors `source` into\n * `node[name]`. A same-value guard (`node[name] !== v`) skips redundant writes, so\n * a property whose write re-dispatches an event cannot feed back into an infinite\n * loop. `undefined` follows the wc-bindable applier profile (A2): it is not written\n * while the source has had no other value (the first evaluation, or after another\n * `undefined`), so the element keeps its own initial state; after a value it is\n * written, so the element restores that state. Returns a disposer; the effect is\n * also torn down by `dispose()` (neither writes anything).\n */\n bindInput<K extends keyof InputsOf<S>>(name: K, source: ReadSignal<InputsOf<S>[K]>): () => void;\n /** Invoke a declared command on the node (imperative); args/return typed from the shape. */\n command<K extends keyof CommandsOf<S>>(name: K, ...args: Parameters<CommandsOf<S>[K]>): ReturnType<CommandsOf<S>[K]>;\n /**\n * Command-token: invoke a declared command whenever `trigger` CHANGES. The initial\n * value does not fire (subscribe-without-firing), so a command like `abort` is not\n * triggered on mount. `mapArgs` shapes the call arguments from the trigger value\n * (default: the value itself as a single argument). Returns a disposer; also torn\n * down by `dispose()`.\n */\n bindCommand<K extends keyof CommandsOf<S>, V = unknown>(\n name: K,\n trigger: ReadSignal<V>,\n mapArgs?: (value: V) => Parameters<CommandsOf<S>[K]>,\n ): () => void;\n /**\n * Detach all listeners/effects and make the adapter inert. After dispose the output\n * signals/streams stop updating and `set`/`command`/`bindInput`/`bindCommand`/`on`\n * throw (use-after-dispose). Idempotent.\n */\n dispose(): void;\n}\n\n// Internal target type. `Record<string, any>` is needed to index arbitrary declared\n// members (target[name]) inside the adapter, but it is DELIBERATELY NOT in the public\n// `bindNode` signature — exposing it there erased the caller's element type and let any\n// stray member access type-check. Kept private; the public entry takes `EventTarget`.\ntype NodeTarget = EventTarget & Record<string, any>;\n\n// Internal, fully-loose surface the adapter object is built against (string keys,\n// `unknown` values). The public `BoundNode<S>` is a stricter projection of this same\n// runtime object; `bindNode` casts the built `UntypedBoundNode` to `BoundNode<S>` at\n// return. Kept private so the loose `unknown`-typed methods never leak to callers.\ninterface UntypedBoundNode {\n readonly signals: Record<string, ReadSignal<unknown>>;\n on<T = unknown, C = unknown>(prop: string, options?: EventStreamOptions<T, C>): ReadSignal<T | undefined>;\n set(name: string, value: unknown): void;\n bindInput(name: string, source: ReadSignal<unknown>): () => void;\n command(name: string, ...args: unknown[]): unknown;\n bindCommand(name: string, trigger: ReadSignal<unknown>, mapArgs?: (value: unknown) => unknown[]): () => void;\n dispose(): void;\n}\n\n// The error thrown by `assertLive` when an adapter method is called after dispose.\n// Carries a brand symbol so callers that need to distinguish a post-dispose throw\n// (e.g. nodeSource's abort bridge) can test it structurally instead of matching the\n// message string — the message is free to change without silently breaking the\n// guard. The brand survives even if a consumer's bundler duplicates the class (e.g.\n// `instanceof` across realms), since it's a Symbol on the instance, not a class\n// identity check.\nconst DISPOSED_ERROR = Symbol(\"bindNode.disposed\");\n\n/**\n * Error thrown when a {@link BoundNode} method is invoked after the adapter has been\n * disposed. Every surface that mutates or subscribes — `on` / `set` / `bindInput` /\n * `command` / `bindCommand` — throws this once `dispose()` has run, so a\n * use-after-dispose is loud instead of silently writing/invoking on an inert adapter.\n *\n * Prefer {@link isDisposedError} over `instanceof` for the check: the brand survives a\n * bundler that duplicates the class across realms, where `instanceof` would not. Use it\n * to make teardown-order races robust — e.g. swallow a post-dispose throw while letting\n * any other error surface:\n *\n * ```ts\n * try {\n * bound.command(\"abort\");\n * } catch (err) {\n * if (!isDisposedError(err)) throw err; // expected during teardown; ignore\n * }\n * ```\n */\nexport class DisposedError extends Error {\n readonly [DISPOSED_ERROR] = true;\n}\n\n/**\n * True if `err` is a {@link DisposedError} — i.e. a use-after-dispose error thrown by a\n * {@link BoundNode} method after `dispose()`. Brand-based (checks a Symbol on the\n * instance), so it stays correct even if a consumer's bundler duplicates the\n * `DisposedError` class across module realms, where `err instanceof DisposedError`\n * could be false.\n */\nexport function isDisposedError(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && (err as Record<symbol, unknown>)[DISPOSED_ERROR] === true;\n}\n\nfunction readProperty(target: NodeTarget, name: string): unknown {\n return target[name];\n}\n\n// wc-bindable SPEC § Default Getter: when a property omits `getter`, an adapter MUST\n// read `e.detail`. This adapter used to read the property instead (#238), which\n// diverged from `@wcstack/state` and `@wc-bindable/core` — the same element could\n// bind correctly in one adapter and not the other. Only the initial seed reads the\n// property (SPEC § Initial Sync: there is no event to derive from at bind time).\nconst DEFAULT_GETTER = (e: Event): unknown => (e as CustomEvent).detail;\n\n/**\n * Adapt a wc-bindable node into signals. The public `target` parameter is a plain\n * `EventTarget` (the internal `Record<string, any>` indexing is cast away here, not\n * leaked to callers — see {@link NodeTarget}). Pass an optional {@link NodeShape} type\n * argument to type the result; omit it for the back-compat all-`unknown` shape.\n *\n * @example typed\n * interface FetchShape extends NodeShape {\n * signals: { value: Person[]; loading: boolean };\n * inputs: { url: string };\n * commands: { fetch: (url: string) => Promise<Person[]>; abort: () => void };\n * }\n * const bound = bindNode<FetchShape>(fetchEl, FetchCore.wcBindable);\n * bound.signals.value.get(); // ReadSignal<Person[]>\n * bound.set(\"url\", \"/api/people\"); // string enforced\n */\nexport function bindNode<S extends NodeShape = DefaultNodeShape>(\n target: EventTarget,\n descriptor?: WcBindableDescriptor,\n): BoundNode<S> {\n // The Record<string, any> indexing surface is needed internally to read/write/invoke\n // declared members by name; keep it private to this body.\n const node = target as NodeTarget;\n const desc = descriptor ?? (node.constructor as { wcBindable?: WcBindableDescriptor }).wcBindable;\n if (!desc) {\n // A custom element whose definition has not run yet has no descriptor yet: say so\n // (docs/signals-definition-timing.md §5.3; docs/seam-apps.md, signals-shop)\n const tag = (target as { localName?: unknown }).localName;\n if (typeof tag === \"string\" && tag.includes(\"-\") && typeof customElements !== \"undefined\" && customElements.get(tag) === undefined) {\n throw new Error(\n `bindNode: <${tag}> is not defined yet: load it before this code, or await customElements.whenDefined(\"${tag}\").`,\n );\n }\n throw new Error(\"bindNode: no wc-bindable descriptor provided and none found on target.constructor.wcBindable\");\n }\n\n // Name → declared-entry lookups so set/command/on reject names the node never\n // declared, instead of silently writing/invoking/listening on an arbitrary member.\n const propByName = new Map(desc.properties.map((p) => [p.name, p]));\n const declaredInputs = new Set((desc.inputs ?? []).map((i) => i.name));\n const declaredCommands = new Set((desc.commands ?? []).map((c) => c.name));\n\n const signals: Record<string, WriteSignal<unknown>> = {};\n const removers: Array<() => void> = [];\n let disposed = false;\n\n const assertLive = (op: string, name: string): void => {\n if (disposed) {\n throw new DisposedError(`bindNode.${op}: \"${name}\" called after dispose (the adapter is inert).`);\n }\n };\n\n for (const prop of desc.properties) {\n // Seed with the node's current value so the signal is valid before the first\n // event fires (e.g. FetchCore.value === null at rest).\n const cell = signal<unknown>(readProperty(node, prop.name));\n signals[prop.name] = cell;\n\n const read = prop.getter ?? DEFAULT_GETTER;\n const handler = (event: Event): void => {\n cell.set(read(event));\n };\n node.addEventListener(prop.event, handler);\n removers.push(() => node.removeEventListener(prop.event, handler));\n // Re-seed AFTER subscribing: the initial read above is a snapshot taken before\n // the listener was attached, so a value change in that gap would be missed.\n // Reading the property once more now closes the race (the equality guard makes\n // it a no-op when nothing changed). Note this is the property snapshot, not a\n // getter(event) — there is no event to derive from at bind time, and the SPEC's\n // default getter (`e.detail`) applies to events only.\n cell.set(readProperty(node, prop.name));\n }\n\n // Implemented against a string-keyed, all-`unknown` surface (`UntypedBoundNode`); the\n // generic typing in `BoundNode<S>` is a compile-time projection over the SAME\n // runtime, so the object is built once and cast to `BoundNode<S>` at return. Runtime\n // name validation against the descriptor is unchanged.\n const bound: UntypedBoundNode = {\n signals,\n\n on<T = unknown, C = unknown>(prop: string, options: EventStreamOptions<T, C> = {}): ReadSignal<T | undefined> {\n assertLive(\"on\", prop);\n const propDesc = propByName.get(prop);\n if (!propDesc) {\n throw new Error(`bindNode.on: \"${prop}\" is not a declared property on this node.`);\n }\n const fold = options.fold ?? ((_acc: T | undefined, chunk: C) => chunk as unknown as T);\n // equals: () => false — a stream notifies on EVERY emit, even an equal value.\n const cell = signal<T | undefined>(options.initial, () => false);\n const read = propDesc.getter ?? DEFAULT_GETTER;\n const handler = (event: Event): void => {\n const chunk = read(event) as C;\n cell.set(fold(cell.peek(), chunk));\n };\n node.addEventListener(propDesc.event, handler);\n removers.push(() => node.removeEventListener(propDesc.event, handler));\n return cell;\n },\n\n set(name: string, value: unknown): void {\n assertLive(\"set\", name);\n if (!declaredInputs.has(name)) {\n throw new Error(`bindNode.set: \"${name}\" is not a declared input on this node.`);\n }\n node[name] = value;\n },\n\n bindInput(name: string, source: ReadSignal<unknown>): () => void {\n assertLive(\"bindInput\", name);\n if (!declaredInputs.has(name)) {\n throw new Error(`bindNode.bindInput: \"${name}\" is not a declared input on this node.`);\n }\n // The previous evaluation, written or not. Its initial `undefined` stands for \"no\n // previous evaluation\", which A2 treats the same as a previous `undefined`.\n let previous: unknown = undefined;\n const handle = effect(() => {\n const v = source.get();\n const before = previous;\n previous = v;\n // A2: an `undefined` that follows no value means \"no value yet\" — writing it\n // would overwrite the element's own initial state (its default, or the markup)\n if (v === undefined && before === undefined) return;\n if (node[name] !== v) {\n node[name] = v; // same-value guard above breaks write→event→write loops\n }\n });\n removers.push(() => handle.dispose());\n return () => handle.dispose();\n },\n\n command(name: string, ...args: unknown[]): unknown {\n assertLive(\"command\", name);\n if (!declaredCommands.has(name)) {\n throw new Error(`bindNode.command: \"${name}\" is not a declared command on this node.`);\n }\n if (typeof node[name] !== \"function\") {\n throw new TypeError(`bindNode.command: \"${name}\" is declared but not a function on the node.`);\n }\n return node[name](...args);\n },\n\n bindCommand(name: string, trigger: ReadSignal<unknown>, mapArgs?: (value: unknown) => unknown[]): () => void {\n assertLive(\"bindCommand\", name);\n if (!declaredCommands.has(name)) {\n throw new Error(`bindNode.bindCommand: \"${name}\" is not a declared command on this node.`);\n }\n // Fail fast at bind time (not on first change), so a wrong name surfaces when\n // the subscription is set up rather than silently later inside a flush.\n if (typeof node[name] !== \"function\") {\n throw new TypeError(`bindNode.bindCommand: \"${name}\" is declared but not a function on the node.`);\n }\n let primed = false;\n const handle = effect(() => {\n const v = trigger.get();\n if (!primed) {\n primed = true; // subscribe on mount without firing (emit on CHANGE only)\n return;\n }\n const args = mapArgs ? mapArgs(v) : [v];\n node[name](...args);\n });\n removers.push(() => handle.dispose());\n return () => handle.dispose();\n },\n\n dispose(): void {\n if (disposed) {\n return; // idempotent\n }\n disposed = true;\n for (const remove of removers) {\n remove();\n }\n },\n };\n\n return bound as unknown as BoundNode<S>;\n}\n\n/**\n * Build a `resource` source from a wc-bindable node, bridging the resource's\n * AbortSignal to the node's cancel command (default `\"abort\"`) before delegating to\n * `run`. This generalizes the earlier hand-wired `sig → core.abort()` bridge (docs §8\n * (e), §5-2): wrap the result in `resource({ args })` and any node that declares an\n * abort command gets switchMap-style cancel/restart for free — an `args` change\n * aborts the in-flight call (firing the node's abort command, which cancels its real\n * AbortController) and starts the next.\n *\n * The node's own value/loading/error stay available via `bound.signals`; `resource`\n * here is used for the cancel/restart lifecycle, not to re-derive that triad.\n *\n * @example\n * const bound = bindNode(fetchEl);\n * const r = resource(\n * nodeSource(bound, (b, id) => b.command(\"fetch\", `/api/${id}`)),\n * { args: () => id.get() },\n * );\n */\nexport function nodeSource<T, A = void, S extends NodeShape = DefaultNodeShape>(\n bound: BoundNode<S>,\n run: (node: BoundNode<S>, args: A) => Promise<T> | T,\n options: { abort?: string } = {},\n): ResourceSource<T, A> {\n const abortName = options.abort ?? \"abort\";\n return (args, signal) => {\n // Honor the resource's cancel by invoking the node's abort command. `once`:\n // each resource run gets a fresh AbortSignal, so the listener fires at most once.\n //\n // GUARD: the abort listener runs SYNCHRONOUSLY inside AbortController.abort().\n // If `bound` was already disposed (e.g. the adapter and the resource share an\n // owner and the adapter's disposer ran first), `command` throws assertLive —\n // and a throw out of an abort listener surfaces as an unhandled exception during\n // the synchronous abort() call. Swallow a post-dispose throw so teardown order is\n // robust; report any OTHER error via the platform reporter without breaking abort.\n signal.addEventListener(\n \"abort\",\n () => {\n try {\n // `abortName` is a runtime string (validated by the adapter); the cast lets\n // it reach `command` regardless of the typed command-name union of `S`.\n (bound.command as (name: string, ...args: unknown[]) => unknown)(abortName);\n } catch (err) {\n // Brand-based check (not a message regex): a post-dispose throw is\n // expected here and swallowed; any OTHER error is reported.\n if (!isDisposedError(err)) {\n reportError(err);\n }\n }\n },\n { once: true },\n );\n return run(bound, args);\n };\n}\n","// Async resource (v1 design notes).\n//\n// Adapts an async producer into a reactive `{ value, loading, error }` triad —\n// the same shape FetchCore exposes (value/loading/error). When the resource's\n// `args` (a reactive getter) change, the in-flight request is aborted and a fresh\n// one starts: dependency-driven cancel/restart, i.e. RxJS switchMap.\n//\n// This is the signals-side counterpart of the state-side `$streams` adapter\n// (docs/state-stream-type-design.md §4-1). The hard part — making sure a stale\n// response from a superseded request never lands on the new state — is handled\n// here by checking `signal.aborted` before committing any result.\n\nimport { signal, innerEffect as effect, onCleanup, ReadSignal } from \"./reactive.js\";\n\nexport interface ResourceState<T> {\n value: ReadSignal<T | undefined>;\n // Progress is a BOOLEAN here, intentionally different from streamResource's\n // `status` enum. A resource is single-shot (one request → resolve/reject), so\n // its progress is binary: in-flight or not. A stream is continuous (idle →\n // active → done/error), so it needs the enum. The \"shared contract\" with the\n // state-side `$streams` adapter covers the cancel/restart SEMANTICS, not this\n // progress representation. (docs §8 (a)).\n loading: ReadSignal<boolean>;\n /** Last error, or `null` when there is none. Initial value is `null`; a (re)start resets it to `null`. */\n error: ReadSignal<unknown>;\n /** Abort any in-flight request and stop reacting to `args` changes. */\n dispose(): void;\n}\n\nexport interface ResourceOptions<T, A> {\n /** Reactive inputs. Reading signals here wires restart-on-change. */\n args?: () => A;\n /** Seed value before the first resolution. */\n initial?: T;\n}\n\nexport type ResourceSource<T, A> = (args: A, signal: AbortSignal) => Promise<T> | T;\n\nexport function resource<T, A = void>(\n source: ResourceSource<T, A>,\n options: ResourceOptions<T, A> = {},\n): ResourceState<T> {\n const value = signal<T | undefined>(options.initial);\n const loading = signal<boolean>(false);\n const error = signal<unknown>(null);\n\n let controller: AbortController | null = null;\n\n const runner = effect(() => {\n // Reading args() inside the effect is what subscribes us to its signals, so a\n // change re-runs this body — that IS the restart trigger.\n //\n // NOTE (effect-internal writes): this effect writes loading/error/value, which\n // are signals OTHER effects may observe. A write that actually CHANGES the value\n // marks those observers stale and queues them on the same flush; the drain loop\n // then runs them in the same tick. (A same-value write — e.g. error.set(null)\n // when error is already null — is a no-op via the equality guard and notifies\n // nothing.) We never read these signals inside THIS effect, so we don't dirty\n // our own dependency — no cycle. (docs §8 (a)).\n const a = (options.args ? options.args() : undefined) as A;\n\n // Abort the previous request before starting the next (switchMap).\n controller?.abort();\n const ac = new AbortController();\n controller = ac;\n\n loading.set(true);\n error.set(null);\n\n // Call the source SYNCHRONOUSLY (so it receives ac.signal immediately and can\n // wire its abort listener before any teardown), but guard it with try/catch so\n // a synchronous throw is normalized into the same error/loading state as a\n // rejected promise. Without the guard a sync throw would escape the effect body\n // (and, on the initial run, the resource() call itself), leaving loading stuck\n // true and error unset.\n let produced: Promise<T> | T;\n try {\n produced = source(a, ac.signal);\n } catch (err) {\n error.set(err);\n loading.set(false);\n return;\n }\n\n // Settle via two-arm `.then` rather than `await` + try/catch (streamResource's\n // shape): a resource is SINGLE-SHOT — one resolve/reject lands once — so a flat\n // resolved/rejected pair maps cleanly. A stream is a CONTINUOUS loop whose chunks\n // and termination must share one error path, which an `await` loop in try/catch\n // expresses; that structure would be needless here.\n Promise.resolve(produced).then(\n (resolved) => {\n // Drop the result if this request was superseded/disposed: committing it\n // would let a stale response overwrite the newer request's state.\n if (ac.signal.aborted) {\n return;\n }\n value.set(resolved);\n loading.set(false);\n },\n (err) => {\n if (ac.signal.aborted) {\n return;\n }\n error.set(err);\n loading.set(false);\n },\n );\n });\n\n const dispose = (): void => {\n controller?.abort();\n runner.dispose();\n };\n\n // Auto-dispose with the enclosing owner (createRoot / parent effect), so a\n // resource created inside a component is aborted on unmount. No-op when there\n // is no owner — the caller then disposes manually.\n onCleanup(dispose);\n\n return { value, loading, error, dispose };\n}\n","// Stream resource (docs §8 (a)). The signals-side counterpart of the state-side\n// `$streams` adapter (docs/state-stream-type-design.md).\n//\n// Adapts a continuous async flow (async iterable / ReadableStream / async\n// generator) into a single reactive value by FOLDING each chunk:\n// - latest (default): replace — value becomes the last chunk.\n// - reduce: accumulate — value = fold(acc, chunk), needs `initial`.\n// When the resource's `args` change, the in-flight stream is aborted and a fresh\n// one starts (switchMap), with `value` reset to `initial`.\n//\n// Deliberate non-goal: backpressure. The fold result IS the buffer; demand does\n// not flow back to the producer. Unbounded accumulation of an infinite stream is\n// a footgun — bound the fold (latest / count / last-N / window) for live streams.\n// This mirrors the state `$streams` norm and is what lets the impedance mismatch\n// be resolved honestly (state-stream §0, §4-3).\n//\n// Shared contract with state `$streams` (settled in v1):\n// - source(args, signal) receives an AbortSignal; honoring it drives restart.\n// - restart RESETS value to `initial`; error KEEPS the last value.\n// - status companion: \"idle\" | \"active\" | \"done\" | \"error\".\n// - async iterable is the lingua franca; anything getReader-bearing\n// (ReadableStream) is read via getReader() — see rescue levels below.\n//\n// CONTRACT (cooperative cancellation — STRONG REQUIREMENT): the `source` MUST honor\n// the `AbortSignal` it is given. Honoring it is what drives switchMap restart/dispose;\n// a source that ignores it cannot be reliably cancelled.\n//\n// Rescue levels on abort:\n// - ReadableStream: FULLY rescued. A parked read() is force-unwound via\n// reader.cancel(), which both releases the underlying source and settles the\n// pending read() so the loop unwinds. Anything getReader-bearing is routed\n// through this path even when it is ALSO natively async-iterable (Node 18+ /\n// Chrome 124+ / Firefox): the spec serializes asyncIterator.return() behind\n// the pending next() ([[ongoingPromise]]), so the AsyncIterable rescue below\n// cannot force-unwind a parked read on a native ReadableStream.\n// - AsyncIterable / async generator: PARTIALLY rescued. On abort we call\n// iterator.return() to trigger the generator's finally/cleanup. But a parked\n// `await` (the producer stalling before its next yield while IGNORING `signal`)\n// cannot be force-unwound from outside — return() only takes effect when the\n// generator next resumes. So a source that parks forever and never observes\n// `signal` still leaks its consume() task. Honor `signal` to bound this.\n// The `if (signal.aborted) return` check only runs after a chunk arrives, not while\n// parked — it drops stale chunks but is not, by itself, a cancellation mechanism.\n\nimport { signal, innerEffect as effect, onCleanup, ReadSignal, WriteSignal } from \"./reactive.js\";\n\nexport type StreamStatus = \"idle\" | \"active\" | \"done\" | \"error\";\n\nexport interface StreamResourceState<T> {\n value: ReadSignal<T | undefined>;\n // Progress is an ENUM here, intentionally different from resource's `loading`\n // boolean: a continuous stream moves idle → active → done/error, which a boolean\n // cannot express. The cancel/restart contract is shared with `resource` and the\n // state-side `$streams` adapter; the progress representation is not.\n status: ReadSignal<StreamStatus>;\n /** Last error, or `null` when there is none. Initial value is `null`; a (re)start resets it to `null`. */\n error: ReadSignal<unknown>;\n /** Abort the in-flight stream and stop reacting to `args`. */\n dispose(): void;\n}\n\nexport interface StreamResourceOptions<T, C, A> {\n /** Reactive inputs. Reading signals here wires restart-on-change. */\n args?: () => A;\n /** Combine the running value with each chunk. Default: latest (replace). */\n fold?: (acc: T | undefined, chunk: C) => T;\n /** Seed value, and the value `value` is reset to on each (re)start. */\n initial?: T;\n}\n\nexport type StreamProducer<C> = AsyncIterable<C> | ReadableStream<C>;\n\n/**\n * Produce a stream for the current `args`. The `signal` aborts on restart/dispose —\n * the source **MUST honor it** (this is a hard contract, not a suggestion): a\n * `ReadableStream` is fully cancelled via `reader.cancel()`, and an async generator\n * should observe `signal` (e.g. reject/break on `signal.aborted`) so a parked `await`\n * can unwind. On abort the adapter also calls the iterator's `return()` to run a\n * generator's `finally`, but a generator that parks forever while ignoring `signal`\n * cannot be force-unwound and will leak. See the module header's CONTRACT.\n */\nexport type StreamSource<C, A> = (\n args: A,\n signal: AbortSignal,\n) => StreamProducer<C> | Promise<StreamProducer<C>>;\n\nexport function streamResource<T, C = T, A = void>(\n source: StreamSource<C, A>,\n options: StreamResourceOptions<T, C, A> = {},\n): StreamResourceState<T> {\n const fold = options.fold ?? ((_acc: T | undefined, chunk: C) => chunk as unknown as T);\n const value = signal<T | undefined>(options.initial);\n const status = signal<StreamStatus>(\"idle\");\n const error = signal<unknown>(null);\n\n let controller: AbortController | null = null;\n\n const runner = effect(() => {\n // NOTE (effect-internal writes): like `resource`, this effect writes\n // value/status/error — signals other effects may observe. Those observers are\n // queued on the same flush and run in the same tick. This effect never reads\n // those signals, so it does not dirty its own dependency (no cycle). The async\n // `consume` writes them later from microtasks/timers, outside this flush.\n const a = (options.args ? options.args() : undefined) as A;\n\n controller?.abort();\n const ac = new AbortController();\n controller = ac;\n\n // Reset for the new run: a restart starts the fold from `initial`.\n value.set(options.initial);\n error.set(null);\n status.set(\"active\");\n\n void consume(source, a, ac.signal, fold, value, status, error);\n });\n\n const dispose = (): void => {\n controller?.abort();\n runner.dispose();\n };\n onCleanup(dispose);\n\n return { value, status, error, dispose };\n}\n\nasync function consume<T, C, A>(\n source: StreamSource<C, A>,\n args: A,\n signal: AbortSignal,\n fold: (acc: T | undefined, chunk: C) => T,\n // Use the public WriteSignal type instead of re-declaring an inline subset, so\n // these stay in lockstep with the signal API (no structural drift).\n value: WriteSignal<T | undefined>,\n status: WriteSignal<StreamStatus>,\n error: WriteSignal<unknown>,\n): Promise<void> {\n // Obtain the iterator EXPLICITLY (not via `for await`'s implicit one) so abort can\n // call `iterator.return()` to trigger an AsyncIterable / async generator's\n // `finally`/cleanup. A `for await` only calls `.return()` when the loop itself exits;\n // if the producer is PARKED (awaiting before the next yield while ignoring `signal`),\n // the loop never advances, so the implicit `.return()` never runs and the task leaks\n // past restart/dispose. Calling `.return()` on abort is the PARTIAL rescue: the\n // parked `await` cannot be force-unwound from outside, but once the generator resumes\n // (its next tick), `.return()` makes it run its `finally` and stop — recovering the\n // common \"generator wakes up after abort\" case. The ReadableStream path is fully\n // rescued via `reader.cancel()` (see `readableToAsyncIterable`).\n let iterator: AsyncIterator<C> | null = null;\n // Guard against returning the SAME iterator twice. `onAbort` is reachable two ways:\n // the abort listener, and the explicit call on line ~163 when abort raced the\n // `await source(...)`. The guard keys on the iterator instance (not a plain \"ran\"\n // flag): the listener firing with iterator still null must NOT consume the single\n // real cleanup that the explicit call performs once the iterator exists. So we only\n // mark an iterator returned once we have actually called `.return()` on it.\n let returned: AsyncIterator<C> | null = null;\n const onAbort = (): void => {\n if (!iterator || iterator === returned) {\n return; // nothing to release yet, or already released this iterator\n }\n returned = iterator;\n // Fire the iterator's cleanup. Swallow any throw/rejection from `.return()` — we\n // are tearing down; a producer that rejects on return must not surface here.\n try {\n void iterator.return?.()?.then?.(undefined, () => {});\n } catch {\n // `.return()` threw synchronously while tearing down — ignore.\n }\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n try {\n const produced = await source(args, signal);\n iterator = iterate(produced, signal)[Symbol.asyncIterator]();\n if (signal.aborted) {\n // Aborted while awaiting the source: the abort listener already ran (iterator\n // was still null then), so explicitly release the just-produced iterator now —\n // this fires a generator's finally / a ReadableStream's cancel for the\n // resource we created but will never iterate.\n onAbort();\n return;\n }\n for (;;) {\n const result = await iterator.next();\n if (result.done) {\n break;\n }\n if (signal.aborted) {\n return; // stale chunk from a superseded/disposed run — drop it\n }\n value.set(fold(value.peek(), result.value));\n }\n if (signal.aborted) {\n return; // stream ended but this run was aborted — don't mark done\n }\n status.set(\"done\");\n } catch (e) {\n if (signal.aborted) {\n return; // an abort that surfaced as a throw is not an error\n }\n error.set(e); // keep the last folded value (do not reset)\n status.set(\"error\");\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction iterate<C>(produced: StreamProducer<C>, signal: AbortSignal): AsyncIterable<C> {\n // Anything ReadableStream-shaped (has getReader) takes the reader path FIRST —\n // even when it is also async-iterable. On runtimes where ReadableStream\n // implements native async iteration (Node 18+ / Chrome 124+ / Firefox), the\n // spec serializes `iterator.return()` behind the pending `next()`\n // ([[ongoingPromise]]), so the AsyncIterable rescue cannot force-unwind a\n // parked read: abort would hang the consume task until the producer's next\n // chunk (or forever on a silent stream), leaking the underlying source.\n // `reader.cancel()` has no such ordering — routing every getReader-bearing\n // source through it keeps the FULL rescue promised for ReadableStream.\n if (typeof (produced as ReadableStream<C>)?.getReader === \"function\") {\n return readableToAsyncIterable(produced as ReadableStream<C>, signal);\n }\n if (typeof (produced as AsyncIterable<C>)?.[Symbol.asyncIterator] === \"function\") {\n return produced as AsyncIterable<C>;\n }\n throw new TypeError(\n \"streamResource: source must return an AsyncIterable or a ReadableStream (got neither).\",\n );\n}\n\nasync function* readableToAsyncIterable<C>(\n stream: ReadableStream<C>,\n signal: AbortSignal,\n): AsyncGenerator<C> {\n const reader = stream.getReader();\n // A ReadableStream read() does NOT observe an AbortSignal on its own. Without\n // this, a switchMap restart / dispose leaves the previous reader parked in a\n // pending read() forever, leaking the underlying source. Cancelling on abort\n // both releases the source AND settles the pending read() so the for-await\n // unwinds and the finally below can release the lock. Abort is the only\n // early-exit path for this generator (the consumer never calls .return()\n // without aborting), so this is the sole place a non-drained stream is cancelled.\n const onAbort = (): void => {\n void reader.cancel().catch(() => {}); // tearing down; swallow a rejected cancel\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n yield value as C;\n }\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n reader.releaseLock();\n }\n}\n"],"names":["reportError","err","r","globalThis","console","error","isDev","__WCS_DEV__","emitted","Set","warnDev","code","dedupeKey","message","detail","id","has","add","warn","currentObserver","track","source","_sources","_observers","untrack","node","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","String","EffectNode","_cleanup","checkTracked","stack","dispose","_runCleanup","prevOwner","signal","initial","Object","is","computed","effect","innerNext","innerEffect","createRoot","disposed","hasOwner","onCleanup","DISPOSED_ERROR","Symbol","DisposedError","isDisposedError","readProperty","target","name","DEFAULT_GETTER","bindNode","descriptor","desc","wcBindable","tag","localName","includes","customElements","propByName","Map","properties","p","declaredInputs","inputs","declaredCommands","commands","c","signals","removers","assertLive","op","prop","cell","read","getter","handler","event","addEventListener","removeEventListener","on","options","propDesc","fold","_acc","chunk","bindInput","handle","v","before","command","args","TypeError","bindCommand","trigger","mapArgs","primed","remove","nodeSource","bound","run","abortName","abort","once","resource","loading","controller","runner","a","ac","AbortController","produced","Promise","resolve","then","resolved","aborted","streamResource","status","async","iterator","returned","onAbort","return","getReader","stream","reader","cancel","catch","done","releaseLock","readableToAsyncIterable","asyncIterator","iterate","result","consume"],"mappings":"AAOM,SAAUA,EAAYC,GAC1B,MAAMC,EAAKC,WAAsDH,YAChD,mBAANE,EACTA,EAAED,GAEFG,QAAQC,MAAMJ,EAElB,UCoBgBK,IACd,OAAiE,IAAzDH,WAAyCI,WACnD,CAKA,MAAMC,EAAU,IAAIC,IAWd,SAAUC,EACdC,EACAC,EACAC,KACGC,GAEH,IAAKR,IACH,OAEF,MAAMS,EAAKJ,EAAO,KAAMC,EACpBJ,EAAQQ,IAAID,KAGhBP,EAAQS,IAAIF,GACZX,QAAQc,KAAK,qBAAqBP,MAASE,OAAcC,GAC3D,CCLA,IAAIK,EAAsC,KAE1C,SAASC,EAAMC,GACW,OAApBF,IACFA,EAAgBG,SAASL,IAAII,GAC7BA,EAAOE,WAAWN,IAAIE,GAE1B,CAEA,SAASK,EAAQC,GACf,IAAK,MAAMJ,KAAUI,EAAKH,SACxBD,EAAOE,WAAWG,OAAOD,GAE3BA,EAAKH,SAASK,OAChB,CAiBA,IAAIC,EAA6B,KAEjC,SAASC,EAAiBC,GACH,OAAjBF,GACFA,EAAaG,OAAOC,KAAKF,EAE7B,CAEA,SAASG,EAAaC,GAEpB,MAAMC,EAAQD,EAAMH,OACpB,IAAK,IAAIK,EAAID,EAAME,OAAS,EAAGD,GAAK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A,SAAgBqH,EAAOpD,OACrC,GAAIuD,EACF,aAEIxH,CACR,CACF,SACEsB,EAAOgD,oBAAoB,QAAS2C,GACpCI,EAAOI,aACT,CACF,CAtCWC,CAAwBpB,EAA+BhF,GAEhE,GAAsE,mBAA1DgF,IAAgCnE,OAAOwF,eACjD,OAAOrB,EAET,MAAM,IAAInB,UACR,yFAEJ,CArDeyC,CAAQtB,EAAUhF,GAAQa,OAAOwF,iBACxCrG,EAAOqF,QAMT,YADAM,IAGF,OAAS,CACP,MAAMY,QAAed,EAASzG,OAC9B,GAAIuH,EAAOL,KACT,MAEF,GAAIlG,EAAOqF,QACT,OAEF3G,EAAMK,IAAIqE,EAAK1E,EAAMI,OAAQyH,EAAO7H,OACtC,CACA,GAAIsB,EAAOqF,QACT,OAEFE,EAAOxG,IAAI,OACb,CAAE,MAAOhC,GACP,GAAIiD,EAAOqF,QACT,OAEFpL,EAAM8E,IAAIhC,GACVwI,EAAOxG,IAAI,QACb,SACEiB,EAAOgD,oBAAoB,QAAS2C,EACtC,CACF,CAzFSa,CAAQvL,EAAQ4J,EAAGC,EAAG9E,OAAQoD,EAAM1E,EAAO6G,EAAQtL,KAGpD4F,EAAU,KACd8E,GAAYJ,QACZK,EAAO/E,WAIT,OAFAc,EAAUd,GAEH,CAAEnB,QAAO6G,SAAQtL,QAAO4F,UACjC"}
|
|
Binary file
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core-kS9CKPFP.esm.js","sources":["../src/reportError.ts","../src/dev.ts","../src/reactive.ts","../src/bindNode.ts","../src/resource.ts","../src/streamResource.ts"],"sourcesContent":["// Internal error-reporting policy (NOT part of the public API; not re-exported\n// from exports.ts). Single source of truth for \"surface an error without crashing\".\n//\n// Delegates to the platform `reportError` when present — it dispatches a window\n// \"error\" event / logs to the console without aborting the current task — and falls\n// back to `console.error` otherwise. It NEVER re-throws (re-throwing would abort the\n// caller's drain / abort handler) and NEVER swallows silently (that would hide bugs).\nexport function reportError(err: unknown): void {\n const r = (globalThis as { reportError?: (e: unknown) => void }).reportError;\n if (typeof r === \"function\") {\n r(err);\n } else {\n console.error(err);\n }\n}\n","// Opt-in development diagnostics (NOT part of the public API; not re-exported from\n// exports.ts). Surfaces \"silent failure\" modes — duplicate/unkeyed list rows,\n// un-owned effects that leak, no-op onCleanup, reactive cycles — that production\n// otherwise swallows.\n//\n// DEFAULT OFF. Nothing here runs unless the consumer flips `globalThis.__WCS_DEV__`\n// to `true` BEFORE the failing operation. `isDev()` reads the flag at CALL TIME (not\n// module-load time), so a page can toggle it on for a debugging session without a\n// rebuild. See README \"Development mode\".\n//\n// TREE-SHAKING: the package sets `\"sideEffects\": false`, and every export here is a\n// pure function with no module-top-level side effects (the dedupe cache is a lazily-\n// populated Set, not eager work). A production bundler that never references warnDev\n// can drop this module entirely; a bundler that does keep it still pays nothing at\n// runtime because `warnDev` short-circuits on the `isDev()` guard before touching the\n// dedupe Set or formatting a message.\n\n/** Stable warning codes, so docs/tests can reference a warning without matching prose. */\nexport type DevWarningCode =\n | \"DUPLICATE_KEY\"\n | \"NON_PRIMITIVE_KEY\"\n | \"NULLISH_KEY\"\n | \"UNOWNED_EFFECT\"\n | \"UNOWNED_INSERT\"\n | \"ORPHAN_CLEANUP\"\n | \"REACTIVE_CYCLE\"\n | \"UNTRACKED_COMPUTED\"\n | \"UNTRACKED_EFFECT\";\n\n/**\n * True only when the consumer has opted in via `globalThis.__WCS_DEV__ === true`.\n * Read at call time so the flag can be toggled at runtime. Kept tiny and pure so a\n * production bundle that strips dev branches pays nothing.\n */\nexport function isDev(): boolean {\n return (globalThis as { __WCS_DEV__?: boolean }).__WCS_DEV__ === true;\n}\n\n// Dedupe set: a given (code + dedupe-key) warning is emitted at most once, so a\n// per-row or per-flush failure does not flood the console. Lazily populated; empty\n// and inert until the first dev warning actually fires.\nconst emitted = new Set<string>();\n\n/**\n * Emit a development warning ONCE per `(code, dedupeKey)`, only when dev mode is on.\n * In production (`isDev()` false) this is a no-op that returns before any work.\n *\n * @param code stable warning code (see DevWarningCode)\n * @param dedupeKey extra discriminator folded into the dedupe identity (e.g. the\n * duplicate key value). Same code + same dedupeKey warns once.\n * @param message human-readable explanation; `detail` is appended for context.\n */\nexport function warnDev(\n code: DevWarningCode,\n dedupeKey: string,\n message: string,\n ...detail: unknown[]\n): void {\n if (!isDev()) {\n return;\n }\n const id = code + \"\u0000\" + dedupeKey;\n if (emitted.has(id)) {\n return;\n }\n emitted.add(id);\n console.warn(`[wcstack/signals][${code}] ${message}`, ...detail);\n}\n\n/**\n * Clear the dedupe cache. Test-only seam so each test can re-exercise a warning that\n * is otherwise emitted once per process. Not meant for application use.\n */\nexport function __resetDevWarnings(): void {\n emitted.clear();\n}\n","// Minimal signal core (v1 design notes).\n//\n// A self-contained, zero-dependency reactive primitive whose public API is\n// shaped after the TC39 Signals proposal (State / Computed / effect). The intent\n// is NOT to ship signal-polyfill as a runtime dependency, but to keep an in-house\n// implementation that can later be swapped for the native one without changing\n// call sites. See docs/signals-state-design.md §2 (the \"case C\" decision).\n//\n// Reactivity model: three-color marking (CLEAN / CHECK / DIRTY), pull-validated\n// (after Reactively / Solid). docs §8 (c).\n// - A signal write marks its direct observers DIRTY and their transitive\n// observers CHECK. Effects scheduled on the CLEAN→stale transition run on a\n// coalesced microtask (docs §5-3).\n// - On read/run, `updateIfNecessary` validates a CHECK node by refreshing its\n// computed sources first; it recomputes only if a source actually changed.\n// - EQUALITY SHORT-CIRCUIT: when a computed recomputes to an equal value it does\n// NOT mark its observers DIRTY, so downstream effects/computeds skip work.\n// - dependencies are re-tracked on every run, so conditional deps are pruned.\n\nimport { reportError } from \"./reportError.js\";\nimport { isDev, warnDev } from \"./dev.js\";\n\nexport type Cleanup = () => void;\nexport type Equals<T> = (a: T, b: T) => boolean;\n\nexport interface ReadSignal<T> {\n /** Read the value AND register the current observer as a dependent. */\n get(): T;\n /** Read the value WITHOUT tracking (no dependency edge created). */\n peek(): T;\n}\n\nexport interface WriteSignal<T> extends ReadSignal<T> {\n set(value: T): void;\n}\n\nexport interface EffectHandle {\n dispose(): void;\n}\n\n// Node freshness. CLEAN: up to date. CHECK: a transitive source may have changed\n// — must validate before use. DIRTY: a direct source changed — must recompute.\n// Typed as `number` (not literals) on purpose: `_state` is mutated through\n// aliasing during `updateIfNecessary`, so literal narrowing would wrongly flag\n// the `=== DIRTY` re-check after a source update.\nconst CLEAN: number = 0;\nconst CHECK: number = 1;\nconst DIRTY: number = 2;\n\ninterface Observable {\n _observers: Set<Computation>;\n}\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 // A first run that read no signal never recomputes: a value read outside the function,\n // or with peek(), was fixed when it ran (docs/seam-apps.md, signals-shop). Dev-only.\n if (isDev() && this._sources.size === 0) {\n warnDev(\n \"UNTRACKED_COMPUTED\",\n String(this._fn).slice(0, 120),\n \"computed read no signal, so it never recomputes: read signals with get() inside it.\",\n this._fn,\n );\n }\n } else if (!this._equals(previous as T, this._value as T)) {\n for (const observer of this._observers) {\n observer._state = DIRTY;\n // Normally this computed is refreshed from inside flushEffects while\n // validating an already-scheduled effect, so the observer is in the queue\n // already. But if it is refreshed out-of-band (e.g. a `peek()` outside a\n // flush) an effect observer could otherwise be promoted to DIRTY without\n // being queued, and never re-run. Re-schedule defensively to keep the\n // \"DIRTY effect always runs\" invariant regardless of refresh path.\n if (observer._isEffect && !(observer as EffectNode)._disposed) {\n pendingEffects.add(observer as EffectNode);\n schedule();\n }\n }\n }\n }\n}\n\n// --- effect -----------------------------------------------------------------\n\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, checkTracked = false) {\n this._fn = fn;\n if (isDev()) {\n this._devStack = new Error().stack;\n }\n // Be owned by the enclosing owner (a parent effect or a createRoot), so a\n // parent teardown disposes this effect.\n registerDisposer(() => this.dispose());\n updateIfNecessary(this); // initial run (state starts DIRTY)\n // An author's effect whose first run read no signal never runs again (docs/seam-apps.md,\n // signals-shop). One that returned a cleanup, registered onCleanup or built children is a\n // setup effect, run once on purpose. The effects dom.ts and the adapters build for an\n // author's values are not checked (checkTracked false): the author did not write them.\n if (checkTracked && isDev() && !this._disposed && this._sources.size === 0 &&\n typeof this._cleanup !== \"function\" && this._owned.length === 0) {\n warnDev(\n \"UNTRACKED_EFFECT\",\n String(fn).slice(0, 120),\n \"effect read no signal, so it never runs again: read signals with get() inside it.\",\n fn,\n );\n }\n }\n\n _update(): void {\n this._runCleanup();\n disposeOwned(this); // tear down children created in the previous run\n untrack(this);\n const prevObserver = currentObserver;\n const prevOwner = currentOwner;\n currentObserver = this;\n currentOwner = this; // children created during the run are owned by this effect\n try {\n this._cleanup = this._fn();\n } finally {\n currentObserver = prevObserver;\n currentOwner = prevOwner;\n }\n }\n\n private _runCleanup(): void {\n if (typeof this._cleanup === \"function\") {\n this._cleanup();\n this._cleanup = undefined;\n }\n }\n\n dispose(): void {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n this._runCleanup();\n disposeOwned(this);\n untrack(this);\n pendingEffects.delete(this);\n }\n}\n\n// --- public API -------------------------------------------------------------\n\nexport function signal<T>(initial: T, equals: Equals<T> = Object.is): WriteSignal<T> {\n return new SignalNode(initial, equals);\n}\n\nexport function computed<T>(fn: () => T, equals: Equals<T> = Object.is): ReadSignal<T> {\n return new ComputedNode(fn, equals);\n}\n\nexport function effect(fn: () => Cleanup | void): EffectHandle {\n // (an effect built by dom.ts or an adapter for the author's value — innerEffect — is not checked for tracking)\n const checkTracked = !innerNext;\n innerNext = false;\n if (isDev() && currentOwner === null) {\n // No enclosing owner: nothing will ever dispose this effect, so it (and the\n // subscriptions it builds) leak. Legitimate top-level effects should be mounted\n // under createRoot / SignalsElement and disposed on teardown. Dev-only warn.\n warnDev(\n \"UNOWNED_EFFECT\",\n \"\",\n \"effect created with no owner — it will never be disposed and may leak. \" +\n \"Wrap it in createRoot(dispose => …) (or a SignalsElement render()) and \" +\n \"dispose on teardown.\",\n );\n }\n return new EffectNode(fn, checkTracked);\n}\n\n/** The next effect() is one the package builds for an author's value (not checked for tracking). */\nlet innerNext = false;\n\n/**\n * Internal (dom.ts, bindNode, the resource adapters): an effect the package builds around an\n * author's value — a function child or prop, a bound node, a fetcher. Behaves as effect(); only\n * the dev-mode UNTRACKED_EFFECT check, which is about effects the author wrote, is skipped.\n */\nexport function innerEffect(fn: () => Cleanup | void): EffectHandle {\n innerNext = true;\n return effect(fn);\n}\n\n/**\n * Run `fn` inside a fresh ownership scope and return its result. Every effect (or\n * nested cleanup) created during `fn` — directly or transitively — is owned by\n * this root; calling the `dispose` passed to `fn` tears them all down.\n *\n * The root is detached: it is NOT auto-disposed by an enclosing owner. The caller\n * holds `dispose` (e.g. a custom element disposes it in disconnectedCallback).\n *\n * If `fn` throws, any effects/cleanups it created BEFORE the throw are disposed\n * before the error propagates — a caller that never received `dispose` (because the\n * call threw) cannot leak the half-built scope.\n */\nexport function createRoot<T>(fn: (dispose: () => void) => T): T {\n const owner: Owner = { _owned: [] };\n let disposed = false;\n const dispose = (): void => {\n if (disposed) {\n return;\n }\n disposed = true;\n disposeOwned(owner);\n };\n const prevOwner = currentOwner;\n const prevObserver = currentObserver;\n currentOwner = owner;\n // Detach the dependency-tracking context too, not just ownership. A root is a\n // fresh reactive boundary: signals read SYNCHRONOUSLY while `fn` builds the scope\n // must not register the OUTER observer as their dependent (Solid's createRoot\n // clears both owner and listener). Without this, a For/Index `each` that reads\n // `index()`/`item()` synchronously in its body would track the outer reconcile\n // effect against the row's idx/item signal, so reordering re-dirties the reconcile\n // effect — a self-loop the equality/MAX_FLUSH guards only paper over.\n currentObserver = null;\n try {\n return fn(dispose);\n } catch (err) {\n dispose(); // tear down whatever fn built before it threw\n throw err;\n } finally {\n currentOwner = prevOwner;\n currentObserver = prevObserver;\n }\n}\n\n/**\n * True when there is a current ownership scope (an enclosing effect or createRoot).\n * Dev-diagnostics seam for the DOM layer to flag un-owned reactive insertions\n * without re-implementing owner tracking. NOT part of the public API.\n */\nexport function hasOwner(): boolean {\n return currentOwner !== null;\n}\n\n/**\n * Register a teardown callback with the current owner. Runs when the owning effect\n * re-runs or is disposed, or when the enclosing root is disposed. A no-op when\n * there is no current owner.\n */\nexport function onCleanup(fn: () => void): void {\n if (currentOwner === null) {\n // No owner → registerDisposer drops `fn` on the floor: the cleanup never runs.\n // Silent in production; flag it in dev so the missing teardown is visible.\n warnDev(\n \"ORPHAN_CLEANUP\",\n \"\",\n \"onCleanup called with no owner — the cleanup will never run. \" +\n \"Call it inside an effect, createRoot, or a SignalsElement render().\",\n );\n }\n registerDisposer(fn);\n}\n","// wc-bindable → signal adapter. The crux of the design.\n//\n// Any async-IO node in wcstack speaks the wc-bindable protocol:\n// - properties: outputs — the node dispatches `event` on change; the value is\n// read via `getter(event)`, defaulting to `e.detail` (wc-bindable\n// SPEC § Default Getter). The property `name` is read only for the\n// initial seed, where no event exists yet (SPEC § Initial Sync).\n// - inputs: settable surface — write `node[name] = value`.\n// - commands: invocable methods — call `node[name](...args)`.\n// The node has NO idea whether the observer behind the binding is a proxy (state)\n// or a signal. So a single adapter that maps these surfaces onto signals makes every\n// existing node plug into the signal core unchanged. See docs/signals-state-design.md\n// §3, and the four mappings of §3-1:\n//\n// element → signal | property (latest snapshot) → read signal [`signals`]\n// element → signal | event-token (per-emit stream) → folded signal [`on`]\n// signal → element | input (write-back) → effect → prop [`bindInput`]\n// signal → element | command-token (start/cancel) → emit on change [`bindCommand`]\n//\n// `signals` is the STATE view of a property (equality-guarded — same value = no\n// update). `on` is the OCCURRENCE view of the same event (a stream — every emit\n// updates, even with an equal value), folded latest-by-default.\n\nimport { signal, innerEffect as effect, WriteSignal, ReadSignal } from \"./reactive.js\";\nimport { reportError } from \"./reportError.js\";\nimport type { ResourceSource } from \"./resource.js\";\n\nexport interface WcBindableProperty<V = unknown> {\n readonly name: string;\n readonly event: string;\n readonly getter?: (event: Event) => V;\n}\n\n// Structurally a SUBSET of the real `IWcBindable` (which additionally carries\n// `protocol` / `version`, and richer input/command entries). A real descriptor is\n// therefore assignable to this type — see __tests__/bindNode.compat.test.ts.\nexport interface WcBindableDescriptor {\n readonly properties: readonly WcBindableProperty[];\n readonly inputs?: readonly { readonly name: string }[];\n readonly commands?: readonly { readonly name: string }[];\n}\n\n// --- typed node shape (D1) ---------------------------------------------------\n//\n// `bindNode` is the package's centerpiece, yet without a type argument every output\n// was `ReadSignal<unknown>` and every `set`/`command` took `unknown` — the feature\n// was effectively untyped in consumer code. `NodeShape` is an OPT-IN description of a\n// node's reactive surface that drives the return type: declare the property value\n// types, the input value types, and the command signatures ONCE, and `bound.signals`,\n// `on`, `set`, `bindInput`, `command`, and `bindCommand` are all typed from it.\n//\n// interface FetchShape extends NodeShape {\n// signals: { value: Person[]; loading: boolean };\n// inputs: { url: string };\n// commands: { fetch: (url: string) => Promise<Person[]>; abort: () => void };\n// }\n// const bound = bindNode<FetchShape>(el, desc);\n// bound.signals.value.get(); // ReadSignal<Person[]> — key & type checked\n// bound.set(\"url\", \"/api/people\"); // string enforced\n// bound.command(\"fetch\", \"/api\"); // arg/return inferred\n//\n// The runtime is UNCHANGED — these types are erased; the adapter still validates names\n// against the descriptor at runtime. The default shape below keeps every existing\n// untyped call site compiling exactly as before (all-`unknown`, string keys).\n// Open command map: a command name → any call signature. `(...args: any[])` (NOT\n// `never[]`) is the constraint a USER shape's commands must satisfy — and, crucially,\n// the OPEN fallback used when a shape omits `commands`. `Parameters<(...args: any[])\n// => unknown>` is `any[]`, so an untyped `command(\"run\", \"/api\")` accepts any args,\n// preserving the pre-generic behaviour (symmetric with `inputs` → `unknown`). A shape\n// that DECLARES a precise signature (e.g. `(url: string) => Promise<X>`) still gets\n// exact arg/return checking on the typed path — the loose constraint only widens the\n// DEFAULT, never a declared command. (`no-explicit-any` is disabled for this package.)\ntype OpenCommandMap = Record<string, (...args: any[]) => unknown>;\n\nexport interface NodeShape {\n /** propertyName → latest-snapshot value type (what `signals[name]` / `on(name)` carry). */\n signals?: Record<string, unknown>;\n /** inputName → settable value type (what `set` / `bindInput` accept). */\n inputs?: Record<string, unknown>;\n /** commandName → its call signature (what `command` / `bindCommand` invoke). */\n commands?: OpenCommandMap;\n}\n\n// Back-compat default: a fully-open shape so `bindNode(target, desc)` with no type\n// argument behaves as before (signals keyed by arbitrary string → unknown; any\n// input/command name; unknown values; any command args). Stronger typing is opt-in\n// via the type arg.\nexport interface DefaultNodeShape extends NodeShape {\n signals: Record<string, unknown>;\n inputs: Record<string, unknown>;\n commands: OpenCommandMap;\n}\n\n// Resolve the three sub-maps with sane fallbacks when a shape omits one of them.\ntype SignalsOf<S extends NodeShape> = S[\"signals\"] extends Record<string, unknown>\n ? S[\"signals\"]\n : Record<string, unknown>;\ntype InputsOf<S extends NodeShape> = S[\"inputs\"] extends Record<string, unknown>\n ? S[\"inputs\"]\n : Record<string, unknown>;\ntype CommandsOf<S extends NodeShape> = S[\"commands\"] extends OpenCommandMap ? S[\"commands\"] : OpenCommandMap;\n\n/** Options for `on` — how each event emission folds into the stream signal. */\nexport interface EventStreamOptions<T, C> {\n /** Combine the running value with each emission. Default: latest (replace). */\n fold?: (acc: T | undefined, chunk: C) => T;\n /** Seed value before the first emission. */\n initial?: T;\n}\n\nexport interface BoundNode<S extends NodeShape = DefaultNodeShape> {\n /**\n * Output properties as read-only signals (latest value), keyed by property name and\n * typed from the node shape: `bound.signals.value.get()` carries the declared value\n * type (no longer `unknown`). Keys are the declared property names.\n */\n readonly signals: { readonly [K in keyof SignalsOf<S>]: ReadSignal<SignalsOf<S>[K]> };\n /**\n * An event-token STREAM for a declared property's event: a read signal that folds\n * every emission (latest by default). Unlike `signals[prop]`, it updates on EVERY\n * emit — even when the derived value is equal — because it models occurrences, not\n * state. The chunk per emit is `getter(event)` if the property declares one, else\n * the property's current value.\n *\n * With no fold the value type defaults to the property's declared snapshot type; a\n * `fold` may reshape it (explicit `T`/`C` type args override).\n */\n on<K extends keyof SignalsOf<S>>(prop: K): ReadSignal<SignalsOf<S>[K] | undefined>;\n on<T, C = SignalsOf<S>[keyof SignalsOf<S>]>(\n prop: keyof SignalsOf<S>,\n options: EventStreamOptions<T, C>,\n ): ReadSignal<T | undefined>;\n /** Write a declared input on the node (imperative); value type checked against the shape. */\n set<K extends keyof InputsOf<S>>(name: K, value: InputsOf<S>[K]): void;\n /**\n * Reactively write a declared input from a signal: an effect mirrors `source` into\n * `node[name]`. A same-value guard (`node[name] !== v`) skips redundant writes, so\n * a property whose write re-dispatches an event cannot feed back into an infinite\n * loop. `undefined` follows the wc-bindable applier profile (A2): it is not written\n * while the source has had no other value (the first evaluation, or after another\n * `undefined`), so the element keeps its own initial state; after a value it is\n * written, so the element restores that state. Returns a disposer; the effect is\n * also torn down by `dispose()` (neither writes anything).\n */\n bindInput<K extends keyof InputsOf<S>>(name: K, source: ReadSignal<InputsOf<S>[K]>): () => void;\n /** Invoke a declared command on the node (imperative); args/return typed from the shape. */\n command<K extends keyof CommandsOf<S>>(name: K, ...args: Parameters<CommandsOf<S>[K]>): ReturnType<CommandsOf<S>[K]>;\n /**\n * Command-token: invoke a declared command whenever `trigger` CHANGES. The initial\n * value does not fire (subscribe-without-firing), so a command like `abort` is not\n * triggered on mount. `mapArgs` shapes the call arguments from the trigger value\n * (default: the value itself as a single argument). Returns a disposer; also torn\n * down by `dispose()`.\n */\n bindCommand<K extends keyof CommandsOf<S>, V = unknown>(\n name: K,\n trigger: ReadSignal<V>,\n mapArgs?: (value: V) => Parameters<CommandsOf<S>[K]>,\n ): () => void;\n /**\n * Detach all listeners/effects and make the adapter inert. After dispose the output\n * signals/streams stop updating and `set`/`command`/`bindInput`/`bindCommand`/`on`\n * throw (use-after-dispose). Idempotent.\n */\n dispose(): void;\n}\n\n// Internal target type. `Record<string, any>` is needed to index arbitrary declared\n// members (target[name]) inside the adapter, but it is DELIBERATELY NOT in the public\n// `bindNode` signature — exposing it there erased the caller's element type and let any\n// stray member access type-check. Kept private; the public entry takes `EventTarget`.\ntype NodeTarget = EventTarget & Record<string, any>;\n\n// Internal, fully-loose surface the adapter object is built against (string keys,\n// `unknown` values). The public `BoundNode<S>` is a stricter projection of this same\n// runtime object; `bindNode` casts the built `UntypedBoundNode` to `BoundNode<S>` at\n// return. Kept private so the loose `unknown`-typed methods never leak to callers.\ninterface UntypedBoundNode {\n readonly signals: Record<string, ReadSignal<unknown>>;\n on<T = unknown, C = unknown>(prop: string, options?: EventStreamOptions<T, C>): ReadSignal<T | undefined>;\n set(name: string, value: unknown): void;\n bindInput(name: string, source: ReadSignal<unknown>): () => void;\n command(name: string, ...args: unknown[]): unknown;\n bindCommand(name: string, trigger: ReadSignal<unknown>, mapArgs?: (value: unknown) => unknown[]): () => void;\n dispose(): void;\n}\n\n// The error thrown by `assertLive` when an adapter method is called after dispose.\n// Carries a brand symbol so callers that need to distinguish a post-dispose throw\n// (e.g. nodeSource's abort bridge) can test it structurally instead of matching the\n// message string — the message is free to change without silently breaking the\n// guard. The brand survives even if a consumer's bundler duplicates the class (e.g.\n// `instanceof` across realms), since it's a Symbol on the instance, not a class\n// identity check.\nconst DISPOSED_ERROR = Symbol(\"bindNode.disposed\");\n\n/**\n * Error thrown when a {@link BoundNode} method is invoked after the adapter has been\n * disposed. Every surface that mutates or subscribes — `on` / `set` / `bindInput` /\n * `command` / `bindCommand` — throws this once `dispose()` has run, so a\n * use-after-dispose is loud instead of silently writing/invoking on an inert adapter.\n *\n * Prefer {@link isDisposedError} over `instanceof` for the check: the brand survives a\n * bundler that duplicates the class across realms, where `instanceof` would not. Use it\n * to make teardown-order races robust — e.g. swallow a post-dispose throw while letting\n * any other error surface:\n *\n * ```ts\n * try {\n * bound.command(\"abort\");\n * } catch (err) {\n * if (!isDisposedError(err)) throw err; // expected during teardown; ignore\n * }\n * ```\n */\nexport class DisposedError extends Error {\n readonly [DISPOSED_ERROR] = true;\n}\n\n/**\n * True if `err` is a {@link DisposedError} — i.e. a use-after-dispose error thrown by a\n * {@link BoundNode} method after `dispose()`. Brand-based (checks a Symbol on the\n * instance), so it stays correct even if a consumer's bundler duplicates the\n * `DisposedError` class across module realms, where `err instanceof DisposedError`\n * could be false.\n */\nexport function isDisposedError(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && (err as Record<symbol, unknown>)[DISPOSED_ERROR] === true;\n}\n\nfunction readProperty(target: NodeTarget, name: string): unknown {\n return target[name];\n}\n\n// wc-bindable SPEC § Default Getter: when a property omits `getter`, an adapter MUST\n// read `e.detail`. This adapter used to read the property instead (#238), which\n// diverged from `@wcstack/state` and `@wc-bindable/core` — the same element could\n// bind correctly in one adapter and not the other. Only the initial seed reads the\n// property (SPEC § Initial Sync: there is no event to derive from at bind time).\nconst DEFAULT_GETTER = (e: Event): unknown => (e as CustomEvent).detail;\n\n/**\n * Adapt a wc-bindable node into signals. The public `target` parameter is a plain\n * `EventTarget` (the internal `Record<string, any>` indexing is cast away here, not\n * leaked to callers — see {@link NodeTarget}). Pass an optional {@link NodeShape} type\n * argument to type the result; omit it for the back-compat all-`unknown` shape.\n *\n * @example typed\n * interface FetchShape extends NodeShape {\n * signals: { value: Person[]; loading: boolean };\n * inputs: { url: string };\n * commands: { fetch: (url: string) => Promise<Person[]>; abort: () => void };\n * }\n * const bound = bindNode<FetchShape>(fetchEl, FetchCore.wcBindable);\n * bound.signals.value.get(); // ReadSignal<Person[]>\n * bound.set(\"url\", \"/api/people\"); // string enforced\n */\nexport function bindNode<S extends NodeShape = DefaultNodeShape>(\n target: EventTarget,\n descriptor?: WcBindableDescriptor,\n): BoundNode<S> {\n // The Record<string, any> indexing surface is needed internally to read/write/invoke\n // declared members by name; keep it private to this body.\n const node = target as NodeTarget;\n const desc = descriptor ?? (node.constructor as { wcBindable?: WcBindableDescriptor }).wcBindable;\n if (!desc) {\n // A custom element whose definition has not run yet has no descriptor yet: say so\n // (docs/signals-definition-timing.md §5.3; docs/seam-apps.md, signals-shop)\n const tag = (target as { localName?: unknown }).localName;\n if (typeof tag === \"string\" && tag.includes(\"-\") && typeof customElements !== \"undefined\" && customElements.get(tag) === undefined) {\n throw new Error(\n `bindNode: <${tag}> is not defined yet: load it before this code, or await customElements.whenDefined(\"${tag}\").`,\n );\n }\n throw new Error(\"bindNode: no wc-bindable descriptor provided and none found on target.constructor.wcBindable\");\n }\n\n // Name → declared-entry lookups so set/command/on reject names the node never\n // declared, instead of silently writing/invoking/listening on an arbitrary member.\n const propByName = new Map(desc.properties.map((p) => [p.name, p]));\n const declaredInputs = new Set((desc.inputs ?? []).map((i) => i.name));\n const declaredCommands = new Set((desc.commands ?? []).map((c) => c.name));\n\n const signals: Record<string, WriteSignal<unknown>> = {};\n const removers: Array<() => void> = [];\n let disposed = false;\n\n const assertLive = (op: string, name: string): void => {\n if (disposed) {\n throw new DisposedError(`bindNode.${op}: \"${name}\" called after dispose (the adapter is inert).`);\n }\n };\n\n for (const prop of desc.properties) {\n // Seed with the node's current value so the signal is valid before the first\n // event fires (e.g. FetchCore.value === null at rest).\n const cell = signal<unknown>(readProperty(node, prop.name));\n signals[prop.name] = cell;\n\n const read = prop.getter ?? DEFAULT_GETTER;\n const handler = (event: Event): void => {\n cell.set(read(event));\n };\n node.addEventListener(prop.event, handler);\n removers.push(() => node.removeEventListener(prop.event, handler));\n // Re-seed AFTER subscribing: the initial read above is a snapshot taken before\n // the listener was attached, so a value change in that gap would be missed.\n // Reading the property once more now closes the race (the equality guard makes\n // it a no-op when nothing changed). Note this is the property snapshot, not a\n // getter(event) — there is no event to derive from at bind time, and the SPEC's\n // default getter (`e.detail`) applies to events only.\n cell.set(readProperty(node, prop.name));\n }\n\n // Implemented against a string-keyed, all-`unknown` surface (`UntypedBoundNode`); the\n // generic typing in `BoundNode<S>` is a compile-time projection over the SAME\n // runtime, so the object is built once and cast to `BoundNode<S>` at return. Runtime\n // name validation against the descriptor is unchanged.\n const bound: UntypedBoundNode = {\n signals,\n\n on<T = unknown, C = unknown>(prop: string, options: EventStreamOptions<T, C> = {}): ReadSignal<T | undefined> {\n assertLive(\"on\", prop);\n const propDesc = propByName.get(prop);\n if (!propDesc) {\n throw new Error(`bindNode.on: \"${prop}\" is not a declared property on this node.`);\n }\n const fold = options.fold ?? ((_acc: T | undefined, chunk: C) => chunk as unknown as T);\n // equals: () => false — a stream notifies on EVERY emit, even an equal value.\n const cell = signal<T | undefined>(options.initial, () => false);\n const read = propDesc.getter ?? DEFAULT_GETTER;\n const handler = (event: Event): void => {\n const chunk = read(event) as C;\n cell.set(fold(cell.peek(), chunk));\n };\n node.addEventListener(propDesc.event, handler);\n removers.push(() => node.removeEventListener(propDesc.event, handler));\n return cell;\n },\n\n set(name: string, value: unknown): void {\n assertLive(\"set\", name);\n if (!declaredInputs.has(name)) {\n throw new Error(`bindNode.set: \"${name}\" is not a declared input on this node.`);\n }\n node[name] = value;\n },\n\n bindInput(name: string, source: ReadSignal<unknown>): () => void {\n assertLive(\"bindInput\", name);\n if (!declaredInputs.has(name)) {\n throw new Error(`bindNode.bindInput: \"${name}\" is not a declared input on this node.`);\n }\n // The previous evaluation, written or not. Its initial `undefined` stands for \"no\n // previous evaluation\", which A2 treats the same as a previous `undefined`.\n let previous: unknown = undefined;\n const handle = effect(() => {\n const v = source.get();\n const before = previous;\n previous = v;\n // A2: an `undefined` that follows no value means \"no value yet\" — writing it\n // would overwrite the element's own initial state (its default, or the markup)\n if (v === undefined && before === undefined) return;\n if (node[name] !== v) {\n node[name] = v; // same-value guard above breaks write→event→write loops\n }\n });\n removers.push(() => handle.dispose());\n return () => handle.dispose();\n },\n\n command(name: string, ...args: unknown[]): unknown {\n assertLive(\"command\", name);\n if (!declaredCommands.has(name)) {\n throw new Error(`bindNode.command: \"${name}\" is not a declared command on this node.`);\n }\n if (typeof node[name] !== \"function\") {\n throw new TypeError(`bindNode.command: \"${name}\" is declared but not a function on the node.`);\n }\n return node[name](...args);\n },\n\n bindCommand(name: string, trigger: ReadSignal<unknown>, mapArgs?: (value: unknown) => unknown[]): () => void {\n assertLive(\"bindCommand\", name);\n if (!declaredCommands.has(name)) {\n throw new Error(`bindNode.bindCommand: \"${name}\" is not a declared command on this node.`);\n }\n // Fail fast at bind time (not on first change), so a wrong name surfaces when\n // the subscription is set up rather than silently later inside a flush.\n if (typeof node[name] !== \"function\") {\n throw new TypeError(`bindNode.bindCommand: \"${name}\" is declared but not a function on the node.`);\n }\n let primed = false;\n const handle = effect(() => {\n const v = trigger.get();\n if (!primed) {\n primed = true; // subscribe on mount without firing (emit on CHANGE only)\n return;\n }\n const args = mapArgs ? mapArgs(v) : [v];\n node[name](...args);\n });\n removers.push(() => handle.dispose());\n return () => handle.dispose();\n },\n\n dispose(): void {\n if (disposed) {\n return; // idempotent\n }\n disposed = true;\n for (const remove of removers) {\n remove();\n }\n },\n };\n\n return bound as unknown as BoundNode<S>;\n}\n\n/**\n * Build a `resource` source from a wc-bindable node, bridging the resource's\n * AbortSignal to the node's cancel command (default `\"abort\"`) before delegating to\n * `run`. This generalizes the earlier hand-wired `sig → core.abort()` bridge (docs §8\n * (e), §5-2): wrap the result in `resource({ args })` and any node that declares an\n * abort command gets switchMap-style cancel/restart for free — an `args` change\n * aborts the in-flight call (firing the node's abort command, which cancels its real\n * AbortController) and starts the next.\n *\n * The node's own value/loading/error stay available via `bound.signals`; `resource`\n * here is used for the cancel/restart lifecycle, not to re-derive that triad.\n *\n * @example\n * const bound = bindNode(fetchEl);\n * const r = resource(\n * nodeSource(bound, (b, id) => b.command(\"fetch\", `/api/${id}`)),\n * { args: () => id.get() },\n * );\n */\nexport function nodeSource<T, A = void, S extends NodeShape = DefaultNodeShape>(\n bound: BoundNode<S>,\n run: (node: BoundNode<S>, args: A) => Promise<T> | T,\n options: { abort?: string } = {},\n): ResourceSource<T, A> {\n const abortName = options.abort ?? \"abort\";\n return (args, signal) => {\n // Honor the resource's cancel by invoking the node's abort command. `once`:\n // each resource run gets a fresh AbortSignal, so the listener fires at most once.\n //\n // GUARD: the abort listener runs SYNCHRONOUSLY inside AbortController.abort().\n // If `bound` was already disposed (e.g. the adapter and the resource share an\n // owner and the adapter's disposer ran first), `command` throws assertLive —\n // and a throw out of an abort listener surfaces as an unhandled exception during\n // the synchronous abort() call. Swallow a post-dispose throw so teardown order is\n // robust; report any OTHER error via the platform reporter without breaking abort.\n signal.addEventListener(\n \"abort\",\n () => {\n try {\n // `abortName` is a runtime string (validated by the adapter); the cast lets\n // it reach `command` regardless of the typed command-name union of `S`.\n (bound.command as (name: string, ...args: unknown[]) => unknown)(abortName);\n } catch (err) {\n // Brand-based check (not a message regex): a post-dispose throw is\n // expected here and swallowed; any OTHER error is reported.\n if (!isDisposedError(err)) {\n reportError(err);\n }\n }\n },\n { once: true },\n );\n return run(bound, args);\n };\n}\n","// Async resource (v1 design notes).\n//\n// Adapts an async producer into a reactive `{ value, loading, error }` triad —\n// the same shape FetchCore exposes (value/loading/error). When the resource's\n// `args` (a reactive getter) change, the in-flight request is aborted and a fresh\n// one starts: dependency-driven cancel/restart, i.e. RxJS switchMap.\n//\n// This is the signals-side counterpart of the state-side `$streams` adapter\n// (docs/state-stream-type-design.md §4-1). The hard part — making sure a stale\n// response from a superseded request never lands on the new state — is handled\n// here by checking `signal.aborted` before committing any result.\n\nimport { signal, innerEffect as effect, onCleanup, ReadSignal } from \"./reactive.js\";\n\nexport interface ResourceState<T> {\n value: ReadSignal<T | undefined>;\n // Progress is a BOOLEAN here, intentionally different from streamResource's\n // `status` enum. A resource is single-shot (one request → resolve/reject), so\n // its progress is binary: in-flight or not. A stream is continuous (idle →\n // active → done/error), so it needs the enum. The \"shared contract\" with the\n // state-side `$streams` adapter covers the cancel/restart SEMANTICS, not this\n // progress representation. (docs §8 (a)).\n loading: ReadSignal<boolean>;\n /** Last error, or `null` when there is none. Initial value is `null`; a (re)start resets it to `null`. */\n error: ReadSignal<unknown>;\n /** Abort any in-flight request and stop reacting to `args` changes. */\n dispose(): void;\n}\n\nexport interface ResourceOptions<T, A> {\n /** Reactive inputs. Reading signals here wires restart-on-change. */\n args?: () => A;\n /** Seed value before the first resolution. */\n initial?: T;\n}\n\nexport type ResourceSource<T, A> = (args: A, signal: AbortSignal) => Promise<T> | T;\n\nexport function resource<T, A = void>(\n source: ResourceSource<T, A>,\n options: ResourceOptions<T, A> = {},\n): ResourceState<T> {\n const value = signal<T | undefined>(options.initial);\n const loading = signal<boolean>(false);\n const error = signal<unknown>(null);\n\n let controller: AbortController | null = null;\n\n const runner = effect(() => {\n // Reading args() inside the effect is what subscribes us to its signals, so a\n // change re-runs this body — that IS the restart trigger.\n //\n // NOTE (effect-internal writes): this effect writes loading/error/value, which\n // are signals OTHER effects may observe. A write that actually CHANGES the value\n // marks those observers stale and queues them on the same flush; the drain loop\n // then runs them in the same tick. (A same-value write — e.g. error.set(null)\n // when error is already null — is a no-op via the equality guard and notifies\n // nothing.) We never read these signals inside THIS effect, so we don't dirty\n // our own dependency — no cycle. (docs §8 (a)).\n const a = (options.args ? options.args() : undefined) as A;\n\n // Abort the previous request before starting the next (switchMap).\n controller?.abort();\n const ac = new AbortController();\n controller = ac;\n\n loading.set(true);\n error.set(null);\n\n // Call the source SYNCHRONOUSLY (so it receives ac.signal immediately and can\n // wire its abort listener before any teardown), but guard it with try/catch so\n // a synchronous throw is normalized into the same error/loading state as a\n // rejected promise. Without the guard a sync throw would escape the effect body\n // (and, on the initial run, the resource() call itself), leaving loading stuck\n // true and error unset.\n let produced: Promise<T> | T;\n try {\n produced = source(a, ac.signal);\n } catch (err) {\n error.set(err);\n loading.set(false);\n return;\n }\n\n // Settle via two-arm `.then` rather than `await` + try/catch (streamResource's\n // shape): a resource is SINGLE-SHOT — one resolve/reject lands once — so a flat\n // resolved/rejected pair maps cleanly. A stream is a CONTINUOUS loop whose chunks\n // and termination must share one error path, which an `await` loop in try/catch\n // expresses; that structure would be needless here.\n Promise.resolve(produced).then(\n (resolved) => {\n // Drop the result if this request was superseded/disposed: committing it\n // would let a stale response overwrite the newer request's state.\n if (ac.signal.aborted) {\n return;\n }\n value.set(resolved);\n loading.set(false);\n },\n (err) => {\n if (ac.signal.aborted) {\n return;\n }\n error.set(err);\n loading.set(false);\n },\n );\n });\n\n const dispose = (): void => {\n controller?.abort();\n runner.dispose();\n };\n\n // Auto-dispose with the enclosing owner (createRoot / parent effect), so a\n // resource created inside a component is aborted on unmount. No-op when there\n // is no owner — the caller then disposes manually.\n onCleanup(dispose);\n\n return { value, loading, error, dispose };\n}\n","// Stream resource (docs §8 (a)). The signals-side counterpart of the state-side\n// `$streams` adapter (docs/state-stream-type-design.md).\n//\n// Adapts a continuous async flow (async iterable / ReadableStream / async\n// generator) into a single reactive value by FOLDING each chunk:\n// - latest (default): replace — value becomes the last chunk.\n// - reduce: accumulate — value = fold(acc, chunk), needs `initial`.\n// When the resource's `args` change, the in-flight stream is aborted and a fresh\n// one starts (switchMap), with `value` reset to `initial`.\n//\n// Deliberate non-goal: backpressure. The fold result IS the buffer; demand does\n// not flow back to the producer. Unbounded accumulation of an infinite stream is\n// a footgun — bound the fold (latest / count / last-N / window) for live streams.\n// This mirrors the state `$streams` norm and is what lets the impedance mismatch\n// be resolved honestly (state-stream §0, §4-3).\n//\n// Shared contract with state `$streams` (settled in v1):\n// - source(args, signal) receives an AbortSignal; honoring it drives restart.\n// - restart RESETS value to `initial`; error KEEPS the last value.\n// - status companion: \"idle\" | \"active\" | \"done\" | \"error\".\n// - async iterable is the lingua franca; anything getReader-bearing\n// (ReadableStream) is read via getReader() — see rescue levels below.\n//\n// CONTRACT (cooperative cancellation — STRONG REQUIREMENT): the `source` MUST honor\n// the `AbortSignal` it is given. Honoring it is what drives switchMap restart/dispose;\n// a source that ignores it cannot be reliably cancelled.\n//\n// Rescue levels on abort:\n// - ReadableStream: FULLY rescued. A parked read() is force-unwound via\n// reader.cancel(), which both releases the underlying source and settles the\n// pending read() so the loop unwinds. Anything getReader-bearing is routed\n// through this path even when it is ALSO natively async-iterable (Node 18+ /\n// Chrome 124+ / Firefox): the spec serializes asyncIterator.return() behind\n// the pending next() ([[ongoingPromise]]), so the AsyncIterable rescue below\n// cannot force-unwind a parked read on a native ReadableStream.\n// - AsyncIterable / async generator: PARTIALLY rescued. On abort we call\n// iterator.return() to trigger the generator's finally/cleanup. But a parked\n// `await` (the producer stalling before its next yield while IGNORING `signal`)\n// cannot be force-unwound from outside — return() only takes effect when the\n// generator next resumes. So a source that parks forever and never observes\n// `signal` still leaks its consume() task. Honor `signal` to bound this.\n// The `if (signal.aborted) return` check only runs after a chunk arrives, not while\n// parked — it drops stale chunks but is not, by itself, a cancellation mechanism.\n\nimport { signal, innerEffect as effect, onCleanup, ReadSignal, WriteSignal } from \"./reactive.js\";\n\nexport type StreamStatus = \"idle\" | \"active\" | \"done\" | \"error\";\n\nexport interface StreamResourceState<T> {\n value: ReadSignal<T | undefined>;\n // Progress is an ENUM here, intentionally different from resource's `loading`\n // boolean: a continuous stream moves idle → active → done/error, which a boolean\n // cannot express. The cancel/restart contract is shared with `resource` and the\n // state-side `$streams` adapter; the progress representation is not.\n status: ReadSignal<StreamStatus>;\n /** Last error, or `null` when there is none. Initial value is `null`; a (re)start resets it to `null`. */\n error: ReadSignal<unknown>;\n /** Abort the in-flight stream and stop reacting to `args`. */\n dispose(): void;\n}\n\nexport interface StreamResourceOptions<T, C, A> {\n /** Reactive inputs. Reading signals here wires restart-on-change. */\n args?: () => A;\n /** Combine the running value with each chunk. Default: latest (replace). */\n fold?: (acc: T | undefined, chunk: C) => T;\n /** Seed value, and the value `value` is reset to on each (re)start. */\n initial?: T;\n}\n\nexport type StreamProducer<C> = AsyncIterable<C> | ReadableStream<C>;\n\n/**\n * Produce a stream for the current `args`. The `signal` aborts on restart/dispose —\n * the source **MUST honor it** (this is a hard contract, not a suggestion): a\n * `ReadableStream` is fully cancelled via `reader.cancel()`, and an async generator\n * should observe `signal` (e.g. reject/break on `signal.aborted`) so a parked `await`\n * can unwind. On abort the adapter also calls the iterator's `return()` to run a\n * generator's `finally`, but a generator that parks forever while ignoring `signal`\n * cannot be force-unwound and will leak. See the module header's CONTRACT.\n */\nexport type StreamSource<C, A> = (\n args: A,\n signal: AbortSignal,\n) => StreamProducer<C> | Promise<StreamProducer<C>>;\n\nexport function streamResource<T, C = T, A = void>(\n source: StreamSource<C, A>,\n options: StreamResourceOptions<T, C, A> = {},\n): StreamResourceState<T> {\n const fold = options.fold ?? ((_acc: T | undefined, chunk: C) => chunk as unknown as T);\n const value = signal<T | undefined>(options.initial);\n const status = signal<StreamStatus>(\"idle\");\n const error = signal<unknown>(null);\n\n let controller: AbortController | null = null;\n\n const runner = effect(() => {\n // NOTE (effect-internal writes): like `resource`, this effect writes\n // value/status/error — signals other effects may observe. Those observers are\n // queued on the same flush and run in the same tick. This effect never reads\n // those signals, so it does not dirty its own dependency (no cycle). The async\n // `consume` writes them later from microtasks/timers, outside this flush.\n const a = (options.args ? options.args() : undefined) as A;\n\n controller?.abort();\n const ac = new AbortController();\n controller = ac;\n\n // Reset for the new run: a restart starts the fold from `initial`.\n value.set(options.initial);\n error.set(null);\n status.set(\"active\");\n\n void consume(source, a, ac.signal, fold, value, status, error);\n });\n\n const dispose = (): void => {\n controller?.abort();\n runner.dispose();\n };\n onCleanup(dispose);\n\n return { value, status, error, dispose };\n}\n\nasync function consume<T, C, A>(\n source: StreamSource<C, A>,\n args: A,\n signal: AbortSignal,\n fold: (acc: T | undefined, chunk: C) => T,\n // Use the public WriteSignal type instead of re-declaring an inline subset, so\n // these stay in lockstep with the signal API (no structural drift).\n value: WriteSignal<T | undefined>,\n status: WriteSignal<StreamStatus>,\n error: WriteSignal<unknown>,\n): Promise<void> {\n // Obtain the iterator EXPLICITLY (not via `for await`'s implicit one) so abort can\n // call `iterator.return()` to trigger an AsyncIterable / async generator's\n // `finally`/cleanup. A `for await` only calls `.return()` when the loop itself exits;\n // if the producer is PARKED (awaiting before the next yield while ignoring `signal`),\n // the loop never advances, so the implicit `.return()` never runs and the task leaks\n // past restart/dispose. Calling `.return()` on abort is the PARTIAL rescue: the\n // parked `await` cannot be force-unwound from outside, but once the generator resumes\n // (its next tick), `.return()` makes it run its `finally` and stop — recovering the\n // common \"generator wakes up after abort\" case. The ReadableStream path is fully\n // rescued via `reader.cancel()` (see `readableToAsyncIterable`).\n let iterator: AsyncIterator<C> | null = null;\n // Guard against returning the SAME iterator twice. `onAbort` is reachable two ways:\n // the abort listener, and the explicit call on line ~163 when abort raced the\n // `await source(...)`. The guard keys on the iterator instance (not a plain \"ran\"\n // flag): the listener firing with iterator still null must NOT consume the single\n // real cleanup that the explicit call performs once the iterator exists. So we only\n // mark an iterator returned once we have actually called `.return()` on it.\n let returned: AsyncIterator<C> | null = null;\n const onAbort = (): void => {\n if (!iterator || iterator === returned) {\n return; // nothing to release yet, or already released this iterator\n }\n returned = iterator;\n // Fire the iterator's cleanup. Swallow any throw/rejection from `.return()` — we\n // are tearing down; a producer that rejects on return must not surface here.\n try {\n void iterator.return?.()?.then?.(undefined, () => {});\n } catch {\n // `.return()` threw synchronously while tearing down — ignore.\n }\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n try {\n const produced = await source(args, signal);\n iterator = iterate(produced, signal)[Symbol.asyncIterator]();\n if (signal.aborted) {\n // Aborted while awaiting the source: the abort listener already ran (iterator\n // was still null then), so explicitly release the just-produced iterator now —\n // this fires a generator's finally / a ReadableStream's cancel for the\n // resource we created but will never iterate.\n onAbort();\n return;\n }\n for (;;) {\n const result = await iterator.next();\n if (result.done) {\n break;\n }\n if (signal.aborted) {\n return; // stale chunk from a superseded/disposed run — drop it\n }\n value.set(fold(value.peek(), result.value));\n }\n if (signal.aborted) {\n return; // stream ended but this run was aborted — don't mark done\n }\n status.set(\"done\");\n } catch (e) {\n if (signal.aborted) {\n return; // an abort that surfaced as a throw is not an error\n }\n error.set(e); // keep the last folded value (do not reset)\n status.set(\"error\");\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction iterate<C>(produced: StreamProducer<C>, signal: AbortSignal): AsyncIterable<C> {\n // Anything ReadableStream-shaped (has getReader) takes the reader path FIRST —\n // even when it is also async-iterable. On runtimes where ReadableStream\n // implements native async iteration (Node 18+ / Chrome 124+ / Firefox), the\n // spec serializes `iterator.return()` behind the pending `next()`\n // ([[ongoingPromise]]), so the AsyncIterable rescue cannot force-unwind a\n // parked read: abort would hang the consume task until the producer's next\n // chunk (or forever on a silent stream), leaking the underlying source.\n // `reader.cancel()` has no such ordering — routing every getReader-bearing\n // source through it keeps the FULL rescue promised for ReadableStream.\n if (typeof (produced as ReadableStream<C>)?.getReader === \"function\") {\n return readableToAsyncIterable(produced as ReadableStream<C>, signal);\n }\n if (typeof (produced as AsyncIterable<C>)?.[Symbol.asyncIterator] === \"function\") {\n return produced as AsyncIterable<C>;\n }\n throw new TypeError(\n \"streamResource: source must return an AsyncIterable or a ReadableStream (got neither).\",\n );\n}\n\nasync function* readableToAsyncIterable<C>(\n stream: ReadableStream<C>,\n signal: AbortSignal,\n): AsyncGenerator<C> {\n const reader = stream.getReader();\n // A ReadableStream read() does NOT observe an AbortSignal on its own. Without\n // this, a switchMap restart / dispose leaves the previous reader parked in a\n // pending read() forever, leaking the underlying source. Cancelling on abort\n // both releases the source AND settles the pending read() so the for-await\n // unwinds and the finally below can release the lock. Abort is the only\n // early-exit path for this generator (the consumer never calls .return()\n // without aborting), so this is the sole place a non-drained stream is cancelled.\n const onAbort = (): void => {\n void reader.cancel().catch(() => {}); // tearing down; swallow a rejected cancel\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n yield value as C;\n }\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n reader.releaseLock();\n }\n}\n"],"names":["effect"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACM,SAAU,WAAW,CAAC,GAAY,EAAA;AACtC,IAAA,MAAM,CAAC,GAAI,UAAqD,CAAC,WAAW;AAC5E,IAAA,IAAI,OAAO,CAAC,KAAK,UAAU,EAAE;QAC3B,CAAC,CAAC,GAAG,CAAC;IACR;SAAO;AACL,QAAA,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC;IACpB;AACF;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAcA;;;;AAIG;SACa,KAAK,GAAA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