@hyperfixi/reactivity 2.6.0 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
@@ -579,6 +589,7 @@ function makeEvaluateBindFeature(runtime) {
579
589
  const context = ctx;
580
590
  const owner = context.me ?? document.body;
581
591
  const n = node;
592
+ const { getElementScopeMap } = await import("@hyperfixi/core");
582
593
  const leftIsVar = isVarRef(n.left);
583
594
  const rightIsVar = isVarRef(n.right);
584
595
  let varSide = null;
@@ -643,14 +654,14 @@ function makeEvaluateBindFeature(runtime) {
643
654
  };
644
655
  const readVar = () => {
645
656
  if (varSide.isGlobal) return context.globals?.get(varSide.name);
646
- return context.locals?.get(varSide.name);
657
+ return getElementScopeMap(owner).get(varSide.name);
647
658
  };
648
659
  const writeVar = (value) => {
649
660
  if (varSide.isGlobal) {
650
661
  context.globals?.set(varSide.name, value);
651
662
  reactive.notifyGlobal(varSide.name);
652
663
  } else {
653
- context.locals?.set(varSide.name, value);
664
+ getElementScopeMap(owner).set(varSide.name, value);
654
665
  reactive.notifyElement(owner, varSide.name);
655
666
  }
656
667
  };
@@ -688,7 +699,7 @@ function isVarRef(node) {
688
699
  if (!node) return false;
689
700
  if (node.type !== "identifier") return false;
690
701
  const scope = node.scope;
691
- if (scope === "local" || scope === "global") return true;
702
+ if (scope === "local" || scope === "element" || scope === "global") return true;
692
703
  const name = node.name ?? "";
693
704
  return name.startsWith("$") || name.startsWith(":");
694
705
  }
@@ -700,7 +711,7 @@ function varRefInfo(node) {
700
711
  if (scope === "global") {
701
712
  isGlobal = true;
702
713
  name = rawName;
703
- } else if (scope === "local") {
714
+ } else if (scope === "local" || scope === "element") {
704
715
  isGlobal = false;
705
716
  name = rawName;
706
717
  } else if (rawName.startsWith("$")) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/signals.ts","../src/caret-var.ts","../src/live.ts","../src/when.ts","../src/bind.ts"],"sourcesContent":["/**\n * @hyperfixi/reactivity — signal-based reactive features for hyperfixi.\n *\n * Adds four constructs from upstream _hyperscript 0.9.90:\n *\n * live [commandList] end reactive block — body re-runs\n * when tracked reads change.\n *\n * when <expr> [or <expr>]* changes observer — body runs when any\n * [commandList] end watched expression changes.\n *\n * bind <var> to <element> two-way DOM ⇄ var binding.\n *\n * ^name [on <target>] DOM-scoped inherited variable\n * (read + write with `^`).\n *\n * Install:\n *\n * ```ts\n * import { createRuntime, installPlugin } from '@hyperfixi/core';\n * import { reactivityPlugin } from '@hyperfixi/reactivity';\n *\n * const runtime = createRuntime();\n * installPlugin(runtime, reactivityPlugin);\n * ```\n */\n\nimport type { HyperfixiPlugin, HyperfixiPluginContext } from '@hyperfixi/core';\nimport { reactive } from './signals';\nimport { parseCaretPrefix, makeEvaluateCaretVar, makeWriteCaretVar } from './caret-var';\nimport { parseLiveFeature, makeEvaluateLiveFeature } from './live';\nimport { parseWhenFeature, makeEvaluateWhenFeature } from './when';\nimport { parseBindFeature, makeEvaluateBindFeature } from './bind';\n\nexport { reactive } from './signals';\nexport type { CaretVarNode } from './caret-var';\nexport type { LiveFeatureNode } from './live';\nexport type { WhenFeatureNode } from './when';\nexport type { BindFeatureNode } from './bind';\n\n/**\n * The plugin object. Install once at app startup; re-installing is idempotent\n * (guarded via a `parserExtensions.hasFeature('live')` check).\n *\n * Registers:\n * - Features: `live`, `when`, `bind` (top-level features with `end` bodies)\n * - Prefix op: `^` (primary expression for DOM-scoped vars)\n * - Node evaluators: `liveFeature`, `whenFeature`, `bindFeature`, `caretVar`\n * - A node writer for `caretVar` so `set ^X to Y` flows through `reactive.writeCaret`\n * - Global read/write hooks so `$name` reads track and writes notify\n *\n * Effect cleanup: each effect-creating evaluator calls\n * `context.registerCleanup(owner, stop, ...)` so the core runtime tears effects\n * down when their owning element is cleaned up. There is no separate plugin-level\n * cleanup hook; `reactive.stopElementEffects(el)` is exposed for explicit teardown\n * by tests and consumers that manage element lifecycle outside the runtime.\n */\nexport const reactivityPlugin: HyperfixiPlugin & { version: string } = {\n name: '@hyperfixi/reactivity',\n version: '2.3.1',\n install(ctx: HyperfixiPluginContext) {\n const { parserExtensions, runtime } = ctx;\n\n // Idempotency: the parser-extension registry is process-singleton, so\n // re-installing into a fresh runtime would otherwise stack additional\n // global read/write hooks on every call. `snapshot()`/`restore()` clears\n // the feature registry — when tests roll back the registry, this guard\n // re-enables a fresh install.\n if (parserExtensions.hasFeature('live')) return;\n\n // Parser hooks — three block features plus a primary-expression caret.\n parserExtensions.registerFeature('live', parseLiveFeature as never);\n parserExtensions.registerFeature('when', parseWhenFeature as never);\n parserExtensions.registerFeature('bind', parseBindFeature as never);\n parserExtensions.registerPrefixOperator('^', 85, parseCaretPrefix as never);\n\n // Runtime evaluators. Features capture `runtime` so effect re-runs can\n // dispatch body commands without going through module-scope state.\n parserExtensions.registerNodeEvaluator(\n 'liveFeature',\n makeEvaluateLiveFeature(runtime as never) as never\n );\n parserExtensions.registerNodeEvaluator(\n 'whenFeature',\n makeEvaluateWhenFeature(runtime as never) as never\n );\n parserExtensions.registerNodeEvaluator(\n 'bindFeature',\n makeEvaluateBindFeature(runtime as never) as never\n );\n parserExtensions.registerNodeEvaluator(\n 'caretVar',\n makeEvaluateCaretVar(runtime as never) as never\n );\n\n // Caret-var write: lets the core `set` command dispatch `set ^X to Y`\n // through `reactive.writeCaret`. Resolves `on <target>` via the captured\n // runtime — no global-scope indirection.\n parserExtensions.registerNodeWriter('caretVar', makeWriteCaretVar(runtime as never) as never);\n\n // Global-write hook: notify the reactive graph whenever `$name` is set.\n // The returned disposer is intentionally discarded — the install-time\n // idempotency guard above is the sole gate against double-registration.\n parserExtensions.registerGlobalWriteHook((name: string, _value: unknown, _context: unknown) => {\n reactive.notifyGlobal(name);\n });\n\n // Global-read hook: track the read against the current effect (if any)\n // so effects re-run when the global changes.\n parserExtensions.registerGlobalReadHook((name: string, _context: unknown) => {\n reactive.trackGlobal(name);\n });\n\n // Local hooks — analogous to globals, but keyed by `context.me` so each\n // element holds independent state. A `set :foo to ...` running in a\n // handler with `me=button1` notifies effects subscribed to (button1, 'foo');\n // a `set :foo` in a different `me` won't reach them. This matches how\n // locals already work — they're never cross-context — and lets two\n // components hold independent `:foo` state without interference.\n parserExtensions.registerLocalWriteHook((name: string, _value: unknown, context) => {\n const owner = (context as { me?: Element | null }).me ?? null;\n if (owner) reactive.notifyElement(owner, name);\n });\n\n parserExtensions.registerLocalReadHook((name: string, context) => {\n const owner = (context as { me?: Element | null }).me ?? null;\n if (owner) reactive.trackElement(owner, name);\n });\n },\n};\n\nexport default reactivityPlugin;\n","/**\n * Signal/effect reactive core.\n *\n * Models three dependency kinds for v1:\n * - `global` — `$name` variables in `context.globals`\n * - `element` — `^name` DOM-scoped variables (per-element storage)\n * - `dom` — DOM properties read via `input`/`change` listeners\n *\n * Inspired by upstream _hyperscript 0.9.91's `src/core/runtime/reactivity.js`\n * but reimplemented in TypeScript against hyperfixi's types. Batched via\n * `queueMicrotask` so synchronous writes coalesce into a single flush. Cycle\n * detection halts at >100 consecutive triggers (matching upstream).\n *\n * External packages never see `Effect` or `Reactive` directly — they hold\n * the disposer returned by `createEffect()` and call it when the owning\n * element is cleaned up.\n */\n\nexport type DepKind = 'global' | 'element' | 'dom';\n\n/**\n * Whether reactive debug logging is enabled. Mirrors the core convention:\n * `localStorage.setItem('hyperfixi:debug', '*')` enables, anything else (or no\n * `localStorage`) disables. Cheap call — no caching, since users toggle this\n * interactively in the console.\n */\nfunction debugEnabled(): boolean {\n try {\n return typeof localStorage !== 'undefined' && localStorage.getItem('hyperfixi:debug') !== null;\n } catch {\n return false;\n }\n}\n\nfunction debugWarn(message: string, err: unknown): void {\n if (!debugEnabled()) return;\n if (typeof console === 'undefined') return;\n console.warn(`[@hyperfixi/reactivity] ${message}`, err);\n}\n\nexport interface Dep {\n readonly key: string;\n readonly kind: DepKind;\n readonly name: string;\n readonly element: Element | null;\n}\n\nconst globalDepKey = (name: string): string => `global:${name}`;\nconst elementDepKey = (el: Element, name: string): string => `element:${reactiveIdFor(el)}:${name}`;\nconst domDepKey = (el: Element, prop: string): string => `dom:${reactiveIdFor(el)}:${prop}`;\n\n// WeakMap-based id assignment so we don't monkey-patch DOM nodes. Ids are\n// per-process and only used to construct stable string keys for an effect's\n// per-effect dependency dedup map.\nconst _reactiveIds = new WeakMap<Element, number>();\nlet _idCounter = 0;\nfunction reactiveIdFor(el: Element): number {\n const existing = _reactiveIds.get(el);\n if (existing !== undefined) return existing;\n const id = ++_idCounter;\n _reactiveIds.set(el, id);\n return id;\n}\n\nexport class Effect {\n readonly dependencies = new Map<string, Dep>();\n private lastValue: unknown = undefined;\n private _stopped = false;\n private _consecutiveTriggers = 0;\n\n constructor(\n private readonly r: Reactive,\n readonly expression: () => unknown | Promise<unknown>,\n readonly handler: (value: unknown) => void | Promise<void>,\n readonly element: Element | null\n ) {}\n\n get stopped(): boolean {\n return this._stopped;\n }\n\n /**\n * Run the effect for the first time: collect dependencies, subscribe, call\n * handler with the initial value. Errors in expression evaluation are caught\n * and silently swallowed (matches upstream's tolerance).\n */\n async initialize(): Promise<void> {\n if (this._stopped) return;\n try {\n const value = await this.r._runWithEffect(this, this.expression);\n this.lastValue = value;\n if (value !== undefined && value !== null) {\n await this.handler(value);\n }\n } catch (err) {\n // Swallow — expression evaluation failed during initial read. Surface\n // via debug log so users diagnosing \"my effect never fires\" can see why.\n debugWarn('effect.initialize failed', err);\n }\n }\n\n /**\n * Re-run the effect after a notify. Cycle-detects (halts at 101 consecutive\n * triggers). If the new value is Object.is-equal to the last, the handler\n * is skipped. If the owning element has disconnected, the effect stops\n * itself and returns.\n */\n async run(): Promise<void> {\n if (this._stopped) return;\n if (this.element && !this.element.isConnected) {\n this.stop();\n return;\n }\n this._consecutiveTriggers++;\n if (this._consecutiveTriggers > 100) {\n if (typeof console !== 'undefined') {\n console.error(\n '[@hyperfixi/reactivity] Effect halted: > 100 consecutive triggers (cycle detected).'\n );\n }\n this.stop();\n return;\n }\n try {\n const value = await this.r._runWithEffect(this, this.expression);\n if (Object.is(value, this.lastValue)) return;\n this.lastValue = value;\n await this.handler(value);\n } catch (err) {\n // Swallow — expression/handler errors don't break the microtask flush.\n debugWarn('effect.run failed', err);\n }\n }\n\n resetTriggerCount(): void {\n this._consecutiveTriggers = 0;\n }\n\n /**\n * Stop the effect and remove it from all dependency subscriptions. Safe to\n * call multiple times.\n */\n stop(): void {\n if (this._stopped) return;\n this._stopped = true;\n this.r._unsubscribeEffect(this);\n this.dependencies.clear();\n }\n}\n\ninterface ElementState {\n symbolSubs: Map<string, Set<Effect>>;\n caretVars: Map<string, unknown>;\n domHandlers: Map<string, DomHandler>;\n effects: Set<Effect>;\n}\n\ninterface DomHandler {\n subs: Set<Effect>;\n detach: () => void;\n}\n\nexport class Reactive {\n private currentEffect: Effect | null = null;\n private pending = new Set<Effect>();\n private scheduled = false;\n\n private globalSubs = new Map<string, Set<Effect>>();\n private elementState = new WeakMap<Element, ElementState>();\n\n private getElementState(el: Element): ElementState {\n let s = this.elementState.get(el);\n if (!s) {\n s = {\n symbolSubs: new Map(),\n caretVars: new Map(),\n domHandlers: new Map(),\n effects: new Set(),\n };\n this.elementState.set(el, s);\n }\n return s;\n }\n\n /**\n * Internal helper invoked by Effect — installs `this` as the current effect,\n * runs the expression, then restores the previous current-effect pointer.\n * Track* methods (called from read-paths) consult `currentEffect` to know\n * which effect to subscribe.\n */\n async _runWithEffect(e: Effect, fn: () => unknown | Promise<unknown>): Promise<unknown> {\n const prev = this.currentEffect;\n this.currentEffect = e;\n // Unsubscribe from previous deps before re-running. The expression will\n // re-record whatever it actually reads this time, avoiding stale subs.\n this._unsubscribeEffect(e);\n e.dependencies.clear();\n try {\n return await fn();\n } finally {\n this.currentEffect = prev;\n }\n }\n\n // ---------------------------------------------------------------------------\n // Track (read-path) — invoked from interceptors / evaluators.\n // ---------------------------------------------------------------------------\n\n trackGlobal(name: string): void {\n const e = this.currentEffect;\n if (!e) return;\n const key = globalDepKey(name);\n if (e.dependencies.has(key)) return;\n e.dependencies.set(key, { key, kind: 'global', name, element: null });\n let subs = this.globalSubs.get(name);\n if (!subs) {\n subs = new Set();\n this.globalSubs.set(name, subs);\n }\n subs.add(e);\n }\n\n trackElement(el: Element, name: string): void {\n const e = this.currentEffect;\n if (!e) return;\n const key = elementDepKey(el, name);\n if (e.dependencies.has(key)) return;\n e.dependencies.set(key, { key, kind: 'element', name, element: el });\n const state = this.getElementState(el);\n let subs = state.symbolSubs.get(name);\n if (!subs) {\n subs = new Set();\n state.symbolSubs.set(name, subs);\n }\n subs.add(e);\n state.effects.add(e);\n }\n\n trackDomProperty(el: Element, prop: string): void {\n const e = this.currentEffect;\n if (!e) return;\n const key = domDepKey(el, prop);\n if (e.dependencies.has(key)) return;\n e.dependencies.set(key, { key, kind: 'dom', name: prop, element: el });\n const state = this.getElementState(el);\n let handler = state.domHandlers.get(prop);\n if (!handler) {\n const subs = new Set<Effect>();\n const listener = (): void => {\n for (const effect of subs) this.schedule(effect);\n };\n // Use both input and change to cover radios/selects which don't fire input.\n el.addEventListener('input', listener);\n el.addEventListener('change', listener);\n handler = {\n subs,\n detach: () => {\n el.removeEventListener('input', listener);\n el.removeEventListener('change', listener);\n },\n };\n state.domHandlers.set(prop, handler);\n }\n handler.subs.add(e);\n state.effects.add(e);\n }\n\n // ---------------------------------------------------------------------------\n // Notify (write-path) — schedules dependent effects for re-run.\n // ---------------------------------------------------------------------------\n\n notifyGlobal(name: string): void {\n const subs = this.globalSubs.get(name);\n if (!subs) return;\n for (const e of subs) this.schedule(e);\n }\n\n notifyElement(el: Element, name: string): void {\n const state = this.elementState.get(el);\n if (!state) return;\n const subs = state.symbolSubs.get(name);\n if (!subs) return;\n for (const e of subs) this.schedule(e);\n }\n\n // ---------------------------------------------------------------------------\n // Effect lifecycle.\n // ---------------------------------------------------------------------------\n\n /**\n * Create + initialize an effect. Returns a disposer that stops the effect.\n * Callers are expected to register the disposer with the core runtime's\n * cleanup registry so it fires on element removal.\n */\n createEffect(\n expression: () => unknown | Promise<unknown>,\n handler: (value: unknown) => void | Promise<void>,\n owner: Element | null\n ): () => void {\n const e = new Effect(this, expression, handler, owner);\n if (owner) this.getElementState(owner).effects.add(e);\n // Fire initialize asynchronously so the caller can set up cleanup registration\n // before the first run touches the DOM.\n queueMicrotask(() => {\n void e.initialize();\n });\n return () => e.stop();\n }\n\n /**\n * Stop all effects owned by an element. Called by the reactivity plugin's\n * cleanup hook registered via `runtime.getCleanupRegistry()`.\n */\n stopElementEffects(el: Element): void {\n const state = this.elementState.get(el);\n if (!state) return;\n for (const e of Array.from(state.effects)) e.stop();\n state.effects.clear();\n }\n\n /**\n * Internal: remove an effect's entries from all subscriber sets. Called by\n * `Effect.stop()`.\n */\n _unsubscribeEffect(e: Effect): void {\n for (const dep of e.dependencies.values()) {\n if (dep.kind === 'global') {\n const subs = this.globalSubs.get(dep.name);\n subs?.delete(e);\n } else if (dep.kind === 'element' && dep.element) {\n const state = this.elementState.get(dep.element);\n const subs = state?.symbolSubs.get(dep.name);\n subs?.delete(e);\n state?.effects.delete(e);\n } else if (dep.kind === 'dom' && dep.element) {\n const state = this.elementState.get(dep.element);\n const handler = state?.domHandlers.get(dep.name);\n handler?.subs.delete(e);\n if (handler && handler.subs.size === 0) {\n handler.detach();\n state?.domHandlers.delete(dep.name);\n }\n state?.effects.delete(e);\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Caret-variable storage — `^name` reads/writes.\n // ---------------------------------------------------------------------------\n\n /**\n * Whether `el` is a `dom-scope=\"isolated\"` boundary. Walks of `^var`\n * lookups stop at boundary elements that don't define the var, so nested\n * components don't accidentally read or write each other's state.\n */\n private isIsolationBoundary(el: Element): boolean {\n return typeof el.getAttribute === 'function' && el.getAttribute('dom-scope') === 'isolated';\n }\n\n /**\n * Walk up the DOM tree from `lookupRoot`, returning the first element whose\n * state has `name` defined. Stops at any `dom-scope=\"isolated\"` boundary\n * that doesn't itself define the var. Returns `null` if no owner is found.\n */\n private findCaretOwner(lookupRoot: Element, name: string): Element | null {\n let el: Element | null = lookupRoot;\n while (el) {\n const state = this.elementState.get(el);\n if (state && state.caretVars.has(name)) return el;\n if (this.isIsolationBoundary(el)) return null;\n el = el.parentElement;\n }\n return null;\n }\n\n /**\n * Read a DOM-scoped variable. Walks up from `lookupRoot`, tracking each\n * element visited as an `element` dep (so writes at any ancestor notify\n * dependent effects). Stops at any `dom-scope=\"isolated\"` boundary that\n * doesn't itself define the var.\n */\n readCaret(lookupRoot: Element, name: string): unknown {\n let el: Element | null = lookupRoot;\n while (el) {\n this.trackElement(el, name);\n const state = this.elementState.get(el);\n if (state && state.caretVars.has(name)) {\n return state.caretVars.get(name);\n }\n if (this.isIsolationBoundary(el)) return undefined;\n el = el.parentElement;\n }\n return undefined;\n }\n\n /**\n * Write a DOM-scoped variable. If `target` is provided, writes there\n * directly; otherwise walks up from `lookupRoot` to find the existing owner,\n * falling back to `lookupRoot` itself if no owner exists.\n */\n writeCaret(lookupRoot: Element, name: string, value: unknown, target?: Element): void {\n const owner = target ?? this.findCaretOwner(lookupRoot, name) ?? lookupRoot;\n const state = this.getElementState(owner);\n state.caretVars.set(name, value);\n this.notifyElement(owner, name);\n }\n\n // ---------------------------------------------------------------------------\n // Scheduler — microtask-batched flush.\n // ---------------------------------------------------------------------------\n\n private schedule(e: Effect): void {\n if (e.stopped) return;\n this.pending.add(e);\n if (this.scheduled) return;\n this.scheduled = true;\n queueMicrotask(() => void this.flush());\n }\n\n private async flush(): Promise<void> {\n try {\n while (this.pending.size > 0) {\n const batch = Array.from(this.pending);\n this.pending.clear();\n for (const e of batch) {\n if (e.stopped) continue;\n await e.run();\n // If the effect's run did not synchronously re-schedule itself, its\n // trigger count is reset. Self-rescheduling (a real cycle) keeps the\n // counter climbing toward the 100 cap. Long-lived effects that fire\n // sporadically (e.g. user-input bindings) stay alive forever.\n if (!this.pending.has(e)) e.resetTriggerCount();\n }\n }\n } finally {\n this.scheduled = false;\n }\n }\n}\n\n// Module singleton. One reactive graph per process; mirrors upstream's\n// `runtime.reactivity` pattern.\nexport const reactive = new Reactive();\n","/**\n * `^name` — DOM-scoped inherited variable.\n *\n * Upstream syntax:\n * ^counter → read from nearest ancestor that has `counter` set\n * ^counter on #target → read from (or near) #target\n * set ^counter to 42 → write to owner (or lookupRoot if not yet defined)\n *\n * Parse side: register `^` as a Pratt prefix operator. The handler consumes\n * the identifier token and an optional `on <target>` clause, emitting a\n * `caretVar` AST node.\n *\n * Eval side: `caretVar` node evaluator calls `reactive.readCaret(anchor,\n * name)` which walks the DOM tree for the owner and records deps as it goes.\n */\n\nimport type { ASTNode, ExecutionContext } from './types';\nimport { reactive } from './signals';\n\nexport interface CaretVarNode extends ASTNode {\n type: 'caretVar';\n name: string;\n onTarget: ASTNode | null;\n}\n\ninterface CaretVarRuntime {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n}\n\n/**\n * Coerce a runtime-evaluated `on <target>` result to a single Element.\n * Selector expressions resolve to an array of matched elements; bare\n * `me`/`it`/`you`/identifier references resolve to single Elements. Take the\n * first element of an array, or the value itself if it's already an Element.\n */\nfunction coerceToElement(value: unknown): Element | null {\n if (value instanceof Element) return value;\n if (Array.isArray(value) && value[0] instanceof Element) return value[0];\n return null;\n}\n\n/**\n * Pratt prefix handler for `^`. Consumes the following identifier token and\n * an optional `on <expr>` clause.\n */\nexport function parseCaretPrefix(token: unknown, ctx: unknown): ASTNode {\n // `ctx` is hyperfixi's PrattContext: { peek, advance, parseExpr, isStopToken, atEnd }.\n const pctx = ctx as {\n peek(): { value?: string; kind?: string } | undefined;\n advance(): { value: string; kind?: string };\n parseExpr(minBp: number): ASTNode;\n };\n const ident = pctx.advance();\n if (!ident || !ident.value) {\n throw new Error(\"Expected identifier after '^'\");\n }\n let onTarget: ASTNode | null = null;\n const next = pctx.peek();\n if (next && next.value === 'on') {\n pctx.advance(); // consume 'on'\n // Binding power 86 — higher than standard comparisons so `^x on me` doesn't\n // over-consume into surrounding expressions.\n onTarget = pctx.parseExpr(86);\n }\n const startTok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'caretVar',\n name: ident.value,\n onTarget,\n start: startTok?.start ?? 0,\n end: startTok?.end ?? 0,\n line: startTok?.line,\n column: startTok?.column,\n } as CaretVarNode;\n}\n\n/**\n * Build a node evaluator for `caretVar` bound to a specific runtime. The\n * evaluator walks up from the resolved anchor element, tracking every element\n * visited so writes at any ancestor notify dependent effects.\n *\n * Capturing `runtime` via a factory closure (matching live/when/bind) keeps\n * the evaluator independent of any module-scope state.\n */\nexport function makeEvaluateCaretVar(\n runtime: CaretVarRuntime\n): (node: ASTNode, ctx: unknown) => Promise<unknown> {\n return async function evaluateCaretVar(node, ctx) {\n const n = node as CaretVarNode;\n const context = ctx as ExecutionContext;\n let anchor: Element | null = (context.me as Element | null) ?? null;\n\n if (n.onTarget) {\n const resolved = await runtime.execute(n.onTarget, context);\n const el = coerceToElement(resolved);\n if (el) anchor = el;\n }\n\n if (!anchor) return undefined;\n return reactive.readCaret(anchor, n.name);\n };\n}\n\n/**\n * Build a node writer for `caretVar` bound to a specific runtime. Used by the\n * core `set` command via `parserExtensions.registerNodeWriter`.\n */\nexport function makeWriteCaretVar(\n runtime: CaretVarRuntime\n): (node: ASTNode, value: unknown, ctx: unknown) => Promise<void> {\n return async function writeCaretVar(node, value, ctx) {\n const n = node as CaretVarNode;\n const context = ctx as ExecutionContext;\n const anchor: Element | null = (context.me as Element | null) ?? null;\n if (!anchor) return;\n\n let target: Element | undefined;\n if (n.onTarget) {\n const resolved = await runtime.execute(n.onTarget, context);\n const el = coerceToElement(resolved);\n if (el) target = el;\n }\n reactive.writeCaret(anchor, n.name, value, target);\n };\n}\n","/**\n * `live ... end` — reactive block. Body re-runs whenever any dependency read\n * during its execution changes.\n *\n * Upstream syntax:\n * live [commandList] end\n *\n * Each command in the body is re-executed as a single effect. The entire\n * body shares one effect instance; its dependency set is the union of every\n * read performed during body execution.\n */\n\nimport type { ASTNode, ExecutionContext, FeatureParserCtx } from './types';\nimport { reactive } from './signals';\n\nexport interface LiveFeatureNode extends ASTNode {\n type: 'liveFeature';\n body: ASTNode[];\n}\n\n/**\n * Parse `live ... end`. The `live` keyword has already been consumed by the\n * parser dispatcher; we parse the body and expect a trailing `end`.\n */\nexport function parseLiveFeature(ctx: unknown, token: unknown): ASTNode {\n const pctx = ctx as FeatureParserCtx;\n const body = pctx.parseCommandListUntilEnd();\n // parseCommandListUntilEnd stops when it sees `end` (but doesn't consume it).\n if (!pctx.isAtEnd() && pctx.check('end')) pctx.match('end');\n const tok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'liveFeature',\n body,\n start: tok?.start ?? 0,\n end: pctx.getPosition().end,\n line: tok?.line,\n column: tok?.column,\n } as LiveFeatureNode;\n}\n\n/**\n * Create an evaluator bound to a runtime reference. The plugin captures\n * `runtime` at install time and passes it in so effect re-runs can dispatch\n * the body commands without going through module-scope state.\n */\nexport function makeEvaluateLiveFeature(runtime: {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n}): (node: ASTNode, ctx: unknown) => unknown | Promise<unknown> {\n return async function evaluateLiveFeature(node, ctx) {\n const context = ctx as ExecutionContext;\n const owner = (context.me as Element) ?? document.body;\n const n = node as LiveFeatureNode;\n\n const stop = reactive.createEffect(\n async () => {\n for (const cmd of n.body) {\n await runtime.execute(cmd, context);\n }\n },\n () => {\n /* no-op — side effects happened inside the expression */\n },\n owner\n );\n context.registerCleanup?.(owner, stop, 'live-effect');\n return undefined;\n };\n}\n","/**\n * `when <expr> [or <expr>]* changes [commandList] end` — observer feature.\n *\n * Runs the body when any watched expression's value changes (Object.is\n * semantics). One effect is created per watched expression so writes to a\n * given dep only re-run that watcher.\n */\n\nimport type { ASTNode, ExecutionContext, FeatureParserCtx } from './types';\nimport { reactive } from './signals';\n\nexport interface WhenFeatureNode extends ASTNode {\n type: 'whenFeature';\n watched: ASTNode[];\n body: ASTNode[];\n}\n\nexport function parseWhenFeature(ctx: unknown, token: unknown): ASTNode {\n const pctx = ctx as FeatureParserCtx;\n const watched: ASTNode[] = [pctx.parseExpression()];\n while (pctx.match('or')) {\n watched.push(pctx.parseExpression());\n }\n pctx.consume('changes', \"Expected 'changes' after when expression list\");\n const body = pctx.parseCommandListUntilEnd();\n if (!pctx.isAtEnd() && pctx.check('end')) pctx.match('end');\n const tok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'whenFeature',\n watched,\n body,\n start: tok?.start ?? 0,\n end: pctx.getPosition().end,\n line: tok?.line,\n column: tok?.column,\n } as WhenFeatureNode;\n}\n\nexport function makeEvaluateWhenFeature(runtime: {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n evaluateExpressionWithResult?: (\n node: ASTNode,\n ctx: ExecutionContext\n ) => Promise<{ value: unknown }>;\n}): (node: ASTNode, ctx: unknown) => unknown | Promise<unknown> {\n return async function evaluateWhenFeature(node, ctx) {\n const context = ctx as ExecutionContext;\n const owner = (context.me as Element) ?? document.body;\n const n = node as WhenFeatureNode;\n\n for (const watchedExpr of n.watched) {\n const stop = reactive.createEffect(\n async () => {\n // Evaluate the watched expression as a regular expression through the\n // runtime so that trackGlobal/trackElement fire via the global-write\n // hook and caret-var reads.\n return await runtime.execute(watchedExpr, context);\n },\n async newValue => {\n // Fire the body with `it` / `result` bound to the new value.\n const subCtx: ExecutionContext = { ...context, it: newValue, result: newValue };\n for (const cmd of n.body) {\n await runtime.execute(cmd, subCtx);\n }\n },\n owner\n );\n context.registerCleanup?.(owner, stop, 'when-effect');\n }\n return undefined;\n };\n}\n","/**\n * `bind X [to|and|with] Y` — two-way binding.\n *\n * Creates two effects (registration order is load-bearing — both initialize\n * via `queueMicrotask` and run in registration order):\n * 1. DOM → var: read DOM, write var. DOM \"wins\" on init.\n * 2. var → DOM: read var, write DOM. Fires on programmatic var writes\n * after init. On its own initial run, var === DOM (Effect 1 just synced\n * them), so the write is a no-op.\n *\n * Two binding forms:\n *\n * 1. Auto-detected (DOM side is a bare element expression):\n *\n * bind $name to #input -- detects `value`\n * bind $checked to me -- detects `checked` on a checkbox\n *\n * Auto-detected property by element type:\n * - INPUT[type=checkbox|radio] → `checked`\n * - INPUT[type=number|range] → `valueAsNumber`\n * - INPUT|TEXTAREA|SELECT → `value`\n * - contenteditable=\"true\" → `textContent`\n * - Custom elements with own `value` → `value`\n *\n * 2. Explicit property (DOM side is a member or possessive expression):\n *\n * bind $color to #picker's value -- possessive (preferred — reads in any language)\n * bind $color to #picker.value -- dot (JS-style alternative)\n * bind $text to #div's textContent -- non-form properties: var→DOM only\n *\n * For form-like elements, both directions work. For non-form elements\n * (e.g., binding a div's `textContent`), only var→DOM fires — there are\n * no input/change events to drive DOM→var, so user mutations of the\n * property via devtools won't propagate back.\n */\n\nimport type { ASTNode, ExecutionContext, FeatureParserCtx } from './types';\nimport { reactive } from './signals';\n\nexport interface BindFeatureNode extends ASTNode {\n type: 'bindFeature';\n left: ASTNode;\n right: ASTNode;\n}\n\nexport function parseBindFeature(ctx: unknown, token: unknown): ASTNode {\n const pctx = ctx as FeatureParserCtx;\n const left = pctx.parseExpression();\n // Accept any of `to` / `and` / `with` as the separator.\n if (!(pctx.match('to') || pctx.match('and') || pctx.match('with'))) {\n throw new Error(\"bind requires 'to', 'and', or 'with' between the two sides\");\n }\n const right = pctx.parseExpression();\n // Optional `end` terminator (matches upstream which allows both forms).\n if (pctx.check('end')) pctx.match('end');\n const tok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'bindFeature',\n left,\n right,\n start: tok?.start ?? 0,\n end: pctx.getPosition().end,\n line: tok?.line,\n column: tok?.column,\n } as BindFeatureNode;\n}\n\n/**\n * Auto-detect the DOM property to bind by element type. Returns null if the\n * target isn't a recognized form/editable element.\n */\nfunction detectProperty(el: Element): string | null {\n const tag = el.tagName;\n if (tag === 'INPUT') {\n const type = (el as HTMLInputElement).type;\n if (type === 'checkbox' || type === 'radio') return 'checked';\n if (type === 'number' || type === 'range') return 'valueAsNumber';\n return 'value';\n }\n if (tag === 'TEXTAREA' || tag === 'SELECT') return 'value';\n const ce = (el as HTMLElement).contentEditable;\n if (ce === 'true') return 'textContent';\n // Custom elements with own `value` prop.\n if ('value' in el) return 'value';\n return null;\n}\n\n/**\n * If `node` is a `memberExpression` or `possessiveExpression` with a static\n * identifier property (`#el.value` or `#el's value`), return the inner element\n * expression and the property name. Returns null for anything else.\n *\n * Computed member access (`#el[prop]`) is intentionally rejected — we'd have to\n * evaluate the index dynamically and the binding direction would be unclear.\n * Chained property access (`#el.dataset.value`) is also not unpacked — we only\n * peel one level. Multi-level support is a future arc.\n */\nfunction unwrapExplicitProperty(node: ASTNode): { element: ASTNode; propertyName: string } | null {\n if (!node || (node.type !== 'memberExpression' && node.type !== 'possessiveExpression')) {\n return null;\n }\n if (node.type === 'memberExpression' && node.computed === true) return null;\n const property = node.property as ASTNode | undefined;\n const object = node.object as ASTNode | undefined;\n if (!property || !object || property.type !== 'identifier') return null;\n const name = (property.name as string) ?? '';\n if (!name) return null;\n return { element: object, propertyName: name };\n}\n\n/**\n * Detect a chained property access on the bind RHS — e.g.\n * `me.style.backgroundColor` or `#el's dataset's value`.\n *\n * After `unwrapExplicitProperty` peels the outermost member, the returned\n * `element` is the object of that member. If that object is itself a\n * member/possessive expression, we have a multi-level chain that v1 of\n * bind doesn't support. Used only for the error path; the parsed AST is\n * left intact.\n */\nfunction isChainedMember(node: ASTNode | undefined): boolean {\n if (!node) return false;\n return node.type === 'memberExpression' || node.type === 'possessiveExpression';\n}\n\n/**\n * Whether the input/change listener installed by `trackDomProperty` would\n * actually fire for this element. Used to decide whether to wire up the\n * DOM→var direction when an explicit property is given.\n */\nfunction isFormLikeElement(el: Element): boolean {\n const tag = el.tagName;\n if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;\n if ((el as HTMLElement).contentEditable === 'true') return true;\n return false;\n}\n\n/**\n * Whether debug logging is enabled. Mirrors signals.ts — keeps a single\n * convention for the package.\n */\nfunction debugEnabled(): boolean {\n try {\n return typeof localStorage !== 'undefined' && localStorage.getItem('hyperfixi:debug') !== null;\n } catch {\n return false;\n }\n}\n\n/**\n * Create the bind evaluator. Because `bind` has unusual parse shape (AST\n * nodes for left/right that may be identifiers, `$name` references, or DOM\n * element lookups), we rely on the runtime to evaluate them.\n */\nexport function makeEvaluateBindFeature(runtime: {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n}): (node: ASTNode, ctx: unknown) => unknown | Promise<unknown> {\n return async function evaluateBindFeature(node, ctx) {\n const context = ctx as ExecutionContext;\n const owner = (context.me as Element) ?? document.body;\n const n = node as BindFeatureNode;\n\n // Resolve sides. One is a var reference (read/write a symbol), the other\n // a DOM target (read/write a property). Determine direction from node shape.\n const leftIsVar = isVarRef(n.left);\n const rightIsVar = isVarRef(n.right);\n\n // We need a DOM-side descriptor (element + property) and a var-side name.\n let varSide: { name: string; isGlobal: boolean } | null = null;\n let domSide: { exprNode: ASTNode } | null = null;\n\n if (leftIsVar && !rightIsVar) {\n varSide = varRefInfo(n.left);\n domSide = { exprNode: n.right };\n } else if (rightIsVar && !leftIsVar) {\n varSide = varRefInfo(n.right);\n domSide = { exprNode: n.left };\n } else if (leftIsVar && rightIsVar) {\n // var-to-var binding not supported in v1 (no DOM side).\n throw new Error('bind: cannot bind two symbols together (need a DOM side)');\n } else {\n throw new Error('bind: could not identify a symbol side');\n }\n\n // Unwrap explicit property syntax: `#el.value` or `#el's value` becomes\n // (element-expression, propertyName). Otherwise, evaluate the whole side\n // and rely on auto-detection.\n const explicit = unwrapExplicitProperty(domSide.exprNode);\n // Multi-level property access (`#el.style.background`, `me's dataset's id`)\n // is not supported in v1. Surface that diagnosis up front; otherwise the\n // user gets the generic \"did not resolve to an element\" message and no\n // hint that the chain is the problem.\n if (explicit && isChainedMember(explicit.element)) {\n throw new Error(\n 'bind: multi-level property access (e.g., `#el.a.b`) is not supported in v1 — restructure to a single property write or pass the element directly for auto-detection (e.g., `bind $x to #el`).'\n );\n }\n const elementExpr = explicit ? explicit.element : domSide.exprNode;\n const domValue = await runtime.execute(elementExpr, context);\n if (!(domValue instanceof Element)) {\n const valueType =\n domValue === null ? 'null' : domValue === undefined ? 'undefined' : typeof domValue;\n const snippet =\n domValue !== null && domValue !== undefined ? ` \"${String(domValue).slice(0, 40)}\"` : '';\n const suggestion = explicit\n ? ''\n : \" If you meant to write to a property, use the explicit form: `<selector>'s <property>`.\";\n throw new Error(\n `bind: right-hand side did not resolve to an element (got ${valueType}${snippet}).${suggestion}`\n );\n }\n const el = domValue;\n // Explicit property bypasses auto-detect; the user takes responsibility for\n // picking something readable from the element. For DOM→var to work without\n // explicit property, fall back to auto-detect.\n const prop = explicit ? explicit.propertyName : detectProperty(el);\n if (!prop) {\n throw new Error(\n `bind: could not auto-detect property for <${el.tagName.toLowerCase()}> — use explicit \\`<expr>'s <property>\\` form`\n );\n }\n // For explicit-property mode on non-form elements, DOM→var can't sync via\n // input/change events. Skip the listener install; only var→DOM runs.\n const installDomToVar = !explicit || isFormLikeElement(el);\n if (explicit && !installDomToVar && debugEnabled() && typeof console !== 'undefined') {\n console.warn(\n `[@hyperfixi/reactivity] bind: DOM→var skipped for <${el.tagName.toLowerCase()}>.${prop} — no input/change event source.`\n );\n }\n\n // Initial sync: DOM → var.\n const readDom = (): unknown => {\n if (prop === 'valueAsNumber') return (el as HTMLInputElement).valueAsNumber;\n if (prop === 'checked') return (el as HTMLInputElement).checked;\n if (prop === 'textContent') return el.textContent ?? '';\n return (el as any)[prop];\n };\n const writeDom = (value: unknown): void => {\n if (prop === 'valueAsNumber') {\n const n = Number(value);\n (el as HTMLInputElement).valueAsNumber = Number.isNaN(n) ? (null as never) : n;\n } else if (prop === 'checked') {\n (el as HTMLInputElement).checked = Boolean(value);\n } else if (prop === 'textContent') {\n el.textContent = value == null ? '' : String(value);\n } else {\n (el as any)[prop] = value;\n }\n };\n const readVar = (): unknown => {\n if (varSide!.isGlobal) return context.globals?.get(varSide!.name);\n return context.locals?.get(varSide!.name);\n };\n const writeVar = (value: unknown): void => {\n if (varSide!.isGlobal) {\n context.globals?.set(varSide!.name, value);\n // Bypass the global-write hook (we're touching the Map directly), so\n // notify the reactive graph manually for the var→DOM effect.\n reactive.notifyGlobal(varSide!.name);\n } else {\n context.locals?.set(varSide!.name, value);\n // Same rationale for locals — direct Map write skips the localWriteHook,\n // so we notify the element-scoped subscription set directly.\n reactive.notifyElement(owner, varSide!.name);\n }\n };\n\n // Effect 1: DOM → var (fires on user input). Skipped for explicit-property\n // bindings on non-form elements — no input/change events would drive it.\n let stopDomToVar: (() => void) | null = null;\n if (installDomToVar) {\n stopDomToVar = reactive.createEffect(\n () => {\n reactive.trackDomProperty(el, prop);\n return readDom();\n },\n newValue => {\n writeVar(newValue);\n },\n owner\n );\n }\n\n // Effect 2: var → DOM (fires on programmatic var writes — for globals\n // via the core's globalWriteHook, for locals via the localWriteHook the\n // reactivity plugin registers).\n const stopVarToDom = reactive.createEffect(\n () => {\n if (varSide!.isGlobal) reactive.trackGlobal(varSide!.name);\n else reactive.trackElement(owner, varSide!.name);\n return readVar();\n },\n newValue => {\n if (newValue === undefined) return;\n writeDom(newValue);\n },\n owner\n );\n\n if (stopDomToVar) context.registerCleanup?.(owner, stopDomToVar, 'bind-dom-to-var');\n context.registerCleanup?.(owner, stopVarToDom, 'bind-var-to-dom');\n return undefined;\n };\n}\n\n/**\n * Is this AST node a var reference we can bind to?\n *\n * The hyperfixi parser emits `identifier` nodes for both globals and locals,\n * but with different shapes:\n * - `$foo` → `{ type: 'identifier', name: '$foo' }` (no scope field)\n * - `:foo` → `{ type: 'identifier', name: 'foo', scope: 'local' }`\n * - `::foo` → `{ type: 'identifier', name: 'foo', scope: 'global' }`\n *\n * We accept all three. The legacy `$`-prefix sniff stays as a fallback because\n * `parseExpression` doesn't always set `scope`.\n */\nfunction isVarRef(node: ASTNode): boolean {\n if (!node) return false;\n if (node.type !== 'identifier') return false;\n const scope = node.scope as string | undefined;\n if (scope === 'local' || scope === 'global') return true;\n const name = (node.name as string) ?? '';\n return name.startsWith('$') || name.startsWith(':');\n}\n\nfunction varRefInfo(node: ASTNode): { name: string; isGlobal: boolean } {\n const rawName = (node.name as string) ?? '';\n const scope = node.scope as string | undefined;\n // Prefer the parser-emitted scope marker. Fall back to prefix sniffing for\n // shapes where scope isn't set (e.g. `$foo` arriving as bare identifier\n // with name '$foo').\n let isGlobal: boolean;\n let name: string;\n if (scope === 'global') {\n isGlobal = true;\n name = rawName;\n } else if (scope === 'local') {\n isGlobal = false;\n name = rawName;\n } else if (rawName.startsWith('$')) {\n isGlobal = true;\n name = rawName.slice(1);\n } else if (rawName.startsWith(':')) {\n isGlobal = false;\n name = rawName.slice(1);\n } else {\n isGlobal = false;\n name = rawName;\n }\n if (!name) {\n throw new Error('bind: variable reference has empty name');\n }\n return { name, isGlobal };\n}\n"],"mappings":";;;;;;;;;;;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,YAAY,kBAAkB,OAAgB,CAAU;AAK5F,qBAAiB,wBAAwB,CAAC,MAAc,QAAiB,aAAsB;AAC7F,eAAS,aAAa,IAAI;AAAA,IAC5B,CAAC;AAID,qBAAiB,uBAAuB,CAAC,MAAc,aAAsB;AAC3E,eAAS,YAAY,IAAI;AAAA,IAC3B,CAAC;AAQD,qBAAiB,uBAAuB,CAAC,MAAc,QAAiB,YAAY;AAClF,YAAM,QAAS,QAAoC,MAAM;AACzD,UAAI,MAAO,UAAS,cAAc,OAAO,IAAI;AAAA,IAC/C,CAAC;AAED,qBAAiB,sBAAsB,CAAC,MAAc,YAAY;AAChE,YAAM,QAAS,QAAoC,MAAM;AACzD,UAAI,MAAO,UAAS,aAAa,OAAO,IAAI;AAAA,IAC9C,CAAC;AAAA,EACH;AACF;AAEA,IAAO,gBAAQ;","names":["debugEnabled","n"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/signals.ts","../src/caret-var.ts","../src/live.ts","../src/when.ts","../src/bind.ts"],"sourcesContent":["/**\n * @hyperfixi/reactivity — signal-based reactive features for hyperfixi.\n *\n * Adds four constructs from upstream _hyperscript 0.9.90:\n *\n * live [commandList] end reactive block — body re-runs\n * when tracked reads change.\n *\n * when <expr> [or <expr>]* changes observer — body runs when any\n * [commandList] end watched expression changes.\n *\n * bind <var> to <element> two-way DOM ⇄ var binding.\n *\n * ^name [on <target>] DOM-scoped inherited variable\n * (read + write with `^`).\n *\n * Install:\n *\n * ```ts\n * import { createRuntime, installPlugin } from '@hyperfixi/core';\n * import { reactivityPlugin } from '@hyperfixi/reactivity';\n *\n * const runtime = createRuntime();\n * installPlugin(runtime, reactivityPlugin);\n * ```\n */\n\nimport type { HyperfixiPlugin, HyperfixiPluginContext } from '@hyperfixi/core';\nimport { reactive } from './signals';\nimport { parseCaretPrefix, makeEvaluateCaretVar, makeWriteCaretVar } from './caret-var';\nimport { parseLiveFeature, makeEvaluateLiveFeature } from './live';\nimport { parseWhenFeature, makeEvaluateWhenFeature } from './when';\nimport { parseBindFeature, makeEvaluateBindFeature } from './bind';\n\nexport { reactive } from './signals';\nexport type { CaretVarNode } from './caret-var';\nexport type { LiveFeatureNode } from './live';\nexport type { WhenFeatureNode } from './when';\nexport type { BindFeatureNode } from './bind';\n\n/**\n * The plugin object. Install once at app startup; re-installing is idempotent\n * (guarded via a `parserExtensions.hasFeature('live')` check).\n *\n * Registers:\n * - Features: `live`, `when`, `bind` (top-level features with `end` bodies)\n * - Prefix op: `^` (primary expression for DOM-scoped vars)\n * - Node evaluators: `liveFeature`, `whenFeature`, `bindFeature`, `caretVar`\n * - A node writer for `caretVar` so `set ^X to Y` flows through `reactive.writeCaret`\n * - Global read/write hooks so `$name` reads track and writes notify\n *\n * Effect cleanup: each effect-creating evaluator calls\n * `context.registerCleanup(owner, stop, ...)` so the core runtime tears effects\n * down when their owning element is cleaned up. There is no separate plugin-level\n * cleanup hook; `reactive.stopElementEffects(el)` is exposed for explicit teardown\n * by tests and consumers that manage element lifecycle outside the runtime.\n */\nexport const reactivityPlugin: HyperfixiPlugin & { version: string } = {\n name: '@hyperfixi/reactivity',\n version: '2.3.1',\n install(ctx: HyperfixiPluginContext) {\n const { parserExtensions, runtime } = ctx;\n\n // Idempotency: the parser-extension registry is process-singleton, so\n // re-installing into a fresh runtime would otherwise stack additional\n // global read/write hooks on every call. `snapshot()`/`restore()` clears\n // the feature registry — when tests roll back the registry, this guard\n // re-enables a fresh install.\n if (parserExtensions.hasFeature('live')) return;\n\n // Parser hooks — three block features plus a primary-expression caret.\n parserExtensions.registerFeature('live', parseLiveFeature as never);\n parserExtensions.registerFeature('when', parseWhenFeature as never);\n parserExtensions.registerFeature('bind', parseBindFeature as never);\n parserExtensions.registerPrefixOperator('^', 85, parseCaretPrefix as never);\n\n // Runtime evaluators. Features capture `runtime` so effect re-runs can\n // dispatch body commands without going through module-scope state.\n parserExtensions.registerNodeEvaluator(\n 'liveFeature',\n makeEvaluateLiveFeature(runtime as never) as never\n );\n parserExtensions.registerNodeEvaluator(\n 'whenFeature',\n makeEvaluateWhenFeature(runtime as never) as never\n );\n parserExtensions.registerNodeEvaluator(\n 'bindFeature',\n makeEvaluateBindFeature(runtime as never) as never\n );\n parserExtensions.registerNodeEvaluator(\n 'caretVar',\n makeEvaluateCaretVar(runtime as never) as never\n );\n\n // Caret-var write: lets the core `set` command dispatch `set ^X to Y`\n // through `reactive.writeCaret`. Resolves `on <target>` via the captured\n // runtime — no global-scope indirection.\n parserExtensions.registerNodeWriter('caretVar', makeWriteCaretVar(runtime as never) as never);\n\n // Global-write hook: notify the reactive graph whenever `$name` is set.\n // The returned disposer is intentionally discarded — the install-time\n // idempotency guard above is the sole gate against double-registration.\n parserExtensions.registerGlobalWriteHook((name: string, _value: unknown, _context: unknown) => {\n reactive.notifyGlobal(name);\n });\n\n // Global-read hook: track the read against the current effect (if any)\n // so effects re-run when the global changes.\n parserExtensions.registerGlobalReadHook((name: string, _context: unknown) => {\n reactive.trackGlobal(name);\n });\n\n // Local hooks — analogous to globals, but keyed by `context.me` so each\n // element holds independent state. A `set :foo to ...` running in a\n // handler with `me=button1` notifies effects subscribed to (button1, 'foo');\n // a `set :foo` in a different `me` won't reach them. This matches how\n // locals already work — they're never cross-context — and lets two\n // components hold independent `:foo` state without interference.\n parserExtensions.registerLocalWriteHook((name: string, _value: unknown, context) => {\n const owner = (context as { me?: Element | null }).me ?? null;\n if (owner) reactive.notifyElement(owner, name);\n });\n\n parserExtensions.registerLocalReadHook((name: string, context) => {\n const owner = (context as { me?: Element | null }).me ?? null;\n if (owner) reactive.trackElement(owner, name);\n });\n },\n};\n\nexport default reactivityPlugin;\n","/**\n * Signal/effect reactive core.\n *\n * Models three dependency kinds for v1:\n * - `global` — `$name` variables in `context.globals`\n * - `element` — `^name` DOM-scoped variables (per-element storage)\n * - `dom` — DOM properties read via `input`/`change` listeners\n *\n * Inspired by upstream _hyperscript 0.9.91's `src/core/runtime/reactivity.js`\n * but reimplemented in TypeScript against hyperfixi's types. Batched via\n * `queueMicrotask` so synchronous writes coalesce into a single flush. Cycle\n * detection halts at >100 consecutive triggers (matching upstream).\n *\n * External packages never see `Effect` or `Reactive` directly — they hold\n * the disposer returned by `createEffect()` and call it when the owning\n * element is cleaned up.\n */\n\nexport type DepKind = 'global' | 'element' | 'dom';\n\n/**\n * Whether reactive debug logging is enabled. Mirrors the core convention:\n * `localStorage.setItem('hyperfixi:debug', '*')` enables, anything else (or no\n * `localStorage`) disables. Cheap call — no caching, since users toggle this\n * interactively in the console.\n */\nfunction debugEnabled(): boolean {\n try {\n return typeof localStorage !== 'undefined' && localStorage.getItem('hyperfixi:debug') !== null;\n } catch {\n return false;\n }\n}\n\nfunction debugWarn(message: string, err: unknown): void {\n if (!debugEnabled()) return;\n if (typeof console === 'undefined') return;\n console.warn(`[@hyperfixi/reactivity] ${message}`, err);\n}\n\nexport interface Dep {\n readonly key: string;\n readonly kind: DepKind;\n readonly name: string;\n readonly element: Element | null;\n}\n\nconst globalDepKey = (name: string): string => `global:${name}`;\nconst elementDepKey = (el: Element, name: string): string => `element:${reactiveIdFor(el)}:${name}`;\nconst domDepKey = (el: Element, prop: string): string => `dom:${reactiveIdFor(el)}:${prop}`;\n\n// WeakMap-based id assignment so we don't monkey-patch DOM nodes. Ids are\n// per-process and only used to construct stable string keys for an effect's\n// per-effect dependency dedup map.\nconst _reactiveIds = new WeakMap<Element, number>();\nlet _idCounter = 0;\nfunction reactiveIdFor(el: Element): number {\n const existing = _reactiveIds.get(el);\n if (existing !== undefined) return existing;\n const id = ++_idCounter;\n _reactiveIds.set(el, id);\n return id;\n}\n\nexport class Effect {\n readonly dependencies = new Map<string, Dep>();\n private lastValue: unknown = undefined;\n private _stopped = false;\n private _consecutiveTriggers = 0;\n\n constructor(\n private readonly r: Reactive,\n readonly expression: () => unknown | Promise<unknown>,\n readonly handler: (value: unknown) => void | Promise<void>,\n readonly element: Element | null\n ) {}\n\n get stopped(): boolean {\n return this._stopped;\n }\n\n /**\n * Run the effect for the first time: collect dependencies, subscribe, call\n * handler with the initial value. Errors in expression evaluation are caught\n * and silently swallowed (matches upstream's tolerance).\n */\n async initialize(): Promise<void> {\n if (this._stopped) return;\n try {\n const value = await this.r._runWithEffect(this, this.expression);\n this.lastValue = value;\n if (value !== undefined && value !== null) {\n await this.handler(value);\n }\n } catch (err) {\n // Swallow — expression evaluation failed during initial read. Surface\n // via debug log so users diagnosing \"my effect never fires\" can see why.\n debugWarn('effect.initialize failed', err);\n }\n }\n\n /**\n * Re-run the effect after a notify. Cycle-detects (halts at 101 consecutive\n * triggers). If the new value is Object.is-equal to the last, the handler\n * is skipped. If the owning element has disconnected, the effect stops\n * itself and returns.\n */\n async run(): Promise<void> {\n if (this._stopped) return;\n if (this.element && !this.element.isConnected) {\n this.stop();\n return;\n }\n this._consecutiveTriggers++;\n if (this._consecutiveTriggers > 100) {\n if (typeof console !== 'undefined') {\n console.error(\n '[@hyperfixi/reactivity] Effect halted: > 100 consecutive triggers (cycle detected).'\n );\n }\n this.stop();\n return;\n }\n try {\n const value = await this.r._runWithEffect(this, this.expression);\n if (Object.is(value, this.lastValue)) return;\n this.lastValue = value;\n await this.handler(value);\n } catch (err) {\n // Swallow — expression/handler errors don't break the microtask flush.\n debugWarn('effect.run failed', err);\n }\n }\n\n resetTriggerCount(): void {\n this._consecutiveTriggers = 0;\n }\n\n /**\n * Stop the effect and remove it from all dependency subscriptions. Safe to\n * call multiple times.\n */\n stop(): void {\n if (this._stopped) return;\n this._stopped = true;\n this.r._unsubscribeEffect(this);\n this.dependencies.clear();\n }\n}\n\ninterface ElementState {\n symbolSubs: Map<string, Set<Effect>>;\n caretVars: Map<string, unknown>;\n domHandlers: Map<string, DomHandler>;\n effects: Set<Effect>;\n}\n\ninterface DomHandler {\n subs: Set<Effect>;\n detach: () => void;\n}\n\nexport class Reactive {\n private currentEffect: Effect | null = null;\n private pending = new Set<Effect>();\n private scheduled = false;\n\n private globalSubs = new Map<string, Set<Effect>>();\n private elementState = new WeakMap<Element, ElementState>();\n\n private getElementState(el: Element): ElementState {\n let s = this.elementState.get(el);\n if (!s) {\n s = {\n symbolSubs: new Map(),\n caretVars: new Map(),\n domHandlers: new Map(),\n effects: new Set(),\n };\n this.elementState.set(el, s);\n }\n return s;\n }\n\n /**\n * Internal helper invoked by Effect — installs `this` as the current effect,\n * runs the expression, then restores the previous current-effect pointer.\n * Track* methods (called from read-paths) consult `currentEffect` to know\n * which effect to subscribe.\n */\n async _runWithEffect(e: Effect, fn: () => unknown | Promise<unknown>): Promise<unknown> {\n const prev = this.currentEffect;\n this.currentEffect = e;\n // Unsubscribe from previous deps before re-running. The expression will\n // re-record whatever it actually reads this time, avoiding stale subs.\n this._unsubscribeEffect(e);\n e.dependencies.clear();\n try {\n return await fn();\n } finally {\n this.currentEffect = prev;\n }\n }\n\n // ---------------------------------------------------------------------------\n // Track (read-path) — invoked from interceptors / evaluators.\n // ---------------------------------------------------------------------------\n\n trackGlobal(name: string): void {\n const e = this.currentEffect;\n if (!e) return;\n const key = globalDepKey(name);\n if (e.dependencies.has(key)) return;\n e.dependencies.set(key, { key, kind: 'global', name, element: null });\n let subs = this.globalSubs.get(name);\n if (!subs) {\n subs = new Set();\n this.globalSubs.set(name, subs);\n }\n subs.add(e);\n }\n\n trackElement(el: Element, name: string): void {\n const e = this.currentEffect;\n if (!e) return;\n const key = elementDepKey(el, name);\n if (e.dependencies.has(key)) return;\n e.dependencies.set(key, { key, kind: 'element', name, element: el });\n const state = this.getElementState(el);\n let subs = state.symbolSubs.get(name);\n if (!subs) {\n subs = new Set();\n state.symbolSubs.set(name, subs);\n }\n subs.add(e);\n state.effects.add(e);\n }\n\n trackDomProperty(el: Element, prop: string): void {\n const e = this.currentEffect;\n if (!e) return;\n const key = domDepKey(el, prop);\n if (e.dependencies.has(key)) return;\n e.dependencies.set(key, { key, kind: 'dom', name: prop, element: el });\n const state = this.getElementState(el);\n let handler = state.domHandlers.get(prop);\n if (!handler) {\n const subs = new Set<Effect>();\n const listener = (): void => {\n for (const effect of subs) this.schedule(effect);\n };\n // Use both input and change to cover radios/selects which don't fire input.\n el.addEventListener('input', listener);\n el.addEventListener('change', listener);\n handler = {\n subs,\n detach: () => {\n el.removeEventListener('input', listener);\n el.removeEventListener('change', listener);\n },\n };\n state.domHandlers.set(prop, handler);\n }\n handler.subs.add(e);\n state.effects.add(e);\n }\n\n // ---------------------------------------------------------------------------\n // Notify (write-path) — schedules dependent effects for re-run.\n // ---------------------------------------------------------------------------\n\n notifyGlobal(name: string): void {\n const subs = this.globalSubs.get(name);\n if (!subs) return;\n for (const e of subs) this.schedule(e);\n }\n\n notifyElement(el: Element, name: string): void {\n const state = this.elementState.get(el);\n if (!state) return;\n const subs = state.symbolSubs.get(name);\n if (!subs) return;\n for (const e of subs) this.schedule(e);\n }\n\n // ---------------------------------------------------------------------------\n // Effect lifecycle.\n // ---------------------------------------------------------------------------\n\n /**\n * Create + initialize an effect. Returns a disposer that stops the effect.\n * Callers are expected to register the disposer with the core runtime's\n * cleanup registry so it fires on element removal.\n */\n createEffect(\n expression: () => unknown | Promise<unknown>,\n handler: (value: unknown) => void | Promise<void>,\n owner: Element | null\n ): () => void {\n const e = new Effect(this, expression, handler, owner);\n if (owner) this.getElementState(owner).effects.add(e);\n // Fire initialize asynchronously so the caller can set up cleanup registration\n // before the first run touches the DOM.\n queueMicrotask(() => {\n void e.initialize();\n });\n return () => e.stop();\n }\n\n /**\n * Stop all effects owned by an element. Called by the reactivity plugin's\n * cleanup hook registered via `runtime.getCleanupRegistry()`.\n */\n stopElementEffects(el: Element): void {\n const state = this.elementState.get(el);\n if (!state) return;\n for (const e of Array.from(state.effects)) e.stop();\n state.effects.clear();\n }\n\n /**\n * Internal: remove an effect's entries from all subscriber sets. Called by\n * `Effect.stop()`.\n */\n _unsubscribeEffect(e: Effect): void {\n for (const dep of e.dependencies.values()) {\n if (dep.kind === 'global') {\n const subs = this.globalSubs.get(dep.name);\n subs?.delete(e);\n } else if (dep.kind === 'element' && dep.element) {\n const state = this.elementState.get(dep.element);\n const subs = state?.symbolSubs.get(dep.name);\n subs?.delete(e);\n state?.effects.delete(e);\n } else if (dep.kind === 'dom' && dep.element) {\n const state = this.elementState.get(dep.element);\n const handler = state?.domHandlers.get(dep.name);\n handler?.subs.delete(e);\n if (handler && handler.subs.size === 0) {\n handler.detach();\n state?.domHandlers.delete(dep.name);\n }\n state?.effects.delete(e);\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Caret-variable storage — `^name` reads/writes.\n // ---------------------------------------------------------------------------\n\n /**\n * Whether `el` is a `dom-scope=\"isolated\"` boundary. Walks of `^var`\n * lookups stop at boundary elements that don't define the var, so nested\n * components don't accidentally read or write each other's state.\n */\n private isIsolationBoundary(el: Element): boolean {\n return typeof el.getAttribute === 'function' && el.getAttribute('dom-scope') === 'isolated';\n }\n\n /**\n * Walk up the DOM tree from `lookupRoot`, returning the first element whose\n * state has `name` defined. Stops at any `dom-scope=\"isolated\"` boundary\n * that doesn't itself define the var. Returns `null` if no owner is found.\n */\n private findCaretOwner(lookupRoot: Element, name: string): Element | null {\n let el: Element | null = lookupRoot;\n while (el) {\n const state = this.elementState.get(el);\n if (state && state.caretVars.has(name)) return el;\n if (this.isIsolationBoundary(el)) return null;\n el = el.parentElement;\n }\n return null;\n }\n\n /**\n * Read a DOM-scoped variable. Walks up from `lookupRoot`, tracking each\n * element visited as an `element` dep (so writes at any ancestor notify\n * dependent effects). Stops at any `dom-scope=\"isolated\"` boundary that\n * doesn't itself define the var.\n */\n readCaret(lookupRoot: Element, name: string): unknown {\n let el: Element | null = lookupRoot;\n while (el) {\n this.trackElement(el, name);\n const state = this.elementState.get(el);\n if (state && state.caretVars.has(name)) {\n return state.caretVars.get(name);\n }\n if (this.isIsolationBoundary(el)) return undefined;\n el = el.parentElement;\n }\n return undefined;\n }\n\n /**\n * Write a DOM-scoped variable. If `target` is provided, writes there\n * directly; otherwise walks up from `lookupRoot` to find the existing owner,\n * falling back to `lookupRoot` itself if no owner exists.\n */\n writeCaret(lookupRoot: Element, name: string, value: unknown, target?: Element): void {\n const owner = target ?? this.findCaretOwner(lookupRoot, name) ?? lookupRoot;\n const state = this.getElementState(owner);\n state.caretVars.set(name, value);\n this.notifyElement(owner, name);\n }\n\n // ---------------------------------------------------------------------------\n // Scheduler — microtask-batched flush.\n // ---------------------------------------------------------------------------\n\n private schedule(e: Effect): void {\n if (e.stopped) return;\n this.pending.add(e);\n if (this.scheduled) return;\n this.scheduled = true;\n queueMicrotask(() => void this.flush());\n }\n\n private async flush(): Promise<void> {\n try {\n while (this.pending.size > 0) {\n const batch = Array.from(this.pending);\n this.pending.clear();\n for (const e of batch) {\n if (e.stopped) continue;\n await e.run();\n // If the effect's run did not synchronously re-schedule itself, its\n // trigger count is reset. Self-rescheduling (a real cycle) keeps the\n // counter climbing toward the 100 cap. Long-lived effects that fire\n // sporadically (e.g. user-input bindings) stay alive forever.\n if (!this.pending.has(e)) e.resetTriggerCount();\n }\n }\n } finally {\n this.scheduled = false;\n }\n }\n}\n\n// Module singleton. One reactive graph per process; mirrors upstream's\n// `runtime.reactivity` pattern.\nexport const reactive = new Reactive();\n","/**\n * `^name` — DOM-scoped inherited variable.\n *\n * Upstream syntax:\n * ^counter → read from nearest ancestor that has `counter` set\n * ^counter on #target → read from (or near) #target\n * set ^counter to 42 → write to owner (or lookupRoot if not yet defined)\n *\n * Parse side: register `^` as a Pratt prefix operator. The handler consumes\n * the identifier token and an optional `on <target>` clause, emitting a\n * `caretVar` AST node.\n *\n * Eval side: `caretVar` node evaluator calls `reactive.readCaret(anchor,\n * name)` which walks the DOM tree for the owner and records deps as it goes.\n */\n\nimport type { ASTNode, ExecutionContext } from './types';\nimport { reactive } from './signals';\n\nexport interface CaretVarNode extends ASTNode {\n type: 'caretVar';\n name: string;\n onTarget: ASTNode | null;\n}\n\ninterface CaretVarRuntime {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n}\n\n/**\n * Coerce a runtime-evaluated `on <target>` result to a single Element.\n * Selector expressions resolve to an array of matched elements; bare\n * `me`/`it`/`you`/identifier references resolve to single Elements. Take the\n * first element of an array, or the value itself if it's already an Element.\n */\nfunction coerceToElement(value: unknown): Element | null {\n if (value instanceof Element) return value;\n if (Array.isArray(value) && value[0] instanceof Element) return value[0];\n return null;\n}\n\n/**\n * Pratt prefix handler for `^`. Consumes the following identifier token and\n * an optional `on <expr>` clause.\n */\nexport function parseCaretPrefix(token: unknown, ctx: unknown): ASTNode {\n // `ctx` is hyperfixi's PrattContext: { peek, advance, parseExpr, isStopToken, atEnd }.\n const pctx = ctx as {\n peek(): { value?: string; kind?: string } | undefined;\n advance(): { value: string; kind?: string };\n parseExpr(minBp: number): ASTNode;\n };\n const ident = pctx.advance();\n if (!ident || !ident.value) {\n throw new Error(\"Expected identifier after '^'\");\n }\n let onTarget: ASTNode | null = null;\n const next = pctx.peek();\n if (next && next.value === 'on') {\n pctx.advance(); // consume 'on'\n // Binding power 86 — higher than standard comparisons so `^x on me` doesn't\n // over-consume into surrounding expressions.\n onTarget = pctx.parseExpr(86);\n }\n const startTok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'caretVar',\n name: ident.value,\n onTarget,\n start: startTok?.start ?? 0,\n end: startTok?.end ?? 0,\n line: startTok?.line,\n column: startTok?.column,\n } as CaretVarNode;\n}\n\n/**\n * Build a node evaluator for `caretVar` bound to a specific runtime. The\n * evaluator walks up from the resolved anchor element, tracking every element\n * visited so writes at any ancestor notify dependent effects.\n *\n * Capturing `runtime` via a factory closure (matching live/when/bind) keeps\n * the evaluator independent of any module-scope state.\n */\nexport function makeEvaluateCaretVar(\n runtime: CaretVarRuntime\n): (node: ASTNode, ctx: unknown) => Promise<unknown> {\n return async function evaluateCaretVar(node, ctx) {\n const n = node as CaretVarNode;\n const context = ctx as ExecutionContext;\n let anchor: Element | null = (context.me as Element | null) ?? null;\n\n if (n.onTarget) {\n const resolved = await runtime.execute(n.onTarget, context);\n const el = coerceToElement(resolved);\n if (el) anchor = el;\n }\n\n if (!anchor) return undefined;\n return reactive.readCaret(anchor, n.name);\n };\n}\n\n/**\n * Build a node writer for `caretVar` bound to a specific runtime. Used by the\n * core `set` command via `parserExtensions.registerNodeWriter`.\n */\nexport function makeWriteCaretVar(\n runtime: CaretVarRuntime\n): (node: ASTNode, value: unknown, ctx: unknown) => Promise<void> {\n return async function writeCaretVar(node, value, ctx) {\n const n = node as CaretVarNode;\n const context = ctx as ExecutionContext;\n const anchor: Element | null = (context.me as Element | null) ?? null;\n if (!anchor) return;\n\n let target: Element | undefined;\n if (n.onTarget) {\n const resolved = await runtime.execute(n.onTarget, context);\n const el = coerceToElement(resolved);\n if (el) target = el;\n }\n reactive.writeCaret(anchor, n.name, value, target);\n };\n}\n","/**\n * `live ... end` — reactive block. Body re-runs whenever any dependency read\n * during its execution changes.\n *\n * Upstream syntax:\n * live [commandList] end\n *\n * Each command in the body is re-executed as a single effect. The entire\n * body shares one effect instance; its dependency set is the union of every\n * read performed during body execution.\n */\n\nimport type { ASTNode, ExecutionContext, FeatureParserCtx } from './types';\nimport { reactive } from './signals';\n\nexport interface LiveFeatureNode extends ASTNode {\n type: 'liveFeature';\n body: ASTNode[];\n}\n\n/**\n * Parse `live ... end`. The `live` keyword has already been consumed by the\n * parser dispatcher; we parse the body and expect a trailing `end`.\n */\nexport function parseLiveFeature(ctx: unknown, token: unknown): ASTNode {\n const pctx = ctx as FeatureParserCtx;\n const body = pctx.parseCommandListUntilEnd();\n // parseCommandListUntilEnd stops when it sees `end` (but doesn't consume it).\n if (!pctx.isAtEnd() && pctx.check('end')) pctx.match('end');\n const tok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'liveFeature',\n body,\n start: tok?.start ?? 0,\n end: pctx.getPosition().end,\n line: tok?.line,\n column: tok?.column,\n } as LiveFeatureNode;\n}\n\n/**\n * Create an evaluator bound to a runtime reference. The plugin captures\n * `runtime` at install time and passes it in so effect re-runs can dispatch\n * the body commands without going through module-scope state.\n */\nexport function makeEvaluateLiveFeature(runtime: {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n}): (node: ASTNode, ctx: unknown) => unknown | Promise<unknown> {\n return async function evaluateLiveFeature(node, ctx) {\n const context = ctx as ExecutionContext;\n const owner = (context.me as Element) ?? document.body;\n const n = node as LiveFeatureNode;\n\n const stop = reactive.createEffect(\n async () => {\n for (const cmd of n.body) {\n await runtime.execute(cmd, context);\n }\n },\n () => {\n /* no-op — side effects happened inside the expression */\n },\n owner\n );\n context.registerCleanup?.(owner, stop, 'live-effect');\n return undefined;\n };\n}\n","/**\n * `when <expr> [or <expr>]* changes [commandList] end` — observer feature.\n *\n * Runs the body when any watched expression's value changes (Object.is\n * semantics). One effect is created per watched expression so writes to a\n * given dep only re-run that watcher.\n */\n\nimport type { ASTNode, ExecutionContext, FeatureParserCtx } from './types';\nimport { reactive } from './signals';\n\nexport interface WhenFeatureNode extends ASTNode {\n type: 'whenFeature';\n watched: ASTNode[];\n body: ASTNode[];\n}\n\nexport function parseWhenFeature(ctx: unknown, token: unknown): ASTNode {\n const pctx = ctx as FeatureParserCtx;\n const watched: ASTNode[] = [pctx.parseExpression()];\n while (pctx.match('or')) {\n watched.push(pctx.parseExpression());\n }\n pctx.consume('changes', \"Expected 'changes' after when expression list\");\n const body = pctx.parseCommandListUntilEnd();\n if (!pctx.isAtEnd() && pctx.check('end')) pctx.match('end');\n const tok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'whenFeature',\n watched,\n body,\n start: tok?.start ?? 0,\n end: pctx.getPosition().end,\n line: tok?.line,\n column: tok?.column,\n } as WhenFeatureNode;\n}\n\nexport function makeEvaluateWhenFeature(runtime: {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n evaluateExpressionWithResult?: (\n node: ASTNode,\n ctx: ExecutionContext\n ) => Promise<{ value: unknown }>;\n}): (node: ASTNode, ctx: unknown) => unknown | Promise<unknown> {\n return async function evaluateWhenFeature(node, ctx) {\n const context = ctx as ExecutionContext;\n const owner = (context.me as Element) ?? document.body;\n const n = node as WhenFeatureNode;\n\n for (const watchedExpr of n.watched) {\n const stop = reactive.createEffect(\n async () => {\n // Evaluate the watched expression as a regular expression through the\n // runtime so that trackGlobal/trackElement fire via the global-write\n // hook and caret-var reads.\n return await runtime.execute(watchedExpr, context);\n },\n async newValue => {\n // Fire the body with `it` / `result` bound to the new value.\n const subCtx: ExecutionContext = { ...context, it: newValue, result: newValue };\n for (const cmd of n.body) {\n await runtime.execute(cmd, subCtx);\n }\n },\n owner\n );\n context.registerCleanup?.(owner, stop, 'when-effect');\n }\n return undefined;\n };\n}\n","/**\n * `bind X [to|and|with] Y` — two-way binding.\n *\n * Creates two effects (registration order is load-bearing — both initialize\n * via `queueMicrotask` and run in registration order):\n * 1. DOM → var: read DOM, write var. DOM \"wins\" on init.\n * 2. var → DOM: read var, write DOM. Fires on programmatic var writes\n * after init. On its own initial run, var === DOM (Effect 1 just synced\n * them), so the write is a no-op.\n *\n * Two binding forms:\n *\n * 1. Auto-detected (DOM side is a bare element expression):\n *\n * bind $name to #input -- detects `value`\n * bind $checked to me -- detects `checked` on a checkbox\n *\n * Auto-detected property by element type:\n * - INPUT[type=checkbox|radio] → `checked`\n * - INPUT[type=number|range] → `valueAsNumber`\n * - INPUT|TEXTAREA|SELECT → `value`\n * - contenteditable=\"true\" → `textContent`\n * - Custom elements with own `value` → `value`\n *\n * 2. Explicit property (DOM side is a member or possessive expression):\n *\n * bind $color to #picker's value -- possessive (preferred — reads in any language)\n * bind $color to #picker.value -- dot (JS-style alternative)\n * bind $text to #div's textContent -- non-form properties: var→DOM only\n *\n * For form-like elements, both directions work. For non-form elements\n * (e.g., binding a div's `textContent`), only var→DOM fires — there are\n * no input/change events to drive DOM→var, so user mutations of the\n * property via devtools won't propagate back.\n */\n\nimport type { ASTNode, ExecutionContext, FeatureParserCtx } from './types';\nimport { reactive } from './signals';\n\nexport interface BindFeatureNode extends ASTNode {\n type: 'bindFeature';\n left: ASTNode;\n right: ASTNode;\n}\n\nexport function parseBindFeature(ctx: unknown, token: unknown): ASTNode {\n const pctx = ctx as FeatureParserCtx;\n const left = pctx.parseExpression();\n // Accept any of `to` / `and` / `with` as the separator.\n if (!(pctx.match('to') || pctx.match('and') || pctx.match('with'))) {\n throw new Error(\"bind requires 'to', 'and', or 'with' between the two sides\");\n }\n const right = pctx.parseExpression();\n // Optional `end` terminator (matches upstream which allows both forms).\n if (pctx.check('end')) pctx.match('end');\n const tok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'bindFeature',\n left,\n right,\n start: tok?.start ?? 0,\n end: pctx.getPosition().end,\n line: tok?.line,\n column: tok?.column,\n } as BindFeatureNode;\n}\n\n/**\n * Auto-detect the DOM property to bind by element type. Returns null if the\n * target isn't a recognized form/editable element.\n */\nfunction detectProperty(el: Element): string | null {\n const tag = el.tagName;\n if (tag === 'INPUT') {\n const type = (el as HTMLInputElement).type;\n if (type === 'checkbox' || type === 'radio') return 'checked';\n if (type === 'number' || type === 'range') return 'valueAsNumber';\n return 'value';\n }\n if (tag === 'TEXTAREA' || tag === 'SELECT') return 'value';\n const ce = (el as HTMLElement).contentEditable;\n if (ce === 'true') return 'textContent';\n // Custom elements with own `value` prop.\n if ('value' in el) return 'value';\n return null;\n}\n\n/**\n * If `node` is a `memberExpression` or `possessiveExpression` with a static\n * identifier property (`#el.value` or `#el's value`), return the inner element\n * expression and the property name. Returns null for anything else.\n *\n * Computed member access (`#el[prop]`) is intentionally rejected — we'd have to\n * evaluate the index dynamically and the binding direction would be unclear.\n * Chained property access (`#el.dataset.value`) is also not unpacked — we only\n * peel one level. Multi-level support is a future arc.\n */\nfunction unwrapExplicitProperty(node: ASTNode): { element: ASTNode; propertyName: string } | null {\n if (!node || (node.type !== 'memberExpression' && node.type !== 'possessiveExpression')) {\n return null;\n }\n if (node.type === 'memberExpression' && node.computed === true) return null;\n const property = node.property as ASTNode | undefined;\n const object = node.object as ASTNode | undefined;\n if (!property || !object || property.type !== 'identifier') return null;\n const name = (property.name as string) ?? '';\n if (!name) return null;\n return { element: object, propertyName: name };\n}\n\n/**\n * Detect a chained property access on the bind RHS — e.g.\n * `me.style.backgroundColor` or `#el's dataset's value`.\n *\n * After `unwrapExplicitProperty` peels the outermost member, the returned\n * `element` is the object of that member. If that object is itself a\n * member/possessive expression, we have a multi-level chain that v1 of\n * bind doesn't support. Used only for the error path; the parsed AST is\n * left intact.\n */\nfunction isChainedMember(node: ASTNode | undefined): boolean {\n if (!node) return false;\n return node.type === 'memberExpression' || node.type === 'possessiveExpression';\n}\n\n/**\n * Whether the input/change listener installed by `trackDomProperty` would\n * actually fire for this element. Used to decide whether to wire up the\n * DOM→var direction when an explicit property is given.\n */\nfunction isFormLikeElement(el: Element): boolean {\n const tag = el.tagName;\n if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;\n if ((el as HTMLElement).contentEditable === 'true') return true;\n return false;\n}\n\n/**\n * Whether debug logging is enabled. Mirrors signals.ts — keeps a single\n * convention for the package.\n */\nfunction debugEnabled(): boolean {\n try {\n return typeof localStorage !== 'undefined' && localStorage.getItem('hyperfixi:debug') !== null;\n } catch {\n return false;\n }\n}\n\n/**\n * Create the bind evaluator. Because `bind` has unusual parse shape (AST\n * nodes for left/right that may be identifiers, `$name` references, or DOM\n * element lookups), we rely on the runtime to evaluate them.\n */\nexport function makeEvaluateBindFeature(runtime: {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n}): (node: ASTNode, ctx: unknown) => unknown | Promise<unknown> {\n return async function evaluateBindFeature(node, ctx) {\n const context = ctx as ExecutionContext;\n const owner = (context.me as Element) ?? document.body;\n const n = node as BindFeatureNode;\n\n // Dynamically import the element-scope accessor from core. A static import\n // would pull core's full index into this module's load graph — and core's\n // index eagerly evaluates `morphlex` (which touches `Element.prototype` at\n // module scope), throwing `Element is not defined` when @hyperfixi/reactivity\n // is imported in bare Node/SSR. This evaluator only runs in a browser (it\n // uses `document.body` above), so deferring the import keeps the package\n // importable in Node while `:name` binds still address the core store.\n const { getElementScopeMap } = await import('@hyperfixi/core');\n\n // Resolve sides. One is a var reference (read/write a symbol), the other\n // a DOM target (read/write a property). Determine direction from node shape.\n const leftIsVar = isVarRef(n.left);\n const rightIsVar = isVarRef(n.right);\n\n // We need a DOM-side descriptor (element + property) and a var-side name.\n let varSide: { name: string; isGlobal: boolean } | null = null;\n let domSide: { exprNode: ASTNode } | null = null;\n\n if (leftIsVar && !rightIsVar) {\n varSide = varRefInfo(n.left);\n domSide = { exprNode: n.right };\n } else if (rightIsVar && !leftIsVar) {\n varSide = varRefInfo(n.right);\n domSide = { exprNode: n.left };\n } else if (leftIsVar && rightIsVar) {\n // var-to-var binding not supported in v1 (no DOM side).\n throw new Error('bind: cannot bind two symbols together (need a DOM side)');\n } else {\n throw new Error('bind: could not identify a symbol side');\n }\n\n // Unwrap explicit property syntax: `#el.value` or `#el's value` becomes\n // (element-expression, propertyName). Otherwise, evaluate the whole side\n // and rely on auto-detection.\n const explicit = unwrapExplicitProperty(domSide.exprNode);\n // Multi-level property access (`#el.style.background`, `me's dataset's id`)\n // is not supported in v1. Surface that diagnosis up front; otherwise the\n // user gets the generic \"did not resolve to an element\" message and no\n // hint that the chain is the problem.\n if (explicit && isChainedMember(explicit.element)) {\n throw new Error(\n 'bind: multi-level property access (e.g., `#el.a.b`) is not supported in v1 — restructure to a single property write or pass the element directly for auto-detection (e.g., `bind $x to #el`).'\n );\n }\n const elementExpr = explicit ? explicit.element : domSide.exprNode;\n const domValue = await runtime.execute(elementExpr, context);\n if (!(domValue instanceof Element)) {\n const valueType =\n domValue === null ? 'null' : domValue === undefined ? 'undefined' : typeof domValue;\n const snippet =\n domValue !== null && domValue !== undefined ? ` \"${String(domValue).slice(0, 40)}\"` : '';\n const suggestion = explicit\n ? ''\n : \" If you meant to write to a property, use the explicit form: `<selector>'s <property>`.\";\n throw new Error(\n `bind: right-hand side did not resolve to an element (got ${valueType}${snippet}).${suggestion}`\n );\n }\n const el = domValue;\n // Explicit property bypasses auto-detect; the user takes responsibility for\n // picking something readable from the element. For DOM→var to work without\n // explicit property, fall back to auto-detect.\n const prop = explicit ? explicit.propertyName : detectProperty(el);\n if (!prop) {\n throw new Error(\n `bind: could not auto-detect property for <${el.tagName.toLowerCase()}> — use explicit \\`<expr>'s <property>\\` form`\n );\n }\n // For explicit-property mode on non-form elements, DOM→var can't sync via\n // input/change events. Skip the listener install; only var→DOM runs.\n const installDomToVar = !explicit || isFormLikeElement(el);\n if (explicit && !installDomToVar && debugEnabled() && typeof console !== 'undefined') {\n console.warn(\n `[@hyperfixi/reactivity] bind: DOM→var skipped for <${el.tagName.toLowerCase()}>.${prop} — no input/change event source.`\n );\n }\n\n // Initial sync: DOM → var.\n const readDom = (): unknown => {\n if (prop === 'valueAsNumber') return (el as HTMLInputElement).valueAsNumber;\n if (prop === 'checked') return (el as HTMLInputElement).checked;\n if (prop === 'textContent') return el.textContent ?? '';\n return (el as any)[prop];\n };\n const writeDom = (value: unknown): void => {\n if (prop === 'valueAsNumber') {\n const n = Number(value);\n (el as HTMLInputElement).valueAsNumber = Number.isNaN(n) ? (null as never) : n;\n } else if (prop === 'checked') {\n (el as HTMLInputElement).checked = Boolean(value);\n } else if (prop === 'textContent') {\n el.textContent = value == null ? '' : String(value);\n } else {\n (el as any)[prop] = value;\n }\n };\n const readVar = (): unknown => {\n if (varSide!.isGlobal) return context.globals?.get(varSide!.name);\n // `:name` is element-scoped — read from the owner element's store, the same\n // place the core `set :name` writes. (Direct Map access, not getElementVar,\n // so we don't double-fire the read hook; bind tracks via trackElement.)\n return getElementScopeMap(owner).get(varSide!.name);\n };\n const writeVar = (value: unknown): void => {\n if (varSide!.isGlobal) {\n context.globals?.set(varSide!.name, value);\n // Bypass the global-write hook (we're touching the Map directly), so\n // notify the reactive graph manually for the var→DOM effect.\n reactive.notifyGlobal(varSide!.name);\n } else {\n // Element-scoped `:name`: write to the owner element's store (same place\n // core's `set :name` writes), then notify manually — the direct Map write\n // skips the localWriteHook.\n getElementScopeMap(owner).set(varSide!.name, value);\n reactive.notifyElement(owner, varSide!.name);\n }\n };\n\n // Effect 1: DOM → var (fires on user input). Skipped for explicit-property\n // bindings on non-form elements — no input/change events would drive it.\n let stopDomToVar: (() => void) | null = null;\n if (installDomToVar) {\n stopDomToVar = reactive.createEffect(\n () => {\n reactive.trackDomProperty(el, prop);\n return readDom();\n },\n newValue => {\n writeVar(newValue);\n },\n owner\n );\n }\n\n // Effect 2: var → DOM (fires on programmatic var writes — for globals\n // via the core's globalWriteHook, for locals via the localWriteHook the\n // reactivity plugin registers).\n const stopVarToDom = reactive.createEffect(\n () => {\n if (varSide!.isGlobal) reactive.trackGlobal(varSide!.name);\n else reactive.trackElement(owner, varSide!.name);\n return readVar();\n },\n newValue => {\n if (newValue === undefined) return;\n writeDom(newValue);\n },\n owner\n );\n\n if (stopDomToVar) context.registerCleanup?.(owner, stopDomToVar, 'bind-dom-to-var');\n context.registerCleanup?.(owner, stopVarToDom, 'bind-var-to-dom');\n return undefined;\n };\n}\n\n/**\n * Is this AST node a var reference we can bind to?\n *\n * The hyperfixi parser emits `identifier` nodes for both globals and locals,\n * but with different shapes:\n * - `$foo` → `{ type: 'identifier', name: '$foo' }` (no scope field)\n * - `:foo` → `{ type: 'identifier', name: 'foo', scope: 'element' }` (element-scoped)\n * - `::foo` → `{ type: 'identifier', name: 'foo', scope: 'global' }`\n *\n * We accept all of them. The legacy `$`-prefix sniff stays as a fallback because\n * `parseExpression` doesn't always set `scope`.\n */\nfunction isVarRef(node: ASTNode): boolean {\n if (!node) return false;\n if (node.type !== 'identifier') return false;\n const scope = node.scope as string | undefined;\n if (scope === 'local' || scope === 'element' || scope === 'global') return true;\n const name = (node.name as string) ?? '';\n return name.startsWith('$') || name.startsWith(':');\n}\n\nfunction varRefInfo(node: ASTNode): { name: string; isGlobal: boolean } {\n const rawName = (node.name as string) ?? '';\n const scope = node.scope as string | undefined;\n // Prefer the parser-emitted scope marker. Fall back to prefix sniffing for\n // shapes where scope isn't set (e.g. `$foo` arriving as bare identifier\n // with name '$foo').\n let isGlobal: boolean;\n let name: string;\n if (scope === 'global') {\n isGlobal = true;\n name = rawName;\n } else if (scope === 'local' || scope === 'element') {\n isGlobal = false;\n name = rawName;\n } else if (rawName.startsWith('$')) {\n isGlobal = true;\n name = rawName.slice(1);\n } else if (rawName.startsWith(':')) {\n isGlobal = false;\n name = rawName.slice(1);\n } else {\n isGlobal = false;\n name = rawName;\n }\n if (!name) {\n throw new Error('bind: variable reference has empty name');\n }\n return { name, isGlobal };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC0BA,SAAS,eAAwB;AAC/B,MAAI;AACF,WAAO,OAAO,iBAAiB,eAAe,aAAa,QAAQ,iBAAiB,MAAM;AAAA,EAC5F,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,UAAU,SAAiB,KAAoB;AACtD,MAAI,CAAC,aAAa,EAAG;AACrB,MAAI,OAAO,YAAY,YAAa;AACpC,UAAQ,KAAK,2BAA2B,OAAO,IAAI,GAAG;AACxD;AASA,IAAM,eAAe,CAAC,SAAyB,UAAU,IAAI;AAC7D,IAAM,gBAAgB,CAAC,IAAa,SAAyB,WAAW,cAAc,EAAE,CAAC,IAAI,IAAI;AACjG,IAAM,YAAY,CAAC,IAAa,SAAyB,OAAO,cAAc,EAAE,CAAC,IAAI,IAAI;AAKzF,IAAM,eAAe,oBAAI,QAAyB;AAClD,IAAI,aAAa;AACjB,SAAS,cAAc,IAAqB;AAC1C,QAAM,WAAW,aAAa,IAAI,EAAE;AACpC,MAAI,aAAa,OAAW,QAAO;AACnC,QAAM,KAAK,EAAE;AACb,eAAa,IAAI,IAAI,EAAE;AACvB,SAAO;AACT;AAEO,IAAM,SAAN,MAAa;AAAA,EAMlB,YACmB,GACR,YACA,SACA,SACT;AAJiB;AACR;AACA;AACA;AAAA,EACR;AAAA,EAVM,eAAe,oBAAI,IAAiB;A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,EAAG;AAGzC,qBAAiB,gBAAgB,QAAQ,gBAAyB;AAClE,qBAAiB,gBAAgB,QAAQ,gBAAyB;AAClE,qBAAiB,gBAAgB,QAAQ,gBAAyB;AAClE,qBAAiB,uBAAuB,KAAK,IAAI,gBAAyB;AAI1E,qBAAiB;AAAA,MACf;AAAA,MACA,wBAAwB,OAAgB;AAAA,IAC1C;AACA,qBAAiB;AAAA,MACf;AAAA,MACA,wBAAwB,OAAgB;AAAA,IAC1C;AACA,qBAAiB;AAAA,MACf;AAAA,MACA,wBAAwB,OAAgB;AAAA,IAC1C;AACA,qBAAiB;AAAA,MACf;AAAA,MACA,qBAAqB,OAAgB;AAAA,IACvC;AAKA,qBAAiB,mBAAmB,YAAY,kBAAkB,OAAgB,CAAU;AAK5F,qBAAiB,wBAAwB,CAAC,MAAc,QAAiB,aAAsB;AAC7F,eAAS,aAAa,IAAI;AAAA,IAC5B,CAAC;AAID,qBAAiB,uBAAuB,CAAC,MAAc,aAAsB;AAC3E,eAAS,YAAY,IAAI;AAAA,IAC3B,CAAC;AAQD,qBAAiB,uBAAuB,CAAC,MAAc,QAAiB,YAAY;AAClF,YAAM,QAAS,QAAoC,MAAM;AACzD,UAAI,MAAO,UAAS,cAAc,OAAO,IAAI;AAAA,IAC/C,CAAC;AAED,qBAAiB,sBAAsB,CAAC,MAAc,YAAY;AAChE,YAAM,QAAS,QAAoC,MAAM;AACzD,UAAI,MAAO,UAAS,aAAa,OAAO,IAAI;AAAA,IAC9C,CAAC;AAAA,EACH;AACF;AAEA,IAAO,gBAAQ;","names":["debugEnabled","n"]}
package/dist/index.js CHANGED
@@ -551,6 +551,7 @@ function makeEvaluateBindFeature(runtime) {
551
551
  const context = ctx;
552
552
  const owner = context.me ?? document.body;
553
553
  const n = node;
554
+ const { getElementScopeMap } = await import("@hyperfixi/core");
554
555
  const leftIsVar = isVarRef(n.left);
555
556
  const rightIsVar = isVarRef(n.right);
556
557
  let varSide = null;
@@ -615,14 +616,14 @@ function makeEvaluateBindFeature(runtime) {
615
616
  };
616
617
  const readVar = () => {
617
618
  if (varSide.isGlobal) return context.globals?.get(varSide.name);
618
- return context.locals?.get(varSide.name);
619
+ return getElementScopeMap(owner).get(varSide.name);
619
620
  };
620
621
  const writeVar = (value) => {
621
622
  if (varSide.isGlobal) {
622
623
  context.globals?.set(varSide.name, value);
623
624
  reactive.notifyGlobal(varSide.name);
624
625
  } else {
625
- context.locals?.set(varSide.name, value);
626
+ getElementScopeMap(owner).set(varSide.name, value);
626
627
  reactive.notifyElement(owner, varSide.name);
627
628
  }
628
629
  };
@@ -660,7 +661,7 @@ function isVarRef(node) {
660
661
  if (!node) return false;
661
662
  if (node.type !== "identifier") return false;
662
663
  const scope = node.scope;
663
- if (scope === "local" || scope === "global") return true;
664
+ if (scope === "local" || scope === "element" || scope === "global") return true;
664
665
  const name = node.name ?? "";
665
666
  return name.startsWith("$") || name.startsWith(":");
666
667
  }
@@ -672,7 +673,7 @@ function varRefInfo(node) {
672
673
  if (scope === "global") {
673
674
  isGlobal = true;
674
675
  name = rawName;
675
- } else if (scope === "local") {
676
+ } else if (scope === "local" || scope === "element") {
676
677
  isGlobal = false;
677
678
  name = rawName;
678
679
  } else if (rawName.startsWith("$")) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/signals.ts","../src/caret-var.ts","../src/live.ts","../src/when.ts","../src/bind.ts","../src/index.ts"],"sourcesContent":["/**\n * Signal/effect reactive core.\n *\n * Models three dependency kinds for v1:\n * - `global` — `$name` variables in `context.globals`\n * - `element` — `^name` DOM-scoped variables (per-element storage)\n * - `dom` — DOM properties read via `input`/`change` listeners\n *\n * Inspired by upstream _hyperscript 0.9.91's `src/core/runtime/reactivity.js`\n * but reimplemented in TypeScript against hyperfixi's types. Batched via\n * `queueMicrotask` so synchronous writes coalesce into a single flush. Cycle\n * detection halts at >100 consecutive triggers (matching upstream).\n *\n * External packages never see `Effect` or `Reactive` directly — they hold\n * the disposer returned by `createEffect()` and call it when the owning\n * element is cleaned up.\n */\n\nexport type DepKind = 'global' | 'element' | 'dom';\n\n/**\n * Whether reactive debug logging is enabled. Mirrors the core convention:\n * `localStorage.setItem('hyperfixi:debug', '*')` enables, anything else (or no\n * `localStorage`) disables. Cheap call — no caching, since users toggle this\n * interactively in the console.\n */\nfunction debugEnabled(): boolean {\n try {\n return typeof localStorage !== 'undefined' && localStorage.getItem('hyperfixi:debug') !== null;\n } catch {\n return false;\n }\n}\n\nfunction debugWarn(message: string, err: unknown): void {\n if (!debugEnabled()) return;\n if (typeof console === 'undefined') return;\n console.warn(`[@hyperfixi/reactivity] ${message}`, err);\n}\n\nexport interface Dep {\n readonly key: string;\n readonly kind: DepKind;\n readonly name: string;\n readonly element: Element | null;\n}\n\nconst globalDepKey = (name: string): string => `global:${name}`;\nconst elementDepKey = (el: Element, name: string): string => `element:${reactiveIdFor(el)}:${name}`;\nconst domDepKey = (el: Element, prop: string): string => `dom:${reactiveIdFor(el)}:${prop}`;\n\n// WeakMap-based id assignment so we don't monkey-patch DOM nodes. Ids are\n// per-process and only used to construct stable string keys for an effect's\n// per-effect dependency dedup map.\nconst _reactiveIds = new WeakMap<Element, number>();\nlet _idCounter = 0;\nfunction reactiveIdFor(el: Element): number {\n const existing = _reactiveIds.get(el);\n if (existing !== undefined) return existing;\n const id = ++_idCounter;\n _reactiveIds.set(el, id);\n return id;\n}\n\nexport class Effect {\n readonly dependencies = new Map<string, Dep>();\n private lastValue: unknown = undefined;\n private _stopped = false;\n private _consecutiveTriggers = 0;\n\n constructor(\n private readonly r: Reactive,\n readonly expression: () => unknown | Promise<unknown>,\n readonly handler: (value: unknown) => void | Promise<void>,\n readonly element: Element | null\n ) {}\n\n get stopped(): boolean {\n return this._stopped;\n }\n\n /**\n * Run the effect for the first time: collect dependencies, subscribe, call\n * handler with the initial value. Errors in expression evaluation are caught\n * and silently swallowed (matches upstream's tolerance).\n */\n async initialize(): Promise<void> {\n if (this._stopped) return;\n try {\n const value = await this.r._runWithEffect(this, this.expression);\n this.lastValue = value;\n if (value !== undefined && value !== null) {\n await this.handler(value);\n }\n } catch (err) {\n // Swallow — expression evaluation failed during initial read. Surface\n // via debug log so users diagnosing \"my effect never fires\" can see why.\n debugWarn('effect.initialize failed', err);\n }\n }\n\n /**\n * Re-run the effect after a notify. Cycle-detects (halts at 101 consecutive\n * triggers). If the new value is Object.is-equal to the last, the handler\n * is skipped. If the owning element has disconnected, the effect stops\n * itself and returns.\n */\n async run(): Promise<void> {\n if (this._stopped) return;\n if (this.element && !this.element.isConnected) {\n this.stop();\n return;\n }\n this._consecutiveTriggers++;\n if (this._consecutiveTriggers > 100) {\n if (typeof console !== 'undefined') {\n console.error(\n '[@hyperfixi/reactivity] Effect halted: > 100 consecutive triggers (cycle detected).'\n );\n }\n this.stop();\n return;\n }\n try {\n const value = await this.r._runWithEffect(this, this.expression);\n if (Object.is(value, this.lastValue)) return;\n this.lastValue = value;\n await this.handler(value);\n } catch (err) {\n // Swallow — expression/handler errors don't break the microtask flush.\n debugWarn('effect.run failed', err);\n }\n }\n\n resetTriggerCount(): void {\n this._consecutiveTriggers = 0;\n }\n\n /**\n * Stop the effect and remove it from all dependency subscriptions. Safe to\n * call multiple times.\n */\n stop(): void {\n if (this._stopped) return;\n this._stopped = true;\n this.r._unsubscribeEffect(this);\n this.dependencies.clear();\n }\n}\n\ninterface ElementState {\n symbolSubs: Map<string, Set<Effect>>;\n caretVars: Map<string, unknown>;\n domHandlers: Map<string, DomHandler>;\n effects: Set<Effect>;\n}\n\ninterface DomHandler {\n subs: Set<Effect>;\n detach: () => void;\n}\n\nexport class Reactive {\n private currentEffect: Effect | null = null;\n private pending = new Set<Effect>();\n private scheduled = false;\n\n private globalSubs = new Map<string, Set<Effect>>();\n private elementState = new WeakMap<Element, ElementState>();\n\n private getElementState(el: Element): ElementState {\n let s = this.elementState.get(el);\n if (!s) {\n s = {\n symbolSubs: new Map(),\n caretVars: new Map(),\n domHandlers: new Map(),\n effects: new Set(),\n };\n this.elementState.set(el, s);\n }\n return s;\n }\n\n /**\n * Internal helper invoked by Effect — installs `this` as the current effect,\n * runs the expression, then restores the previous current-effect pointer.\n * Track* methods (called from read-paths) consult `currentEffect` to know\n * which effect to subscribe.\n */\n async _runWithEffect(e: Effect, fn: () => unknown | Promise<unknown>): Promise<unknown> {\n const prev = this.currentEffect;\n this.currentEffect = e;\n // Unsubscribe from previous deps before re-running. The expression will\n // re-record whatever it actually reads this time, avoiding stale subs.\n this._unsubscribeEffect(e);\n e.dependencies.clear();\n try {\n return await fn();\n } finally {\n this.currentEffect = prev;\n }\n }\n\n // ---------------------------------------------------------------------------\n // Track (read-path) — invoked from interceptors / evaluators.\n // ---------------------------------------------------------------------------\n\n trackGlobal(name: string): void {\n const e = this.currentEffect;\n if (!e) return;\n const key = globalDepKey(name);\n if (e.dependencies.has(key)) return;\n e.dependencies.set(key, { key, kind: 'global', name, element: null });\n let subs = this.globalSubs.get(name);\n if (!subs) {\n subs = new Set();\n this.globalSubs.set(name, subs);\n }\n subs.add(e);\n }\n\n trackElement(el: Element, name: string): void {\n const e = this.currentEffect;\n if (!e) return;\n const key = elementDepKey(el, name);\n if (e.dependencies.has(key)) return;\n e.dependencies.set(key, { key, kind: 'element', name, element: el });\n const state = this.getElementState(el);\n let subs = state.symbolSubs.get(name);\n if (!subs) {\n subs = new Set();\n state.symbolSubs.set(name, subs);\n }\n subs.add(e);\n state.effects.add(e);\n }\n\n trackDomProperty(el: Element, prop: string): void {\n const e = this.currentEffect;\n if (!e) return;\n const key = domDepKey(el, prop);\n if (e.dependencies.has(key)) return;\n e.dependencies.set(key, { key, kind: 'dom', name: prop, element: el });\n const state = this.getElementState(el);\n let handler = state.domHandlers.get(prop);\n if (!handler) {\n const subs = new Set<Effect>();\n const listener = (): void => {\n for (const effect of subs) this.schedule(effect);\n };\n // Use both input and change to cover radios/selects which don't fire input.\n el.addEventListener('input', listener);\n el.addEventListener('change', listener);\n handler = {\n subs,\n detach: () => {\n el.removeEventListener('input', listener);\n el.removeEventListener('change', listener);\n },\n };\n state.domHandlers.set(prop, handler);\n }\n handler.subs.add(e);\n state.effects.add(e);\n }\n\n // ---------------------------------------------------------------------------\n // Notify (write-path) — schedules dependent effects for re-run.\n // ---------------------------------------------------------------------------\n\n notifyGlobal(name: string): void {\n const subs = this.globalSubs.get(name);\n if (!subs) return;\n for (const e of subs) this.schedule(e);\n }\n\n notifyElement(el: Element, name: string): void {\n const state = this.elementState.get(el);\n if (!state) return;\n const subs = state.symbolSubs.get(name);\n if (!subs) return;\n for (const e of subs) this.schedule(e);\n }\n\n // ---------------------------------------------------------------------------\n // Effect lifecycle.\n // ---------------------------------------------------------------------------\n\n /**\n * Create + initialize an effect. Returns a disposer that stops the effect.\n * Callers are expected to register the disposer with the core runtime's\n * cleanup registry so it fires on element removal.\n */\n createEffect(\n expression: () => unknown | Promise<unknown>,\n handler: (value: unknown) => void | Promise<void>,\n owner: Element | null\n ): () => void {\n const e = new Effect(this, expression, handler, owner);\n if (owner) this.getElementState(owner).effects.add(e);\n // Fire initialize asynchronously so the caller can set up cleanup registration\n // before the first run touches the DOM.\n queueMicrotask(() => {\n void e.initialize();\n });\n return () => e.stop();\n }\n\n /**\n * Stop all effects owned by an element. Called by the reactivity plugin's\n * cleanup hook registered via `runtime.getCleanupRegistry()`.\n */\n stopElementEffects(el: Element): void {\n const state = this.elementState.get(el);\n if (!state) return;\n for (const e of Array.from(state.effects)) e.stop();\n state.effects.clear();\n }\n\n /**\n * Internal: remove an effect's entries from all subscriber sets. Called by\n * `Effect.stop()`.\n */\n _unsubscribeEffect(e: Effect): void {\n for (const dep of e.dependencies.values()) {\n if (dep.kind === 'global') {\n const subs = this.globalSubs.get(dep.name);\n subs?.delete(e);\n } else if (dep.kind === 'element' && dep.element) {\n const state = this.elementState.get(dep.element);\n const subs = state?.symbolSubs.get(dep.name);\n subs?.delete(e);\n state?.effects.delete(e);\n } else if (dep.kind === 'dom' && dep.element) {\n const state = this.elementState.get(dep.element);\n const handler = state?.domHandlers.get(dep.name);\n handler?.subs.delete(e);\n if (handler && handler.subs.size === 0) {\n handler.detach();\n state?.domHandlers.delete(dep.name);\n }\n state?.effects.delete(e);\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Caret-variable storage — `^name` reads/writes.\n // ---------------------------------------------------------------------------\n\n /**\n * Whether `el` is a `dom-scope=\"isolated\"` boundary. Walks of `^var`\n * lookups stop at boundary elements that don't define the var, so nested\n * components don't accidentally read or write each other's state.\n */\n private isIsolationBoundary(el: Element): boolean {\n return typeof el.getAttribute === 'function' && el.getAttribute('dom-scope') === 'isolated';\n }\n\n /**\n * Walk up the DOM tree from `lookupRoot`, returning the first element whose\n * state has `name` defined. Stops at any `dom-scope=\"isolated\"` boundary\n * that doesn't itself define the var. Returns `null` if no owner is found.\n */\n private findCaretOwner(lookupRoot: Element, name: string): Element | null {\n let el: Element | null = lookupRoot;\n while (el) {\n const state = this.elementState.get(el);\n if (state && state.caretVars.has(name)) return el;\n if (this.isIsolationBoundary(el)) return null;\n el = el.parentElement;\n }\n return null;\n }\n\n /**\n * Read a DOM-scoped variable. Walks up from `lookupRoot`, tracking each\n * element visited as an `element` dep (so writes at any ancestor notify\n * dependent effects). Stops at any `dom-scope=\"isolated\"` boundary that\n * doesn't itself define the var.\n */\n readCaret(lookupRoot: Element, name: string): unknown {\n let el: Element | null = lookupRoot;\n while (el) {\n this.trackElement(el, name);\n const state = this.elementState.get(el);\n if (state && state.caretVars.has(name)) {\n return state.caretVars.get(name);\n }\n if (this.isIsolationBoundary(el)) return undefined;\n el = el.parentElement;\n }\n return undefined;\n }\n\n /**\n * Write a DOM-scoped variable. If `target` is provided, writes there\n * directly; otherwise walks up from `lookupRoot` to find the existing owner,\n * falling back to `lookupRoot` itself if no owner exists.\n */\n writeCaret(lookupRoot: Element, name: string, value: unknown, target?: Element): void {\n const owner = target ?? this.findCaretOwner(lookupRoot, name) ?? lookupRoot;\n const state = this.getElementState(owner);\n state.caretVars.set(name, value);\n this.notifyElement(owner, name);\n }\n\n // ---------------------------------------------------------------------------\n // Scheduler — microtask-batched flush.\n // ---------------------------------------------------------------------------\n\n private schedule(e: Effect): void {\n if (e.stopped) return;\n this.pending.add(e);\n if (this.scheduled) return;\n this.scheduled = true;\n queueMicrotask(() => void this.flush());\n }\n\n private async flush(): Promise<void> {\n try {\n while (this.pending.size > 0) {\n const batch = Array.from(this.pending);\n this.pending.clear();\n for (const e of batch) {\n if (e.stopped) continue;\n await e.run();\n // If the effect's run did not synchronously re-schedule itself, its\n // trigger count is reset. Self-rescheduling (a real cycle) keeps the\n // counter climbing toward the 100 cap. Long-lived effects that fire\n // sporadically (e.g. user-input bindings) stay alive forever.\n if (!this.pending.has(e)) e.resetTriggerCount();\n }\n }\n } finally {\n this.scheduled = false;\n }\n }\n}\n\n// Module singleton. One reactive graph per process; mirrors upstream's\n// `runtime.reactivity` pattern.\nexport const reactive = new Reactive();\n","/**\n * `^name` — DOM-scoped inherited variable.\n *\n * Upstream syntax:\n * ^counter → read from nearest ancestor that has `counter` set\n * ^counter on #target → read from (or near) #target\n * set ^counter to 42 → write to owner (or lookupRoot if not yet defined)\n *\n * Parse side: register `^` as a Pratt prefix operator. The handler consumes\n * the identifier token and an optional `on <target>` clause, emitting a\n * `caretVar` AST node.\n *\n * Eval side: `caretVar` node evaluator calls `reactive.readCaret(anchor,\n * name)` which walks the DOM tree for the owner and records deps as it goes.\n */\n\nimport type { ASTNode, ExecutionContext } from './types';\nimport { reactive } from './signals';\n\nexport interface CaretVarNode extends ASTNode {\n type: 'caretVar';\n name: string;\n onTarget: ASTNode | null;\n}\n\ninterface CaretVarRuntime {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n}\n\n/**\n * Coerce a runtime-evaluated `on <target>` result to a single Element.\n * Selector expressions resolve to an array of matched elements; bare\n * `me`/`it`/`you`/identifier references resolve to single Elements. Take the\n * first element of an array, or the value itself if it's already an Element.\n */\nfunction coerceToElement(value: unknown): Element | null {\n if (value instanceof Element) return value;\n if (Array.isArray(value) && value[0] instanceof Element) return value[0];\n return null;\n}\n\n/**\n * Pratt prefix handler for `^`. Consumes the following identifier token and\n * an optional `on <expr>` clause.\n */\nexport function parseCaretPrefix(token: unknown, ctx: unknown): ASTNode {\n // `ctx` is hyperfixi's PrattContext: { peek, advance, parseExpr, isStopToken, atEnd }.\n const pctx = ctx as {\n peek(): { value?: string; kind?: string } | undefined;\n advance(): { value: string; kind?: string };\n parseExpr(minBp: number): ASTNode;\n };\n const ident = pctx.advance();\n if (!ident || !ident.value) {\n throw new Error(\"Expected identifier after '^'\");\n }\n let onTarget: ASTNode | null = null;\n const next = pctx.peek();\n if (next && next.value === 'on') {\n pctx.advance(); // consume 'on'\n // Binding power 86 — higher than standard comparisons so `^x on me` doesn't\n // over-consume into surrounding expressions.\n onTarget = pctx.parseExpr(86);\n }\n const startTok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'caretVar',\n name: ident.value,\n onTarget,\n start: startTok?.start ?? 0,\n end: startTok?.end ?? 0,\n line: startTok?.line,\n column: startTok?.column,\n } as CaretVarNode;\n}\n\n/**\n * Build a node evaluator for `caretVar` bound to a specific runtime. The\n * evaluator walks up from the resolved anchor element, tracking every element\n * visited so writes at any ancestor notify dependent effects.\n *\n * Capturing `runtime` via a factory closure (matching live/when/bind) keeps\n * the evaluator independent of any module-scope state.\n */\nexport function makeEvaluateCaretVar(\n runtime: CaretVarRuntime\n): (node: ASTNode, ctx: unknown) => Promise<unknown> {\n return async function evaluateCaretVar(node, ctx) {\n const n = node as CaretVarNode;\n const context = ctx as ExecutionContext;\n let anchor: Element | null = (context.me as Element | null) ?? null;\n\n if (n.onTarget) {\n const resolved = await runtime.execute(n.onTarget, context);\n const el = coerceToElement(resolved);\n if (el) anchor = el;\n }\n\n if (!anchor) return undefined;\n return reactive.readCaret(anchor, n.name);\n };\n}\n\n/**\n * Build a node writer for `caretVar` bound to a specific runtime. Used by the\n * core `set` command via `parserExtensions.registerNodeWriter`.\n */\nexport function makeWriteCaretVar(\n runtime: CaretVarRuntime\n): (node: ASTNode, value: unknown, ctx: unknown) => Promise<void> {\n return async function writeCaretVar(node, value, ctx) {\n const n = node as CaretVarNode;\n const context = ctx as ExecutionContext;\n const anchor: Element | null = (context.me as Element | null) ?? null;\n if (!anchor) return;\n\n let target: Element | undefined;\n if (n.onTarget) {\n const resolved = await runtime.execute(n.onTarget, context);\n const el = coerceToElement(resolved);\n if (el) target = el;\n }\n reactive.writeCaret(anchor, n.name, value, target);\n };\n}\n","/**\n * `live ... end` — reactive block. Body re-runs whenever any dependency read\n * during its execution changes.\n *\n * Upstream syntax:\n * live [commandList] end\n *\n * Each command in the body is re-executed as a single effect. The entire\n * body shares one effect instance; its dependency set is the union of every\n * read performed during body execution.\n */\n\nimport type { ASTNode, ExecutionContext, FeatureParserCtx } from './types';\nimport { reactive } from './signals';\n\nexport interface LiveFeatureNode extends ASTNode {\n type: 'liveFeature';\n body: ASTNode[];\n}\n\n/**\n * Parse `live ... end`. The `live` keyword has already been consumed by the\n * parser dispatcher; we parse the body and expect a trailing `end`.\n */\nexport function parseLiveFeature(ctx: unknown, token: unknown): ASTNode {\n const pctx = ctx as FeatureParserCtx;\n const body = pctx.parseCommandListUntilEnd();\n // parseCommandListUntilEnd stops when it sees `end` (but doesn't consume it).\n if (!pctx.isAtEnd() && pctx.check('end')) pctx.match('end');\n const tok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'liveFeature',\n body,\n start: tok?.start ?? 0,\n end: pctx.getPosition().end,\n line: tok?.line,\n column: tok?.column,\n } as LiveFeatureNode;\n}\n\n/**\n * Create an evaluator bound to a runtime reference. The plugin captures\n * `runtime` at install time and passes it in so effect re-runs can dispatch\n * the body commands without going through module-scope state.\n */\nexport function makeEvaluateLiveFeature(runtime: {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n}): (node: ASTNode, ctx: unknown) => unknown | Promise<unknown> {\n return async function evaluateLiveFeature(node, ctx) {\n const context = ctx as ExecutionContext;\n const owner = (context.me as Element) ?? document.body;\n const n = node as LiveFeatureNode;\n\n const stop = reactive.createEffect(\n async () => {\n for (const cmd of n.body) {\n await runtime.execute(cmd, context);\n }\n },\n () => {\n /* no-op — side effects happened inside the expression */\n },\n owner\n );\n context.registerCleanup?.(owner, stop, 'live-effect');\n return undefined;\n };\n}\n","/**\n * `when <expr> [or <expr>]* changes [commandList] end` — observer feature.\n *\n * Runs the body when any watched expression's value changes (Object.is\n * semantics). One effect is created per watched expression so writes to a\n * given dep only re-run that watcher.\n */\n\nimport type { ASTNode, ExecutionContext, FeatureParserCtx } from './types';\nimport { reactive } from './signals';\n\nexport interface WhenFeatureNode extends ASTNode {\n type: 'whenFeature';\n watched: ASTNode[];\n body: ASTNode[];\n}\n\nexport function parseWhenFeature(ctx: unknown, token: unknown): ASTNode {\n const pctx = ctx as FeatureParserCtx;\n const watched: ASTNode[] = [pctx.parseExpression()];\n while (pctx.match('or')) {\n watched.push(pctx.parseExpression());\n }\n pctx.consume('changes', \"Expected 'changes' after when expression list\");\n const body = pctx.parseCommandListUntilEnd();\n if (!pctx.isAtEnd() && pctx.check('end')) pctx.match('end');\n const tok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'whenFeature',\n watched,\n body,\n start: tok?.start ?? 0,\n end: pctx.getPosition().end,\n line: tok?.line,\n column: tok?.column,\n } as WhenFeatureNode;\n}\n\nexport function makeEvaluateWhenFeature(runtime: {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n evaluateExpressionWithResult?: (\n node: ASTNode,\n ctx: ExecutionContext\n ) => Promise<{ value: unknown }>;\n}): (node: ASTNode, ctx: unknown) => unknown | Promise<unknown> {\n return async function evaluateWhenFeature(node, ctx) {\n const context = ctx as ExecutionContext;\n const owner = (context.me as Element) ?? document.body;\n const n = node as WhenFeatureNode;\n\n for (const watchedExpr of n.watched) {\n const stop = reactive.createEffect(\n async () => {\n // Evaluate the watched expression as a regular expression through the\n // runtime so that trackGlobal/trackElement fire via the global-write\n // hook and caret-var reads.\n return await runtime.execute(watchedExpr, context);\n },\n async newValue => {\n // Fire the body with `it` / `result` bound to the new value.\n const subCtx: ExecutionContext = { ...context, it: newValue, result: newValue };\n for (const cmd of n.body) {\n await runtime.execute(cmd, subCtx);\n }\n },\n owner\n );\n context.registerCleanup?.(owner, stop, 'when-effect');\n }\n return undefined;\n };\n}\n","/**\n * `bind X [to|and|with] Y` — two-way binding.\n *\n * Creates two effects (registration order is load-bearing — both initialize\n * via `queueMicrotask` and run in registration order):\n * 1. DOM → var: read DOM, write var. DOM \"wins\" on init.\n * 2. var → DOM: read var, write DOM. Fires on programmatic var writes\n * after init. On its own initial run, var === DOM (Effect 1 just synced\n * them), so the write is a no-op.\n *\n * Two binding forms:\n *\n * 1. Auto-detected (DOM side is a bare element expression):\n *\n * bind $name to #input -- detects `value`\n * bind $checked to me -- detects `checked` on a checkbox\n *\n * Auto-detected property by element type:\n * - INPUT[type=checkbox|radio] → `checked`\n * - INPUT[type=number|range] → `valueAsNumber`\n * - INPUT|TEXTAREA|SELECT → `value`\n * - contenteditable=\"true\" → `textContent`\n * - Custom elements with own `value` → `value`\n *\n * 2. Explicit property (DOM side is a member or possessive expression):\n *\n * bind $color to #picker's value -- possessive (preferred — reads in any language)\n * bind $color to #picker.value -- dot (JS-style alternative)\n * bind $text to #div's textContent -- non-form properties: var→DOM only\n *\n * For form-like elements, both directions work. For non-form elements\n * (e.g., binding a div's `textContent`), only var→DOM fires — there are\n * no input/change events to drive DOM→var, so user mutations of the\n * property via devtools won't propagate back.\n */\n\nimport type { ASTNode, ExecutionContext, FeatureParserCtx } from './types';\nimport { reactive } from './signals';\n\nexport interface BindFeatureNode extends ASTNode {\n type: 'bindFeature';\n left: ASTNode;\n right: ASTNode;\n}\n\nexport function parseBindFeature(ctx: unknown, token: unknown): ASTNode {\n const pctx = ctx as FeatureParserCtx;\n const left = pctx.parseExpression();\n // Accept any of `to` / `and` / `with` as the separator.\n if (!(pctx.match('to') || pctx.match('and') || pctx.match('with'))) {\n throw new Error(\"bind requires 'to', 'and', or 'with' between the two sides\");\n }\n const right = pctx.parseExpression();\n // Optional `end` terminator (matches upstream which allows both forms).\n if (pctx.check('end')) pctx.match('end');\n const tok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'bindFeature',\n left,\n right,\n start: tok?.start ?? 0,\n end: pctx.getPosition().end,\n line: tok?.line,\n column: tok?.column,\n } as BindFeatureNode;\n}\n\n/**\n * Auto-detect the DOM property to bind by element type. Returns null if the\n * target isn't a recognized form/editable element.\n */\nfunction detectProperty(el: Element): string | null {\n const tag = el.tagName;\n if (tag === 'INPUT') {\n const type = (el as HTMLInputElement).type;\n if (type === 'checkbox' || type === 'radio') return 'checked';\n if (type === 'number' || type === 'range') return 'valueAsNumber';\n return 'value';\n }\n if (tag === 'TEXTAREA' || tag === 'SELECT') return 'value';\n const ce = (el as HTMLElement).contentEditable;\n if (ce === 'true') return 'textContent';\n // Custom elements with own `value` prop.\n if ('value' in el) return 'value';\n return null;\n}\n\n/**\n * If `node` is a `memberExpression` or `possessiveExpression` with a static\n * identifier property (`#el.value` or `#el's value`), return the inner element\n * expression and the property name. Returns null for anything else.\n *\n * Computed member access (`#el[prop]`) is intentionally rejected — we'd have to\n * evaluate the index dynamically and the binding direction would be unclear.\n * Chained property access (`#el.dataset.value`) is also not unpacked — we only\n * peel one level. Multi-level support is a future arc.\n */\nfunction unwrapExplicitProperty(node: ASTNode): { element: ASTNode; propertyName: string } | null {\n if (!node || (node.type !== 'memberExpression' && node.type !== 'possessiveExpression')) {\n return null;\n }\n if (node.type === 'memberExpression' && node.computed === true) return null;\n const property = node.property as ASTNode | undefined;\n const object = node.object as ASTNode | undefined;\n if (!property || !object || property.type !== 'identifier') return null;\n const name = (property.name as string) ?? '';\n if (!name) return null;\n return { element: object, propertyName: name };\n}\n\n/**\n * Detect a chained property access on the bind RHS — e.g.\n * `me.style.backgroundColor` or `#el's dataset's value`.\n *\n * After `unwrapExplicitProperty` peels the outermost member, the returned\n * `element` is the object of that member. If that object is itself a\n * member/possessive expression, we have a multi-level chain that v1 of\n * bind doesn't support. Used only for the error path; the parsed AST is\n * left intact.\n */\nfunction isChainedMember(node: ASTNode | undefined): boolean {\n if (!node) return false;\n return node.type === 'memberExpression' || node.type === 'possessiveExpression';\n}\n\n/**\n * Whether the input/change listener installed by `trackDomProperty` would\n * actually fire for this element. Used to decide whether to wire up the\n * DOM→var direction when an explicit property is given.\n */\nfunction isFormLikeElement(el: Element): boolean {\n const tag = el.tagName;\n if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;\n if ((el as HTMLElement).contentEditable === 'true') return true;\n return false;\n}\n\n/**\n * Whether debug logging is enabled. Mirrors signals.ts — keeps a single\n * convention for the package.\n */\nfunction debugEnabled(): boolean {\n try {\n return typeof localStorage !== 'undefined' && localStorage.getItem('hyperfixi:debug') !== null;\n } catch {\n return false;\n }\n}\n\n/**\n * Create the bind evaluator. Because `bind` has unusual parse shape (AST\n * nodes for left/right that may be identifiers, `$name` references, or DOM\n * element lookups), we rely on the runtime to evaluate them.\n */\nexport function makeEvaluateBindFeature(runtime: {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n}): (node: ASTNode, ctx: unknown) => unknown | Promise<unknown> {\n return async function evaluateBindFeature(node, ctx) {\n const context = ctx as ExecutionContext;\n const owner = (context.me as Element) ?? document.body;\n const n = node as BindFeatureNode;\n\n // Resolve sides. One is a var reference (read/write a symbol), the other\n // a DOM target (read/write a property). Determine direction from node shape.\n const leftIsVar = isVarRef(n.left);\n const rightIsVar = isVarRef(n.right);\n\n // We need a DOM-side descriptor (element + property) and a var-side name.\n let varSide: { name: string; isGlobal: boolean } | null = null;\n let domSide: { exprNode: ASTNode } | null = null;\n\n if (leftIsVar && !rightIsVar) {\n varSide = varRefInfo(n.left);\n domSide = { exprNode: n.right };\n } else if (rightIsVar && !leftIsVar) {\n varSide = varRefInfo(n.right);\n domSide = { exprNode: n.left };\n } else if (leftIsVar && rightIsVar) {\n // var-to-var binding not supported in v1 (no DOM side).\n throw new Error('bind: cannot bind two symbols together (need a DOM side)');\n } else {\n throw new Error('bind: could not identify a symbol side');\n }\n\n // Unwrap explicit property syntax: `#el.value` or `#el's value` becomes\n // (element-expression, propertyName). Otherwise, evaluate the whole side\n // and rely on auto-detection.\n const explicit = unwrapExplicitProperty(domSide.exprNode);\n // Multi-level property access (`#el.style.background`, `me's dataset's id`)\n // is not supported in v1. Surface that diagnosis up front; otherwise the\n // user gets the generic \"did not resolve to an element\" message and no\n // hint that the chain is the problem.\n if (explicit && isChainedMember(explicit.element)) {\n throw new Error(\n 'bind: multi-level property access (e.g., `#el.a.b`) is not supported in v1 — restructure to a single property write or pass the element directly for auto-detection (e.g., `bind $x to #el`).'\n );\n }\n const elementExpr = explicit ? explicit.element : domSide.exprNode;\n const domValue = await runtime.execute(elementExpr, context);\n if (!(domValue instanceof Element)) {\n const valueType =\n domValue === null ? 'null' : domValue === undefined ? 'undefined' : typeof domValue;\n const snippet =\n domValue !== null && domValue !== undefined ? ` \"${String(domValue).slice(0, 40)}\"` : '';\n const suggestion = explicit\n ? ''\n : \" If you meant to write to a property, use the explicit form: `<selector>'s <property>`.\";\n throw new Error(\n `bind: right-hand side did not resolve to an element (got ${valueType}${snippet}).${suggestion}`\n );\n }\n const el = domValue;\n // Explicit property bypasses auto-detect; the user takes responsibility for\n // picking something readable from the element. For DOM→var to work without\n // explicit property, fall back to auto-detect.\n const prop = explicit ? explicit.propertyName : detectProperty(el);\n if (!prop) {\n throw new Error(\n `bind: could not auto-detect property for <${el.tagName.toLowerCase()}> — use explicit \\`<expr>'s <property>\\` form`\n );\n }\n // For explicit-property mode on non-form elements, DOM→var can't sync via\n // input/change events. Skip the listener install; only var→DOM runs.\n const installDomToVar = !explicit || isFormLikeElement(el);\n if (explicit && !installDomToVar && debugEnabled() && typeof console !== 'undefined') {\n console.warn(\n `[@hyperfixi/reactivity] bind: DOM→var skipped for <${el.tagName.toLowerCase()}>.${prop} — no input/change event source.`\n );\n }\n\n // Initial sync: DOM → var.\n const readDom = (): unknown => {\n if (prop === 'valueAsNumber') return (el as HTMLInputElement).valueAsNumber;\n if (prop === 'checked') return (el as HTMLInputElement).checked;\n if (prop === 'textContent') return el.textContent ?? '';\n return (el as any)[prop];\n };\n const writeDom = (value: unknown): void => {\n if (prop === 'valueAsNumber') {\n const n = Number(value);\n (el as HTMLInputElement).valueAsNumber = Number.isNaN(n) ? (null as never) : n;\n } else if (prop === 'checked') {\n (el as HTMLInputElement).checked = Boolean(value);\n } else if (prop === 'textContent') {\n el.textContent = value == null ? '' : String(value);\n } else {\n (el as any)[prop] = value;\n }\n };\n const readVar = (): unknown => {\n if (varSide!.isGlobal) return context.globals?.get(varSide!.name);\n return context.locals?.get(varSide!.name);\n };\n const writeVar = (value: unknown): void => {\n if (varSide!.isGlobal) {\n context.globals?.set(varSide!.name, value);\n // Bypass the global-write hook (we're touching the Map directly), so\n // notify the reactive graph manually for the var→DOM effect.\n reactive.notifyGlobal(varSide!.name);\n } else {\n context.locals?.set(varSide!.name, value);\n // Same rationale for locals — direct Map write skips the localWriteHook,\n // so we notify the element-scoped subscription set directly.\n reactive.notifyElement(owner, varSide!.name);\n }\n };\n\n // Effect 1: DOM → var (fires on user input). Skipped for explicit-property\n // bindings on non-form elements — no input/change events would drive it.\n let stopDomToVar: (() => void) | null = null;\n if (installDomToVar) {\n stopDomToVar = reactive.createEffect(\n () => {\n reactive.trackDomProperty(el, prop);\n return readDom();\n },\n newValue => {\n writeVar(newValue);\n },\n owner\n );\n }\n\n // Effect 2: var → DOM (fires on programmatic var writes — for globals\n // via the core's globalWriteHook, for locals via the localWriteHook the\n // reactivity plugin registers).\n const stopVarToDom = reactive.createEffect(\n () => {\n if (varSide!.isGlobal) reactive.trackGlobal(varSide!.name);\n else reactive.trackElement(owner, varSide!.name);\n return readVar();\n },\n newValue => {\n if (newValue === undefined) return;\n writeDom(newValue);\n },\n owner\n );\n\n if (stopDomToVar) context.registerCleanup?.(owner, stopDomToVar, 'bind-dom-to-var');\n context.registerCleanup?.(owner, stopVarToDom, 'bind-var-to-dom');\n return undefined;\n };\n}\n\n/**\n * Is this AST node a var reference we can bind to?\n *\n * The hyperfixi parser emits `identifier` nodes for both globals and locals,\n * but with different shapes:\n * - `$foo` → `{ type: 'identifier', name: '$foo' }` (no scope field)\n * - `:foo` → `{ type: 'identifier', name: 'foo', scope: 'local' }`\n * - `::foo` → `{ type: 'identifier', name: 'foo', scope: 'global' }`\n *\n * We accept all three. The legacy `$`-prefix sniff stays as a fallback because\n * `parseExpression` doesn't always set `scope`.\n */\nfunction isVarRef(node: ASTNode): boolean {\n if (!node) return false;\n if (node.type !== 'identifier') return false;\n const scope = node.scope as string | undefined;\n if (scope === 'local' || scope === 'global') return true;\n const name = (node.name as string) ?? '';\n return name.startsWith('$') || name.startsWith(':');\n}\n\nfunction varRefInfo(node: ASTNode): { name: string; isGlobal: boolean } {\n const rawName = (node.name as string) ?? '';\n const scope = node.scope as string | undefined;\n // Prefer the parser-emitted scope marker. Fall back to prefix sniffing for\n // shapes where scope isn't set (e.g. `$foo` arriving as bare identifier\n // with name '$foo').\n let isGlobal: boolean;\n let name: string;\n if (scope === 'global') {\n isGlobal = true;\n name = rawName;\n } else if (scope === 'local') {\n isGlobal = false;\n name = rawName;\n } else if (rawName.startsWith('$')) {\n isGlobal = true;\n name = rawName.slice(1);\n } else if (rawName.startsWith(':')) {\n isGlobal = false;\n name = rawName.slice(1);\n } else {\n isGlobal = false;\n name = rawName;\n }\n if (!name) {\n throw new Error('bind: variable reference has empty name');\n }\n return { name, isGlobal };\n}\n","/**\n * @hyperfixi/reactivity — signal-based reactive features for hyperfixi.\n *\n * Adds four constructs from upstream _hyperscript 0.9.90:\n *\n * live [commandList] end reactive block — body re-runs\n * when tracked reads change.\n *\n * when <expr> [or <expr>]* changes observer — body runs when any\n * [commandList] end watched expression changes.\n *\n * bind <var> to <element> two-way DOM ⇄ var binding.\n *\n * ^name [on <target>] DOM-scoped inherited variable\n * (read + write with `^`).\n *\n * Install:\n *\n * ```ts\n * import { createRuntime, installPlugin } from '@hyperfixi/core';\n * import { reactivityPlugin } from '@hyperfixi/reactivity';\n *\n * const runtime = createRuntime();\n * installPlugin(runtime, reactivityPlugin);\n * ```\n */\n\nimport type { HyperfixiPlugin, HyperfixiPluginContext } from '@hyperfixi/core';\nimport { reactive } from './signals';\nimport { parseCaretPrefix, makeEvaluateCaretVar, makeWriteCaretVar } from './caret-var';\nimport { parseLiveFeature, makeEvaluateLiveFeature } from './live';\nimport { parseWhenFeature, makeEvaluateWhenFeature } from './when';\nimport { parseBindFeature, makeEvaluateBindFeature } from './bind';\n\nexport { reactive } from './signals';\nexport type { CaretVarNode } from './caret-var';\nexport type { LiveFeatureNode } from './live';\nexport type { WhenFeatureNode } from './when';\nexport type { BindFeatureNode } from './bind';\n\n/**\n * The plugin object. Install once at app startup; re-installing is idempotent\n * (guarded via a `parserExtensions.hasFeature('live')` check).\n *\n * Registers:\n * - Features: `live`, `when`, `bind` (top-level features with `end` bodies)\n * - Prefix op: `^` (primary expression for DOM-scoped vars)\n * - Node evaluators: `liveFeature`, `whenFeature`, `bindFeature`, `caretVar`\n * - A node writer for `caretVar` so `set ^X to Y` flows through `reactive.writeCaret`\n * - Global read/write hooks so `$name` reads track and writes notify\n *\n * Effect cleanup: each effect-creating evaluator calls\n * `context.registerCleanup(owner, stop, ...)` so the core runtime tears effects\n * down when their owning element is cleaned up. There is no separate plugin-level\n * cleanup hook; `reactive.stopElementEffects(el)` is exposed for explicit teardown\n * by tests and consumers that manage element lifecycle outside the runtime.\n */\nexport const reactivityPlugin: HyperfixiPlugin & { version: string } = {\n name: '@hyperfixi/reactivity',\n version: '2.3.1',\n install(ctx: HyperfixiPluginContext) {\n const { parserExtensions, runtime } = ctx;\n\n // Idempotency: the parser-extension registry is process-singleton, so\n // re-installing into a fresh runtime would otherwise stack additional\n // global read/write hooks on every call. `snapshot()`/`restore()` clears\n // the feature registry — when tests roll back the registry, this guard\n // re-enables a fresh install.\n if (parserExtensions.hasFeature('live')) return;\n\n // Parser hooks — three block features plus a primary-expression caret.\n parserExtensions.registerFeature('live', parseLiveFeature as never);\n parserExtensions.registerFeature('when', parseWhenFeature as never);\n parserExtensions.registerFeature('bind', parseBindFeature as never);\n parserExtensions.registerPrefixOperator('^', 85, parseCaretPrefix as never);\n\n // Runtime evaluators. Features capture `runtime` so effect re-runs can\n // dispatch body commands without going through module-scope state.\n parserExtensions.registerNodeEvaluator(\n 'liveFeature',\n makeEvaluateLiveFeature(runtime as never) as never\n );\n parserExtensions.registerNodeEvaluator(\n 'whenFeature',\n makeEvaluateWhenFeature(runtime as never) as never\n );\n parserExtensions.registerNodeEvaluator(\n 'bindFeature',\n makeEvaluateBindFeature(runtime as never) as never\n );\n parserExtensions.registerNodeEvaluator(\n 'caretVar',\n makeEvaluateCaretVar(runtime as never) as never\n );\n\n // Caret-var write: lets the core `set` command dispatch `set ^X to Y`\n // through `reactive.writeCaret`. Resolves `on <target>` via the captured\n // runtime — no global-scope indirection.\n parserExtensions.registerNodeWriter('caretVar', makeWriteCaretVar(runtime as never) as never);\n\n // Global-write hook: notify the reactive graph whenever `$name` is set.\n // The returned disposer is intentionally discarded — the install-time\n // idempotency guard above is the sole gate against double-registration.\n parserExtensions.registerGlobalWriteHook((name: string, _value: unknown, _context: unknown) => {\n reactive.notifyGlobal(name);\n });\n\n // Global-read hook: track the read against the current effect (if any)\n // so effects re-run when the global changes.\n parserExtensions.registerGlobalReadHook((name: string, _context: unknown) => {\n reactive.trackGlobal(name);\n });\n\n // Local hooks — analogous to globals, but keyed by `context.me` so each\n // element holds independent state. A `set :foo to ...` running in a\n // handler with `me=button1` notifies effects subscribed to (button1, 'foo');\n // a `set :foo` in a different `me` won't reach them. This matches how\n // locals already work — they're never cross-context — and lets two\n // components hold independent `:foo` state without interference.\n parserExtensions.registerLocalWriteHook((name: string, _value: unknown, context) => {\n const owner = (context as { me?: Element | null }).me ?? null;\n if (owner) reactive.notifyElement(owner, name);\n });\n\n parserExtensions.registerLocalReadHook((name: string, context) => {\n const owner = (context as { me?: Element | null }).me ?? null;\n if (owner) reactive.trackElement(owner, name);\n });\n },\n};\n\nexport default reactivityPlugin;\n"],"mappings":";AA0BA,SAAS,eAAwB;AAC/B,MAAI;AACF,WAAO,OAAO,iBAAiB,eAAe,aAAa,QAAQ,iBAAiB,MAAM;AAAA,EAC5F,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,UAAU,SAAiB,KAAoB;AACtD,MAAI,CAAC,aAAa,EAAG;AACrB,MAAI,OAAO,YAAY,YAAa;AACpC,UAAQ,KAAK,2BAA2B,OAAO,IAAI,GAAG;AACxD;AASA,IAAM,eAAe,CAAC,SAAyB,UAAU,IAAI;AAC7D,IAAM,gBAAgB,CAAC,IAAa,SAAyB,WAAW,cAAc,EAAE,CAAC,IAAI,IAAI;AACjG,IAAM,YAAY,CAAC,IAAa,SAAyB,OAAO,cAAc,EAAE,CAAC,IAAI,IAAI;AAKzF,IAAM,eAAe,oBAAI,QAAyB;AAClD,IAAI,aAAa;AACjB,SAAS,cAAc,IAAqB;AAC1C,QAAM,WAAW,aAAa,IAAI,EAAE;AACpC,MAAI,aAAa,OAAW,QAAO;AACnC,QAAM,KAAK,EAAE;AACb,eAAa,IAAI,IAAI,EAAE;AACvB,SAAO;AACT;AAEO,IAAM,SAAN,MAAa;AAAA,EAMlB,YACmB,GACR,YACA,SACA,SACT;AAJiB;AACR;AACA;AACA;AAAA,EACR;AAAA,EAVM,eAAe,oBAAI,IAAiB;AAAA,EACrC,YAAqB;AAAA,EACrB,WAAW;AAAA,EACX,uBAAuB;AAAA,EAS/B,IAAI,UAAmB;AACrB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,aAA4B;AAChC,QAAI,KAAK,SAAU;AACnB,QAAI;AACF,YAAM,QAAQ,MAAM,KAAK,EAAE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A,MACA,wBAAwB,OAAgB;AAAA,IAC1C;AACA,qBAAiB;AAAA,MACf;AAAA,MACA,qBAAqB,OAAgB;AAAA,IACvC;AAKA,qBAAiB,mBAAmB,YAAY,kBAAkB,OAAgB,CAAU;AAK5F,qBAAiB,wBAAwB,CAAC,MAAc,QAAiB,aAAsB;AAC7F,eAAS,aAAa,IAAI;AAAA,IAC5B,CAAC;AAID,qBAAiB,uBAAuB,CAAC,MAAc,aAAsB;AAC3E,eAAS,YAAY,IAAI;AAAA,IAC3B,CAAC;AAQD,qBAAiB,uBAAuB,CAAC,MAAc,QAAiB,YAAY;AAClF,YAAM,QAAS,QAAoC,MAAM;AACzD,UAAI,MAAO,UAAS,cAAc,OAAO,IAAI;AAAA,IAC/C,CAAC;AAED,qBAAiB,sBAAsB,CAAC,MAAc,YAAY;AAChE,YAAM,QAAS,QAAoC,MAAM;AACzD,UAAI,MAAO,UAAS,aAAa,OAAO,IAAI;AAAA,IAC9C,CAAC;AAAA,EACH;AACF;AAEA,IAAO,gBAAQ;","names":["debugEnabled","n"]}
1
+ {"version":3,"sources":["../src/signals.ts","../src/caret-var.ts","../src/live.ts","../src/when.ts","../src/bind.ts","../src/index.ts"],"sourcesContent":["/**\n * Signal/effect reactive core.\n *\n * Models three dependency kinds for v1:\n * - `global` — `$name` variables in `context.globals`\n * - `element` — `^name` DOM-scoped variables (per-element storage)\n * - `dom` — DOM properties read via `input`/`change` listeners\n *\n * Inspired by upstream _hyperscript 0.9.91's `src/core/runtime/reactivity.js`\n * but reimplemented in TypeScript against hyperfixi's types. Batched via\n * `queueMicrotask` so synchronous writes coalesce into a single flush. Cycle\n * detection halts at >100 consecutive triggers (matching upstream).\n *\n * External packages never see `Effect` or `Reactive` directly — they hold\n * the disposer returned by `createEffect()` and call it when the owning\n * element is cleaned up.\n */\n\nexport type DepKind = 'global' | 'element' | 'dom';\n\n/**\n * Whether reactive debug logging is enabled. Mirrors the core convention:\n * `localStorage.setItem('hyperfixi:debug', '*')` enables, anything else (or no\n * `localStorage`) disables. Cheap call — no caching, since users toggle this\n * interactively in the console.\n */\nfunction debugEnabled(): boolean {\n try {\n return typeof localStorage !== 'undefined' && localStorage.getItem('hyperfixi:debug') !== null;\n } catch {\n return false;\n }\n}\n\nfunction debugWarn(message: string, err: unknown): void {\n if (!debugEnabled()) return;\n if (typeof console === 'undefined') return;\n console.warn(`[@hyperfixi/reactivity] ${message}`, err);\n}\n\nexport interface Dep {\n readonly key: string;\n readonly kind: DepKind;\n readonly name: string;\n readonly element: Element | null;\n}\n\nconst globalDepKey = (name: string): string => `global:${name}`;\nconst elementDepKey = (el: Element, name: string): string => `element:${reactiveIdFor(el)}:${name}`;\nconst domDepKey = (el: Element, prop: string): string => `dom:${reactiveIdFor(el)}:${prop}`;\n\n// WeakMap-based id assignment so we don't monkey-patch DOM nodes. Ids are\n// per-process and only used to construct stable string keys for an effect's\n// per-effect dependency dedup map.\nconst _reactiveIds = new WeakMap<Element, number>();\nlet _idCounter = 0;\nfunction reactiveIdFor(el: Element): number {\n const existing = _reactiveIds.get(el);\n if (existing !== undefined) return existing;\n const id = ++_idCounter;\n _reactiveIds.set(el, id);\n return id;\n}\n\nexport class Effect {\n readonly dependencies = new Map<string, Dep>();\n private lastValue: unknown = undefined;\n private _stopped = false;\n private _consecutiveTriggers = 0;\n\n constructor(\n private readonly r: Reactive,\n readonly expression: () => unknown | Promise<unknown>,\n readonly handler: (value: unknown) => void | Promise<void>,\n readonly element: Element | null\n ) {}\n\n get stopped(): boolean {\n return this._stopped;\n }\n\n /**\n * Run the effect for the first time: collect dependencies, subscribe, call\n * handler with the initial value. Errors in expression evaluation are caught\n * and silently swallowed (matches upstream's tolerance).\n */\n async initialize(): Promise<void> {\n if (this._stopped) return;\n try {\n const value = await this.r._runWithEffect(this, this.expression);\n this.lastValue = value;\n if (value !== undefined && value !== null) {\n await this.handler(value);\n }\n } catch (err) {\n // Swallow — expression evaluation failed during initial read. Surface\n // via debug log so users diagnosing \"my effect never fires\" can see why.\n debugWarn('effect.initialize failed', err);\n }\n }\n\n /**\n * Re-run the effect after a notify. Cycle-detects (halts at 101 consecutive\n * triggers). If the new value is Object.is-equal to the last, the handler\n * is skipped. If the owning element has disconnected, the effect stops\n * itself and returns.\n */\n async run(): Promise<void> {\n if (this._stopped) return;\n if (this.element && !this.element.isConnected) {\n this.stop();\n return;\n }\n this._consecutiveTriggers++;\n if (this._consecutiveTriggers > 100) {\n if (typeof console !== 'undefined') {\n console.error(\n '[@hyperfixi/reactivity] Effect halted: > 100 consecutive triggers (cycle detected).'\n );\n }\n this.stop();\n return;\n }\n try {\n const value = await this.r._runWithEffect(this, this.expression);\n if (Object.is(value, this.lastValue)) return;\n this.lastValue = value;\n await this.handler(value);\n } catch (err) {\n // Swallow — expression/handler errors don't break the microtask flush.\n debugWarn('effect.run failed', err);\n }\n }\n\n resetTriggerCount(): void {\n this._consecutiveTriggers = 0;\n }\n\n /**\n * Stop the effect and remove it from all dependency subscriptions. Safe to\n * call multiple times.\n */\n stop(): void {\n if (this._stopped) return;\n this._stopped = true;\n this.r._unsubscribeEffect(this);\n this.dependencies.clear();\n }\n}\n\ninterface ElementState {\n symbolSubs: Map<string, Set<Effect>>;\n caretVars: Map<string, unknown>;\n domHandlers: Map<string, DomHandler>;\n effects: Set<Effect>;\n}\n\ninterface DomHandler {\n subs: Set<Effect>;\n detach: () => void;\n}\n\nexport class Reactive {\n private currentEffect: Effect | null = null;\n private pending = new Set<Effect>();\n private scheduled = false;\n\n private globalSubs = new Map<string, Set<Effect>>();\n private elementState = new WeakMap<Element, ElementState>();\n\n private getElementState(el: Element): ElementState {\n let s = this.elementState.get(el);\n if (!s) {\n s = {\n symbolSubs: new Map(),\n caretVars: new Map(),\n domHandlers: new Map(),\n effects: new Set(),\n };\n this.elementState.set(el, s);\n }\n return s;\n }\n\n /**\n * Internal helper invoked by Effect — installs `this` as the current effect,\n * runs the expression, then restores the previous current-effect pointer.\n * Track* methods (called from read-paths) consult `currentEffect` to know\n * which effect to subscribe.\n */\n async _runWithEffect(e: Effect, fn: () => unknown | Promise<unknown>): Promise<unknown> {\n const prev = this.currentEffect;\n this.currentEffect = e;\n // Unsubscribe from previous deps before re-running. The expression will\n // re-record whatever it actually reads this time, avoiding stale subs.\n this._unsubscribeEffect(e);\n e.dependencies.clear();\n try {\n return await fn();\n } finally {\n this.currentEffect = prev;\n }\n }\n\n // ---------------------------------------------------------------------------\n // Track (read-path) — invoked from interceptors / evaluators.\n // ---------------------------------------------------------------------------\n\n trackGlobal(name: string): void {\n const e = this.currentEffect;\n if (!e) return;\n const key = globalDepKey(name);\n if (e.dependencies.has(key)) return;\n e.dependencies.set(key, { key, kind: 'global', name, element: null });\n let subs = this.globalSubs.get(name);\n if (!subs) {\n subs = new Set();\n this.globalSubs.set(name, subs);\n }\n subs.add(e);\n }\n\n trackElement(el: Element, name: string): void {\n const e = this.currentEffect;\n if (!e) return;\n const key = elementDepKey(el, name);\n if (e.dependencies.has(key)) return;\n e.dependencies.set(key, { key, kind: 'element', name, element: el });\n const state = this.getElementState(el);\n let subs = state.symbolSubs.get(name);\n if (!subs) {\n subs = new Set();\n state.symbolSubs.set(name, subs);\n }\n subs.add(e);\n state.effects.add(e);\n }\n\n trackDomProperty(el: Element, prop: string): void {\n const e = this.currentEffect;\n if (!e) return;\n const key = domDepKey(el, prop);\n if (e.dependencies.has(key)) return;\n e.dependencies.set(key, { key, kind: 'dom', name: prop, element: el });\n const state = this.getElementState(el);\n let handler = state.domHandlers.get(prop);\n if (!handler) {\n const subs = new Set<Effect>();\n const listener = (): void => {\n for (const effect of subs) this.schedule(effect);\n };\n // Use both input and change to cover radios/selects which don't fire input.\n el.addEventListener('input', listener);\n el.addEventListener('change', listener);\n handler = {\n subs,\n detach: () => {\n el.removeEventListener('input', listener);\n el.removeEventListener('change', listener);\n },\n };\n state.domHandlers.set(prop, handler);\n }\n handler.subs.add(e);\n state.effects.add(e);\n }\n\n // ---------------------------------------------------------------------------\n // Notify (write-path) — schedules dependent effects for re-run.\n // ---------------------------------------------------------------------------\n\n notifyGlobal(name: string): void {\n const subs = this.globalSubs.get(name);\n if (!subs) return;\n for (const e of subs) this.schedule(e);\n }\n\n notifyElement(el: Element, name: string): void {\n const state = this.elementState.get(el);\n if (!state) return;\n const subs = state.symbolSubs.get(name);\n if (!subs) return;\n for (const e of subs) this.schedule(e);\n }\n\n // ---------------------------------------------------------------------------\n // Effect lifecycle.\n // ---------------------------------------------------------------------------\n\n /**\n * Create + initialize an effect. Returns a disposer that stops the effect.\n * Callers are expected to register the disposer with the core runtime's\n * cleanup registry so it fires on element removal.\n */\n createEffect(\n expression: () => unknown | Promise<unknown>,\n handler: (value: unknown) => void | Promise<void>,\n owner: Element | null\n ): () => void {\n const e = new Effect(this, expression, handler, owner);\n if (owner) this.getElementState(owner).effects.add(e);\n // Fire initialize asynchronously so the caller can set up cleanup registration\n // before the first run touches the DOM.\n queueMicrotask(() => {\n void e.initialize();\n });\n return () => e.stop();\n }\n\n /**\n * Stop all effects owned by an element. Called by the reactivity plugin's\n * cleanup hook registered via `runtime.getCleanupRegistry()`.\n */\n stopElementEffects(el: Element): void {\n const state = this.elementState.get(el);\n if (!state) return;\n for (const e of Array.from(state.effects)) e.stop();\n state.effects.clear();\n }\n\n /**\n * Internal: remove an effect's entries from all subscriber sets. Called by\n * `Effect.stop()`.\n */\n _unsubscribeEffect(e: Effect): void {\n for (const dep of e.dependencies.values()) {\n if (dep.kind === 'global') {\n const subs = this.globalSubs.get(dep.name);\n subs?.delete(e);\n } else if (dep.kind === 'element' && dep.element) {\n const state = this.elementState.get(dep.element);\n const subs = state?.symbolSubs.get(dep.name);\n subs?.delete(e);\n state?.effects.delete(e);\n } else if (dep.kind === 'dom' && dep.element) {\n const state = this.elementState.get(dep.element);\n const handler = state?.domHandlers.get(dep.name);\n handler?.subs.delete(e);\n if (handler && handler.subs.size === 0) {\n handler.detach();\n state?.domHandlers.delete(dep.name);\n }\n state?.effects.delete(e);\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Caret-variable storage — `^name` reads/writes.\n // ---------------------------------------------------------------------------\n\n /**\n * Whether `el` is a `dom-scope=\"isolated\"` boundary. Walks of `^var`\n * lookups stop at boundary elements that don't define the var, so nested\n * components don't accidentally read or write each other's state.\n */\n private isIsolationBoundary(el: Element): boolean {\n return typeof el.getAttribute === 'function' && el.getAttribute('dom-scope') === 'isolated';\n }\n\n /**\n * Walk up the DOM tree from `lookupRoot`, returning the first element whose\n * state has `name` defined. Stops at any `dom-scope=\"isolated\"` boundary\n * that doesn't itself define the var. Returns `null` if no owner is found.\n */\n private findCaretOwner(lookupRoot: Element, name: string): Element | null {\n let el: Element | null = lookupRoot;\n while (el) {\n const state = this.elementState.get(el);\n if (state && state.caretVars.has(name)) return el;\n if (this.isIsolationBoundary(el)) return null;\n el = el.parentElement;\n }\n return null;\n }\n\n /**\n * Read a DOM-scoped variable. Walks up from `lookupRoot`, tracking each\n * element visited as an `element` dep (so writes at any ancestor notify\n * dependent effects). Stops at any `dom-scope=\"isolated\"` boundary that\n * doesn't itself define the var.\n */\n readCaret(lookupRoot: Element, name: string): unknown {\n let el: Element | null = lookupRoot;\n while (el) {\n this.trackElement(el, name);\n const state = this.elementState.get(el);\n if (state && state.caretVars.has(name)) {\n return state.caretVars.get(name);\n }\n if (this.isIsolationBoundary(el)) return undefined;\n el = el.parentElement;\n }\n return undefined;\n }\n\n /**\n * Write a DOM-scoped variable. If `target` is provided, writes there\n * directly; otherwise walks up from `lookupRoot` to find the existing owner,\n * falling back to `lookupRoot` itself if no owner exists.\n */\n writeCaret(lookupRoot: Element, name: string, value: unknown, target?: Element): void {\n const owner = target ?? this.findCaretOwner(lookupRoot, name) ?? lookupRoot;\n const state = this.getElementState(owner);\n state.caretVars.set(name, value);\n this.notifyElement(owner, name);\n }\n\n // ---------------------------------------------------------------------------\n // Scheduler — microtask-batched flush.\n // ---------------------------------------------------------------------------\n\n private schedule(e: Effect): void {\n if (e.stopped) return;\n this.pending.add(e);\n if (this.scheduled) return;\n this.scheduled = true;\n queueMicrotask(() => void this.flush());\n }\n\n private async flush(): Promise<void> {\n try {\n while (this.pending.size > 0) {\n const batch = Array.from(this.pending);\n this.pending.clear();\n for (const e of batch) {\n if (e.stopped) continue;\n await e.run();\n // If the effect's run did not synchronously re-schedule itself, its\n // trigger count is reset. Self-rescheduling (a real cycle) keeps the\n // counter climbing toward the 100 cap. Long-lived effects that fire\n // sporadically (e.g. user-input bindings) stay alive forever.\n if (!this.pending.has(e)) e.resetTriggerCount();\n }\n }\n } finally {\n this.scheduled = false;\n }\n }\n}\n\n// Module singleton. One reactive graph per process; mirrors upstream's\n// `runtime.reactivity` pattern.\nexport const reactive = new Reactive();\n","/**\n * `^name` — DOM-scoped inherited variable.\n *\n * Upstream syntax:\n * ^counter → read from nearest ancestor that has `counter` set\n * ^counter on #target → read from (or near) #target\n * set ^counter to 42 → write to owner (or lookupRoot if not yet defined)\n *\n * Parse side: register `^` as a Pratt prefix operator. The handler consumes\n * the identifier token and an optional `on <target>` clause, emitting a\n * `caretVar` AST node.\n *\n * Eval side: `caretVar` node evaluator calls `reactive.readCaret(anchor,\n * name)` which walks the DOM tree for the owner and records deps as it goes.\n */\n\nimport type { ASTNode, ExecutionContext } from './types';\nimport { reactive } from './signals';\n\nexport interface CaretVarNode extends ASTNode {\n type: 'caretVar';\n name: string;\n onTarget: ASTNode | null;\n}\n\ninterface CaretVarRuntime {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n}\n\n/**\n * Coerce a runtime-evaluated `on <target>` result to a single Element.\n * Selector expressions resolve to an array of matched elements; bare\n * `me`/`it`/`you`/identifier references resolve to single Elements. Take the\n * first element of an array, or the value itself if it's already an Element.\n */\nfunction coerceToElement(value: unknown): Element | null {\n if (value instanceof Element) return value;\n if (Array.isArray(value) && value[0] instanceof Element) return value[0];\n return null;\n}\n\n/**\n * Pratt prefix handler for `^`. Consumes the following identifier token and\n * an optional `on <expr>` clause.\n */\nexport function parseCaretPrefix(token: unknown, ctx: unknown): ASTNode {\n // `ctx` is hyperfixi's PrattContext: { peek, advance, parseExpr, isStopToken, atEnd }.\n const pctx = ctx as {\n peek(): { value?: string; kind?: string } | undefined;\n advance(): { value: string; kind?: string };\n parseExpr(minBp: number): ASTNode;\n };\n const ident = pctx.advance();\n if (!ident || !ident.value) {\n throw new Error(\"Expected identifier after '^'\");\n }\n let onTarget: ASTNode | null = null;\n const next = pctx.peek();\n if (next && next.value === 'on') {\n pctx.advance(); // consume 'on'\n // Binding power 86 — higher than standard comparisons so `^x on me` doesn't\n // over-consume into surrounding expressions.\n onTarget = pctx.parseExpr(86);\n }\n const startTok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'caretVar',\n name: ident.value,\n onTarget,\n start: startTok?.start ?? 0,\n end: startTok?.end ?? 0,\n line: startTok?.line,\n column: startTok?.column,\n } as CaretVarNode;\n}\n\n/**\n * Build a node evaluator for `caretVar` bound to a specific runtime. The\n * evaluator walks up from the resolved anchor element, tracking every element\n * visited so writes at any ancestor notify dependent effects.\n *\n * Capturing `runtime` via a factory closure (matching live/when/bind) keeps\n * the evaluator independent of any module-scope state.\n */\nexport function makeEvaluateCaretVar(\n runtime: CaretVarRuntime\n): (node: ASTNode, ctx: unknown) => Promise<unknown> {\n return async function evaluateCaretVar(node, ctx) {\n const n = node as CaretVarNode;\n const context = ctx as ExecutionContext;\n let anchor: Element | null = (context.me as Element | null) ?? null;\n\n if (n.onTarget) {\n const resolved = await runtime.execute(n.onTarget, context);\n const el = coerceToElement(resolved);\n if (el) anchor = el;\n }\n\n if (!anchor) return undefined;\n return reactive.readCaret(anchor, n.name);\n };\n}\n\n/**\n * Build a node writer for `caretVar` bound to a specific runtime. Used by the\n * core `set` command via `parserExtensions.registerNodeWriter`.\n */\nexport function makeWriteCaretVar(\n runtime: CaretVarRuntime\n): (node: ASTNode, value: unknown, ctx: unknown) => Promise<void> {\n return async function writeCaretVar(node, value, ctx) {\n const n = node as CaretVarNode;\n const context = ctx as ExecutionContext;\n const anchor: Element | null = (context.me as Element | null) ?? null;\n if (!anchor) return;\n\n let target: Element | undefined;\n if (n.onTarget) {\n const resolved = await runtime.execute(n.onTarget, context);\n const el = coerceToElement(resolved);\n if (el) target = el;\n }\n reactive.writeCaret(anchor, n.name, value, target);\n };\n}\n","/**\n * `live ... end` — reactive block. Body re-runs whenever any dependency read\n * during its execution changes.\n *\n * Upstream syntax:\n * live [commandList] end\n *\n * Each command in the body is re-executed as a single effect. The entire\n * body shares one effect instance; its dependency set is the union of every\n * read performed during body execution.\n */\n\nimport type { ASTNode, ExecutionContext, FeatureParserCtx } from './types';\nimport { reactive } from './signals';\n\nexport interface LiveFeatureNode extends ASTNode {\n type: 'liveFeature';\n body: ASTNode[];\n}\n\n/**\n * Parse `live ... end`. The `live` keyword has already been consumed by the\n * parser dispatcher; we parse the body and expect a trailing `end`.\n */\nexport function parseLiveFeature(ctx: unknown, token: unknown): ASTNode {\n const pctx = ctx as FeatureParserCtx;\n const body = pctx.parseCommandListUntilEnd();\n // parseCommandListUntilEnd stops when it sees `end` (but doesn't consume it).\n if (!pctx.isAtEnd() && pctx.check('end')) pctx.match('end');\n const tok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'liveFeature',\n body,\n start: tok?.start ?? 0,\n end: pctx.getPosition().end,\n line: tok?.line,\n column: tok?.column,\n } as LiveFeatureNode;\n}\n\n/**\n * Create an evaluator bound to a runtime reference. The plugin captures\n * `runtime` at install time and passes it in so effect re-runs can dispatch\n * the body commands without going through module-scope state.\n */\nexport function makeEvaluateLiveFeature(runtime: {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n}): (node: ASTNode, ctx: unknown) => unknown | Promise<unknown> {\n return async function evaluateLiveFeature(node, ctx) {\n const context = ctx as ExecutionContext;\n const owner = (context.me as Element) ?? document.body;\n const n = node as LiveFeatureNode;\n\n const stop = reactive.createEffect(\n async () => {\n for (const cmd of n.body) {\n await runtime.execute(cmd, context);\n }\n },\n () => {\n /* no-op — side effects happened inside the expression */\n },\n owner\n );\n context.registerCleanup?.(owner, stop, 'live-effect');\n return undefined;\n };\n}\n","/**\n * `when <expr> [or <expr>]* changes [commandList] end` — observer feature.\n *\n * Runs the body when any watched expression's value changes (Object.is\n * semantics). One effect is created per watched expression so writes to a\n * given dep only re-run that watcher.\n */\n\nimport type { ASTNode, ExecutionContext, FeatureParserCtx } from './types';\nimport { reactive } from './signals';\n\nexport interface WhenFeatureNode extends ASTNode {\n type: 'whenFeature';\n watched: ASTNode[];\n body: ASTNode[];\n}\n\nexport function parseWhenFeature(ctx: unknown, token: unknown): ASTNode {\n const pctx = ctx as FeatureParserCtx;\n const watched: ASTNode[] = [pctx.parseExpression()];\n while (pctx.match('or')) {\n watched.push(pctx.parseExpression());\n }\n pctx.consume('changes', \"Expected 'changes' after when expression list\");\n const body = pctx.parseCommandListUntilEnd();\n if (!pctx.isAtEnd() && pctx.check('end')) pctx.match('end');\n const tok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'whenFeature',\n watched,\n body,\n start: tok?.start ?? 0,\n end: pctx.getPosition().end,\n line: tok?.line,\n column: tok?.column,\n } as WhenFeatureNode;\n}\n\nexport function makeEvaluateWhenFeature(runtime: {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n evaluateExpressionWithResult?: (\n node: ASTNode,\n ctx: ExecutionContext\n ) => Promise<{ value: unknown }>;\n}): (node: ASTNode, ctx: unknown) => unknown | Promise<unknown> {\n return async function evaluateWhenFeature(node, ctx) {\n const context = ctx as ExecutionContext;\n const owner = (context.me as Element) ?? document.body;\n const n = node as WhenFeatureNode;\n\n for (const watchedExpr of n.watched) {\n const stop = reactive.createEffect(\n async () => {\n // Evaluate the watched expression as a regular expression through the\n // runtime so that trackGlobal/trackElement fire via the global-write\n // hook and caret-var reads.\n return await runtime.execute(watchedExpr, context);\n },\n async newValue => {\n // Fire the body with `it` / `result` bound to the new value.\n const subCtx: ExecutionContext = { ...context, it: newValue, result: newValue };\n for (const cmd of n.body) {\n await runtime.execute(cmd, subCtx);\n }\n },\n owner\n );\n context.registerCleanup?.(owner, stop, 'when-effect');\n }\n return undefined;\n };\n}\n","/**\n * `bind X [to|and|with] Y` — two-way binding.\n *\n * Creates two effects (registration order is load-bearing — both initialize\n * via `queueMicrotask` and run in registration order):\n * 1. DOM → var: read DOM, write var. DOM \"wins\" on init.\n * 2. var → DOM: read var, write DOM. Fires on programmatic var writes\n * after init. On its own initial run, var === DOM (Effect 1 just synced\n * them), so the write is a no-op.\n *\n * Two binding forms:\n *\n * 1. Auto-detected (DOM side is a bare element expression):\n *\n * bind $name to #input -- detects `value`\n * bind $checked to me -- detects `checked` on a checkbox\n *\n * Auto-detected property by element type:\n * - INPUT[type=checkbox|radio] → `checked`\n * - INPUT[type=number|range] → `valueAsNumber`\n * - INPUT|TEXTAREA|SELECT → `value`\n * - contenteditable=\"true\" → `textContent`\n * - Custom elements with own `value` → `value`\n *\n * 2. Explicit property (DOM side is a member or possessive expression):\n *\n * bind $color to #picker's value -- possessive (preferred — reads in any language)\n * bind $color to #picker.value -- dot (JS-style alternative)\n * bind $text to #div's textContent -- non-form properties: var→DOM only\n *\n * For form-like elements, both directions work. For non-form elements\n * (e.g., binding a div's `textContent`), only var→DOM fires — there are\n * no input/change events to drive DOM→var, so user mutations of the\n * property via devtools won't propagate back.\n */\n\nimport type { ASTNode, ExecutionContext, FeatureParserCtx } from './types';\nimport { reactive } from './signals';\n\nexport interface BindFeatureNode extends ASTNode {\n type: 'bindFeature';\n left: ASTNode;\n right: ASTNode;\n}\n\nexport function parseBindFeature(ctx: unknown, token: unknown): ASTNode {\n const pctx = ctx as FeatureParserCtx;\n const left = pctx.parseExpression();\n // Accept any of `to` / `and` / `with` as the separator.\n if (!(pctx.match('to') || pctx.match('and') || pctx.match('with'))) {\n throw new Error(\"bind requires 'to', 'and', or 'with' between the two sides\");\n }\n const right = pctx.parseExpression();\n // Optional `end` terminator (matches upstream which allows both forms).\n if (pctx.check('end')) pctx.match('end');\n const tok = token as { start?: number; end?: number; line?: number; column?: number };\n return {\n type: 'bindFeature',\n left,\n right,\n start: tok?.start ?? 0,\n end: pctx.getPosition().end,\n line: tok?.line,\n column: tok?.column,\n } as BindFeatureNode;\n}\n\n/**\n * Auto-detect the DOM property to bind by element type. Returns null if the\n * target isn't a recognized form/editable element.\n */\nfunction detectProperty(el: Element): string | null {\n const tag = el.tagName;\n if (tag === 'INPUT') {\n const type = (el as HTMLInputElement).type;\n if (type === 'checkbox' || type === 'radio') return 'checked';\n if (type === 'number' || type === 'range') return 'valueAsNumber';\n return 'value';\n }\n if (tag === 'TEXTAREA' || tag === 'SELECT') return 'value';\n const ce = (el as HTMLElement).contentEditable;\n if (ce === 'true') return 'textContent';\n // Custom elements with own `value` prop.\n if ('value' in el) return 'value';\n return null;\n}\n\n/**\n * If `node` is a `memberExpression` or `possessiveExpression` with a static\n * identifier property (`#el.value` or `#el's value`), return the inner element\n * expression and the property name. Returns null for anything else.\n *\n * Computed member access (`#el[prop]`) is intentionally rejected — we'd have to\n * evaluate the index dynamically and the binding direction would be unclear.\n * Chained property access (`#el.dataset.value`) is also not unpacked — we only\n * peel one level. Multi-level support is a future arc.\n */\nfunction unwrapExplicitProperty(node: ASTNode): { element: ASTNode; propertyName: string } | null {\n if (!node || (node.type !== 'memberExpression' && node.type !== 'possessiveExpression')) {\n return null;\n }\n if (node.type === 'memberExpression' && node.computed === true) return null;\n const property = node.property as ASTNode | undefined;\n const object = node.object as ASTNode | undefined;\n if (!property || !object || property.type !== 'identifier') return null;\n const name = (property.name as string) ?? '';\n if (!name) return null;\n return { element: object, propertyName: name };\n}\n\n/**\n * Detect a chained property access on the bind RHS — e.g.\n * `me.style.backgroundColor` or `#el's dataset's value`.\n *\n * After `unwrapExplicitProperty` peels the outermost member, the returned\n * `element` is the object of that member. If that object is itself a\n * member/possessive expression, we have a multi-level chain that v1 of\n * bind doesn't support. Used only for the error path; the parsed AST is\n * left intact.\n */\nfunction isChainedMember(node: ASTNode | undefined): boolean {\n if (!node) return false;\n return node.type === 'memberExpression' || node.type === 'possessiveExpression';\n}\n\n/**\n * Whether the input/change listener installed by `trackDomProperty` would\n * actually fire for this element. Used to decide whether to wire up the\n * DOM→var direction when an explicit property is given.\n */\nfunction isFormLikeElement(el: Element): boolean {\n const tag = el.tagName;\n if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;\n if ((el as HTMLElement).contentEditable === 'true') return true;\n return false;\n}\n\n/**\n * Whether debug logging is enabled. Mirrors signals.ts — keeps a single\n * convention for the package.\n */\nfunction debugEnabled(): boolean {\n try {\n return typeof localStorage !== 'undefined' && localStorage.getItem('hyperfixi:debug') !== null;\n } catch {\n return false;\n }\n}\n\n/**\n * Create the bind evaluator. Because `bind` has unusual parse shape (AST\n * nodes for left/right that may be identifiers, `$name` references, or DOM\n * element lookups), we rely on the runtime to evaluate them.\n */\nexport function makeEvaluateBindFeature(runtime: {\n execute(node: ASTNode, ctx: ExecutionContext): Promise<unknown>;\n}): (node: ASTNode, ctx: unknown) => unknown | Promise<unknown> {\n return async function evaluateBindFeature(node, ctx) {\n const context = ctx as ExecutionContext;\n const owner = (context.me as Element) ?? document.body;\n const n = node as BindFeatureNode;\n\n // Dynamically import the element-scope accessor from core. A static import\n // would pull core's full index into this module's load graph — and core's\n // index eagerly evaluates `morphlex` (which touches `Element.prototype` at\n // module scope), throwing `Element is not defined` when @hyperfixi/reactivity\n // is imported in bare Node/SSR. This evaluator only runs in a browser (it\n // uses `document.body` above), so deferring the import keeps the package\n // importable in Node while `:name` binds still address the core store.\n const { getElementScopeMap } = await import('@hyperfixi/core');\n\n // Resolve sides. One is a var reference (read/write a symbol), the other\n // a DOM target (read/write a property). Determine direction from node shape.\n const leftIsVar = isVarRef(n.left);\n const rightIsVar = isVarRef(n.right);\n\n // We need a DOM-side descriptor (element + property) and a var-side name.\n let varSide: { name: string; isGlobal: boolean } | null = null;\n let domSide: { exprNode: ASTNode } | null = null;\n\n if (leftIsVar && !rightIsVar) {\n varSide = varRefInfo(n.left);\n domSide = { exprNode: n.right };\n } else if (rightIsVar && !leftIsVar) {\n varSide = varRefInfo(n.right);\n domSide = { exprNode: n.left };\n } else if (leftIsVar && rightIsVar) {\n // var-to-var binding not supported in v1 (no DOM side).\n throw new Error('bind: cannot bind two symbols together (need a DOM side)');\n } else {\n throw new Error('bind: could not identify a symbol side');\n }\n\n // Unwrap explicit property syntax: `#el.value` or `#el's value` becomes\n // (element-expression, propertyName). Otherwise, evaluate the whole side\n // and rely on auto-detection.\n const explicit = unwrapExplicitProperty(domSide.exprNode);\n // Multi-level property access (`#el.style.background`, `me's dataset's id`)\n // is not supported in v1. Surface that diagnosis up front; otherwise the\n // user gets the generic \"did not resolve to an element\" message and no\n // hint that the chain is the problem.\n if (explicit && isChainedMember(explicit.element)) {\n throw new Error(\n 'bind: multi-level property access (e.g., `#el.a.b`) is not supported in v1 — restructure to a single property write or pass the element directly for auto-detection (e.g., `bind $x to #el`).'\n );\n }\n const elementExpr = explicit ? explicit.element : domSide.exprNode;\n const domValue = await runtime.execute(elementExpr, context);\n if (!(domValue instanceof Element)) {\n const valueType =\n domValue === null ? 'null' : domValue === undefined ? 'undefined' : typeof domValue;\n const snippet =\n domValue !== null && domValue !== undefined ? ` \"${String(domValue).slice(0, 40)}\"` : '';\n const suggestion = explicit\n ? ''\n : \" If you meant to write to a property, use the explicit form: `<selector>'s <property>`.\";\n throw new Error(\n `bind: right-hand side did not resolve to an element (got ${valueType}${snippet}).${suggestion}`\n );\n }\n const el = domValue;\n // Explicit property bypasses auto-detect; the user takes responsibility for\n // picking something readable from the element. For DOM→var to work without\n // explicit property, fall back to auto-detect.\n const prop = explicit ? explicit.propertyName : detectProperty(el);\n if (!prop) {\n throw new Error(\n `bind: could not auto-detect property for <${el.tagName.toLowerCase()}> — use explicit \\`<expr>'s <property>\\` form`\n );\n }\n // For explicit-property mode on non-form elements, DOM→var can't sync via\n // input/change events. Skip the listener install; only var→DOM runs.\n const installDomToVar = !explicit || isFormLikeElement(el);\n if (explicit && !installDomToVar && debugEnabled() && typeof console !== 'undefined') {\n console.warn(\n `[@hyperfixi/reactivity] bind: DOM→var skipped for <${el.tagName.toLowerCase()}>.${prop} — no input/change event source.`\n );\n }\n\n // Initial sync: DOM → var.\n const readDom = (): unknown => {\n if (prop === 'valueAsNumber') return (el as HTMLInputElement).valueAsNumber;\n if (prop === 'checked') return (el as HTMLInputElement).checked;\n if (prop === 'textContent') return el.textContent ?? '';\n return (el as any)[prop];\n };\n const writeDom = (value: unknown): void => {\n if (prop === 'valueAsNumber') {\n const n = Number(value);\n (el as HTMLInputElement).valueAsNumber = Number.isNaN(n) ? (null as never) : n;\n } else if (prop === 'checked') {\n (el as HTMLInputElement).checked = Boolean(value);\n } else if (prop === 'textContent') {\n el.textContent = value == null ? '' : String(value);\n } else {\n (el as any)[prop] = value;\n }\n };\n const readVar = (): unknown => {\n if (varSide!.isGlobal) return context.globals?.get(varSide!.name);\n // `:name` is element-scoped — read from the owner element's store, the same\n // place the core `set :name` writes. (Direct Map access, not getElementVar,\n // so we don't double-fire the read hook; bind tracks via trackElement.)\n return getElementScopeMap(owner).get(varSide!.name);\n };\n const writeVar = (value: unknown): void => {\n if (varSide!.isGlobal) {\n context.globals?.set(varSide!.name, value);\n // Bypass the global-write hook (we're touching the Map directly), so\n // notify the reactive graph manually for the var→DOM effect.\n reactive.notifyGlobal(varSide!.name);\n } else {\n // Element-scoped `:name`: write to the owner element's store (same place\n // core's `set :name` writes), then notify manually — the direct Map write\n // skips the localWriteHook.\n getElementScopeMap(owner).set(varSide!.name, value);\n reactive.notifyElement(owner, varSide!.name);\n }\n };\n\n // Effect 1: DOM → var (fires on user input). Skipped for explicit-property\n // bindings on non-form elements — no input/change events would drive it.\n let stopDomToVar: (() => void) | null = null;\n if (installDomToVar) {\n stopDomToVar = reactive.createEffect(\n () => {\n reactive.trackDomProperty(el, prop);\n return readDom();\n },\n newValue => {\n writeVar(newValue);\n },\n owner\n );\n }\n\n // Effect 2: var → DOM (fires on programmatic var writes — for globals\n // via the core's globalWriteHook, for locals via the localWriteHook the\n // reactivity plugin registers).\n const stopVarToDom = reactive.createEffect(\n () => {\n if (varSide!.isGlobal) reactive.trackGlobal(varSide!.name);\n else reactive.trackElement(owner, varSide!.name);\n return readVar();\n },\n newValue => {\n if (newValue === undefined) return;\n writeDom(newValue);\n },\n owner\n );\n\n if (stopDomToVar) context.registerCleanup?.(owner, stopDomToVar, 'bind-dom-to-var');\n context.registerCleanup?.(owner, stopVarToDom, 'bind-var-to-dom');\n return undefined;\n };\n}\n\n/**\n * Is this AST node a var reference we can bind to?\n *\n * The hyperfixi parser emits `identifier` nodes for both globals and locals,\n * but with different shapes:\n * - `$foo` → `{ type: 'identifier', name: '$foo' }` (no scope field)\n * - `:foo` → `{ type: 'identifier', name: 'foo', scope: 'element' }` (element-scoped)\n * - `::foo` → `{ type: 'identifier', name: 'foo', scope: 'global' }`\n *\n * We accept all of them. The legacy `$`-prefix sniff stays as a fallback because\n * `parseExpression` doesn't always set `scope`.\n */\nfunction isVarRef(node: ASTNode): boolean {\n if (!node) return false;\n if (node.type !== 'identifier') return false;\n const scope = node.scope as string | undefined;\n if (scope === 'local' || scope === 'element' || scope === 'global') return true;\n const name = (node.name as string) ?? '';\n return name.startsWith('$') || name.startsWith(':');\n}\n\nfunction varRefInfo(node: ASTNode): { name: string; isGlobal: boolean } {\n const rawName = (node.name as string) ?? '';\n const scope = node.scope as string | undefined;\n // Prefer the parser-emitted scope marker. Fall back to prefix sniffing for\n // shapes where scope isn't set (e.g. `$foo` arriving as bare identifier\n // with name '$foo').\n let isGlobal: boolean;\n let name: string;\n if (scope === 'global') {\n isGlobal = true;\n name = rawName;\n } else if (scope === 'local' || scope === 'element') {\n isGlobal = false;\n name = rawName;\n } else if (rawName.startsWith('$')) {\n isGlobal = true;\n name = rawName.slice(1);\n } else if (rawName.startsWith(':')) {\n isGlobal = false;\n name = rawName.slice(1);\n } else {\n isGlobal = false;\n name = rawName;\n }\n if (!name) {\n throw new Error('bind: variable reference has empty name');\n }\n return { name, isGlobal };\n}\n","/**\n * @hyperfixi/reactivity — signal-based reactive features for hyperfixi.\n *\n * Adds four constructs from upstream _hyperscript 0.9.90:\n *\n * live [commandList] end reactive block — body re-runs\n * when tracked reads change.\n *\n * when <expr> [or <expr>]* changes observer — body runs when any\n * [commandList] end watched expression changes.\n *\n * bind <var> to <element> two-way DOM ⇄ var binding.\n *\n * ^name [on <target>] DOM-scoped inherited variable\n * (read + write with `^`).\n *\n * Install:\n *\n * ```ts\n * import { createRuntime, installPlugin } from '@hyperfixi/core';\n * import { reactivityPlugin } from '@hyperfixi/reactivity';\n *\n * const runtime = createRuntime();\n * installPlugin(runtime, reactivityPlugin);\n * ```\n */\n\nimport type { HyperfixiPlugin, HyperfixiPluginContext } from '@hyperfixi/core';\nimport { reactive } from './signals';\nimport { parseCaretPrefix, makeEvaluateCaretVar, makeWriteCaretVar } from './caret-var';\nimport { parseLiveFeature, makeEvaluateLiveFeature } from './live';\nimport { parseWhenFeature, makeEvaluateWhenFeature } from './when';\nimport { parseBindFeature, makeEvaluateBindFeature } from './bind';\n\nexport { reactive } from './signals';\nexport type { CaretVarNode } from './caret-var';\nexport type { LiveFeatureNode } from './live';\nexport type { WhenFeatureNode } from './when';\nexport type { BindFeatureNode } from './bind';\n\n/**\n * The plugin object. Install once at app startup; re-installing is idempotent\n * (guarded via a `parserExtensions.hasFeature('live')` check).\n *\n * Registers:\n * - Features: `live`, `when`, `bind` (top-level features with `end` bodies)\n * - Prefix op: `^` (primary expression for DOM-scoped vars)\n * - Node evaluators: `liveFeature`, `whenFeature`, `bindFeature`, `caretVar`\n * - A node writer for `caretVar` so `set ^X to Y` flows through `reactive.writeCaret`\n * - Global read/write hooks so `$name` reads track and writes notify\n *\n * Effect cleanup: each effect-creating evaluator calls\n * `context.registerCleanup(owner, stop, ...)` so the core runtime tears effects\n * down when their owning element is cleaned up. There is no separate plugin-level\n * cleanup hook; `reactive.stopElementEffects(el)` is exposed for explicit teardown\n * by tests and consumers that manage element lifecycle outside the runtime.\n */\nexport const reactivityPlugin: HyperfixiPlugin & { version: string } = {\n name: '@hyperfixi/reactivity',\n version: '2.3.1',\n install(ctx: HyperfixiPluginContext) {\n const { parserExtensions, runtime } = ctx;\n\n // Idempotency: the parser-extension registry is process-singleton, so\n // re-installing into a fresh runtime would otherwise stack additional\n // global read/write hooks on every call. `snapshot()`/`restore()` clears\n // the feature registry — when tests roll back the registry, this guard\n // re-enables a fresh install.\n if (parserExtensions.hasFeature('live')) return;\n\n // Parser hooks — three block features plus a primary-expression caret.\n parserExtensions.registerFeature('live', parseLiveFeature as never);\n parserExtensions.registerFeature('when', parseWhenFeature as never);\n parserExtensions.registerFeature('bind', parseBindFeature as never);\n parserExtensions.registerPrefixOperator('^', 85, parseCaretPrefix as never);\n\n // Runtime evaluators. Features capture `runtime` so effect re-runs can\n // dispatch body commands without going through module-scope state.\n parserExtensions.registerNodeEvaluator(\n 'liveFeature',\n makeEvaluateLiveFeature(runtime as never) as never\n );\n parserExtensions.registerNodeEvaluator(\n 'whenFeature',\n makeEvaluateWhenFeature(runtime as never) as never\n );\n parserExtensions.registerNodeEvaluator(\n 'bindFeature',\n makeEvaluateBindFeature(runtime as never) as never\n );\n parserExtensions.registerNodeEvaluator(\n 'caretVar',\n makeEvaluateCaretVar(runtime as never) as never\n );\n\n // Caret-var write: lets the core `set` command dispatch `set ^X to Y`\n // through `reactive.writeCaret`. Resolves `on <target>` via the captured\n // runtime — no global-scope indirection.\n parserExtensions.registerNodeWriter('caretVar', makeWriteCaretVar(runtime as never) as never);\n\n // Global-write hook: notify the reactive graph whenever `$name` is set.\n // The returned disposer is intentionally discarded — the install-time\n // idempotency guard above is the sole gate against double-registration.\n parserExtensions.registerGlobalWriteHook((name: string, _value: unknown, _context: unknown) => {\n reactive.notifyGlobal(name);\n });\n\n // Global-read hook: track the read against the current effect (if any)\n // so effects re-run when the global changes.\n parserExtensions.registerGlobalReadHook((name: string, _context: unknown) => {\n reactive.trackGlobal(name);\n });\n\n // Local hooks — analogous to globals, but keyed by `context.me` so each\n // element holds independent state. A `set :foo to ...` running in a\n // handler with `me=button1` notifies effects subscribed to (button1, 'foo');\n // a `set :foo` in a different `me` won't reach them. This matches how\n // locals already work — they're never cross-context — and lets two\n // components hold independent `:foo` state without interference.\n parserExtensions.registerLocalWriteHook((name: string, _value: unknown, context) => {\n const owner = (context as { me?: Element | null }).me ?? null;\n if (owner) reactive.notifyElement(owner, name);\n });\n\n parserExtensions.registerLocalReadHook((name: string, context) => {\n const owner = (context as { me?: Element | null }).me ?? null;\n if (owner) reactive.trackElement(owner, name);\n });\n },\n};\n\nexport default reactivityPlugin;\n"],"mappings":";AA0BA,SAAS,eAAwB;AAC/B,MAAI;AACF,WAAO,OAAO,iBAAiB,eAAe,aAAa,QAAQ,iBAAiB,MAAM;AAAA,EAC5F,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,UAAU,SAAiB,KAAoB;AACtD,MAAI,CAAC,aAAa,EAAG;AACrB,MAAI,OAAO,YAAY,YAAa;AACpC,UAAQ,KAAK,2BAA2B,OAAO,IAAI,GAAG;AACxD;AASA,IAAM,eAAe,CAAC,SAAyB,UAAU,IAAI;AAC7D,IAAM,gBAAgB,CAAC,IAAa,SAAyB,WAAW,cAAc,EAAE,CAAC,IAAI,IAAI;AACjG,IAAM,YAAY,CAAC,IAAa,SAAyB,OAAO,cAAc,EAAE,CAAC,IAAI,IAAI;AAKzF,IAAM,eAAe,oBAAI,QAAyB;AAClD,IAAI,aAAa;AACjB,SAAS,cAAc,IAAqB;AAC1C,QAAM,WAAW,aAAa,IAAI,EAAE;AACpC,MAAI,aAAa,OAAW,QAAO;AACnC,QAAM,KAAK,EAAE;AACb,eAAa,IAAI,IAAI,EAAE;AACvB,SAAO;AACT;AAEO,IAAM,SAAN,MAAa;AAAA,EAMlB,YACmB,GACR,YACA,SACA,SACT;AAJiB;AACR;AACA;AACA;AAA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,IAAI;AAOtC,QAAI,iBAAiB,WAAW,MAAM,EAAG;AAGzC,qBAAiB,gBAAgB,QAAQ,gBAAyB;AAClE,qBAAiB,gBAAgB,QAAQ,gBAAyB;AAClE,qBAAiB,gBAAgB,QAAQ,gBAAyB;AAClE,qBAAiB,uBAAuB,KAAK,IAAI,gBAAyB;AAI1E,qBAAiB;AAAA,MACf;AAAA,MACA,wBAAwB,OAAgB;AAAA,IAC1C;AACA,qBAAiB;AAAA,MACf;AAAA,MACA,wBAAwB,OAAgB;AAAA,IAC1C;AACA,qBAAiB;AAAA,MACf;AAAA,MACA,wBAAwB,OAAgB;AAAA,IAC1C;AACA,qBAAiB;AAAA,MACf;AAAA,MACA,qBAAqB,OAAgB;AAAA,IACvC;AAKA,qBAAiB,mBAAmB,YAAY,kBAAkB,OAAgB,CAAU;AAK5F,qBAAiB,wBAAwB,CAAC,MAAc,QAAiB,aAAsB;AAC7F,eAAS,aAAa,IAAI;AAAA,IAC5B,CAAC;AAID,qBAAiB,uBAAuB,CAAC,MAAc,aAAsB;AAC3E,eAAS,YAAY,IAAI;AAAA,IAC3B,CAAC;AAQD,qBAAiB,uBAAuB,CAAC,MAAc,QAAiB,YAAY;AAClF,YAAM,QAAS,QAAoC,MAAM;AACzD,UAAI,MAAO,UAAS,cAAc,OAAO,IAAI;AAAA,IAC/C,CAAC;AAED,qBAAiB,sBAAsB,CAAC,MAAc,YAAY;AAChE,YAAM,QAAS,QAAoC,MAAM;AACzD,UAAI,MAAO,UAAS,aAAa,OAAO,IAAI;AAAA,IAC9C,CAAC;AAAA,EACH;AACF;AAEA,IAAO,gBAAQ;","names":["debugEnabled","n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperfixi/reactivity",
3
- "version": "2.6.0",
3
+ "version": "2.7.1",
4
4
  "description": "Reactive features for hyperfixi — adds `live`, `bind`, `when X changes`, and `^name` DOM-scoped vars (upstream _hyperscript 0.9.90).",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -22,7 +22,7 @@
22
22
  "typecheck": "tsc --noEmit"
23
23
  },
24
24
  "dependencies": {
25
- "@hyperfixi/core": "^2.6.0"
25
+ "@hyperfixi/core": "^2.7.1"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^20.0.0",
package/src/bind.ts CHANGED
@@ -160,6 +160,15 @@ export function makeEvaluateBindFeature(runtime: {
160
160
  const owner = (context.me as Element) ?? document.body;
161
161
  const n = node as BindFeatureNode;
162
162
 
163
+ // Dynamically import the element-scope accessor from core. A static import
164
+ // would pull core's full index into this module's load graph — and core's
165
+ // index eagerly evaluates `morphlex` (which touches `Element.prototype` at
166
+ // module scope), throwing `Element is not defined` when @hyperfixi/reactivity
167
+ // is imported in bare Node/SSR. This evaluator only runs in a browser (it
168
+ // uses `document.body` above), so deferring the import keeps the package
169
+ // importable in Node while `:name` binds still address the core store.
170
+ const { getElementScopeMap } = await import('@hyperfixi/core');
171
+
163
172
  // Resolve sides. One is a var reference (read/write a symbol), the other
164
173
  // a DOM target (read/write a property). Determine direction from node shape.
165
174
  const leftIsVar = isVarRef(n.left);
@@ -249,7 +258,10 @@ export function makeEvaluateBindFeature(runtime: {
249
258
  };
250
259
  const readVar = (): unknown => {
251
260
  if (varSide!.isGlobal) return context.globals?.get(varSide!.name);
252
- return context.locals?.get(varSide!.name);
261
+ // `:name` is element-scoped — read from the owner element's store, the same
262
+ // place the core `set :name` writes. (Direct Map access, not getElementVar,
263
+ // so we don't double-fire the read hook; bind tracks via trackElement.)
264
+ return getElementScopeMap(owner).get(varSide!.name);
253
265
  };
254
266
  const writeVar = (value: unknown): void => {
255
267
  if (varSide!.isGlobal) {
@@ -258,9 +270,10 @@ export function makeEvaluateBindFeature(runtime: {
258
270
  // notify the reactive graph manually for the var→DOM effect.
259
271
  reactive.notifyGlobal(varSide!.name);
260
272
  } else {
261
- context.locals?.set(varSide!.name, value);
262
- // Same rationale for locals — direct Map write skips the localWriteHook,
263
- // so we notify the element-scoped subscription set directly.
273
+ // Element-scoped `:name`: write to the owner element's store (same place
274
+ // core's `set :name` writes), then notify manually — the direct Map write
275
+ // skips the localWriteHook.
276
+ getElementScopeMap(owner).set(varSide!.name, value);
264
277
  reactive.notifyElement(owner, varSide!.name);
265
278
  }
266
279
  };
@@ -309,17 +322,17 @@ export function makeEvaluateBindFeature(runtime: {
309
322
  * The hyperfixi parser emits `identifier` nodes for both globals and locals,
310
323
  * but with different shapes:
311
324
  * - `$foo` → `{ type: 'identifier', name: '$foo' }` (no scope field)
312
- * - `:foo` → `{ type: 'identifier', name: 'foo', scope: 'local' }`
325
+ * - `:foo` → `{ type: 'identifier', name: 'foo', scope: 'element' }` (element-scoped)
313
326
  * - `::foo` → `{ type: 'identifier', name: 'foo', scope: 'global' }`
314
327
  *
315
- * We accept all three. The legacy `$`-prefix sniff stays as a fallback because
328
+ * We accept all of them. The legacy `$`-prefix sniff stays as a fallback because
316
329
  * `parseExpression` doesn't always set `scope`.
317
330
  */
318
331
  function isVarRef(node: ASTNode): boolean {
319
332
  if (!node) return false;
320
333
  if (node.type !== 'identifier') return false;
321
334
  const scope = node.scope as string | undefined;
322
- if (scope === 'local' || scope === 'global') return true;
335
+ if (scope === 'local' || scope === 'element' || scope === 'global') return true;
323
336
  const name = (node.name as string) ?? '';
324
337
  return name.startsWith('$') || name.startsWith(':');
325
338
  }
@@ -335,7 +348,7 @@ function varRefInfo(node: ASTNode): { name: string; isGlobal: boolean } {
335
348
  if (scope === 'global') {
336
349
  isGlobal = true;
337
350
  name = rawName;
338
- } else if (scope === 'local') {
351
+ } else if (scope === 'local' || scope === 'element') {
339
352
  isGlobal = false;
340
353
  name = rawName;
341
354
  } else if (rawName.startsWith('$')) {
@@ -8,7 +8,7 @@
8
8
  import { describe, it, expect, beforeEach, afterEach } from 'vitest';
9
9
  import { Runtime, hyperscript } from '@hyperfixi/core';
10
10
  import { parse } from '@hyperfixi/core';
11
- import { getParserExtensionRegistry, installPlugin } from '@hyperfixi/core';
11
+ import { getParserExtensionRegistry, installPlugin, getElementScopeMap } from '@hyperfixi/core';
12
12
  import type { ExecutionContext } from '@hyperfixi/core/src/types/core';
13
13
  import { reactivityPlugin, reactive } from './index';
14
14
 
@@ -141,6 +141,36 @@ describe('@hyperfixi/reactivity — integration', () => {
141
141
  });
142
142
 
143
143
  describe('bind', () => {
144
+ it('parses and runs a `then`-joined bind chain (two-way share between inputs)', async () => {
145
+ const inputA = document.createElement('input');
146
+ const inputB = document.createElement('input');
147
+ inputA.id = 'input-a';
148
+ inputB.id = 'input-b';
149
+ inputA.value = 'first';
150
+ document.body.append(inputA, inputB);
151
+ const ctx = createContext(inputA);
152
+
153
+ const r = parse('bind $name to #input-a then bind $name to #input-b');
154
+ expect(r.success).toBe(true);
155
+ const program = r.node as unknown as { type: string; statements?: { type: string }[] };
156
+ expect(program.statements).toHaveLength(2);
157
+ expect(program.statements![0].type).toBe('bindFeature');
158
+ expect(program.statements![1].type).toBe('bindFeature');
159
+
160
+ await runtime.execute(r.node!, ctx);
161
+ await settle();
162
+
163
+ // Both inputs share $name: typing in A propagates to B.
164
+ inputA.value = 'typed';
165
+ inputA.dispatchEvent(new Event('input'));
166
+ await settle();
167
+ expect(ctx.globals.get('name')).toBe('typed');
168
+ expect(inputB.value).toBe('typed');
169
+
170
+ inputA.remove();
171
+ inputB.remove();
172
+ });
173
+
144
174
  it('two-way binds a global var to an input value', async () => {
145
175
  const input = document.createElement('input');
146
176
  input.type = 'text';
@@ -179,7 +209,8 @@ describe('@hyperfixi/reactivity — integration', () => {
179
209
  input.value = 'initial';
180
210
  document.body.appendChild(input);
181
211
  const ctx = createContext(input);
182
- ctx.locals.set('greeting', 'pending');
212
+ // `:greeting` is element-scoped (keyed by the handler element).
213
+ getElementScopeMap(input).set('greeting', 'pending');
183
214
 
184
215
  const r = parse('bind :greeting to me');
185
216
  expect(r.success).toBe(true);
@@ -187,13 +218,13 @@ describe('@hyperfixi/reactivity — integration', () => {
187
218
  await settle();
188
219
 
189
220
  // DOM → var on init (DOM wins).
190
- expect(ctx.locals.get('greeting')).toBe('initial');
221
+ expect(getElementScopeMap(input).get('greeting')).toBe('initial');
191
222
 
192
- // User input updates the local via DOM→var effect.
223
+ // User input updates the element-scoped var via the DOM→var effect.
193
224
  input.value = 'typed';
194
225
  input.dispatchEvent(new Event('input'));
195
226
  await settle();
196
- expect(ctx.locals.get('greeting')).toBe('typed');
227
+ expect(getElementScopeMap(input).get('greeting')).toBe('typed');
197
228
 
198
229
  document.body.removeChild(input);
199
230
  });
@@ -472,7 +503,8 @@ describe('@hyperfixi/reactivity — integration', () => {
472
503
  expect(r.success).toBe(true);
473
504
  await runtime.execute(r.node!, ctx);
474
505
  await settle();
475
- expect(ctx.locals.get('t')).toBe('dark');
506
+ // `:t` is element-scoped on `child` (the context element).
507
+ expect(getElementScopeMap(child).get('t')).toBe('dark');
476
508
 
477
509
  document.body.removeChild(parent);
478
510
  });
@@ -493,7 +525,8 @@ describe('@hyperfixi/reactivity — integration', () => {
493
525
  await runtime.execute(r.node!, ctx);
494
526
  await settle();
495
527
 
496
- expect(ctx.locals.get('v')).toBe(99);
528
+ // `:v` is element-scoped on `a` (the context element).
529
+ expect(getElementScopeMap(a).get('v')).toBe(99);
497
530
 
498
531
  document.body.removeChild(a);
499
532
  document.body.removeChild(b);
@@ -505,14 +538,15 @@ describe('@hyperfixi/reactivity — integration', () => {
505
538
  const el = document.createElement('div');
506
539
  document.body.appendChild(el);
507
540
  const ctx = createContext(el);
508
- ctx.locals.set('foo', 'initial');
541
+ // `:foo` is element-scoped (keyed by the context element).
542
+ getElementScopeMap(el).set('foo', 'initial');
509
543
 
510
- // Effect tracking the local read via the runtime path (so localReadHook fires).
544
+ // Effect tracking the element-scoped read via the runtime path (so localReadHook fires).
511
545
  let lastSeen: unknown = undefined;
512
546
  const stop = reactive.createEffect(
513
547
  async () => await runtime.execute(parse('set :v to :foo').node!, ctx),
514
548
  () => {
515
- lastSeen = ctx.locals.get('v');
549
+ lastSeen = getElementScopeMap(el).get('v');
516
550
  },
517
551
  el
518
552
  );