@nisli/core 0.57.0 → 0.57.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.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/diagnostics.ts", "../src/disposable.ts", "../src/signal.ts", "../src/context.ts", "../src/emitter.ts", "../src/injector.ts", "../src/element-context.ts", "../src/lifecycle.ts", "../src/component.ts", "../src/ref.ts", "../src/template-audit.ts", "../src/template.ts", "../src/projection.ts", "../src/settle.ts", "../src/query.ts", "../src/resource.ts", "../src/view-transition.ts"],
4
- "sourcesContent": ["/**\n * diagnostics.ts \u2014 coded diagnostics leaf + the dev-mode gate (ADR 0030.2, Wave 1)\n *\n * The shared foundation every core layer reports through. Two rules keep it a\n * LEAF (ADR 0030.2 \u00A77): zero imports from other core modules (so signal.ts,\n * template.ts, component.ts, injector.ts can all use it without cycles), and\n * codes + a minimal payload emitter only \u2014 no docs prose.\n *\n * Contract:\n * - Every diagnostic carries a stable machine code `N<range><nn>` and renders\n * as ONE console.error line: `[nisli CODE] message` (+ structured detail as\n * the second console argument when given). Thrown coded errors reuse the\n * same `[nisli CODE]` prefix via {@link formatDiag} so `grep '\\[nisli '`\n * finds every framework-reported failure, logged or thrown.\n * - `diag()` itself is NOT dev-gated: gating is the CALL SITE's policy. Some\n * diagnostics are production facts (T6 containment N401/N402 \u2014 parity with\n * the pre-T6 unconditional console.error); others are dev-only attribution\n * (N201/N202/N501) and their callers guard with {@link isDev}.\n *\n * Availability belongs to the artifact (ADR 0048). Bundler ESM leaves standard\n * NODE_ENV guards at each optional work site; the native browser artifacts\n * resolve them at publication. No process global is needed in either browser\n * artifact. The runtime override controls available diagnostics only: it cannot\n * resurrect instrumentation removed from a production artifact.\n */\n\n// \u2500\u2500 Code registry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// The minimal central code table (0030.1 B2, landed as part of T6 per \u00A78).\n// `Nxyz` = concrete code; `Nxxx` range keys document ownership so parallel\n// waves allocate without collision. Ranges owned by other Wave-1 worktrees\n// (template, reactivity, async) are seeded here as placeholders only \u2014 their\n// concrete codes land with their waves.\nexport const codes: Record<string, string> = {\n // Range placeholders \u2014 owner module in parentheses.\n N1xx: 'template: parse/static-audit diagnostics (template.ts \u2014 template wave)',\n N2xx: 'define/props: registration and prop-contract diagnostics (component.ts)',\n N3xx: 'reactivity: scheduler/purity diagnostics (signal.ts \u2014 scheduler wave)',\n N4xx: 'lifecycle: setup/mount containment (component.ts, lifecycle.ts)',\n N5xx: 'dependency injection (injector.ts)',\n N6xx: 'async: query/resource/settle diagnostics (query.ts, resource.ts \u2014 async wave)',\n // Assigned codes.\n N201: 'duplicate component definition \u2014 tag already defined; first definition stays live',\n N202: 'unknown-prop echo \u2014 prop written after mount but never read by setup()',\n N401: 'setup failed \u2014 scope contained, host stamped data-nisli-error=\"N401\"',\n N402: 'onMount failed \u2014 scope contained, host stamped data-nisli-error=\"N402\"',\n N501: 'provide() after the token was already instantiated \u2014 resetInjector() first',\n N101: 'template audit \u2014 dash-tag never defined (misspelled or unimported component?)',\n N102: 'template audit \u2014 unknown @event name',\n N103: 'template audit \u2014 unknown event modifier',\n N104: 'template audit \u2014 undeclared attribute on a component with declared attrs',\n N105: 'template \u2014 remounting a live bound TemplateResult (shared-binding corruption)',\n N106: 'template \u2014 html:inner requires a branded value: raw(), sanitized(), or TrustedHTML',\n N107: 'template \u2014 html:inner sanitized() has no sink: no native Element.setHTML() and no setSanitizerFallback() hook',\n N301: 'reactivity \u2014 effect exceeded the consecutive re-schedule cap (loop); disposed',\n N302: 'reactivity \u2014 effect wrote a signal in its own dependency set (attribution)',\n N303: 'reactivity \u2014 flush()/tick() iteration cap reached before quiescence',\n N310: 'reactivity \u2014 effect callback returned a Promise; use resource() for async',\n N602: 'query \u2014 invalid key element (flat primitives only; null is the optional sentinel)',\n N603: 'settle() \u2014 no quiescence within the iteration cap; returning anyway',\n // N601 (mixed QueryClients) was retired before release: N501 makes that\n // state unrepresentable at its cause. The number is not reused.\n};\n\n// \u2500\u2500 Dev gate \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nlet override: boolean | null = null;\n\n/** Runtime preference within this artifact's development capability. */\nexport function isDev(): boolean {\n return process.env.NODE_ENV !== 'production' && (override ?? true);\n}\n\n/**\n * Enable/suppress available development diagnostics, or restore the artifact's\n * default (`null`). A production artifact cannot re-enable removed diagnostics.\n */\nexport function setDevMode(on: boolean | null): void {\n if (process.env.NODE_ENV !== 'production') override = on;\n}\n\n// \u2500\u2500 Emission \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The shared `[nisli CODE] message` line, for both logged and thrown paths. */\nexport function formatDiag(code: string, message: string): string {\n return `[nisli ${code}] ${message}`;\n}\n\n/**\n * Emit one coded diagnostic: a single console.error line\n * `[nisli CODE] message`, with `detail` attached as structured payload.\n * NOT dev-gated here \u2014 the caller owns the policy (see module doc).\n */\nexport function diag(code: string, message: string, detail?: Record<string, unknown>): void {\n if (detail === undefined) {\n console.error(formatDiag(code, message));\n } else {\n console.error(formatDiag(code, message), detail);\n }\n}\n", "/** A disposal surface that exposes ERM when the consumer's lib supports it. */\ntype DisposeSymbol = typeof Symbol extends {\n readonly dispose: infer Key extends symbol;\n} ? Key : never;\n\nexport type DisposableResource = {\n [Key in DisposeSymbol]: () => void;\n};\n\n/** Callable disposer returned by effects, subscriptions, and emitter handles. */\nexport interface Disposer extends DisposableResource {\n (): void;\n}\n\nconst DISPOSE = Symbol.dispose as typeof Symbol.dispose | undefined;\n\n/** Attach a guarded Symbol.dispose alias without polyfilling the platform. */\nexport function disposable<T extends object>(\n value: T,\n dispose: () => void,\n): T & DisposableResource {\n if (DISPOSE) (value as Record<symbol, () => void>)[DISPOSE] = dispose;\n return value as T & DisposableResource;\n}\n", "/**\n * signal.ts \u2014 Reactive primitives: signal(), computed(), effect()\n *\n * Push-pull hybrid model:\n * - Writes push dirty flags up the dependency graph in two flavors: a signal\n * write pushes Dirty (the value definitely changed), a computed propagates\n * MaybeDirty (recompute to find out). Flags never downgrade.\n * - Reads pull fresh values lazily (computed only recalculates when read)\n * - Multiple synchronous writes coalesce into one microtask flush\n *\n * Scheduler invariants (ADR 0030.2 T5):\n * - An effect re-runs iff a value it read changed. Before a MaybeDirty\n * effect runs, its computed sources are polled (recomputed via the\n * node\u2192impl back-pointer); if no source's change-epoch advanced past the\n * effect's last completed run, the run is skipped. A computed's\n * change-epoch also bumps on every error-state TRANSITION (enter and\n * exit), so effects never skip across error entry or equal-value recovery\n * (issue 0003 containment happens at the effect's own read).\n * - Pending effects flush in creation order (monotonic index), so identical\n * writes produce identical run order. Documented cost: a later-created\n * writer effect costs one deterministic extra run vs. topological order.\n * - The loop guard is clock-free: an effect that re-schedules ITSELF on\n * MAX_EFFECT_RERUNS consecutive runs is diagnosed (N301) and disposed.\n *\n * Dependency tracking is automatic: reading a signal inside a computed\n * or effect registers it as a dependency. Dependencies are re-tracked\n * on every execution (dynamic/conditional tracking).\n */\n\n// \u2500\u2500 Late-bound context hook for auto-disposal \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Avoids circular dependency: context.ts imports nothing from signal.ts,\n// but signal.ts needs to check for component context to auto-dispose effects.\n// component.ts wires this up at import time via `setContextHook()`.\n\nlet contextHook: (() => ((fn: () => void) => void) | null) | null = null;\n\n/**\n * Register the context hook. Called by component.ts at module init.\n * The hook returns an `addDisposer` function if inside setup context, null otherwise.\n */\nexport function setContextHook(hook: () => ((fn: () => void) => void) | null): void {\n contextHook = hook;\n}\n\n// \u2500\u2500 Brand symbol for signal detection in templates \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport const SIGNAL_BRAND = Symbol.for('backlog.signal');\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Readable reactive container. */\nexport interface ReadonlySignal<T> {\n readonly [SIGNAL_BRAND]: true;\n readonly value: T;\n /** Subscribe to value changes. Returns unsubscribe function. */\n subscribe(fn: (value: T) => void): Disposer;\n /**\n * Read the current value WITHOUT registering a dependency.\n * Equivalent to reading inside `untrack()`. On a computed this still\n * pulls a fresh value (and rethrows a cached error) \u2014 it only skips\n * dependency registration.\n */\n peek(): T;\n}\n\n/** Read-write reactive container. */\nexport interface Signal<T> extends ReadonlySignal<T> {\n value: T;\n}\n\n// \u2500\u2500 Internal tracking state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The currently executing reactive context (computed or effect).\n * When non-null, any signal read during execution is recorded as a dependency.\n */\nlet activeObserver: ReactiveNode | null = null;\n\n/**\n * The effect whose fn frame is currently executing. Unlike activeObserver\n * (which switches to a computed during its recompute, and to null under\n * untrack()), this stays pinned to the running effect \u2014 it exists solely to\n * attribute writes to the effect that performed them (N302).\n */\nlet runningEffect: EffectNode | null = null;\n\n/**\n * Global epoch counter. Incremented on every observable change: a signal\n * write, a computed recomputing to a different value, and a computed's\n * error-state transitions (enter and exit). A node's `lastChanged` epoch is\n * compared against an observer's last-validated/last-run epoch to decide\n * staleness.\n */\nlet globalEpoch = 0;\n\n/** Monotonic effect creation index \u2014 pending effects flush in this order. */\nlet nextEffectOrder = 0;\n\n// \u2500\u2500 Dev diagnostics \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Reporting goes through the diagnostics leaf (its dev gate governs);\n// guard BEHAVIOR (loop disposal, rejection containment) is never gated \u2014\n// only the reporting. Assigned codes: N301 effect loop, N302\n// write-in-own-effect, N303 flush/tick cap, N310 effect(async).\n\nimport { diag as emitDiag, isDev } from './diagnostics.js';\nimport { disposable, type Disposer } from './disposable.js';\n\nexport type { Disposer } from './disposable.js';\n\nfunction diag(code: string, message: string, detail?: object): void {\n if (!isDev()) return;\n emitDiag(code, message, detail as Record<string, unknown> | undefined);\n}\n\n// \u2500\u2500 Effect scheduling \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst pendingEffects = new Set<EffectNode>();\nlet flushScheduled = false;\n\nfunction scheduleFlush(): void {\n if (!flushScheduled) {\n flushScheduled = true;\n queueMicrotask(flushPendingEffects);\n }\n}\n\nfunction flushPendingEffects(): void {\n flushScheduled = false;\n // Copy to avoid mutation during iteration; sort by creation index so\n // identical writes produce identical run order forever (ADR 0030.2 T5).\n const effects = [...pendingEffects].sort((a, b) => a.order - b.order);\n pendingEffects.clear();\n for (const effect of effects) {\n if (!effect.disposed) {\n runEffect(effect);\n }\n }\n}\n\n// \u2500\u2500 Dependency graph node types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst enum NodeState {\n Clean = 0,\n MaybeDirty = 1, // A computed source may have changed \u2014 poll before acting\n Dirty = 2, // A signal source definitely changed \u2014 must recompute/run\n}\n\n/** Notification flavor: Dirty from signal writes, MaybeDirty through computeds. */\ntype DirtyFlavor = NodeState.MaybeDirty | NodeState.Dirty;\n\nconst NO_COMPUTED_ERROR = Symbol('no-computed-error');\n\ninterface ReactiveNode {\n state: NodeState;\n /** Signals/computeds this node reads from */\n sources: Set<SignalNode<unknown> | ComputedNode<unknown>>;\n /** Called when a source changes. Never downgrades an existing dirtier state. */\n notify(flavor: DirtyFlavor): void;\n}\n\n// \u2500\u2500 Signal (writable) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface SignalNode<T> {\n value: T;\n lastChanged: number;\n observers: Set<ReactiveNode>;\n}\n\nclass SignalImpl<T> implements Signal<T> {\n readonly [SIGNAL_BRAND] = true as const;\n /** @internal */\n _node: SignalNode<T>;\n\n constructor(initialValue: T) {\n this._node = {\n value: initialValue,\n lastChanged: globalEpoch,\n observers: new Set(),\n };\n }\n\n get value(): T {\n // Track dependency if inside a reactive context\n if (activeObserver) {\n activeObserver.sources.add(this._node);\n this._node.observers.add(activeObserver);\n }\n return this._node.value;\n }\n\n set value(newValue: T) {\n if (Object.is(this._node.value, newValue)) return;\n // N302: write-in-own-sources \u2014 the running effect wrote a signal it also\n // reads this run, so this write re-triggers it. Attribution-only (never\n // disposes; the loop guard owns disposal). Placed AFTER the Object.is\n // cutoff so certified converging writers \u2014 registry reflect effects,\n // each() item-signal reuse \u2014 never warn on equal-value writes.\n if (\n process.env.NODE_ENV !== 'production' && isDev() &&\n runningEffect !== null &&\n runningEffect.sources.has(this._node as SignalNode<unknown>)\n ) {\n diag(\n 'N302',\n 'Effect wrote to a signal it also reads \u2014 the write re-schedules the ' +\n 'effect. If this does not converge to an equal value it is an ' +\n 'infinite loop. Derive the value with computed() instead.',\n runningEffect.createdAt ? { effect: runningEffect.createdAt } : undefined,\n );\n }\n this._node.value = newValue;\n this._node.lastChanged = ++globalEpoch;\n notifyObservers(this._node.observers, NodeState.Dirty);\n }\n\n peek(): T {\n return this._node.value;\n }\n\n subscribe(fn: (value: T) => void): Disposer {\n return effect(() => {\n const value = this.value;\n // A subscription depends on THIS signal only. Reads performed by the\n // consumer callback are observational work, not reactive dependencies\n // of the subscription itself (issue 0004).\n untrack(() => fn(value));\n });\n }\n}\n\nfunction notifyObservers(observers: Set<ReactiveNode>, flavor: DirtyFlavor): void {\n for (const observer of observers) {\n observer.notify(flavor);\n }\n}\n\n// \u2500\u2500 Computed (derived, lazy, cached) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface ComputedNode<T> {\n value: T;\n lastChanged: number;\n observers: Set<ReactiveNode>;\n /**\n * Back-pointer into the owning ComputedImpl (ADR 0030.2 \u00A78 T5): recompute\n * this computed if stale, WITHOUT dependency tracking. Lets an effect's\n * pre-run poll refresh a computed source's change-epoch. Throws the\n * computed's (possibly cached) error.\n */\n pull(): void;\n}\n\nclass ComputedImpl<T> implements ReadonlySignal<T> {\n readonly [SIGNAL_BRAND] = true as const;\n /** @internal */\n _node: ComputedNode<T>;\n\n private compute: () => T;\n private state: NodeState = NodeState.Dirty; // Start dirty so first read computes\n private sources = new Set<SignalNode<unknown> | ComputedNode<unknown>>();\n private computing = false;\n private error: unknown = NO_COMPUTED_ERROR;\n /**\n * globalEpoch snapshot at the end of the last update()/validation pass.\n * A MaybeDirty computed recomputes only if some source's lastChanged\n * advanced past this \u2014 otherwise it revalidates to Clean for free.\n */\n private lastValidated = 0;\n\n constructor(fn: () => T) {\n this.compute = fn;\n this._node = {\n value: undefined as T,\n lastChanged: 0,\n observers: new Set(),\n pull: () => { this.peek(); },\n };\n }\n\n get value(): T {\n if (this.computing) {\n throw new Error('Circular dependency detected in computed()');\n }\n\n // Track dependency if inside a reactive context\n if (activeObserver) {\n activeObserver.sources.add(this._node as ComputedNode<unknown>);\n this._node.observers.add(activeObserver);\n }\n\n // Pull: recalculate if (maybe) dirty\n if (this.state !== NodeState.Clean) {\n this.update();\n }\n\n if (this.error !== NO_COMPUTED_ERROR) {\n throw this.error;\n }\n\n return this._node.value;\n }\n\n peek(): T {\n if (this.computing) {\n throw new Error('Circular dependency detected in computed()');\n }\n // Same pull as `get value`, minus dependency registration.\n if (this.state !== NodeState.Clean) {\n this.update();\n }\n if (this.error !== NO_COMPUTED_ERROR) {\n throw this.error;\n }\n return this._node.value;\n }\n\n /**\n * MaybeDirty validation: pull each source (computeds recompute lazily) and\n * report whether any source's change-epoch advanced past our last\n * validation. A pulled source may throw \u2014 its error-state transition\n * already bumped its change-epoch, so the epoch comparison decides.\n */\n private sourcesChanged(): boolean {\n for (const source of this.sources) {\n if ('pull' in source) {\n try { source.pull(); } catch (_) { /* transition bumped lastChanged */ }\n }\n if (source.lastChanged > this.lastValidated) return true;\n }\n return false;\n }\n\n private update(): void {\n // MaybeDirty means \"an upstream computed MAY have changed\". Validate\n // first: if no polled source advanced, revalidate to Clean without\n // recomputing (the half of push-pull that was previously unimplemented).\n if (this.state === NodeState.MaybeDirty && !this.sourcesChanged()) {\n this.state = NodeState.Clean;\n this.lastValidated = globalEpoch;\n return;\n }\n\n // Unsubscribe from previous sources (for dynamic dependency tracking)\n for (const source of this.sources) {\n source.observers.delete(this as unknown as ReactiveNode);\n }\n this.sources.clear();\n\n // Run compute with tracking\n const prevObserver = activeObserver;\n activeObserver = this as unknown as ReactiveNode;\n this.computing = true;\n const wasError = this.error !== NO_COMPUTED_ERROR;\n try {\n const newValue = this.compute();\n this.error = NO_COMPUTED_ERROR;\n if (!Object.is(this._node.value, newValue)) {\n this._node.value = newValue;\n this._node.lastChanged = ++globalEpoch;\n // NOTE: no notifyObservers() here. This update() is a *lazy* recompute\n // triggered by a read; every downstream observer was already marked\n // dirty / scheduled eagerly when the source signal changed (notify()\n // propagates through the computed chain). Re-notifying here would\n // re-schedule the very effect performing this read \u2014 a spurious\n // double-run that only surfaced once flush() began draining cascades.\n } else if (wasError) {\n // Error-state TRANSITION (exit) recovering to an EQUAL value: the\n // epoch must still advance, or downstream effects would skip the\n // recovery in their pre-run poll (ADR 0030.2 \u00A78 T5 error rule).\n this._node.lastChanged = ++globalEpoch;\n }\n } catch (error) {\n this.error = error;\n if (!wasError) {\n // Error-state TRANSITION (enter) counts as a change: polls must see\n // the epoch advance so the effect re-runs and its own read rethrows\n // into the effect's containment (issue 0003 semantics).\n this._node.lastChanged = ++globalEpoch;\n }\n throw error;\n } finally {\n this.computing = false;\n activeObserver = prevObserver;\n // A failed computed remains in an error state, but it must look clean to\n // notify(): the next dependency write then marks it dirty and propagates\n // to downstream observers so the computation can recover (issue 0003).\n this.state = NodeState.Clean;\n this.lastValidated = globalEpoch;\n }\n }\n\n /** @internal \u2014 called by the ReactiveNode interface when a source changes */\n notify(flavor: DirtyFlavor): void {\n // Never downgrade: a Dirty mark (definite signal change) survives a\n // later MaybeDirty from a parallel computed path.\n if (flavor > this.state) {\n const wasClean = this.state === NodeState.Clean;\n this.state = flavor;\n // Propagate once per dirty episode. Downstream observers always get\n // MaybeDirty \u2014 through a computed, \"changed\" is only knowable after a\n // recompute, which stays lazy (pull-based).\n if (wasClean) {\n notifyObservers(this._node.observers, NodeState.MaybeDirty);\n }\n }\n }\n\n subscribe(fn: (value: T) => void): Disposer {\n return effect(() => {\n const value = this.value;\n untrack(() => fn(value));\n });\n }\n\n // ReactiveNode interface \u2014 used by dependency tracking\n get sources_(): Set<SignalNode<unknown> | ComputedNode<unknown>> {\n return this.sources;\n }\n}\n\n// Make ComputedImpl satisfy ReactiveNode for the dependency tracker\nObject.defineProperty(ComputedImpl.prototype, 'sources', {\n enumerable: false,\n});\n\n// \u2500\u2500 Effect (side-effect, auto-tracks, auto-disposes) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Maximum CONSECUTIVE self-re-schedules before we assume an infinite loop.\n * An effect that writes to a signal it reads re-schedules itself on every\n * run; when that happens MAX_EFFECT_RERUNS times in a row (the counter\n * resets whenever a run does NOT re-schedule the effect), the effect is\n * diagnosed (N301) and disposed. Clock-free \u2014 deterministic under CI and\n * fake timers, and convergent clamps pass because their second run writes\n * an equal value (Object.is cutoff \u2192 no re-schedule \u2192 counter reset).\n * See ADR 0008 Gap 2 / ADR 0009 / ADR 0030.2 T5.\n */\nconst MAX_EFFECT_RERUNS = 100;\n\ninterface EffectNode extends ReactiveNode {\n fn: () => void | (() => void);\n cleanup: (() => void) | null;\n disposed: boolean;\n sources: Set<SignalNode<unknown> | ComputedNode<unknown>>;\n /** List of dispose callbacks registered by the component */\n disposers: (() => void)[];\n /** Monotonic creation index \u2014 flush order (deterministic scheduler) */\n order: number;\n /** globalEpoch snapshot at the end of the last completed run */\n lastRunEpoch: number;\n /** Consecutive runs that re-scheduled this effect (clock-free loop guard) */\n selfReschedules: number;\n /** Dev-captured creation-site stack \u2014 effect identity for N301/N302 */\n createdAt?: string;\n /** N310 (async effect) already reported for this effect */\n asyncWarned?: boolean;\n}\n\nfunction createEffectNode(fn: () => void | (() => void)): EffectNode {\n return {\n state: NodeState.Dirty,\n fn,\n cleanup: null,\n disposed: false,\n sources: new Set(),\n disposers: [],\n order: nextEffectOrder++,\n lastRunEpoch: 0,\n selfReschedules: 0,\n notify(flavor: DirtyFlavor) {\n if (this.disposed) return;\n // Never downgrade Dirty (definite signal change) to MaybeDirty.\n if (flavor > this.state) this.state = flavor;\n pendingEffects.add(this);\n scheduleFlush();\n },\n };\n}\n\n/**\n * Pre-run poll (ADR 0030.2 T5): the effect was notified MaybeDirty, meaning\n * only computed sources MAY have changed. Pull each computed source (via the\n * node back-pointer) so its change-epoch is fresh, then compare every\n * source's epoch against the effect's last completed run. A pull may throw:\n * the computed's error-state transition already bumped its epoch, so the\n * comparison decides \u2014 a NEW error re-runs the effect (whose own read\n * rethrows into its containment, issue 0003), while an error the effect\n * already observed does not.\n */\nfunction effectSourcesChanged(node: EffectNode): boolean {\n for (const source of node.sources) {\n if ('pull' in source) {\n try { source.pull(); } catch (_) { /* transition bumped lastChanged */ }\n }\n if (source.lastChanged > node.lastRunEpoch) return true;\n }\n return false;\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\nfunction runEffect(node: EffectNode): void {\n if (node.disposed) return;\n\n // MaybeDirty: poll sources \u2014 skip the run when no value the effect read\n // actually changed (equal recomputes through a computed chain stop here).\n if (node.state === NodeState.MaybeDirty && !effectSourcesChanged(node)) {\n node.state = NodeState.Clean;\n return;\n }\n\n // Run cleanup from previous execution\n if (node.cleanup) {\n try { node.cleanup(); } catch (_) { /* cleanup errors are swallowed */ }\n node.cleanup = null;\n }\n\n // Unsubscribe from previous sources\n for (const source of node.sources) {\n source.observers.delete(node);\n }\n node.sources.clear();\n\n // Reset state BEFORE running: a notify fired by the effect's own writes\n // must survive into the next flush pass, not be clobbered afterwards.\n node.state = NodeState.Clean;\n\n // Run effect with tracking\n const prevObserver = activeObserver;\n const prevRunning = process.env.NODE_ENV !== 'production' ? runningEffect : null;\n activeObserver = node;\n if (process.env.NODE_ENV !== 'production') runningEffect = node;\n try {\n const result: unknown = node.fn();\n if (typeof result === 'function') {\n node.cleanup = result as () => void;\n } else if (isThenable(result)) {\n // effect(async \u2026) \u2014 rejected at the type level, guarded at runtime for\n // JS callers (ADR 0030.2 \u00A73). The Promise is NOT a cleanup; route its\n // rejection into the effect error path so nothing goes unhandled.\n if (process.env.NODE_ENV !== 'production' && isDev() && !node.asyncWarned) {\n node.asyncWarned = true;\n diag(\n 'N310',\n 'effect() callback returned a Promise \u2014 effects must be synchronous. ' +\n 'Async state belongs in resource(). The returned Promise is not a ' +\n 'cleanup function; its rejection is contained by the effect error path.',\n node.createdAt ? { effect: node.createdAt } : undefined,\n );\n }\n result.then(undefined, (err: unknown) => {\n console.error('Effect error:', err);\n });\n }\n } catch (err) {\n // Effect errors: log but don't crash the system.\n // The effect is NOT disposed \u2014 it may succeed on next signal change.\n console.error('Effect error:', err);\n } finally {\n activeObserver = prevObserver;\n if (process.env.NODE_ENV !== 'production') runningEffect = prevRunning;\n // Everything observable up to now \u2014 including epochs bumped by this\n // run's own lazy computed pulls \u2014 counts as SEEN by this run.\n node.lastRunEpoch = globalEpoch;\n }\n\n // Clock-free loop guard: this run re-scheduled the effect iff the effect\n // is back in the pending set (only its own writes can do that mid-run).\n if (pendingEffects.has(node)) {\n if (++node.selfReschedules > MAX_EFFECT_RERUNS) {\n if (process.env.NODE_ENV !== 'production' && isDev()) diag(\n 'N301',\n `Effect exceeded maximum re-run limit (${MAX_EFFECT_RERUNS}). ` +\n `This usually means the effect writes to a signal it reads. ` +\n `The effect has been disposed to prevent a UI freeze.`,\n node.createdAt ? { effect: node.createdAt } : undefined,\n );\n // Dispose as today: unsubscribe everywhere and drop from the queue.\n node.disposed = true;\n for (const source of node.sources) {\n source.observers.delete(node);\n }\n node.sources.clear();\n pendingEffects.delete(node);\n }\n } else {\n node.selfReschedules = 0;\n }\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Create a writable reactive signal.\n *\n * ```ts\n * const count = signal(0);\n * count.value; // read (auto-tracks in reactive contexts)\n * count.value = 5; // write (notifies dependents)\n * count.peek(); // read WITHOUT tracking\n * ```\n */\nexport function signal<T>(initialValue: T): Signal<T> {\n return new SignalImpl(initialValue);\n}\n\n/**\n * Create a derived, lazy, cached computed signal.\n * Re-evaluates only when dependencies change AND the value is read.\n *\n * ```ts\n * const doubled = computed(() => count.value * 2);\n * doubled.value; // lazy evaluation\n * ```\n */\nexport function computed<T>(fn: () => T): ReadonlySignal<T> {\n return new ComputedImpl(fn);\n}\n\n/**\n * Type-level rejection of async callbacks: a Promise-returning fn makes the\n * call require an impossible second argument, so `effect(async () => {})`\n * fails to compile. Async work belongs in resource() (ADR 0030.2 \u00A73; N310).\n */\ntype SyncEffectGuard<R> = [R] extends [Promise<unknown>]\n ? [error: 'effect() callbacks must be synchronous \u2014 async work belongs in resource() (nisli N310)']\n : [];\n\n/**\n * Create a side-effect that re-runs when its dependencies change.\n * Returns a dispose function to stop the effect.\n *\n * The effect function may return a cleanup callback that runs\n * before each re-execution and on disposal. It must be SYNCHRONOUS \u2014\n * async functions are rejected at the type level and diagnosed at\n * runtime (N310); async state belongs in resource().\n *\n * ```ts\n * const dispose = effect(() => {\n * console.log('count is', count.value);\n * return () => { // cleanup\n * console.log('cleaning up');\n * };\n * });\n * dispose(); // stop the effect\n * ```\n */\nexport function effect<R>(fn: () => R, ..._rejectAsync: SyncEffectGuard<R>): Disposer {\n const node = createEffectNode(fn as unknown as () => void | (() => void));\n if (process.env.NODE_ENV !== 'production' && isDev()) {\n // Dev-captured effect identity: N301/N302 diagnostics name this site.\n node.createdAt = new Error('effect() created here').stack;\n }\n // Run immediately to establish initial dependencies\n runEffect(node);\n\n const dispose = () => {\n node.disposed = true;\n // Run final cleanup\n if (node.cleanup) {\n try { node.cleanup(); } catch (_) { /* swallow */ }\n node.cleanup = null;\n }\n // Unsubscribe from all sources\n for (const source of node.sources) {\n source.observers.delete(node);\n }\n node.sources.clear();\n pendingEffects.delete(node);\n };\n\n // Auto-dispose when inside component setup context\n if (contextHook) {\n const addDisposer = contextHook();\n if (addDisposer) {\n addDisposer(dispose);\n }\n }\n\n return disposable(dispose, dispose);\n}\n\n/**\n * Check if a value is a signal (writable or computed).\n * Used by the template engine to detect signals in expression slots.\n */\nexport function isSignal(value: unknown): value is ReadonlySignal<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n SIGNAL_BRAND in (value as Record<symbol, unknown>)\n );\n}\n\n// \u2500\u2500 Observer isolation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Run a function with activeObserver set to null, preventing any\n * signal reads inside `fn` from being tracked by an outer effect,\n * and return the function's result.\n *\n * Used by component.ts to isolate connectedCallback: child component\n * setup signal reads must not leak into a parent effect's dependency\n * set. See ADR 0008 Gap 1.\n */\nexport function untrack<T>(fn: () => T): T {\n const prev = activeObserver;\n activeObserver = null;\n try {\n return fn();\n } finally {\n activeObserver = prev;\n }\n}\n\n// \u2500\u2500 Synchronous flush \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Synchronously execute all pending effects.\n *\n * In normal usage, effects run automatically on the next microtask.\n * Use flush() only when you need effects to have executed before\n * the next line \u2014 e.g., imperative DOM measurement after state change.\n *\n * flush() is idempotent: calling it with no pending effects is a no-op.\n */\nexport function flush(): void {\n // Drain cascades: an effect may write a signal that schedules more effects\n // (e.g. A computes \u2192 B renders). Loop until the queue is empty so a single\n // flush() settles the whole synchronous cascade \u2014 no double-flush idiom.\n // Bounded to mirror the effect-loop guard; a runaway is a bug, not silence.\n let guard = 0;\n while (pendingEffects.size > 0) {\n flushPendingEffects();\n if (++guard > 100000) {\n if (process.env.NODE_ENV !== 'production' && isDev()) diag(\n 'N303',\n 'flush() cascade cap reached (100000 passes) \u2014 effects keep ' +\n 'scheduling more effects (a cross-effect write cycle?). Breaking out ' +\n 'to avoid a freeze; pending work remains unflushed.',\n );\n break;\n }\n }\n}\n\n/** Backward compat alias for tests. */\nexport { flush as flushEffects };\n\n/**\n * Settle the synchronous effect cascade AND all MICROTASK-scheduled work\n * pending at await time (content-projection sweeps, query/command initial\n * passes \u2014 at any queueMicrotask depth), plus the effects that work\n * schedules. Replaces the hand-rolled `flush(); await Promise.resolve();\n * flush()` and double-`flushEffects()` idioms.\n *\n * Bounded contract \u2014 deliberately NOT awaited: timers and other future\n * TASKS scheduled by that microtask work (e.g. a microtask calling\n * setTimeout) may fire after tick() resolves; awaiting arbitrary future\n * tasks is unbounded. Self-perpetuating schedulers are cut off at the\n * iteration cap (loudly \u2014 N303).\n *\n * ```ts\n * host.setProp('x', 1);\n * await tick();\n * expect(el.textContent).toBe('1');\n * ```\n */\nexport async function tick(): Promise<void> {\n flush(); // drain the synchronous effect cascade first\n // Each iteration crosses a MACROTASK boundary (setTimeout 0). Doing so runs\n // the ENTIRE microtask queue to completion first \u2014 including microtasks a\n // microtask schedules, at any depth \u2014 so a 3-deep `queueMicrotask` chain is\n // fully drained before the timer fires. After the drain we flush the effects\n // that work scheduled. When a full iteration schedules no effects, the queue\n // is quiescent and we return. Contract: microtask-scheduled work + effect\n // cascades pending at await time settle; TIMER-scheduled work does not\n // (see the doc above \u2014 bounded by design). The iteration cap is a\n // documented backstop for self-perpetuating schedulers, not a silent hang.\n for (let i = 0; i < 50; i++) {\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n if (pendingEffects.size === 0) return; // the microtask drain scheduled nothing\n flush();\n }\n if (process.env.NODE_ENV !== 'production' && isDev()) diag(\n 'N303',\n 'tick() iteration cap (50) reached with effects still pending \u2014 ' +\n 'something keeps scheduling reactive work every task (a ' +\n 'self-perpetuating scheduler?). Returning with work still queued.',\n );\n}\n", "/**\n * context.ts \u2014 Setup context for pure function DI\n *\n * The setup context lets pure functions (inject(), listen(), effect())\n * access the component they belong to without needing `this`.\n *\n * The context exists ONLY during component initialization (setup()).\n * It is NOT a runtime thing \u2014 it's a synchronous initialization-time concept.\n *\n * Same pattern as Angular's inject(), Solid's createSignal(), Vue's setup().\n */\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Minimal interface for a component host. component.ts provides the\n * full implementation; this file only needs the disposal hook.\n */\nexport interface ComponentHost {\n /** Register a cleanup function to run on disconnectedCallback */\n addDisposer(fn: () => void): void;\n /** The raw HTMLElement */\n element: HTMLElement;\n}\n\n// \u2500\u2500 Context state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nlet currentComponent: ComponentHost | null = null;\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Run a function with a component as the active context.\n * Pure functions called during `fn` can access the component via\n * `getCurrentComponent()`.\n *\n * Context is strictly synchronous \u2014 it does NOT survive across\n * await boundaries or microtasks.\n */\nexport function runWithContext(component: ComponentHost, fn: () => void): void {\n const prev = currentComponent;\n currentComponent = component;\n try {\n fn();\n } finally {\n currentComponent = prev;\n }\n}\n\n/**\n * Get the currently active component host.\n * Throws if called outside a setup() context.\n *\n * This is framework-internal \u2014 component authors use inject(), effect(),\n * etc., which call this internally.\n */\nexport function getCurrentComponent(): ComponentHost {\n if (!currentComponent) {\n throw new Error(\n 'getCurrentComponent() called outside setup(). ' +\n 'inject(), effect(), and other context-dependent functions ' +\n 'can only be called during component initialization.'\n );\n }\n return currentComponent;\n}\n\n/**\n * Check if there is an active setup context.\n * Returns true during component setup, false otherwise.\n */\nexport function hasContext(): boolean {\n return currentComponent !== null;\n}\n", "/**\n * emitter.ts \u2014 Typed pub/sub base class for services.\n *\n * Replaces `document.dispatchEvent(new CustomEvent(...))` with typed,\n * scoped event emitters. Services extend Emitter<T> where T defines\n * the event contract as a record of event names \u2192 payload types.\n *\n * ```ts\n * class NavigationEvents extends Emitter<{\n * select: { id: string };\n * filter: { filter: string };\n * }> {}\n *\n * const nav = inject(NavigationEvents);\n * nav.emit('select', { id: 'TASK-1' }); // typed\n * nav.on('select', ({ id }) => console.log(id)); // typed\n * const selectedId = nav.toSignal('select', e => e.id, null);\n * ```\n */\n\nimport { signal, type Signal } from './signal.js';\nimport { hasContext, getCurrentComponent } from './context.js';\nimport { disposable, type Disposer } from './disposable.js';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ntype EventMap = Record<string, unknown>;\ntype Listener<T> = (payload: T) => void;\n\n// \u2500\u2500 Emitter base class \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport class Emitter<Events extends EventMap> {\n private listeners = new Map<keyof Events, Set<Listener<any>>>();\n\n /**\n * Emit a typed event. All subscribers for this event name are called\n * synchronously. If a subscriber throws, other subscribers still fire.\n */\n emit<K extends keyof Events>(event: K, payload: Events[K]): void {\n const set = this.listeners.get(event);\n if (!set) return;\n\n // Iterate a copy to allow unsubscribe during callback\n for (const fn of [...set]) {\n try {\n fn(payload);\n } catch (err) {\n console.error(`Emitter: subscriber for '${String(event)}' threw:`, err);\n }\n }\n }\n\n /**\n * Subscribe to a typed event. Returns an unsubscribe function.\n *\n * If called during component setup, the subscription is automatically\n * disposed on disconnectedCallback.\n */\n on<K extends keyof Events>(event: K, fn: Listener<Events[K]>): Disposer {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(fn);\n\n const unsubscribe = () => {\n set!.delete(fn);\n if (set!.size === 0) {\n this.listeners.delete(event);\n }\n };\n\n // Auto-dispose if inside component setup context\n if (hasContext()) {\n getCurrentComponent().addDisposer(unsubscribe);\n }\n\n return disposable(unsubscribe, unsubscribe);\n }\n\n /**\n * Bridge an event into the signal system.\n * Returns a signal that updates whenever the event fires.\n *\n * @param event - Event name to subscribe to\n * @param selector - Transform the payload into the signal value\n * @param initial - Initial signal value before any event fires\n */\n toSignal<K extends keyof Events, V>(\n event: K,\n selector: (payload: Events[K]) => V,\n initial: V,\n ): Signal<V> {\n const s = signal(initial);\n this.on(event, (payload) => {\n s.value = selector(payload);\n });\n return s;\n }\n\n /**\n * Remove all subscribers. Useful for testing cleanup.\n */\n clear(): void {\n this.listeners.clear();\n }\n}\n", "/**\n * injector.ts \u2014 Dependency injection: inject(), provide(), class-as-token\n *\n * Two key insights from Angular's evolution:\n * 1. The class IS the token \u2014 no createToken() needed for 99% of cases\n * 2. provide() is optional \u2014 inject() auto-creates singletons on first call\n *\n * ```ts\n * class BacklogAPI {\n * async getTasks(): Promise<Task[]> { ... }\n * }\n *\n * // In component setup:\n * const api = inject(BacklogAPI); // auto-created singleton\n *\n * // In tests:\n * provide(BacklogAPI, () => new MockAPI());\n * ```\n */\n\nimport { hasContext, getCurrentComponent } from './context.js';\nimport { formatDiag, isDev } from './diagnostics.js';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Any class constructor \u2014 used as both the token and the type. */\nexport type Constructor<T = unknown> = new (...args: any[]) => T;\n\n/** Opaque token for non-class dependencies (config objects, primitives). */\nexport interface InjectionToken<T> {\n readonly __brand: 'InjectionToken';\n readonly name: string;\n /** @internal default factory */\n _factory?: () => T;\n}\n\n// \u2500\u2500 Global singleton registry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Stores singleton instances keyed by constructor or token. */\nconst singletonCache = new Map<Constructor | InjectionToken<unknown>, unknown>();\n\n/** Stores factory overrides from provide(). */\nconst factoryOverrides = new Map<Constructor | InjectionToken<unknown>, () => unknown>();\n\n/** Tracks which constructors are currently being instantiated (circular detection). */\nconst instantiating = new Set<Constructor | InjectionToken<unknown>>();\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Get or create a singleton instance of the given class.\n *\n * On first call: creates the instance via `new Class()` (or the\n * factory from provide(), if one exists). On subsequent calls:\n * returns the same instance.\n *\n * Can be called inside or outside component setup context.\n * When inside, the inject result is available for the component's lifetime.\n */\nexport function inject<T>(token: Constructor<T>): T;\nexport function inject<T>(token: InjectionToken<T>): T;\nexport function inject<T>(token: Constructor<T> | InjectionToken<T>): T {\n // Check cache first\n if (singletonCache.has(token)) {\n return singletonCache.get(token) as T;\n }\n\n // Circular dependency detection\n if (instantiating.has(token)) {\n const name = typeof token === 'function' ? token.name : (token as InjectionToken<T>).name;\n throw new Error(\n `Circular dependency detected when instantiating '${name}'. ` +\n 'Check your service constructors for circular inject() calls.'\n );\n }\n\n instantiating.add(token);\n try {\n let instance: T;\n\n // Check for factory override\n const factory = factoryOverrides.get(token as Constructor | InjectionToken<unknown>);\n if (factory) {\n instance = factory() as T;\n } else if (typeof token === 'function') {\n // Class token \u2014 auto-create via constructor\n instance = new (token as Constructor<T>)();\n } else {\n // InjectionToken with default factory\n const injToken = token as InjectionToken<T>;\n if (injToken._factory) {\n instance = injToken._factory();\n } else {\n throw new Error(\n `No provider found for token '${injToken.name}'. ` +\n 'Use provide() to register a factory before calling inject().'\n );\n }\n }\n\n singletonCache.set(token as Constructor | InjectionToken<unknown>, instance);\n return instance;\n } finally {\n instantiating.delete(token);\n }\n}\n\n/**\n * Register a factory override for a class or token.\n * The factory will be called on the next inject() if no cached instance exists.\n *\n * Call provide() before the first inject() of that token. Once a token has\n * been instantiated the injector is FROZEN for it (dev, coded error N501):\n * everything that already injected holds the old instance while later\n * inject() calls would get the new one \u2014 a silent mixed-instance split\n * (ADR 0030.2 \u00A73). `resetInjector()` is the escape hatch (tests use it).\n * Production keeps the historical silent replace so a live page never breaks\n * over an ordering issue that dev already surfaced.\n */\nexport function provide<T>(token: Constructor<T>, factory: () => T): void;\nexport function provide<T>(token: InjectionToken<T>, factory: () => T): void;\nexport function provide<T>(token: Constructor<T> | InjectionToken<T>, factory: () => T): void {\n if (process.env.NODE_ENV !== 'production' && isDev() && singletonCache.has(token as Constructor | InjectionToken<unknown>)) {\n const name = typeof token === 'function' ? token.name : (token as InjectionToken<T>).name;\n throw new Error(formatDiag(\n 'N501',\n `provide(${name}) after '${name}' was already instantiated \u2014 existing `\n + `consumers keep the old instance while new inject() calls would get the `\n + `new one (mixed-instance split). Call resetInjector() first (tests), or `\n + `provide() before the first inject().`,\n ));\n }\n factoryOverrides.set(token as Constructor | InjectionToken<unknown>, factory);\n // Remove cached instance so next inject() uses the new factory\n singletonCache.delete(token as Constructor | InjectionToken<unknown>);\n}\n\n/**\n * Create an injection token for non-class dependencies.\n * Use this for config objects, primitives, or interfaces.\n *\n * ```ts\n * const AppConfig = createToken<{ apiUrl: string }>('AppConfig');\n * provide(AppConfig, () => ({ apiUrl: '/api' }));\n * const config = inject(AppConfig);\n * ```\n */\nexport function createToken<T>(name: string, defaultFactory?: () => T): InjectionToken<T> {\n return {\n __brand: 'InjectionToken' as const,\n name,\n _factory: defaultFactory,\n };\n}\n\n// Hooks run by resetInjector() \u2014 module-level caches elsewhere (settle's\n// pending registry) stay test-isolated without upside-down imports: those\n// modules import the injector and self-register, never the reverse.\nconst resetHooks = new Set<() => void>();\n\n/** @internal Register a hook run by every resetInjector() call. */\nexport function registerResetHook(hook: () => void): void {\n resetHooks.add(hook);\n}\n\n/**\n * Reset the injector \u2014 clears all singletons and factory overrides.\n * Used in tests to ensure isolation between test cases.\n */\nexport function resetInjector(): void {\n singletonCache.clear();\n factoryOverrides.clear();\n instantiating.clear();\n for (const hook of resetHooks) hook();\n}\n", "/**\n * element-context.ts \u2014 subtree-scoped context (provide / inject).\n *\n * The DOM-native equivalent of React/Radix context: a provider publishes a\n * typed value on its host element, and descendant components `inject()` it by\n * walking up the element tree. It replaces the userland `host.__uiX = state` +\n * `host.closest('ui-x')` convention (stringly-typed, invisible to TypeScript,\n * re-implemented per family) with an identity-keyed, end-to-end-typed primitive.\n *\n * ```ts\n * interface TabsState { value: ReadonlySignal<string>; setValue(v: string): void }\n * const TabsContext = createContext<TabsState>('Tabs');\n *\n * // provider setup:\n * TabsContext.provide(host, state);\n *\n * // descendant setup:\n * const tabs = TabsContext.inject(); // throws (error boundary) if absent\n * const maybe = TabsContext.inject.optional(); // TabsState | undefined\n * ```\n *\n * Design (see ADR 0025 \u00A72):\n *\n * - **Typed, no string keys.** Each `createContext` mints a private `Symbol`\n * used as the storage key; consumers reference the context object, never a\n * string. Two contexts never collide even with the same `name` (name is for\n * diagnostics only).\n *\n * - **Capture at setup, not at lookup.** `inject()` resolves during component\n * setup, while the injecting host is still a DOM descendant of its provider.\n * It returns the value *once*; because provider values carry signals,\n * reactivity flows through them with no further tree-walks. This is what makes\n * it **portal-safe**: after a subtree is reparented to `<body>` (dialog, menu,\n * \u2026) the injected value is already held, so the component keeps resolving its\n * ORIGINAL provider \u2014 a later walk from the portaled host would find nothing.\n * `inject()` therefore requires an active setup context when no host is passed.\n *\n * - **Zero cost for non-users.** Providing sets one symbol property on the host;\n * injecting is a `parentElement` walk. Components that use neither pay nothing,\n * and there is no global registry to maintain.\n */\n\nimport { getCurrentComponent, hasContext } from './context.js';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface Inject<T> {\n /**\n * Resolve the nearest provider's value by walking up from `host` (default:\n * the current component's host, requiring a setup context). Throws if no\n * provider is found \u2014 in a component this surfaces via the error boundary.\n */\n (host?: HTMLElement): T;\n /** Like `inject()` but returns `undefined` instead of throwing when absent. */\n optional(host?: HTMLElement): T | undefined;\n}\n\nexport interface Context<T> {\n /** Diagnostic label (error messages); not an identity key. */\n readonly name: string;\n /** Publish `value` on `host` so descendants can `inject()` it. */\n provide(host: HTMLElement, value: T): void;\n /** Resolve this context from a descendant (see {@link Inject}). */\n readonly inject: Inject<T>;\n /**\n * Read the value provided on THIS host only \u2014 no ancestor walk. `undefined`\n * if `host` is not a provider of this context. The low-level primitive for\n * bespoke walks (e.g. \"nearest provider of context A OR context B\", which\n * `inject` can't express in one pass); prefer `inject`/`inject.optional`\n * for ordinary descendant resolution.\n */\n peek(host: HTMLElement): T | undefined;\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Create a subtree-scoped context. `name` is used only in diagnostics; the\n * context's identity (a private symbol) is what keys storage and lookup.\n *\n * Pass `{ providerTag }` to name the provider element so a missing-provider\n * `inject()` produces an ACTIONABLE, element-language error \u2014\n * `<injecting-tag> must be used inside <provider-tag>.` \u2014 instead of naming the\n * private context object. Set it whenever consumers are DOM elements (the whole\n * registry): it's the difference between a message a plain-HTML user can act on\n * and one they can't.\n */\nexport function createContext<T>(\n name: string,\n options: { providerTag?: string } = {},\n): Context<T> {\n const { providerTag } = options;\n // Private per-context storage key. Not derived from `name`, so same-named\n // contexts stay distinct, and it never appears in userland.\n const KEY = Symbol(`nisli.context:${name}`);\n\n const store = (el: Element): Record<symbol, unknown> =>\n el as unknown as Record<symbol, unknown>;\n\n const provide = (host: HTMLElement, value: T): void => {\n store(host)[KEY] = value;\n };\n\n const peek = (host: HTMLElement): T | undefined =>\n KEY in host ? (store(host)[KEY] as T) : undefined;\n\n // Walk up the element tree (inclusive of `start`) to the nearest provider.\n // `parentElement` transparently crosses `display: contents` hosts.\n const find = (start: HTMLElement): T | undefined => {\n let el: Element | null = start;\n while (el) {\n if (KEY in el) return store(el)[KEY] as T;\n el = el.parentElement;\n }\n return undefined;\n };\n\n const startHost = (host: HTMLElement | undefined, caller: string): HTMLElement | null => {\n if (host) return host;\n if (!hasContext()) {\n throw new Error(\n `${caller} for context \"${name}\" was called without a host and outside component ` +\n `setup. Call it during setup (so the provider is resolved before any portal move), ` +\n `or pass an explicit host.`,\n );\n }\n return getCurrentComponent().element;\n };\n\n const inject = ((host?: HTMLElement): T => {\n const start = startHost(host, 'inject()')!;\n const found = find(start);\n if (found === undefined) {\n const injectingTag = start.tagName.toLowerCase();\n // With a declared provider tag, speak element-language the consumer can\n // act on; otherwise fall back to the generic (provider named by API).\n throw new Error(\n providerTag\n ? `Context \"${name}\": <${injectingTag}> must be used inside <${providerTag}>.`\n : `Context \"${name}\" not found: <${injectingTag}> must be rendered ` +\n `inside a provider that calls ${name}Context.provide(host, \u2026).`,\n );\n }\n return found;\n }) as Inject<T>;\n\n inject.optional = (host?: HTMLElement): T | undefined => {\n // Outside setup with no host: there is nothing to resolve from \u2014 undefined.\n if (!host && !hasContext()) return undefined;\n return find(startHost(host, 'inject.optional()')!);\n };\n\n return { name, provide, inject, peek };\n}\n", "/**\n * lifecycle.ts \u2014 Post-mount and cleanup lifecycle hooks\n *\n * `onMount()` registers a callback that runs after the component's\n * template is mounted to the DOM. If the callback returns a function,\n * that function runs on disconnect (cleanup).\n *\n * `onCleanup()` registers a standalone cleanup callback that runs\n * on disconnect \u2014 for cases where you need cleanup without mount logic.\n *\n * Both must be called synchronously during component setup.\n *\n * ```ts\n * component('my-el', (props, host) => {\n * onMount(() => {\n * host.querySelector('input')?.focus();\n * return () => console.log('unmounted');\n * });\n *\n * onCleanup(() => clearInterval(timerId));\n *\n * return html`<input />`;\n * });\n * ```\n */\n\nimport { hasContext, getCurrentComponent } from './context.js';\n\n// \u2500\u2500 Mount callback storage \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Mount callbacks are stored on the component host and called after template mount. */\nconst mountCallbacks = new WeakMap<object, (() => void | (() => void))[]>();\n\n/**\n * Register a callback to run after the component's template is mounted.\n * If the callback returns a function, it will be called on disconnect.\n *\n * Must be called synchronously during component setup.\n */\nexport function onMount(callback: () => void | (() => void)): void {\n if (!hasContext()) {\n throw new Error(\n 'onMount() called outside setup(). ' +\n 'It can only be called during component initialization.'\n );\n }\n const comp = getCurrentComponent();\n let callbacks = mountCallbacks.get(comp);\n if (!callbacks) {\n callbacks = [];\n mountCallbacks.set(comp, callbacks);\n }\n callbacks.push(callback);\n}\n\n/**\n * Register a cleanup callback to run on disconnect.\n * This is a convenience for cases where you need cleanup without mount logic.\n *\n * Must be called synchronously during component setup.\n */\nexport function onCleanup(callback: () => void): void {\n if (!hasContext()) {\n throw new Error(\n 'onCleanup() called outside setup(). ' +\n 'It can only be called during component initialization.'\n );\n }\n getCurrentComponent().addDisposer(callback);\n}\n\n/**\n * Listen for a DOM event on a target and auto-dispose the listener when the\n * component disconnects. Works with any EventTarget (host element, document,\n * window, etc.). Must be called during component setup.\n *\n * ```ts\n * useHostEvent(host, 'click', (e) => {\n * // Runs on each click\n * });\n * ```\n */\nexport function useHostEvent<E extends Event = Event>(\n target: EventTarget,\n eventName: string,\n handler: (event: E) => void,\n): void {\n if (!hasContext()) {\n throw new Error(\n 'useHostEvent() called outside setup(). ' +\n 'It can only be called during component initialization.'\n );\n }\n target.addEventListener(eventName, handler as EventListener);\n getCurrentComponent().addDisposer(() => {\n target.removeEventListener(eventName, handler as EventListener);\n });\n}\n\n/**\n * Run all registered mount callbacks for a component host.\n * Called by component.ts after the template is mounted to the DOM.\n *\n * A throw here PROPAGATES to component.ts's containment boundary \u2014 the SAME\n * boundary as a setup throw (ADR 0030.2 T6, code N402): remaining callbacks\n * are skipped, the partial scope (including cleanups already registered by\n * earlier callbacks) is disposed, the error fallback renders, and the host is\n * stamped `data-nisli-error`. The pre-T6 behavior (console-and-limp per\n * callback) left a half-mounted component alive with no machine-readable\n * trace and no teardown \u2014 the one containment semantics setup already had\n * (issue 0010) now covers mount too.\n * @internal\n */\nexport function runMountCallbacks(comp: object): void {\n const callbacks = mountCallbacks.get(comp);\n if (!callbacks) return;\n\n try {\n for (const cb of callbacks) {\n const cleanup = cb();\n if (typeof cleanup === 'function') {\n // Register cleanup as a disposer on the component\n (comp as any).addDisposer(cleanup);\n }\n }\n } finally {\n // Clear \u2014 mount callbacks run once (also when a throw contains the scope:\n // the boundary re-runs setup from scratch on the next mount, which\n // re-registers a fresh callback list).\n mountCallbacks.delete(comp);\n }\n}\n", "/**\n * component.ts \u2014 Web component shell with typed props and factory composition\n *\n * `component()` is the single entry point for defining components.\n * It registers a custom element and returns a typed factory function.\n *\n * Component authors write a setup function that receives typed props\n * (each wrapped as a Signal) and optionally the host element.\n * The setup function returns a TemplateResult from html`...`.\n *\n * The class internals (connectedCallback, etc.) are completely hidden.\n */\n\nimport { signal, effect, setContextHook, isSignal, untrack, type Signal, type ReadonlySignal } from './signal.js';\nimport { runWithContext, hasContext, getCurrentComponent, type ComponentHost } from './context.js';\nimport type { TemplateResult } from './template.js';\nimport { runMountCallbacks } from './lifecycle.js';\nimport { diag, formatDiag, isDev } from './diagnostics.js';\n\n// Diagnostic state is external to production component/props objects. Each\n// allocation and use is statically gated so the entire maps disappear (0048).\nconst propsReadKeys = process.env.NODE_ENV !== 'production'\n ? new WeakMap<object, Set<string>>() : undefined;\nconst completedSetups = process.env.NODE_ENV !== 'production'\n ? new WeakSet<HTMLElement>() : undefined;\nconst echoedProps = process.env.NODE_ENV !== 'production'\n ? new WeakMap<HTMLElement, Set<string>>() : undefined;\n\n// Wire up effect auto-disposal: when effect() is called during component setup,\n// auto-register the dispose function with the component host.\nsetContextHook(() => {\n if (hasContext()) {\n const comp = getCurrentComponent();\n return (disposer: () => void) => comp.addDisposer(disposer);\n }\n return null;\n});\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Narrows one prop's reactive value to the runtime type its `attrs`\n * declaration guarantees (ADR 0025 candidate (b)). Only the two kinds core\n * reconciles to a NON-`undefined` runtime value narrow; everything else is\n * left as the author's `T` (= `P[K]`):\n *\n * - `'boolean'` / `{ type:'boolean' }` (any default) \u2192 `boolean` \u2014 a declared\n * boolean is absent\u2192`false`, never `undefined`.\n * - `{ type:'number'; default }` \u2192 `number` \u2014 the default guarantees a value.\n * - `'number'` / `{ type:'number' }` WITHOUT a default \u2192 `number | undefined`.\n * - `'string'` / `{ type:'string' }` / `'forward'` / undeclared \u2192 `T` unchanged\n * (a string attr is genuinely absent\u2192`undefined`; forwarding does not touch\n * the value type).\n *\n * SOUND FALLBACK on an incompatible declaration: the narrowed runtime type is\n * applied ONLY when the declared kind and `NonNullable<T>` (the prop's author\n * type) agree EXACTLY \u2014 mutual assignability, BOTH directions. A one-way check\n * (`boolean extends NonNullable<T>`) is unsound: it would still narrow a\n * `boolean | string` prop to `boolean` (silently dropping `string`), and a\n * one-way check the other way would widen a literal `true`/`1` prop. So a\n * declaration is honored only when `NonNullable<T>` IS the kind \u2014 `boolean` for\n * a boolean declaration, `number` for a numeric one \u2014 via {@link IsExactKind}.\n * Every genuine mismatch or partial overlap (`boolean | string` declared\n * `'boolean'`, `'boolean'` on a `string` prop, a numeric decl on a boolean prop,\n * a literal `true`/`1` prop) falls back to `T` unchanged \u2014 never a compile-time\n * lie about the value. The whole registry declares props as exactly `boolean` /\n * `number`, so it narrows as before; only unions/literals/mismatches are refused.\n *\n * `D` is the declaration at that key (or `undefined` when the key is absent\n * from the `attrs` map, in which case the caller passes `T` through directly).\n */\nexport type AttrValueType<T, D> =\n D extends 'boolean' ? (IsExactKind<T, boolean> extends true ? boolean : T)\n : D extends { type: 'boolean' } ? (IsExactKind<T, boolean> extends true ? boolean : T)\n : D extends { type: 'number'; default: number } ? (IsExactKind<T, number> extends true ? number : T)\n : D extends 'number' ? (IsExactKind<T, number> extends true ? number | undefined : T)\n : D extends { type: 'number' } ? (IsExactKind<T, number> extends true ? number | undefined : T)\n : T;\n\n/**\n * `true` iff `NonNullable<T>` is EXACTLY `K` \u2014 mutually assignable in both\n * directions (`NonNullable<T> extends K` AND `K extends NonNullable<T>`). The\n * tuple wrappers block distribution so `boolean` (`= true | false`) is compared\n * whole: `boolean | string` is NOT exactly `boolean` (fails the first arm), and\n * `true` is NOT exactly `boolean` (fails the second), so both are refused.\n */\ntype IsExactKind<T, K> =\n [NonNullable<T>] extends [K] ? ([K] extends [NonNullable<T>] ? true : false) : false;\n\n/**\n * Maps a props interface to reactive signals, narrowed by the `attrs`\n * declaration `A` (ADR 0025 candidate (b)).\n *\n * Each prop `P[K]` becomes `Signal<AttrValueType<P[K], A[K]>>` when `K` is\n * declared in `A`, otherwise `Signal<P[K]>`. So a declared `'boolean'` types as\n * `Signal<boolean>` (not `Signal<boolean | undefined>`), retiring the\n * registry's `as boolean` stopgap. `A` defaults to `{}` (no declared keys \u2192\n * every prop unchanged), so `ReactiveProps<P>` keeps its pre-candidate-(b)\n * meaning and existing single-argument uses are unaffected.\n *\n * Optionality is stripped (`-?`): the props Proxy always returns a signal,\n * even for props never set \u2014 an optional prop `variant?: T` is\n * `Signal<T | undefined>`, not `Signal<T> | undefined`.\n */\nexport type ReactiveProps<P, A extends ComponentAttrs<P> = {}> = {\n readonly [K in keyof P]-?: Signal<K extends keyof A ? AttrValueType<P[K], A[K]> : P[K]>;\n};\n\n/**\n * The setup function signature. Receives reactive props (narrowed by the\n * `attrs` declaration `A`) and the host element. Returns a TemplateResult to be\n * mounted into the component.\n */\nexport type SetupFunction<P, A extends ComponentAttrs<P> = {}> = (\n props: ReactiveProps<P, A>,\n host: HTMLElement,\n) => TemplateResult;\n\n/**\n * Accepts either a Signal<T> (reactive) or a plain T (static, auto-wrapped).\n * This eliminates the need to wrap static values in `signal()` at call sites.\n * See ADR 0009 Gap 4.\n */\nexport type PropInput<T> = T | Signal<T> | ReadonlySignal<T>;\n\n/**\n * Host-level attributes that every factory accepts, independent of component props.\n * `class` is applied to the host element via classList \u2014 it does not collide with\n * the component's own class attribute or class:name directives.\n * See ADR 0009 Gap 3.\n */\nexport interface HostAttrs {\n class?: PropInput<string>;\n}\n\n/**\n * A factory function for type-safe component composition.\n * Props accept both Signal<T> (reactive) and plain T (static, auto-wrapped).\n * An optional second argument provides host-level attributes (class).\n */\nexport type ComponentFactory<P> = (\n props: { [K in keyof P]: PropInput<P[K]> },\n hostAttrs?: HostAttrs,\n) => TemplateResult;\n\n/**\n * Opt-in attribute reactivity declaration (ADR 0025 item 3).\n *\n * Declares how a host attribute maps onto a prop signal, subsuming userland\n * `attr()`/`boolAttr()`/`forwardedAttr()`. Unlike those (which read the\n * attribute once at setup), a declared attribute is `observedAttributes`-wired,\n * so `setAttribute()` AFTER mount writes the prop signal LIVE.\n *\n * - `'string'` \u2014 the attribute's string value (absent \u2192 `undefined`).\n * - `'boolean'` \u2014 OUR boolean semantics: bare/any value \u2192 `true`, literal\n * `\"false\"` \u2192 `false`, absent \u2192 `false`.\n * - `'number'` \u2014 `Number(raw)`; absent \u2192 the default (else `undefined`); a\n * non-numeric value behaves as absent \u2192 the default (else `undefined`), so a\n * garbage attribute never propagates `NaN` into layout math.\n * - `{ type: 'boolean', default: true }` \u2014 as above but absent \u2192 the default\n * (so a default-`true` flag can be opted out with `attr=\"false\"`).\n * - `{ type: 'string', default: '\u2026' }` \u2014 string with an absent-value default.\n * - `{ type: 'number', default: 0 }` \u2014 number with an absent-value default.\n * - `'forward'` \u2014 string semantics PLUS relocation: the attribute is removed\n * from the (layout-transparent) host so `id`/`name` live only on the inner\n * control (native form participation), matching `forwardedAttr()`.\n *\n * The observed attribute name is the kebab-case of the prop key (`className` \u2194\n * `class-name`, `showOutsideDays` \u2194 `show-outside-days`, `id` \u2194 `id`). The\n * object forms accept an `attr` override for props whose native attribute is\n * NOT the kebab derivation \u2014 e.g. `readOnly: { type: 'boolean', attr: 'readonly' }`\n * (the native boolean attribute is `readonly`, not `read-only`). (v1.1)\n */\nexport type AttrDecl =\n | 'string'\n | 'boolean'\n | 'number'\n | 'forward'\n | { type: 'boolean'; default?: boolean; attr?: string }\n | { type: 'string'; default?: string; attr?: string }\n | { type: 'number'; default?: number; attr?: string };\n\n/**\n * The `attrs` declaration map for a props interface `P`: prop keys \u2192 attribute\n * behavior. This is the type an `attrs` object satisfies; capture its literal\n * type with `typeof` and pass it as `component`'s second type argument to\n * unlock declared-type narrowing (ADR 0025 candidate (b)):\n *\n * ```ts\n * const attrs = { checked: 'boolean' } satisfies ComponentAttrs<SwitchProps>;\n * const Switch = component<SwitchProps, typeof attrs>('ui-switch', setup, { attrs });\n * // inside setup: props.checked.value is `boolean`, not `boolean | undefined`\n * ```\n */\nexport type ComponentAttrs<P> = Partial<Record<Extract<keyof P, string>, AttrDecl>>;\n\n/** Options for component() registration */\nexport interface ComponentOptions<P = unknown> {\n /** Custom error fallback renderer */\n onError?: (error: Error, host: HTMLElement) => TemplateResult | string;\n /**\n * Opt-in attribute reactivity (ADR 0025 item 3). Maps prop keys\n * to attribute declarations. Omitted entirely \u2192 zero cost (empty\n * `observedAttributes`, no `attributeChangedCallback` work).\n */\n attrs?: ComponentAttrs<P>;\n}\n\n// \u2500\u2500 Attribute-reactivity helpers (ADR 0025 item 3) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface AttrEntry {\n /** camelCase prop key. */\n key: string;\n /** kebab-case observed attribute name. */\n attrName: string;\n decl: AttrDecl;\n}\n\nconst camelToKebab = (s: string): string =>\n s.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n\nconst declType = (decl: AttrDecl): 'string' | 'boolean' | 'number' | 'forward' =>\n typeof decl === 'string' ? decl : decl.type;\n\n/** The observed attribute name: an explicit `attr` override, else kebab(key). */\nconst declAttrName = (key: string, decl: AttrDecl): string =>\n typeof decl === 'object' && decl.attr ? decl.attr : camelToKebab(key);\n\n/** Resolve a raw attribute string (or null when absent) to the prop value. */\nfunction resolveAttrValue(decl: AttrDecl, raw: string | null): unknown {\n const t = declType(decl);\n if (t === 'boolean') {\n const def =\n typeof decl === 'object' && 'default' in decl && decl.default !== undefined\n ? decl.default\n : false;\n if (raw === null) return def; // absent \u2192 declared default (else false)\n return raw !== 'false'; // bare/any \u2192 true, literal \"false\" \u2192 false\n }\n if (t === 'number') {\n const def = typeof decl === 'object' && 'default' in decl ? decl.default : undefined;\n if (raw === null) return def; // absent \u2192 declared default (else undefined)\n const n = Number(raw);\n // Garbage behaves as ABSENT \u2192 the declared default (else undefined). A\n // default exists to guarantee non-undefined; letting garbage fall to\n // literal undefined would reintroduce exactly what the default prevents.\n return Number.isNaN(n) ? def : n;\n }\n // 'string' | 'forward'\n if (raw === null) {\n return typeof decl === 'object' && 'default' in decl ? decl.default : undefined;\n }\n return raw;\n}\n\n// \u2500\u2500 Internal component host \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass ComponentHostImpl implements ComponentHost {\n element: HTMLElement;\n private disposers: (() => void)[] = [];\n private setupComplete = false;\n\n constructor(element: HTMLElement) {\n this.element = element;\n }\n\n addDisposer(fn: () => void): void {\n this.disposers.push(fn);\n }\n\n dispose(): void {\n for (const fn of this.disposers) {\n try { fn(); } catch (_) { /* swallow disposal errors */ }\n }\n this.disposers.length = 0;\n }\n}\n\n// \u2500\u2500 Prop signal management via Proxy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Creates a Proxy-based props object that lazily creates signals\n * for each property on first access. When a parent sets a property\n * on the element, the Proxy intercepts it and updates (or creates)\n * the backing signal.\n */\nfunction createPropsProxy<P>(): {\n props: ReactiveProps<P>;\n setProperty: (key: string, value: unknown) => void;\n} {\n const signals = new Map<string, Signal<unknown>>();\n\n // Keys the component has READ through the proxy, accumulated over the\n // COMPONENT LIFETIME (the proxy is constructor-owned and survives\n // remounts/HMR swaps, so a re-setup never false-positives). This is the\n // truth source for the unknown-prop echo (N202, ADR 0030.2): a post-mount\n // write to a never-read key is attribution noise, not state. A component\n // that stashes `props` and reads a key dynamically AFTER such a write gets\n // one stale echo \u2014 accepted; the echo is attribution-only. The dev-only\n // propsReadKeys map above owns this bookkeeping, outside production objects.\n const getOrCreate = (key: string, initialValue?: unknown): Signal<unknown> => {\n let s = signals.get(key);\n if (!s) {\n s = signal(initialValue);\n signals.set(key, s);\n }\n return s;\n };\n\n const props = new Proxy({} as ReactiveProps<P>, {\n get(_target, key) {\n // Symbol probes (well-known symbols, thenable checks) are not props.\n if (typeof key !== 'string') return undefined;\n if (process.env.NODE_ENV !== 'production') propsReadKeys!.get(props)!.add(key);\n return getOrCreate(key);\n },\n });\n\n if (process.env.NODE_ENV !== 'production') propsReadKeys!.set(props, new Set());\n\n const setProperty = (key: string, value: unknown) => {\n const s = getOrCreate(key, value);\n s.value = value;\n };\n\n return { props, setProperty };\n}\n\n// \u2500\u2500 Duplicate-define attribution (N201, dev only) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** First definition site per tag, captured in dev for N201 attribution. */\nconst firstDefineSites = process.env.NODE_ENV !== 'production'\n ? new Map<string, string>() : undefined;\n\n/**\n * Best-effort caller frame for N201: the first stack line that is neither the\n * Error header nor a frame inside this module. Dev-only; a user file that is\n * itself named `component.ts` gets skipped too (best-effort attribution, never\n * behavior).\n */\nfunction captureDefineSite(): string {\n const stack = new Error().stack;\n if (!stack) return '(site unavailable)';\n const lines = stack.split('\\n');\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i]!.trim();\n if (!line) continue;\n if (line.includes('captureDefineSite') || /[/\\\\]component\\.(?:ts|js)\\b/.test(line)) continue;\n return line;\n }\n return '(site unavailable)';\n}\n\n// \u2500\u2500 component() \u2014 the main entry point \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Define a web component with typed props and a setup function.\n *\n * Returns a typed factory function for compile-time-safe composition.\n *\n * ```ts\n * interface TaskItemProps {\n * task: Task;\n * selected: boolean;\n * }\n *\n * const TaskItem = component<TaskItemProps>('task-item', (props, host) => {\n * const title = computed(() => props.task.value.title);\n * return html`<div>${title}</div>`;\n * });\n *\n * // Factory usage:\n * TaskItem({ task: taskSignal, selected: isSelected })\n * ```\n */\nexport function component<\n P extends object = Record<string, never>,\n A extends ComponentAttrs<P> = {},\n>(\n tagName: string,\n setup: SetupFunction<P, A>,\n // When `A` is explicitly given a non-empty attrs literal (the narrowing\n // opt-in), the options argument \u2014 carrying `attrs: A` \u2014 is REQUIRED: a\n // `component<P, typeof attrs>(tag, setup)` that types the props as narrowed but\n // never actually wires the attrs at runtime would be a compile-time lie. When\n // `A` is `{}` (the legacy default, no second type arg), options stays optional\n // exactly as before. `attrs` in that legacy branch is still validated as\n // `ComponentAttrs<P>` via `ComponentOptions<P>`.\n ...[options]: [keyof A] extends [never]\n ? [options?: ComponentOptions<P>]\n : [options: ComponentOptions<P> & { attrs: A }]\n): ComponentFactory<P> {\n // Attribute-reactivity wiring (ADR 0025 item 3). Computed once\n // per component definition; empty when no `attrs` declared (\u2192 zero cost).\n const attrEntries = new Map<string, AttrEntry>(); // by attrName\n const attrEntriesByKey = new Map<string, AttrEntry>(); // by prop key\n if (options?.attrs) {\n for (const key of Object.keys(options.attrs)) {\n const decl = (options.attrs as Record<string, AttrDecl>)[key]!;\n const attrName = declAttrName(key, decl);\n const entry: AttrEntry = { key, attrName, decl };\n attrEntries.set(attrName, entry);\n attrEntriesByKey.set(key, entry);\n }\n }\n const observedList = Array.from(attrEntries.keys());\n\n // The custom element class\n class FrameworkComponent extends HTMLElement {\n private _host: ComponentHostImpl | null = null;\n private _propsProxy: ReturnType<typeof createPropsProxy<P>> | null = null;\n private _mounted = false;\n private _templateResult: TemplateResult | null = null;\n private _errorTemplateResult: TemplateResult | null = null;\n private _teardownScheduled = false;\n // Props explicitly set via _setProp (factory / direct assignment) are\n // \"pinned\": an explicit prop wins, so attribute writes no longer overwrite\n // it. (Precedence ruling: prop-pins.)\n private _pinned = new Set<string>();\n // Guards our own removeAttribute() during 'forward' relocation from\n // re-entering attributeChangedCallback.\n private _relocating = false;\n\n /** The browser reads this once at define time. Empty \u2192 no callbacks. */\n static get observedAttributes(): string[] {\n return observedList;\n }\n\n constructor() {\n super();\n this._propsProxy = createPropsProxy<P>();\n }\n\n /** Write one declared attribute onto its prop signal, honoring pinning. */\n private _applyAttr(entry: AttrEntry, raw: string | null): void {\n if (declType(entry.decl) === 'forward') {\n // Relocate off the layout-transparent host (no duplicate id/name), but\n // only adopt the attribute's value when no explicit prop pinned it. A\n // null `raw` here (absent OR already-relocated) is a NO-OP: the seed\n // and attributeChangedCallback must not clobber an adopted value. The\n // explicit unpin path (in _setProp) handles clearing.\n if (raw !== null) {\n if (!this._pinned.has(entry.key)) {\n this._propsProxy!.setProperty(entry.key, raw);\n }\n this._relocating = true;\n this.removeAttribute(entry.attrName);\n this._relocating = false;\n }\n return;\n }\n if (this._pinned.has(entry.key)) return; // explicit prop wins\n this._propsProxy!.setProperty(entry.key, resolveAttrValue(entry.decl, raw));\n }\n\n /** Seed initial prop values from current attributes (incl. defaults). */\n private _seedAttrs(): void {\n for (const entry of attrEntries.values()) {\n this._applyAttr(entry, this.getAttribute(entry.attrName));\n }\n }\n\n attributeChangedCallback(name: string, _old: string | null, next: string | null): void {\n if (this._relocating) return;\n const entry = attrEntries.get(name);\n if (entry) this._applyAttr(entry, next);\n }\n\n connectedCallback() {\n if (this._mounted) return; // guard against re-connection\n this._mounted = true;\n\n // Isolate activeObserver: child component setup signal reads must NOT\n // leak into a parent effect's dependency set. Without this, a parent\n // effect running replaceChildren/appendChild triggers child\n // connectedCallback synchronously, and child signal reads would be\n // tracked as parent dependencies \u2014 causing infinite re-render loops.\n // See ADR 0008 Gap 1 / ADR 0009.\n untrack(() => {\n const host = new ComponentHostImpl(this);\n this._host = host;\n\n // Canonical pre-setup order: SEED \u2192 CAPTURE \u2192 CONTEXT (then setup).\n //\n // SEED (ADR 0025 item 3): write prop signals from current\n // attributes (incl. declared defaults and 'forward' relocation) so setup\n // sees correct initial values. No-op when no attrs are declared.\n if (attrEntries.size) this._seedAttrs();\n\n // CAPTURE (ADR 0025 item 1): snapshot the host's light-DOM\n // children so children() can project them. Snapshot only \u2014 children()\n // removes/projects on demand \u2014 so non-projecting components are\n // untouched. Zero-cost when the host has no light DOM.\n if (this.childNodes.length) {\n (this as unknown as { __capturedChildren?: Node[] }).__capturedChildren =\n Array.from(this.childNodes);\n }\n\n // Phase attribution for the SHARED containment boundary (ADR 0030.2\n // T6): 'setup' (N401) until the template is committed, 'mount' (N402)\n // once onMount callbacks begin. Both phases route through the ONE\n // catch below \u2014 runMountCallbacks no longer swallows (lifecycle.ts).\n let phase: 'setup' | 'mount' = 'setup';\n try {\n // CONTEXT is established by runWithContext(host, \u2026) below; setup then\n // runs with seed + capture already in place.\n runWithContext(host, () => {\n // The Proxy is runtime-untyped; the declared narrowing (A) is a\n // compile-time view the setup function requested (ADR 0025 (b)).\n this._templateResult = setup(\n this._propsProxy!.props as ReactiveProps<P, A>,\n this,\n );\n });\n\n // Mount the template result\n if (this._templateResult) {\n mountTemplate(this, this._templateResult, host);\n }\n\n // PROJECTION PHASE (ADR 0030.2 \u00A73): if setup called children(), run\n // its late-children sweep scheduling NOW \u2014 after the template\n // committed, BEFORE any onMount callback. The rendered-roots\n // snapshot therefore never depends on where children() sat relative\n // to onMount() registrations (the 0025 batch-3B ordering trap), and\n // the rule becomes universal: any host child appearing after this\n // point \u2014 late parser/innerHTML content OR an onMount host-append \u2014\n // classifies as projected content.\n const sweepHost = this as unknown as { __nisliProjectionSweep?: () => void };\n if (sweepHost.__nisliProjectionSweep) {\n const sweep = sweepHost.__nisliProjectionSweep;\n sweepHost.__nisliProjectionSweep = undefined; // consumed once per cycle\n sweep();\n }\n\n // Run onMount() callbacks \u2014 DOM is now committed\n phase = 'mount';\n runMountCallbacks(host);\n\n if (process.env.NODE_ENV !== 'production') completedSetups!.add(this);\n // T6: a SUCCESSFUL (re-)setup \u2014 including _remount(), the documented\n // boundary reset \u2014 removes the failure stamp.\n this.removeAttribute('data-nisli-error');\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n const code = phase === 'setup' ? 'N401' : 'N402';\n diag(code, `<${tagName}> ${phase} failed: ${error.message}`, {\n tag: tagName,\n phase,\n error,\n });\n\n // Setup may already have registered effects/lifecycle cleanup, or\n // mountTemplate() may have partially installed bindings before\n // throwing \u2014 and a mount-phase throw arrives with the whole scope\n // live. Tear the partial scope down BEFORE mounting the error\n // fallback so no hidden work survives behind it (issue 0010; the\n // onMount phase now shares these exact semantics per T6). An\n // unconsumed projection sweep hook is part of that partial scope.\n (this as unknown as { __nisliProjectionSweep?: () => void }).__nisliProjectionSweep =\n undefined;\n if (this._templateResult?.dispose) {\n this._templateResult.dispose();\n }\n this._templateResult = null;\n host.dispose();\n this._host = null;\n this.replaceChildren();\n\n // T6 \u2014 failure is a DOM fact. The attribute is the DURABLE channel:\n // `querySelectorAll('[data-nisli-error]')` answers \"which component\n // failed\" long after the fact, with no listener installed in\n // advance. Client-runtime only \u2014 SSG failures stay build failures.\n this.setAttribute('data-nisli-error', code);\n\n if (options?.onError) {\n try {\n const fallback = options.onError(error, this);\n if (typeof fallback === 'string') {\n this.innerHTML = fallback;\n } else {\n this._errorTemplateResult = fallback;\n mountTemplate(this, fallback);\n }\n } catch (_) {\n if (this._errorTemplateResult?.dispose) {\n this._errorTemplateResult.dispose();\n }\n this._errorTemplateResult = null;\n this.innerHTML = `<div style=\"color:red;padding:4px\">Error in &lt;${tagName}&gt;</div>`;\n }\n } else {\n this.innerHTML = `<div style=\"color:red;padding:4px\">Error in &lt;${tagName}&gt;</div>`;\n }\n\n // T6 \u2014 the EVENT is the live channel: one document-level listener\n // observes every contained failure as it happens. Dispatched LAST so\n // listeners see the settled DOM (stamp + fallback). Bubbling is a\n // DOM-tree walk, so CSS (display:contents transparent hosts) never\n // affects delivery \u2014 but a component mounted into a DETACHED\n // fragment has no path to document and the event is swallowed; the\n // attribute above is the durable record for those (ADR 0030.2 \u00A78).\n this.dispatchEvent(\n new CustomEvent('nisli-error', {\n bubbles: true,\n composed: true,\n detail: { code, tag: tagName, phase, message: error.message },\n }),\n );\n }\n });\n }\n\n disconnectedCallback() {\n // A same-tick remove+reinsert is a MOVE, not a removal: per WHATWG,\n // append-based moves fire disconnected+connected (only moveBefore()\n // preserves state). Moves happen routinely inside the framework \u2014\n // each() keyed reorders, light-DOM projection of nested components \u2014\n // and re-running setup on them duplicates rendered output and loses\n // state. Defer teardown one microtask and skip it if the element is\n // connected again; connectedCallback's _mounted guard then makes the\n // whole move a no-op. True removals still dispose, one microtask\n // later. See ADR 0023.\n if (this._teardownScheduled) return;\n this._teardownScheduled = true;\n queueMicrotask(() => {\n this._teardownScheduled = false;\n if (this.isConnected) return;\n this._teardownNow();\n });\n }\n\n /**\n * Atomic DOM moves preserve this component's position-independent state,\n * so the platform-level lifecycle is a no-op. ADR 0023's deferred\n * disconnect teardown remains the fallback for append-based moves.\n */\n connectedMoveCallback(): void {}\n\n /**\n * Synchronously dispose the current component scope and restore any\n * projected light-DOM children as direct host children. Normal disconnect\n * calls this after the move-detection microtask; HMR calls it directly so\n * reconnect cannot be defeated by the `_mounted` guard (issues 0001/0002).\n */\n private _teardownNow(): void {\n this._mounted = false;\n if (process.env.NODE_ENV !== 'production') completedSetups!.delete(this);\n if (this._templateResult?.dispose) {\n this._templateResult.dispose();\n }\n this._templateResult = null;\n if (this._errorTemplateResult?.dispose) {\n this._errorTemplateResult.dispose();\n }\n this._errorTemplateResult = null;\n if (this._host) {\n this._host.dispose();\n this._host = null;\n }\n\n // children() records the plain light-DOM nodes it owns during cleanup.\n // Replacing the rendered tree with those nodes preserves author content\n // for a later true reconnect/HMR setup; components without projection\n // simply become empty before the fresh setup appends its new subtree.\n const captured = (this as unknown as { __capturedChildren?: Node[] })\n .__capturedChildren ?? [];\n this.replaceChildren(...captured);\n }\n\n /** @internal \u2014 transport-agnostic HMR in-place remount hook. */\n _remount(): void {\n this._teardownScheduled = false;\n this._teardownNow();\n this.connectedCallback();\n }\n\n /**\n * Set a prop value. Called by the factory and by direct property assignment.\n * The Proxy intercepts and creates/updates backing signals.\n *\n * Precedence = DEFINED-write-pins (ADR 0025 item 3): a defined\n * value pins the key so a declared attribute no longer overwrites it. An\n * explicit `undefined` (e.g. a factory spreading an unset optional prop \u2014\n * `{...opts}` fires _setProp(key, undefined) per the Object.entries walk)\n * must NOT pin; it falls back to the declared attribute/default, matching\n * attr()'s coalesce. For a declared attribute, that fallback re-resolves\n * from the current attribute, keeping declared-default booleans\n * non-undefined.\n */\n _setProp(key: string, value: unknown): void {\n // Unknown-prop echo (N202, dev, ADR 0030.2): post-mount, a DEFINED write\n // to a key setup() never read is attribution noise \u2014 a misspelled prop\n // (`varian=`) arriving through the factory or the template\n // auto-resolution path (both funnel through _setProp). `undefined`\n // writes are exempt BY CONTRACT: a factory spreading unset optional\n // props fires _setProp(key, undefined) per the Object.entries walk (see\n // the pinning doc above). Attribution-only \u2014 the write still lands\n // exactly as before; deduped per key per element.\n if (\n process.env.NODE_ENV !== 'production'\n && completedSetups!.has(this)\n && value !== undefined\n && isDev()\n // A declared attrs key is contract, not a typo \u2014 'forward' especially,\n // where CORE owns the read and setup() never touches the prop. Gate\n // ruling on ADR 0030.2 \u00A78 T6 Q3: declared keys are exempt.\n && !attrEntriesByKey.has(key)\n && !propsReadKeys!.get(this._propsProxy!.props)!.has(key)\n && !echoedProps!.get(this)?.has(key)\n ) {\n const echoed = echoedProps!.get(this) ?? new Set<string>();\n echoed.add(key);\n echoedProps!.set(this, echoed);\n diag(\n 'N202',\n `<${tagName}> prop '${key}' was set but setup() never read it \u2014 misspelled or unsupported prop?`,\n { tag: tagName, key },\n );\n }\n if (value === undefined) {\n this._pinned.delete(key);\n const entry = attrEntriesByKey.get(key);\n if (entry) {\n const raw = this.getAttribute(entry.attrName);\n // A 'forward' attribute is removed from the host on adoption, so an\n // unpin can't re-read it \u2014 resolve the absent value directly to CLEAR\n // a previously pinned id/name (rev audit fix). _applyAttr's forward\n // branch deliberately no-ops on absent (so the seed/attr callback\n // never clobber an adopted value); the explicit unpin does not.\n if (raw === null && declType(entry.decl) === 'forward') {\n this._propsProxy?.setProperty(key, resolveAttrValue(entry.decl, null));\n } else {\n this._applyAttr(entry, raw);\n }\n return;\n }\n } else {\n this._pinned.add(key);\n }\n this._propsProxy?.setProperty(key, value);\n }\n\n /**\n * Read a prop's backing signal (framework-internal). Used by children()\n * to fold the factory `children` prop into the projection slot (ADR 0025\n * item 1) without a new public read API.\n */\n _propSignal(key: string): Signal<unknown> {\n return (this._propsProxy!.props as Record<string, Signal<unknown>>)[key]!;\n }\n\n /**\n * Whether a prop is currently pinned by a defined factory/property write\n * (framework-internal, like _propSignal). The attribute-as-truth open-state\n * pattern needs this as its controlled-mode discriminator: a declared\n * 'boolean' prop is never undefined (absent \u2192 false), so pin state is the\n * ONLY way a component can tell \"parent drives this\" from \"the attribute\n * drives this\" \u2014 e.g. setOpen() must not write the open attribute while a\n * controlled parent has it pinned, or the DOM attribute diverges from the\n * pinned state until the next prop write.\n */\n _isPinned(key: string): boolean {\n return this._pinned.has(key);\n }\n }\n\n // Register the custom element. A DUPLICATE definition is a coded dev error\n // (N201, ADR 0030.2 \u00A73/\u00A78): first-wins-silently rendered the WRONG component\n // while the second factory typechecked against the wrong props. The error\n // names both definition sites and is thrown to the SECOND definer; the\n // first definition stays live (first-wins preserved). Exemptions:\n // - HMR re-evaluations arrive with the registry's marked indirection thunk\n // (hmr/registry.ts __register) \u2014 the live thunk already swapped setup, so\n // re-registration is the mechanism working, not a collision.\n // - Production keeps the historical SILENT first-wins: a name clash must\n // not take down a live page (redefine-as-swap stays HMR/dev-only because\n // the copy-in registry model makes genuine duplicate tags structural).\n if (!customElements.get(tagName)) {\n customElements.define(tagName, FrameworkComponent);\n if (process.env.NODE_ENV !== 'production' && isDev()) firstDefineSites!.set(tagName, captureDefineSite());\n } else if (process.env.NODE_ENV !== 'production' && isDev() && !(setup as { __nisliHmr?: boolean }).__nisliHmr) {\n const first = firstDefineSites!.get(tagName)\n ?? '(unknown site \u2014 defined outside component(), or before dev mode was enabled)';\n throw new Error(formatDiag(\n 'N201',\n `duplicate define for <${tagName}>. First defined ${first}; the second `\n + `definition site is this error's own stack. The first definition stays `\n + `live (first-wins) \u2014 rename one of the components.`,\n ));\n }\n\n // Return the typed factory function\n const factory: ComponentFactory<P> = (props, hostAttrs?) => {\n return {\n __type: 'factory' as const,\n tagName,\n props: props as Record<string, PropInput<unknown>>,\n hostAttrs,\n } as unknown as TemplateResult;\n };\n\n return factory;\n}\n\n/**\n * Ensure a value is a signal. If it already is, return as-is.\n * If it's a plain value, wrap it in signal().\n * Used by factory mount to support PropInput<T> = T | Signal<T>.\n */\nfunction ensureSignal<T>(value: PropInput<T>): ReadonlySignal<T> {\n if (isSignal(value)) return value as ReadonlySignal<T>;\n return signal(value as T);\n}\n\n/**\n * Mount a TemplateResult into a host element.\n * This is the bridge between component.ts and template.ts.\n * Template.ts will provide the actual implementation via the\n * TemplateResult.mount() method.\n *\n * @param hostImpl \u2014 optional ComponentHostImpl for registering disposers\n */\nfunction mountTemplate(host: HTMLElement, result: TemplateResult, hostImpl?: ComponentHostImpl): void {\n if (result && typeof result === 'object' && 'mount' in result && typeof result.mount === 'function') {\n result.mount(host);\n } else if (result && typeof result === 'object' && '__type' in result) {\n // Factory result \u2014 create the child element\n const factoryResult = result as unknown as {\n __type: 'factory';\n tagName: string;\n props: Record<string, PropInput<unknown>>;\n hostAttrs?: HostAttrs;\n };\n const el = document.createElement(factoryResult.tagName);\n\n // Forward props as signals (auto-wrap plain values)\n for (const [key, raw] of Object.entries(factoryResult.props)) {\n const sig = ensureSignal(raw);\n (el as any)._setProp(key, sig.value);\n // Subscribe to signal changes to update the child's props\n const unsub = sig.subscribe((newVal: unknown) => {\n (el as any)._setProp(key, newVal);\n });\n // Register unsub for cleanup on disconnect\n if (hostImpl) {\n hostImpl.addDisposer(unsub);\n }\n }\n\n // Apply host-level attributes (class)\n if (factoryResult.hostAttrs?.class != null) {\n const classSig = ensureSignal(factoryResult.hostAttrs.class);\n // Apply initial value\n applyHostClass(el, '', classSig.value);\n // Subscribe to reactive changes\n let prevClass = classSig.value;\n const unsub = classSig.subscribe((newClass: string) => {\n applyHostClass(el, prevClass, newClass);\n prevClass = newClass;\n });\n if (hostImpl) {\n hostImpl.addDisposer(unsub);\n }\n }\n\n host.appendChild(el);\n }\n}\n\n/**\n * Apply a class string to an element via classList, replacing the previous\n * class string's classes. Uses add/remove to avoid interfering with classes\n * set by the component's own template (class:name directives, etc.).\n */\nfunction applyHostClass(el: Element, prev: string, next: string): void {\n const prevClasses = prev ? prev.split(/\\s+/).filter(Boolean) : [];\n const nextClasses = next ? next.split(/\\s+/).filter(Boolean) : [];\n for (const cls of prevClasses) {\n if (!nextClasses.includes(cls)) el.classList.remove(cls);\n }\n for (const cls of nextClasses) {\n if (!prevClasses.includes(cls)) el.classList.add(cls);\n }\n}\n", "/**\n * ref.ts \u2014 Element reference primitive for imperative DOM access\n *\n * `ref()` creates a container that receives a DOM element reference\n * after the template is mounted. Use it for focus management, DOM\n * measurement, scroll management, and third-party library init.\n *\n * ```ts\n * const inputRef = ref<HTMLInputElement>();\n *\n * onMount(() => inputRef.current?.focus());\n *\n * return html`<input ref=\"${inputRef}\" @keydown.enter=${onSubmit} />`;\n * ```\n *\n * The template engine detects `Ref` objects in `ref=\"${...}\"`\n * attribute bindings and assigns the referenced element.\n */\n\n// \u2500\u2500 Brand for ref detection in templates \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport const REF_BRAND = Symbol.for('backlog.ref');\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface Ref<T extends Element = Element> {\n readonly [REF_BRAND]: true;\n /** The DOM element, or null before mount / after unmount */\n current: T | null;\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Create a ref container for imperative DOM access.\n *\n * After the template is mounted, `ref.current` holds the element.\n * After dispose, `ref.current` is set back to null.\n */\nexport function ref<T extends Element = Element>(): Ref<T> {\n return {\n [REF_BRAND]: true as const,\n current: null,\n };\n}\n\n/**\n * Check if a value is a Ref.\n * Used by the template engine to detect refs in expression slots.\n */\nexport function isRef(value: unknown): value is Ref {\n return (\n value !== null &&\n typeof value === 'object' &&\n REF_BRAND in (value as Record<symbol, unknown>)\n );\n}\n", "/**\n * template-audit.ts \u2014 First-parse static template audit (ADR 0030.2 T4).\n *\n * Attached to the parse-once cache in template.ts: runs ONCE per `html`\n * callsite (keyed by TemplateStringsArray identity) at the first parse, and\n * walks the parsed-but-never-mounted template element checking its STATIC\n * parts. The silent-static-typo class \u2014 the no-build equivalent of a compile\n * error \u2014 dies in the engine, amortized free.\n *\n * Checks (per ADR 0030.2 \u00A72 T4 as amended by \u00A78 \"T4 (template)\"):\n * - N101 \u2014 a dash-tag with no customElements definition. Races\n * `customElements.whenDefined` against a microtask + macrotask grace so\n * ordinary lazy definition (module import order) never warns.\n * - N102 \u2014 an `@event` name that is neither a known native event nor an\n * allowlisted component-dispatched event (`ui-*`, `nisli-*`).\n * - N103 \u2014 an unknown `@event.modifier`.\n * - N104 \u2014 an attribute on a component tag that declares attributes\n * (non-empty `static observedAttributes`) which is neither declared nor a\n * global HTML attribute. Components WITHOUT declared attributes get NO\n * attribute audit: pre-schema (T3) there is no truth source \u2014 auto-resolved\n * props are deliberately not attributes (\u00A78).\n *\n * Suppression escape (designed for lazy islands, \u00A78): a comment directive as\n * the template's FIRST node (leading whitespace allowed):\n *\n * html`<!-- nisli-audit off --><my-island>\u2026</my-island>`\n * \u2014 disables the whole audit for this template.\n *\n * html`<!-- nisli-audit allow-undefined: my-island other-tag --><\u2026>`\n * \u2014 suppresses only N101 for the named tags (other checks stay live).\n *\n * The directive comment is static content: it survives into the mounted DOM\n * (and SSG output) as an inert HTML comment. Documented, accepted for the\n * prototype; the design gate may choose to strip it at parse.\n *\n * Calls AND module allocations are statically gated (ADR 0048). The runtime\n * override can suppress or restore available audits, never restore removed code.\n * No SSG/happy-dom detection is attempted; production rendering uses NODE_ENV\n * or the native production artifact.\n */\n\n// Reporting goes through the diagnostics leaf. The audit keeps its own\n// enable override (tests, SSG environments) and otherwise follows the\n// leaf's dev gate \u2014 under NODE_ENV=production builds it is silent.\nimport { diag as emitDiag, isDev } from './diagnostics.js';\n\nlet enabledOverride: boolean | null = null;\n\n/**\n * Enable/disable the first-parse audit (and its callsite capture);\n * `null` restores the dev-gate default.\n */\nexport function setTemplateAuditEnabled(enabled: boolean | null): void {\n if (process.env.NODE_ENV !== 'production') enabledOverride = enabled;\n}\n\n/** Current audit gate state (exposed for template.ts and tests). */\nexport function isTemplateAuditEnabled(): boolean {\n return process.env.NODE_ENV !== 'production' && (enabledOverride ?? isDev());\n}\n\n/** Emit a coded audit diagnostic through the diagnostics leaf (audit-gated). */\nexport function diag(code: string, message: string, detail?: unknown): void {\n if (!isTemplateAuditEnabled()) return;\n emitDiag(code, message, detail === undefined ? undefined : { detail });\n}\n\n// \u2500\u2500 Callsite capture \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** First-seen authoring callsite per template identity (dev only). */\nconst callsites = process.env.NODE_ENV !== 'production'\n ? new WeakMap<TemplateStringsArray, string>() : undefined;\n\n/**\n * Remember the authoring callsite of an `html` template the first time its\n * strings identity is seen. Must be called from `html()` itself \u2014 by the\n * time the first parse happens (first mount), the authoring frame is gone\n * from the stack. No-op when the audit is disabled or already captured.\n */\nexport function captureCallsite(strings: TemplateStringsArray): void {\n if (!isTemplateAuditEnabled() || callsites!.has(strings)) return;\n const stack = new Error().stack ?? '';\n const frame = stack\n .split('\\n')\n .slice(1)\n .find(line => line.includes('at ') && !/template(-audit)?\\.(ts|js|mjs|cjs)/.test(line));\n callsites!.set(strings, frame ? frame.trim() : '(unknown callsite)');\n}\n\n// \u2500\u2500 Audit \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst audited = process.env.NODE_ENV !== 'production'\n ? new WeakSet<TemplateStringsArray>() : undefined;\n\n/** Modifiers understood by bindEvent (template.ts). */\nconst KNOWN_MODIFIERS = process.env.NODE_ENV !== 'production'\n ? new Set(['stop', 'prevent', 'once', 'enter', 'escape', 'space', 'tab']) : undefined;\n\n/** Component-dispatched event prefixes exempt from the native-event check (\u00A78). */\nconst COMPONENT_EVENT_PREFIXES = ['ui-', 'nisli-'];\n\n/** Real native events with no `on*` IDL attribute (the `in`-check misses them). */\nconst NATIVE_EVENTS_WITHOUT_IDL = process.env.NODE_ENV !== 'production'\n ? new Set(['focusin', 'focusout']) : undefined;\n\n/**\n * Global HTML attributes legal on ANY component tag. Mirrors (and must stay a\n * superset of) template.ts's auto-resolution exclusion list \u2014 these reach the\n * element as plain attributes, never `_setProp`.\n */\nconst GLOBAL_ATTRS = process.env.NODE_ENV !== 'production' ? new Set([\n 'id', 'class', 'style', 'slot', 'title', 'role', 'tabindex', 'name',\n 'part', 'hidden', 'dir', 'lang', 'is',\n]) : undefined;\n\ninterface AuditDirectives {\n off: boolean;\n allowUndefined: Set<string>;\n}\n\n/** Parse the leading `<!-- nisli-audit \u2026 -->` directive comment, if any. */\nfunction parseDirectives(content: DocumentFragment): AuditDirectives {\n const directives: AuditDirectives = { off: false, allowUndefined: new Set() };\n for (const node of content.childNodes) {\n if (node.nodeType === Node.TEXT_NODE) {\n if ((node.textContent ?? '').trim() === '') continue; // leading whitespace\n break;\n }\n if (node.nodeType === Node.COMMENT_NODE) {\n const body = (node.textContent ?? '').trim();\n if (!body.startsWith('nisli-audit')) break;\n const rest = body.slice('nisli-audit'.length).trim();\n if (rest === 'off') {\n directives.off = true;\n } else if (rest.startsWith('allow-undefined')) {\n const tags = rest\n .slice('allow-undefined'.length)\n .replace(/^[:\\s]+/, '')\n .split(/[\\s,]+/)\n .filter(Boolean);\n for (const tag of tags) directives.allowUndefined.add(tag.toLowerCase());\n }\n }\n break; // only the FIRST non-whitespace node may carry the directive\n }\n return directives;\n}\n\n/**\n * N101 \u2014 dash-tag with no definition. Rather than warning synchronously (the\n * defining module may simply import later in the same task), race\n * `customElements.whenDefined(tag)` against a microtask + macrotask grace;\n * warn only if the tag is still undefined after the grace elapses.\n */\nfunction checkDashTag(tag: string, site: string): void {\n let registry: CustomElementRegistry | undefined;\n try {\n registry = customElements;\n } catch {\n return; // no registry in this environment \u2014 nothing to check\n }\n if (!registry || registry.get(tag)) return;\n\n let defined = false;\n try {\n registry.whenDefined(tag).then(\n () => { defined = true; },\n () => { /* invalid name \u2014 the synchronous throw below already covers it */ },\n );\n } catch {\n diag('N101', `<${tag}> is not a valid custom element name \u2014 at ${site}`);\n return;\n }\n\n // Grace: one microtask hop (whenDefined settlements for definitions made\n // earlier in this task) + one macrotask hop (definitions made later in the\n // same task, e.g. module evaluation order). Under fake timers the macrotask\n // may never fire \u2014 the warning is simply skipped, never wrong.\n queueMicrotask(() => {\n if (defined) return;\n setTimeout(() => {\n try {\n if (!isTemplateAuditEnabled() || defined || registry!.get(tag)) return;\n diag(\n 'N101',\n `<${tag}> is used in a template but never defined (customElements.get returned ` +\n `undefined after grace) \u2014 at ${site}. If this tag is a lazily-loaded island, ` +\n `suppress with a leading <!-- nisli-audit allow-undefined: ${tag} --> comment.`,\n );\n } catch { /* environment torn down during grace \u2014 nothing to report */ }\n }, 0);\n });\n}\n\n/** N102/N103 \u2014 event-name and modifier checks for one `@event.mods` attribute. */\nfunction checkEvent(el: Element, attrName: string, site: string): void {\n const parts = attrName.slice(1).split('.');\n const eventName = parts[0] ?? '';\n const modifiers = parts.slice(1);\n\n const isNative = `on${eventName}` in el || NATIVE_EVENTS_WITHOUT_IDL!.has(eventName);\n const isComponentEvent = COMPONENT_EVENT_PREFIXES.some(p => eventName.startsWith(p));\n if (eventName && !isNative && !isComponentEvent) {\n diag(\n 'N102',\n `@${eventName} on <${el.tagName.toLowerCase()}> is not a known native event ` +\n `(and not an allowlisted ${COMPONENT_EVENT_PREFIXES.join('/')} component event) \u2014 at ${site}`,\n );\n }\n for (const mod of modifiers) {\n if (!KNOWN_MODIFIERS!.has(mod)) {\n diag(\n 'N103',\n `unknown event modifier \".${mod}\" in \"${attrName}\" \u2014 known: ` +\n `${[...KNOWN_MODIFIERS!].join(', ')} \u2014 at ${site}`,\n );\n }\n }\n}\n\n/** N104 \u2014 undeclared attribute on a component that DECLARES attributes. */\nfunction checkComponentAttr(tag: string, name: string, observed: string[], site: string): void {\n if (name.startsWith('data-') || name.startsWith('aria-')) return;\n if (GLOBAL_ATTRS!.has(name) || observed.includes(name)) return;\n diag(\n 'N104',\n `<${tag}> declares attributes [${observed.join(', ')}] but the template sets ` +\n `unknown \"${name}\" \u2014 at ${site}. Undeclared names route through _setProp and are ` +\n `silently dead as attributes.`,\n );\n}\n\n/**\n * Run the one-time static audit over a freshly parsed template. Called by\n * template.ts's parse-once cache on cache miss; idempotent per template\n * identity, no-op when the audit is disabled. Read-only over the cached\n * template element \u2014 mounting state is never touched.\n */\nexport function auditTemplate(strings: TemplateStringsArray, template: HTMLTemplateElement): void {\n if (!isTemplateAuditEnabled() || audited!.has(strings)) return;\n audited!.add(strings);\n\n const site = callsites!.get(strings) ?? '(unknown callsite)';\n const content = template.content;\n const directives = parseDirectives(content);\n if (directives.off) return;\n\n for (const el of content.querySelectorAll('*')) {\n const tag = el.tagName.toLowerCase();\n const isDashTag = tag.includes('-');\n\n if (isDashTag && !directives.allowUndefined.has(tag)) {\n checkDashTag(tag, site);\n }\n\n // Attribute audit ONLY for components with declared attrs (\u00A78): a\n // non-empty static observedAttributes is the single pre-T3 truth source.\n let observed: string[] | undefined;\n if (isDashTag) {\n const ctor = customElements.get(tag) as { observedAttributes?: unknown } | undefined;\n const list = ctor?.observedAttributes;\n if (Array.isArray(list) && list.length > 0) observed = list as string[];\n }\n\n for (const attr of [...el.attributes]) {\n const name = attr.name;\n if (name.startsWith('@')) {\n checkEvent(el, name, site);\n continue;\n }\n // Directive positions with their own semantics \u2014 never attributes.\n if (name.startsWith('class:') || name === 'ref' || name === 'html:inner') continue;\n if (observed) checkComponentAttr(tag, name, observed, site);\n }\n }\n}\n", "/**\n * template.ts \u2014 Tagged template engine with targeted DOM binding\n *\n * The html tagged template literal parses HTML with expression slots,\n * creates bindings for signals, and produces a TemplateResult that\n * can be mounted into the DOM with surgical updates.\n *\n * Two phases:\n * 1. First render: parse template, clone, create bindings, mount\n * 2. Updates: signal changes trigger individual binding updates (O(1))\n */\n\nimport {\n signal,\n isSignal,\n effect,\n computed,\n untrack,\n type Signal,\n type ReadonlySignal,\n} from './signal.js';\nimport { isRef, type Ref } from './ref.js';\n// First-parse audit (ADR 0030.2 T4). The import is static \u2014 core has no\n// build-time dev/prod define yet (a named Wave-1 deliverable, \u00A78) \u2014 but every\n// entry point is a no-op behind template-audit's own dev flag.\nimport { auditTemplate, captureCallsite } from './template-audit.js';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface TemplateResult {\n /** Mount this template into a host element */\n mount(host: HTMLElement): void;\n /** Dispose all bindings and effects */\n dispose(): void;\n /** Brand for type checking */\n __templateResult: true;\n}\n\n// TypeScript's DOM library does not expose moveBefore() yet.\ninterface MoveCapableParent extends ParentNode {\n moveBefore(node: Node, child: Node | null): void;\n}\n\nconst canMoveWithin = (parent: ParentNode): parent is MoveCapableParent =>\n typeof (parent as Partial<MoveCapableParent>).moveBefore === 'function';\n\n/** A DOM event handler whose event type is inferred from its native event name. */\nexport type TypedEventHandler<K extends keyof HTMLElementEventMap> = (\n event: HTMLElementEventMap[K],\n) => void;\n\n/**\n * Value-returning untrack. signal.ts's `untrack` is `(fn: () => void) => void`\n * (the value-returning form is a 0030.2 \u00A73 papercut owned elsewhere); this\n * local wrapper closes over the result until that lands.\n */\nfunction untracked<T>(fn: () => T): T {\n let result!: T;\n untrack(() => { result = fn(); });\n return result;\n}\n\n// \u2500\u2500 Trusted HTML brand (raw) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Branded trusted-HTML value accepted by `html:inner` (and by @nisli/ssg's\n * static renderer, which re-exports this brand \u2014 core owns it, ADR 0030.2 \u00A78).\n * Structural, not nominal: cross-package/cross-realm values with the same\n * shape stay valid.\n */\nexport interface RawHtml {\n value: string;\n __raw: true;\n}\n\n/**\n * Mark a string as trusted raw HTML. `html:inner` accepts ONLY branded\n * values \u2014 a bare string throws N106 (the accidental-XSS-sink class closes,\n * ADR 0030.2 \u00A73). NEVER wrap user-generated input.\n */\nexport function raw(value: string): RawHtml {\n return { __raw: true as const, value };\n}\n\nfunction isRawHtml(value: unknown): value is RawHtml {\n return (\n typeof value === 'object'\n && value !== null\n && '__raw' in value\n && (value as RawHtml).__raw === true\n && typeof (value as RawHtml).value === 'string'\n );\n}\n\n// \u2500\u2500 Sanitized HTML brand (untrusted markup) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Branded UNTRUSTED-HTML value accepted by `html:inner`. The mirror image of\n * {@link RawHtml}: where `raw()` is the author asserting markup is already\n * trustworthy, this brand asserts the opposite \u2014 the string is untrusted and\n * MUST pass a sanitizer before it reaches the DOM (ADR 0019:124\u2013128, executed\n * by bet-09(c)). Structural, not nominal, on the same rule as RawHtml.\n */\nexport interface SanitizedHtml {\n value: string;\n __sanitize: true;\n}\n\n/**\n * Mark a string as untrusted markup to be sanitized at the sink \u2014 the brand\n * for user-generated HTML, which must NEVER go through `raw()`.\n *\n * `html:inner` writes it with the platform's `Element.setHTML()` (the spec's\n * XSS-safe default sanitizer) when the engine has one, otherwise with the hook\n * registered by {@link setSanitizerFallback}. With NEITHER available the\n * binding throws N107: it never falls back to `innerHTML`. nisli bundles no\n * sanitizer \u2014 the trust decision, and its bytes, stay in the app.\n */\nexport function sanitized(value: string): SanitizedHtml {\n return { __sanitize: true as const, value };\n}\n\nfunction isSanitizedHtml(value: unknown): value is SanitizedHtml {\n return (\n typeof value === 'object'\n && value !== null\n && '__sanitize' in value\n && (value as SanitizedHtml).__sanitize === true\n && typeof (value as SanitizedHtml).value === 'string'\n );\n}\n\n// \u2500\u2500 Sanitizer sinks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** A sanitizing writer: sanitize `html`, then put the result inside `el`. */\nexport type SanitizerFallback = (el: Element, html: string) => void;\n\nlet sanitizerFallback: SanitizerFallback | null = null;\n\n/**\n * Register the sanitizing writer used for `sanitized()` values on engines\n * WITHOUT native `Element.setHTML()` (Safari today, older Chromium/Firefox),\n * or `null` to unregister. Native `setHTML()` always wins where it exists, so\n * modern engines never pay the hook. nisli ships no sanitizer; wire one:\n *\n * setSanitizerFallback((el, html) => {\n * el.innerHTML = DOMPurify.sanitize(html);\n * });\n */\nexport function setSanitizerFallback(fn: SanitizerFallback | null): void {\n sanitizerFallback = fn;\n}\n\n// TypeScript's DOM library does not expose Element.setHTML() yet.\ninterface SanitizeCapableElement extends Element {\n setHTML(html: string): void;\n}\n\nconst nativeSetHtml: SanitizerFallback = (el, html) => {\n (el as SanitizeCapableElement).setHTML(html);\n};\n\n/**\n * The sanitizing writer for this element, or `null` when the engine has none\n * and the app registered none \u2014 the fail-closed signal N107 is thrown on.\n *\n * The method must be the one on `Element.prototype`, not merely *a* callable\n * named `setHTML`. A duck-typed check here is a sanitizer bypass: an element\n * carrying its own `setHTML` \u2014 DOM clobbering, an unsafe polyfill, a library\n * shim \u2014 would be trusted as the platform sanitizer and would preempt the\n * fallback the app explicitly registered as safe. Verified: with an\n * own-property `setHTML`, the registered fallback was never called and\n * `<img src=x onerror=\u2026>` reached innerHTML intact.\n *\n * Read from the prototype per write rather than captured at module load, so a\n * late polyfill or a test's stub is still honoured; identity is what is\n * checked, not existence. Replacing `Element.prototype.setHTML` wholesale is\n * out of scope \u2014 an attacker who can do that owns the realm regardless.\n */\nfunction sanitizerFor(el: Element): SanitizerFallback | null {\n const platform = typeof Element === 'function'\n ? (Element.prototype as Partial<SanitizeCapableElement>).setHTML\n : undefined;\n return typeof platform === 'function'\n && (el as Partial<SanitizeCapableElement>).setHTML === platform\n ? nativeSetHtml\n : sanitizerFallback;\n}\n\n// \u2500\u2500 Trusted Types pass-through \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The native `TrustedHTML` shape \u2014 also missing from TypeScript's DOM library.\n * Only `isHTML()` recognition is needed: under CSP\n * `require-trusted-types-for 'script'` the raw sink's plain-string `innerHTML`\n * assignment throws, so policy-created values pass through `html:inner`\n * unwrapped instead of being re-wrapped in `raw()`.\n */\ninterface TrustedHtml {\n toJSON(): string;\n}\n\ninterface TrustedTypeChecker {\n isHTML(value: unknown): boolean;\n}\n\nfunction isTrustedHtml(value: unknown): value is TrustedHtml {\n const tt = (globalThis as { trustedTypes?: TrustedTypeChecker }).trustedTypes;\n return tt !== undefined && tt.isHTML(value);\n}\n\n// TODO(diagnostics): replace with the core diagnostics leaf (parallel\n// worktree); template-layer codes N101\u2013N107 register there. N105\u2013N107 are\n// thrown (correctness/security guards), unlike the warn-level audit codes.\nfunction nisliError(code: string, message: string): Error {\n return new Error(`[nisli] ${code}: ${message}`);\n}\n\n// \u2500\u2500 Template cache \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Cache parsed templates by their static string parts.\n * Since tagged templates always produce the same static strings array\n * reference per call site, we use WeakMap for efficient caching.\n */\nconst templateCache = new WeakMap<TemplateStringsArray, HTMLTemplateElement>();\n\n/** Parses performed since module load \u2014 test-only regression hook (issue 0015). */\nlet parseCount = 0;\n\n/** @internal Test-only: number of actual `<template>` parses performed. */\nexport function __templateParseCount(): number {\n return parseCount;\n}\n\n/**\n * Parse-once (ADR 0030.2 T4, issue 0015): build the marker HTML string and\n * parse it into a `<template>` exactly once per callsite, keyed by\n * TemplateStringsArray identity. The string depends only on the static\n * `strings` (marker indices are positional), so every TemplateResult from the\n * same callsite shares one parsed template and clones per mount.\n *\n * The first parse also runs the one-time static audit (template-audit.ts)\n * over the pristine parsed element \u2014 it still carries the raw `@event`/\n * `class:`/marker attributes that processAttributes later strips from clones.\n */\nfunction parseTemplate(strings: TemplateStringsArray, valueCount: number): HTMLTemplateElement {\n let template = templateCache.get(strings);\n if (template) return template;\n\n // Build the HTML string with markers.\n // Track HTML parsing state to auto-quote markers in unquoted\n // attribute positions where the > in --> would close the tag.\n // See ADR 0069.\n let htmlStr = '';\n let inTag = false;\n let quoteChar: string | null = null;\n\n for (let i = 0; i < strings.length; i++) {\n const s = strings[i] ?? '';\n for (let c = 0; c < s.length; c++) {\n const ch = s.charAt(c);\n if (quoteChar) { if (ch === quoteChar) quoteChar = null; }\n else if (inTag) {\n if (ch === '>') inTag = false;\n else if (ch === '\"' || ch === \"'\") quoteChar = ch;\n } else { if (ch === '<') inTag = true; }\n }\n htmlStr += s;\n if (i < valueCount) {\n const needsQuotes = inTag && !quoteChar && /=\\s*$/.test(s);\n htmlStr += needsQuotes ? `\"${createMarker(i)}\"` : createMarker(i);\n }\n }\n\n parseCount++;\n template = document.createElement('template');\n template.innerHTML = htmlStr;\n templateCache.set(strings, template);\n\n // Dev-only first-parse audit (N101\u2013N104); no-op when disabled.\n if (process.env.NODE_ENV !== 'production') auditTemplate(strings, template);\n\n return template;\n}\n\n// \u2500\u2500 Marker for expression slots \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst MARKER_PREFIX = '<!--bk-';\nconst MARKER_SUFFIX = '-->';\nconst ATTR_MARKER = 'bk-';\n\n/**\n * Generate a unique marker for each expression slot.\n * We use HTML comments as markers in text positions and\n * special attribute prefixes for attribute positions.\n */\nfunction createMarker(index: number): string {\n return `${MARKER_PREFIX}${index}${MARKER_SUFFIX}`;\n}\n\n// \u2500\u2500 Binding types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface TextBinding {\n type: 'text';\n node: Text;\n dispose?: () => void;\n}\n\ninterface AttributeBinding {\n type: 'attribute';\n element: Element;\n name: string;\n dispose?: () => void;\n}\n\ninterface ClassBinding {\n type: 'class';\n element: Element;\n className: string;\n dispose?: () => void;\n}\n\ninterface EventBinding {\n type: 'event';\n element: Element;\n eventName: string;\n handler: EventListener;\n modifiers: string[];\n dispose?: () => void;\n}\n\ninterface InnerHtmlBinding {\n type: 'innerHtml';\n element: Element;\n dispose?: () => void;\n}\n\ninterface ChildBinding {\n type: 'child';\n startMarker: Comment;\n endMarker: Comment;\n currentNodes: Node[];\n dispose?: () => void;\n}\n\ntype Binding = TextBinding | AttributeBinding | ClassBinding | EventBinding | InnerHtmlBinding | ChildBinding;\n\n// \u2500\u2500 html tagged template \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Tagged template literal for creating reactive DOM templates.\n *\n * ```ts\n * const name = signal('World');\n * const greeting = html`<h1>Hello, ${name}!</h1>`;\n * ```\n *\n * Signals in expression slots are detected automatically and\n * create fine-grained bindings. When the signal changes, only\n * the specific text node or attribute updates \u2014 no diffing needed.\n */\nexport function html(\n strings: TemplateStringsArray,\n ...values: unknown[]\n): TemplateResult {\n const bindings: Binding[] = [];\n const disposers: (() => void)[] = [];\n // Dev-only: remember the authoring callsite for first-parse audit\n // diagnostics \u2014 by first-mount time this frame is gone from the stack.\n if (process.env.NODE_ENV !== 'production') captureCallsite(strings);\n let mounted = false;\n\n return {\n __templateResult: true as const,\n\n mount(host: HTMLElement): void {\n // Single-mount guard (ADR 0030.2 T4 + \u00A78): a second mount of a live,\n // un-disposed result with value bindings would attach a second set of\n // bindings to the same shared arrays \u2014 shared-binding corruption.\n // Zero-binding templates (the registry's shared static icon pattern)\n // stay multi-mountable; dispose() \u2192 mount() stays legal.\n if (mounted && values.length > 0) {\n throw nisliError(\n 'N105',\n `mount() on an already-mounted TemplateResult with ${values.length} value ` +\n `binding(s) \u2014 dispose() it first or create a fresh template per mount. ` +\n `Template starts: ${JSON.stringify((strings[0] ?? '').slice(0, 60))}`,\n );\n }\n mounted = true;\n\n // Parse-once: the parsed template is cached per callsite; each mount\n // only pays the clone + binding walk. The per-mount processNode walk\n // below REMAINS by design until the ADR 0014-class work \u2014 caching\n // removes the *parse*, not the walk (ADR 0030.2 \u00A78).\n const template = parseTemplate(strings, values.length);\n const fragment = template.content.cloneNode(true) as DocumentFragment;\n\n // Walk the DOM tree and replace markers with bindings\n processNode(fragment, values, bindings, disposers);\n\n // Mount into host\n host.appendChild(fragment);\n },\n\n dispose(): void {\n for (const d of disposers) {\n try { d(); } catch (_) {}\n }\n disposers.length = 0;\n for (const b of bindings) {\n if ('dispose' in b && b.dispose) {\n try { b.dispose(); } catch (_) {}\n }\n }\n bindings.length = 0;\n mounted = false;\n },\n };\n}\n\n// \u2500\u2500 DOM walking and binding creation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction processNode(\n node: Node,\n values: unknown[],\n bindings: Binding[],\n disposers: (() => void)[],\n): void {\n // Process element attributes\n if (node.nodeType === Node.ELEMENT_NODE) {\n const el = node as Element;\n processAttributes(el, values, bindings, disposers);\n }\n\n // Process text nodes and comments (markers)\n if (node.nodeType === Node.COMMENT_NODE) {\n const comment = node as Comment;\n const text = comment.textContent || '';\n // Check if this is one of our markers\n if (text.startsWith('bk-') && !isNaN(Number(text.slice(3)))) {\n const index = Number(text.slice(3));\n const value = values[index];\n replaceMarkerWithBinding(comment, value, bindings, disposers);\n return; // Don't recurse into replaced content\n }\n }\n\n // Process child nodes (make a copy since we may mutate)\n const children = [...node.childNodes];\n for (const child of children) {\n processNode(child, values, bindings, disposers);\n }\n}\n\nfunction processAttributes(\n el: Element,\n values: unknown[],\n bindings: Binding[],\n disposers: (() => void)[],\n): void {\n // We need to find attributes that contain markers\n const attrsToRemove: string[] = [];\n\n for (const attr of [...el.attributes]) {\n const name = attr.name;\n const attrValue = attr.value;\n\n // Check for @event bindings\n if (name.startsWith('@')) {\n const eventParts = name.slice(1).split('.');\n const eventName = eventParts[0] ?? '';\n const modifiers = eventParts.slice(1);\n\n // The value should be a marker containing the handler\n const markerMatch = attrValue.match(/<!--bk-(\\d+)-->/);\n if (markerMatch) {\n const index = Number(markerMatch[1]);\n const handler = values[index];\n if (typeof handler === 'function') {\n // Cleanup is registered on the EventBinding (removes the installed\n // safeHandler); a manual removeEventListener here would target the\n // original handler and no-op. See bindEvent (UI-33-R).\n bindEvent(el, eventName, handler as EventListener, modifiers, bindings);\n }\n }\n attrsToRemove.push(name);\n continue;\n }\n\n // Check for class:name bindings\n if (name.startsWith('class:')) {\n const className = name.slice(6);\n const markerMatch = attrValue.match(/<!--bk-(\\d+)-->/);\n if (markerMatch) {\n const index = Number(markerMatch[1]);\n const value = values[index];\n bindClass(el, className, value, bindings, disposers);\n }\n attrsToRemove.push(name);\n continue;\n }\n\n // Check for html:inner binding (trusted HTML rendering)\n if (name === 'html:inner') {\n const markerMatch = attrValue.match(/<!--bk-(\\d+)-->/);\n if (markerMatch) {\n const index = Number(markerMatch[1]);\n const value = values[index];\n bindInnerHtml(el, value, bindings, disposers);\n }\n attrsToRemove.push(name);\n continue;\n }\n\n // Check for ref binding: ref=\"${myRef}\"\n if (name === 'ref' && attrValue.includes(MARKER_PREFIX)) {\n const markerMatch = attrValue.match(/<!--bk-(\\d+)-->/);\n if (markerMatch) {\n const index = Number(markerMatch[1]);\n const value = values[index];\n if (isRef(value)) {\n (value as Ref).current = el;\n disposers.push(() => { (value as Ref).current = null; });\n }\n }\n attrsToRemove.push(name);\n continue;\n }\n\n // Check for regular attribute bindings with markers\n if (attrValue.includes(MARKER_PREFIX)) {\n const markers = [...attrValue.matchAll(/<!--bk-(\\d+)-->/g)];\n if (markers.length) {\n const first = markers[0];\n // Single expression = entire value: preserve raw type and signal\n if (markers.length === 1 && first && attrValue === first[0]) {\n bindAttribute(el, name, values[Number(first[1])], bindings, disposers);\n } else {\n // Mixed static + dynamic: resolve markers into string\n const resolve = () => attrValue.replace(/<!--bk-(\\d+)-->/g, (_, i) => {\n const v = values[Number(i)];\n const raw = isSignal(v) ? (v as ReadonlySignal<unknown>).value : v;\n return raw == null || raw === false ? '' : String(raw);\n });\n const hasSignals = markers.some(m => isSignal(values[Number(m[1])]));\n bindAttribute(el, name, hasSignals ? computed(resolve) : resolve(), bindings, disposers);\n }\n }\n continue;\n }\n }\n\n for (const name of attrsToRemove) {\n el.removeAttribute(name);\n }\n}\n\n/**\n * Mount a factory result (from component() factory functions) into a DOM element.\n * Handles prop forwarding (with signal subscriptions) and host-level class attrs.\n */\nfunction mountFactoryResult(\n factory: { tagName: string; props: Record<string, unknown>; hostAttrs?: { class?: unknown } },\n): { element: HTMLElement; dispose: () => void } {\n const el = document.createElement(factory.tagName);\n const localDisposers: (() => void)[] = [];\n for (const [key, raw] of Object.entries(factory.props)) {\n if (isSignal(raw)) {\n const sig = raw as ReadonlySignal<unknown>;\n const unsub = sig.subscribe((newVal: unknown) => {\n (el as any)._setProp?.(key, newVal);\n });\n localDisposers.push(unsub);\n } else {\n (el as any)._setProp?.(key, raw);\n }\n }\n if (factory.hostAttrs?.class != null) {\n const classVal = factory.hostAttrs.class;\n if (isSignal(classVal)) {\n const sig = classVal as ReadonlySignal<string>;\n let prevClasses: string[] = [];\n const applyClasses = (raw: string) => {\n const next = raw ? raw.split(/\\s+/).filter(Boolean) : [];\n for (const cls of prevClasses) {\n if (!next.includes(cls)) el.classList.remove(cls);\n }\n for (const cls of next) {\n if (!prevClasses.includes(cls)) el.classList.add(cls);\n }\n prevClasses = next;\n };\n const unsub = sig.subscribe(applyClasses);\n localDisposers.push(unsub);\n } else if (typeof classVal === 'string' && classVal) {\n for (const cls of classVal.split(/\\s+/).filter(Boolean)) {\n el.classList.add(cls);\n }\n }\n }\n return {\n element: el,\n dispose() {\n for (const dispose of localDisposers.splice(0)) {\n try { dispose(); } catch (_) { /* swallow */ }\n }\n },\n };\n}\n\nfunction replaceMarkerWithBinding(\n comment: Comment,\n value: unknown,\n bindings: Binding[],\n disposers: (() => void)[],\n): void {\n const parent = comment.parentNode;\n if (!parent) return;\n\n if (isSignal(value)) {\n // Every reactive child is a slot because its future values may have any\n // documented child type. The slot still keeps a single Text node alive for\n // primitive-to-primitive updates, preserving the O(1) text fast path.\n const startMarker = document.createComment('slot-start');\n const endMarker = document.createComment('slot-end');\n parent.replaceChild(endMarker, comment);\n parent.insertBefore(startMarker, endMarker);\n\n let currentResults: TemplateResult[] = [];\n let currentNodes: Node[] = [];\n let currentFactoryDisposers: (() => void)[] = [];\n let currentText: Text | null = null;\n // Sentinel distinct from any resolvable value (including null/undefined)\n // so the FIRST effect run always mounts. See ADR 0008.1.\n const NOT_RENDERED = Symbol('not-rendered');\n let lastValue: unknown = NOT_RENDERED;\n\n const dispose = effect(() => {\n const newValue = (value as ReadonlySignal<unknown>).value;\n // Use endMarker.parentNode \u2014 the captured `parent` may be a\n // DocumentFragment that was already appended to the real DOM,\n // leaving the markers reparented under the actual DOM element.\n const liveParent = endMarker.parentNode;\n if (!liveParent) return;\n\n // Memoize by referential identity. A computed/signal only notifies\n // when its value changes by Object.is, so an EQUAL value here means\n // this effect was re-triggered by some OTHER dependency (a tracking\n // leak), not by an actual change to this slot. Re-mounting identical\n // content would destroy live DOM (and reset scroll/focus) for nothing.\n // See ADR 0008.1.\n if (newValue === lastValue) return;\n lastValue = newValue;\n\n const isTemplate = Boolean(\n newValue\n && typeof newValue === 'object'\n && '__templateResult' in newValue,\n );\n const isFactory = Boolean(\n newValue\n && typeof newValue === 'object'\n && '__type' in newValue\n && (newValue as any).__type === 'factory',\n );\n const isPrimitive = newValue != null\n && newValue !== false\n && !Array.isArray(newValue)\n && !isTemplate\n && !isFactory;\n\n if (isPrimitive && currentText) {\n currentText.data = String(newValue);\n return;\n }\n\n // Dispose and remove the previous slot value before mounting the next.\n // Ownership is per VALUE, not per outer template lifetime: factory prop\n // subscriptions must stop as soon as their child leaves (issue 0011).\n for (const r of currentResults) {\n try { r.dispose(); } catch (_) {}\n }\n for (const dispose of currentFactoryDisposers) {\n try { dispose(); } catch (_) {}\n }\n for (const node of currentNodes) {\n node.parentNode?.removeChild(node);\n }\n currentNodes = [];\n currentResults = [];\n currentFactoryDisposers = [];\n currentText = null;\n\n if (newValue == null) {\n // null/undefined \u2014 nothing to mount\n } else if (Array.isArray(newValue)) {\n // Array of TemplateResults (or mixed content)\n for (const item of newValue) {\n if (item && typeof item === 'object' && '__templateResult' in item) {\n const tpl = item as TemplateResult;\n const wrapper = document.createDocumentFragment();\n tpl.mount(wrapper as unknown as HTMLElement);\n const nodes = [...wrapper.childNodes];\n currentNodes.push(...nodes);\n currentResults.push(tpl);\n liveParent.insertBefore(wrapper, endMarker);\n } else if (item && typeof item === 'object' && '__type' in item && (item as any).__type === 'factory') {\n const mounted = mountFactoryResult(item as any);\n currentNodes.push(mounted.element);\n currentFactoryDisposers.push(mounted.dispose);\n liveParent.insertBefore(mounted.element, endMarker);\n } else if (item != null && item !== false) {\n const textNode = document.createTextNode(String(item));\n currentNodes.push(textNode);\n liveParent.insertBefore(textNode, endMarker);\n }\n }\n } else if (isTemplate) {\n // Single TemplateResult\n const tpl = newValue as TemplateResult;\n const wrapper = document.createDocumentFragment();\n tpl.mount(wrapper as unknown as HTMLElement);\n currentNodes = [...wrapper.childNodes];\n currentResults.push(tpl);\n liveParent.insertBefore(wrapper, endMarker);\n } else if (isFactory) {\n // Factory result \u2014 create child element\n const mounted = mountFactoryResult(newValue as any);\n currentNodes.push(mounted.element);\n currentFactoryDisposers.push(mounted.dispose);\n liveParent.insertBefore(mounted.element, endMarker);\n } else if (newValue !== false) {\n currentText = document.createTextNode(String(newValue));\n currentNodes.push(currentText);\n liveParent.insertBefore(currentText, endMarker);\n }\n });\n disposers.push(dispose);\n // TemplateResult.dispose() intentionally leaves mounted DOM in place, but\n // it must still dispose bindings owned by the CURRENT reactive slot value.\n disposers.push(() => {\n for (const r of currentResults.splice(0)) {\n try { r.dispose(); } catch (_) {}\n }\n for (const factoryDispose of currentFactoryDisposers.splice(0)) {\n try { factoryDispose(); } catch (_) {}\n }\n currentNodes = [];\n currentText = null;\n });\n } else if (value && typeof value === 'object' && '__templateResult' in value) {\n // Nested template result \u2014 mount it\n const result = value as TemplateResult;\n const startMarker = document.createComment('tpl-start');\n const endMarker = document.createComment('tpl-end');\n parent.replaceChild(endMarker, comment);\n parent.insertBefore(startMarker, endMarker);\n\n // Create a wrapper element to mount into\n const wrapper = document.createDocumentFragment();\n result.mount(wrapper as unknown as HTMLElement);\n parent.insertBefore(wrapper, endMarker);\n\n disposers.push(() => result.dispose());\n } else if (value && typeof value === 'object' && '__type' in value && (value as any).__type === 'factory') {\n // Factory result \u2014 create child element\n const mounted = mountFactoryResult(value as any);\n parent.replaceChild(mounted.element, comment);\n disposers.push(mounted.dispose);\n } else if (Array.isArray(value)) {\n // Array of template results\n const startMarker = document.createComment('list-start');\n const endMarker = document.createComment('list-end');\n parent.replaceChild(endMarker, comment);\n parent.insertBefore(startMarker, endMarker);\n\n for (const item of value) {\n if (item && typeof item === 'object' && '__templateResult' in item) {\n const wrapper = document.createDocumentFragment();\n (item as TemplateResult).mount(wrapper as unknown as HTMLElement);\n parent.insertBefore(wrapper, endMarker);\n disposers.push(() => (item as TemplateResult).dispose());\n } else if (item && typeof item === 'object' && '__type' in item && (item as any).__type === 'factory') {\n const mounted = mountFactoryResult(item as any);\n parent.insertBefore(mounted.element, endMarker);\n disposers.push(mounted.dispose);\n } else {\n const textNode = document.createTextNode(String(item));\n parent.insertBefore(textNode, endMarker);\n }\n }\n } else if (value == null || value === false) {\n // null, undefined, false \u2014 render nothing\n parent.removeChild(comment);\n } else {\n // Primitive value \u2014 render as text\n const textNode = document.createTextNode(String(value));\n parent.replaceChild(textNode, comment);\n }\n}\n\nfunction bindAttribute(\n el: Element,\n name: string,\n value: unknown,\n bindings: Binding[],\n disposers: (() => void)[],\n): void {\n // class attribute gets special handling to avoid conflicts with\n // class:name directives (see bindClassAttribute for details).\n if (name === 'class') {\n bindClassAttribute(el, value, bindings, disposers);\n return;\n }\n\n // Auto-resolution: framework components get _setProp for custom props\n // (preserves types). Standard HTML attributes (id, style, data-*, aria-*,\n // and \u2014 ADR 0030.2 \u00A78 \u2014 title/role/tabindex/name) always use setAttribute\n // even on framework components: routed through _setProp they were silently\n // dead (no component declares them as props).\n const isHtmlAttr = name === 'id' || name === 'style'\n || name === 'slot' || name === 'title' || name === 'role'\n || name === 'tabindex' || name === 'name'\n || name.startsWith('data-') || name.startsWith('aria-');\n const hasPropSetter = !isHtmlAttr && typeof (el as any)._setProp === 'function';\n\n if (hasPropSetter) {\n if (isSignal(value)) {\n const binding: AttributeBinding = { type: 'attribute', element: el, name };\n bindings.push(binding);\n const dispose = effect(() => {\n (el as any)._setProp(name, (value as ReadonlySignal<unknown>).value);\n });\n binding.dispose = dispose;\n disposers.push(dispose);\n } else {\n (el as any)._setProp(name, value);\n }\n return;\n }\n\n bindPlainAttribute(el, name, value, bindings, disposers);\n}\n\n/**\n * Bind a value as a plain HTML attribute via `setAttribute`, reactive when it\n * is a signal, with `html`'s boolean/null semantics (true \u2192 present empty,\n * false/null/undefined \u2192 absent). NEVER uses `_setProp` \u2014 this is the shared\n * attribute path used by both `bindAttribute` (its non-component branch) and\n * `el()`, whose contract is *plain-HTML authoring*: a framework component tag\n * reached this way receives its values as attributes and resolves them through\n * its `attr()`/`boolAttr()` fallbacks, not typed prop setters.\n */\nfunction bindPlainAttribute(\n el: Element,\n name: string,\n value: unknown,\n bindings: Binding[],\n disposers: (() => void)[],\n): void {\n if (isSignal(value)) {\n const binding: AttributeBinding = { type: 'attribute', element: el, name };\n bindings.push(binding);\n\n const dispose = effect(() => {\n const v = (value as ReadonlySignal<unknown>).value;\n if (v == null || v === false) {\n el.removeAttribute(name);\n } else if (v === true) {\n el.setAttribute(name, '');\n } else {\n el.setAttribute(name, String(v));\n }\n });\n binding.dispose = dispose;\n disposers.push(dispose);\n } else {\n if (value == null || value === false) {\n el.removeAttribute(name);\n } else if (value === true) {\n el.setAttribute(name, '');\n } else {\n el.setAttribute(name, String(value));\n }\n }\n}\n\n/**\n * Bind a reactive class attribute using classList.add/remove instead of\n * setAttribute('class', ...). This prevents the class attribute binding\n * from overwriting classes toggled by class:name directives.\n *\n * The problem: setAttribute('class', 'foo bar') replaces ALL classes,\n * wiping out any classes added by classList.toggle() from class:name\n * bindings. By tracking which classes \"belong\" to the class attribute\n * and using classList operations, we only manage our own classes.\n */\nfunction bindClassAttribute(\n el: Element,\n value: unknown,\n bindings: Binding[],\n disposers: (() => void)[],\n): void {\n // On first call, we must clear the parser-set class attribute which\n // contains raw marker text (e.g. \"badge status-<!--bk-0-->\").\n // We snapshot any non-marker classes set by the parser before clearing.\n let initialized = false;\n let prevClasses: string[] = [];\n\n const applyClasses = (raw: unknown) => {\n if (!initialized) {\n // Clear the parser's class attribute (contains marker text)\n el.setAttribute('class', '');\n initialized = true;\n }\n const str = raw == null || raw === false ? '' : String(raw);\n const next = str.split(/\\s+/).filter(Boolean);\n\n // Remove classes no longer in the attribute value\n for (const cls of prevClasses) {\n if (!next.includes(cls)) {\n el.classList.remove(cls);\n }\n }\n // Add new classes\n for (const cls of next) {\n if (!prevClasses.includes(cls)) {\n el.classList.add(cls);\n }\n }\n prevClasses = next;\n };\n\n if (isSignal(value)) {\n const binding: AttributeBinding = { type: 'attribute', element: el, name: 'class' };\n bindings.push(binding);\n\n const dispose = effect(() => {\n applyClasses((value as ReadonlySignal<unknown>).value);\n });\n binding.dispose = dispose;\n disposers.push(dispose);\n } else {\n applyClasses(value);\n }\n}\n\nfunction bindClass(\n el: Element,\n className: string,\n value: unknown,\n bindings: Binding[],\n disposers: (() => void)[],\n): void {\n if (isSignal(value)) {\n const binding: ClassBinding = { type: 'class', element: el, className };\n bindings.push(binding);\n\n const dispose = effect(() => {\n const v = (value as ReadonlySignal<unknown>).value;\n el.classList.toggle(className, !!v);\n });\n binding.dispose = dispose;\n disposers.push(dispose);\n } else {\n el.classList.toggle(className, !!value);\n }\n}\n\n/**\n * Bind branded HTML content to an element's inner markup.\n *\n * Never a bare string \u2014 a brand is the author's explicit decision about where\n * the markup came from, which is what closes the accidental-XSS-sink class\n * (ADR 0030.2 \u00A73/\u00A78). Three shapes resolve, in the order they are checked:\n *\n * - `raw()` (core owns the `__raw` brand; @nisli/ssg re-exports it):\n * author-asserted trust \u2192 today's `innerHTML` sink, unchanged.\n * NEVER wrap user-generated input in raw().\n * - `sanitized()` \u2192 the sanitizer sink: native `Element.setHTML()`, else the\n * `setSanitizerFallback()` hook, else N107. It NEVER reaches `innerHTML`\n * (ADR 0019:124\u2013128, bet-09(c)).\n * - A native `TrustedHTML` object \u2192 the same `innerHTML` sink as `raw()`,\n * passed through unwrapped so Trusted-Types-enforcing apps can assign\n * policy output directly.\n *\n * Anything else throws N106. Supports both static values and reactive\n * `Signal`s of them; when the signal changes the content is rewritten through\n * the same branch. null/undefined (branded or not) clears the content.\n *\n * Usage in templates:\n * html`<span html:inner=\"${raw(highlightedHtml)}\"></span>`\n * html`<span html:inner=\"${sanitized(userComment)}\"></span>`\n */\nfunction bindInnerHtml(\n el: Element,\n value: unknown,\n bindings: Binding[],\n disposers: (() => void)[],\n): void {\n // PURE \u2014 validates the brand and proves a sink exists without writing\n // anything, so the eager signal check below can run it for its throw alone.\n // A SanitizedHtml resolves to ITSELF (the writer routes it to the\n // sanitizer); everything else resolves to the innerHTML payload.\n const resolveHtml = (v: unknown): string | SanitizedHtml | TrustedHtml => {\n if (v == null) return '';\n if (isRawHtml(v)) {\n // Both brands at once: trust is not resolvable in favour of the raw\n // sink, so reject rather than guess which one the author meant.\n if (isSanitizedHtml(v)) {\n throw nisliError(\n 'N106',\n `html:inner rejects a value branded both raw() and sanitized() \u2014 the ` +\n `trust decision is ambiguous. Pick one brand.`,\n );\n }\n return v.value;\n }\n if (isSanitizedHtml(v)) {\n // FAIL CLOSED. Untrusted markup is only ever eligible to be written once\n // a sanitizing sink is proven to exist; no native setHTML() and no\n // registered hook is a hard error, because silently downgrading to\n // innerHTML would reopen the exact XSS hole this brand closes.\n if (sanitizerFor(el) === null) {\n throw nisliError(\n 'N107',\n `html:inner cannot render sanitized() markup: this engine has no native ` +\n `Element.setHTML() and no fallback is registered. Wire one at startup \u2014 ` +\n `setSanitizerFallback((el, html) => { el.innerHTML = DOMPurify.sanitize(html) }) ` +\n `\u2014 nisli ships no sanitizer and will not fall back to innerHTML.`,\n );\n }\n return v;\n }\n if (isTrustedHtml(v)) return v;\n throw nisliError(\n 'N106',\n `html:inner rejects unbranded values (got ${typeof v}). Wrap trusted markup ` +\n `in raw(html), untrusted markup in sanitized(html) \u2014 and never wrap ` +\n `user-generated input in raw().`,\n );\n };\n\n const writeHtml = (v: unknown): void => {\n const resolved = resolveHtml(v);\n if (isSanitizedHtml(resolved)) {\n // The sanitizer sink. resolveHtml has already proven a writer exists,\n // and `el.innerHTML` is unreachable from this branch by construction.\n sanitizerFor(el)?.(el, resolved.value);\n return;\n }\n // The raw sink, unchanged: a plain string, or a TrustedHTML object handed\n // over WITHOUT stringifying it (stringifying would defeat the CSP check).\n // The cast only satisfies the DOM library's `string` typing.\n el.innerHTML = resolved as string;\n };\n\n if (isSignal(value)) {\n // Validate the INITIAL value untracked and eagerly so an unbranded or\n // unsanitizable signal throws synchronously out of mount(); later invalid\n // values throw inside the effect and land in effect error containment\n // (console.error, element content untouched).\n untracked(() => resolveHtml((value as ReadonlySignal<unknown>).value));\n\n const binding: InnerHtmlBinding = { type: 'innerHtml', element: el };\n bindings.push(binding);\n\n const dispose = effect(() => {\n writeHtml((value as ReadonlySignal<unknown>).value);\n });\n binding.dispose = dispose;\n disposers.push(dispose);\n } else {\n writeHtml(value);\n }\n}\n\nfunction bindEvent(\n el: Element,\n eventName: string,\n handler: EventListener,\n modifiers: string[],\n bindings: Binding[],\n): void {\n // One canonical INSTALLED identity that every removal path references \u2014 the\n // EventBinding `dispose` below AND the `once` self-removal. Forward-declared\n // so the modifier wrappers close over it before it is assigned; it is only\n // ever *called* after addEventListener, so the reference always resolves.\n // This identity-mismatch class bit el() dispose, html dispose, and once \u2014 a\n // single installed handler that all removals target closes it (UI-33-R2).\n let safeHandler!: EventListener;\n\n // Compose the modifier chain (inner); safeHandler wraps it in try/catch below.\n let composed: EventListener = handler;\n\n if (modifiers.includes('stop')) {\n const inner = composed;\n composed = (e: Event) => {\n e.stopPropagation();\n inner(e);\n };\n }\n if (modifiers.includes('prevent')) {\n const inner = composed;\n composed = (e: Event) => {\n e.preventDefault();\n inner(e);\n };\n }\n if (modifiers.includes('once')) {\n const inner = composed;\n composed = (e: Event) => {\n // Remove the ACTUALLY-INSTALLED listener, not this intermediate wrapper.\n el.removeEventListener(eventName, safeHandler);\n inner(e);\n };\n }\n\n // Keyboard modifiers\n for (const mod of modifiers) {\n if (['enter', 'escape', 'space', 'tab'].includes(mod)) {\n const keyMap: Record<string, string> = {\n enter: 'Enter',\n escape: 'Escape',\n space: ' ',\n tab: 'Tab',\n };\n const inner = composed;\n composed = (e: Event) => {\n if ((e as KeyboardEvent).key === keyMap[mod]) {\n inner(e);\n }\n };\n }\n }\n\n // Wrap in try/catch for error containment \u2014 THIS is the installed handler.\n // Handler bodies run UNTRACKED (ADR 0030.2 \u00A78, surfaced by the T5 review):\n // synchronous dispatchEvent from inside an effect would otherwise run the\n // handler under that effect's observer \u2014 widening the effect's dependency\n // set with every signal the handler reads and mis-attributing its writes.\n safeHandler = (e: Event) => {\n try {\n untrack(() => composed(e));\n } catch (err) {\n console.error(`Event handler error for '${eventName}':`, err);\n }\n };\n\n el.addEventListener(eventName, safeHandler);\n\n // Register cleanup of the ACTUALLY-INSTALLED handler (safeHandler), not the\n // caller's original \u2014 their identities differ, so a removeEventListener with\n // the original is a silent no-op (the UI-33-R leak). Both `html` dispose and\n // `el()` dispose iterate bindings and call `dispose`, so this is the single\n // correct cleanup path for event listeners.\n bindings.push({\n type: 'event',\n element: el,\n eventName,\n handler: safeHandler,\n modifiers,\n dispose: () => el.removeEventListener(eventName, safeHandler),\n });\n}\n\n// \u2500\u2500 each() reactive list rendering \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Brand for each result detection */\nconst EACH_BRAND = Symbol.for('backlog.each');\n\ninterface EachEntry<T> {\n key: string | number;\n itemSignal: Signal<T>;\n indexSignal: Signal<number>;\n templateResult: TemplateResult;\n /** Stable wrapper element that survives inner reactive content changes. */\n wrapper: HTMLElement;\n}\n\n/**\n * Reactive list rendering with keyed reconciliation.\n *\n * Renders a list of items from a signal, tracking each item by key.\n * When the array changes, only affected DOM nodes are added, removed,\n * or reordered \u2014 existing items update in-place via their signals.\n *\n * ```ts\n * const tasks = signal([{ id: '1', title: 'A' }, { id: '2', title: 'B' }]);\n * html`<ul>${each(tasks, t => t.id, (task, index) =>\n * html`<li>${computed(() => task.value.title)}</li>`\n * )}</ul>`\n * ```\n */\n/**\n * Adapt whatever a template callback returned into a mountable TemplateResult.\n * Factory descriptors (the value `component()` factories actually return) are\n * mounted through the same path every other slot uses (issue 0021).\n */\nfunction asTemplateResult(result: unknown): TemplateResult {\n if (result && typeof result === 'object' && '__templateResult' in result) {\n return result as TemplateResult;\n }\n if (result && typeof result === 'object' && (result as any).__type === 'factory') {\n let mounted: { element: HTMLElement; dispose: () => void } | null = null;\n return {\n __templateResult: true as const,\n mount(host: HTMLElement) {\n mounted = mountFactoryResult(result as any);\n host.appendChild(mounted.element);\n },\n dispose() {\n mounted?.dispose();\n mounted?.element.remove();\n mounted = null;\n },\n };\n }\n throw new TypeError(\n `each(): template callback must return a TemplateResult or a component factory result, got ${\n result === null ? 'null' : typeof result\n }`,\n );\n}\n\nexport function each<T>(\n items: ReadonlySignal<T[]>,\n keyFn: (item: T, index: number) => string | number,\n templateFn: (item: ReadonlySignal<T>, index: ReadonlySignal<number>) => TemplateResult | { __type: 'factory' },\n): TemplateResult {\n let startMarker: Comment;\n let endMarker: Comment;\n let entries: EachEntry<T>[] = [];\n let effectDispose: (() => void) | null = null;\n\n return {\n __templateResult: true as const,\n\n mount(host: HTMLElement) {\n startMarker = document.createComment('each-start');\n endMarker = document.createComment('each-end');\n host.appendChild(startMarker);\n host.appendChild(endMarker);\n\n effectDispose = effect(() => {\n const newItems = items.value;\n reconcile(newItems);\n });\n },\n\n dispose() {\n if (effectDispose) {\n effectDispose();\n effectDispose = null;\n }\n for (const entry of entries) {\n entry.templateResult.dispose();\n }\n entries = [];\n },\n };\n\n function reconcile(newItems: T[]) {\n const parent = endMarker.parentNode;\n if (!parent) return;\n\n // Validate the whole key set before updating item signals, mounting new\n // entries, or touching DOM. A duplicate update must leave the last valid\n // reconciliation intact so a later corrected array can recover normally.\n const keyedItems: Array<{ item: T; index: number; key: string | number }> = [];\n const keyIndices = new Map<string | number, number>();\n for (let i = 0; i < newItems.length; i++) {\n const item = newItems[i];\n if (item === undefined) continue;\n const key = keyFn(item, i);\n const previousIndex = keyIndices.get(key);\n if (previousIndex !== undefined) {\n const formattedKey = typeof key === 'string' ? JSON.stringify(key) : String(key);\n console.error(\n `each() requires unique keys. Duplicate key ${formattedKey} ` +\n `found at indices ${previousIndex} and ${i}; reconciliation skipped.`,\n );\n return;\n }\n keyIndices.set(key, i);\n keyedItems.push({ item, index: i, key });\n }\n\n // Build old key \u2192 entry map\n const oldMap = new Map<string | number, EachEntry<T>>();\n for (const entry of entries) {\n oldMap.set(entry.key, entry);\n }\n\n // Build new entries list\n const newEntries: EachEntry<T>[] = [];\n const newKeys = new Set<string | number>();\n\n for (const { item, index, key } of keyedItems) {\n newKeys.add(key);\n\n const existing = oldMap.get(key);\n if (existing) {\n // Reuse \u2014 update signals in place\n existing.itemSignal.value = item;\n existing.indexSignal.value = index;\n newEntries.push(existing);\n } else {\n // Create new entry with a stable wrapper element.\n // Using display:contents so the wrapper is invisible to layout \u2014\n // inner reactive content can freely swap DOM nodes without\n // invalidating the each() reconciler's node tracking.\n const itemSignal = signal(item) as Signal<T>;\n const indexSignal = signal(index);\n const wrapper = document.createElement('each-item');\n wrapper.style.display = 'contents';\n const templateResult = asTemplateResult(templateFn(itemSignal, indexSignal));\n templateResult.mount(wrapper);\n newEntries.push({ key, itemSignal, indexSignal, templateResult, wrapper });\n }\n }\n\n // Remove entries whose key is gone\n for (const entry of entries) {\n if (!newKeys.has(entry.key)) {\n entry.templateResult.dispose();\n entry.wrapper.parentNode?.removeChild(entry.wrapper);\n }\n }\n\n // Reorder DOM nodes to match new order.\n // Each entry has exactly one stable wrapper element, so positioning\n // is simple and immune to inner reactive content swaps.\n let cursor: Node = startMarker;\n for (const entry of newEntries) {\n const nextSibling = cursor.nextSibling;\n if (nextSibling !== entry.wrapper) {\n if (entry.wrapper.parentNode === parent && canMoveWithin(parent)) {\n // Already attached under this parent: atomic move preconditions hold.\n parent.moveBefore(entry.wrapper, nextSibling);\n } else {\n // Fresh wrapper, or a browser without moveBefore().\n parent.insertBefore(entry.wrapper, nextSibling);\n }\n }\n cursor = entry.wrapper;\n }\n\n entries = newEntries;\n }\n}\n\n/**\n * Conditional rendering helper (ADR 0030.2 \u00A73, boolean-gated with `else`).\n *\n * Shows `template` when the condition is truthy, `elseTemplate` (optional)\n * when falsy. Both arms accept a TemplateResult or a lazy callback\n * `() => TemplateResult`; callbacks are only evaluated for the active arm.\n *\n * Semantics for signal conditions:\n * - The gate is `!!condition.value` \u2014 a truthy\u2192truthy (or falsy\u2192falsy)\n * transition returns the memoized previous result, so the live branch is\n * NEVER rebuilt (no state/scroll/focus loss) and callbacks never re-run.\n * - Branch callbacks evaluate UNTRACKED: a signal read during branch\n * construction does not subscribe the when() computed, so it cannot\n * trigger a rebuild. Reactive parts inside a branch must be interpolated\n * as signals/computeds (values), not read raw at construction time.\n */\nexport function when(\n condition: unknown,\n template: TemplateResult | (() => TemplateResult),\n elseTemplate?: TemplateResult | (() => TemplateResult),\n): TemplateResult | ReadonlySignal<TemplateResult | null> | null {\n const resolveBranch = (\n branch: TemplateResult | (() => TemplateResult) | undefined,\n ): TemplateResult | null => {\n if (branch === undefined) return null;\n if (typeof branch === 'function') return untracked(branch);\n return branch;\n };\n\n if (isSignal(condition)) {\n // Boolean-gated memo: notify() marks observers dirty EAGERLY (before\n // value-equality is known), so a computed chain alone cannot stop a\n // truthy\u2192truthy recompute from re-evaluating the branch. The memo pins\n // branch evaluation to actual boolean FLIPS; equal gates return the\n // cached result, which the slot then memoizes by identity (ADR 0008.1).\n let lastGate: boolean | undefined;\n let lastResult: TemplateResult | null = null;\n return computed(() => {\n const gate = !!(condition as ReadonlySignal<unknown>).value;\n if (gate === lastGate) return lastResult;\n const next = gate ? resolveBranch(template) : resolveBranch(elseTemplate);\n // Commit the memo only after a successful resolve so a throwing branch\n // callback retries on the next read (computed error containment).\n lastGate = gate;\n lastResult = next;\n return next;\n });\n }\n return condition ? resolveBranch(template) : resolveBranch(elseTemplate);\n}\n\n// \u2500\u2500 el(): dynamic tag names (ADR 0025 item 11) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** A value bindable to an `el()` attribute \u2014 static or reactive. */\ntype ElAttrValue = string | number | boolean | null | undefined | ReadonlySignal<unknown>;\n\nexport interface ElProps {\n /** Assigned to `.current` on mount, nulled on dispose. */\n ref?: Ref;\n /** Event handlers by native event name; auto-removed on dispose. */\n on?: Record<string, EventListener>;\n /** Any other key is an HTML attribute (static or signal \u2192 reactive). */\n [attr: string]: ElAttrValue | Ref | Record<string, EventListener> | undefined;\n}\n\n/** A child accepted by `el()` \u2014 anything an `html` text slot accepts, plus arrays. */\nexport type ElChild =\n | string\n | number\n | boolean\n | null\n | undefined\n | TemplateResult\n | ReadonlySignal<unknown>\n | { __type: 'factory' }\n | ElChild[];\n\n/**\n * Build a DOM element by a (possibly *dynamic*) tag name with reactive\n * attributes, event handlers, and children, returned as a mountable/disposable\n * `TemplateResult` \u2014 so it composes in an `html` slot:\n * `` html`${el(tag, { class: cls }, children)}` ``.\n *\n * `el()` is the \"author plain HTML programmatically\" primitive. It exists for\n * the one thing `html` cannot express \u2014 a tag name chosen at runtime \u2014 while\n * the `html` PARSER STAYS 100% STATIC: `el()` is a separate construction path\n * that shares `html`'s binding helpers (`bindPlainAttribute`, `bindClassAttribute`,\n * `bindEvent`, and the `replaceMarkerWithBinding` slot mounter). Prefer `html`\n * for static tags and typed factories for typed composition.\n *\n * Semantics (ADR 0025 item 11):\n * - Props are **HTML attributes**: `class` uses the reactive class binder, every\n * other key uses `setAttribute` with `html`'s boolean/null rules \u2014 NEVER\n * `_setProp`. A framework component tag reached via `el()` receives its values\n * as attributes and resolves them through its `attr()`/`boolAttr()` fallbacks.\n * - `ref` assigns `.current`; `on: { event: handler }` adds auto-removed listeners.\n * - Children accept the full `html` text-slot range \u2014 string/number, signals\n * (reactive text or reactive template slot), `TemplateResult`, factory results,\n * and arrays \u2014 via the shared slot mounter.\n * - v1 is HTML-only: SVG/namespaced tags (`createElementNS`) are deferred until a\n * real consumer needs them.\n */\nexport function el(\n tag: string,\n props: ElProps = {},\n children?: ElChild | ElChild[],\n): TemplateResult {\n let node: HTMLElement | null = null;\n const bindings: Binding[] = [];\n const disposers: (() => void)[] = [];\n\n return {\n __templateResult: true,\n\n mount(host: HTMLElement): void {\n const element = document.createElement(tag);\n node = element;\n\n for (const [key, val] of Object.entries(props)) {\n if (val === undefined) continue;\n if (key === 'ref') {\n if (isRef(val)) {\n (val as Ref).current = element;\n disposers.push(() => { (val as Ref).current = null; });\n }\n continue;\n }\n if (key === 'on') {\n // bindEvent registers correct disposal on the EventBinding (removes\n // the installed safeHandler); no manual removeEventListener (UI-33-R).\n for (const [event, handler] of Object.entries(val as Record<string, EventListener>)) {\n bindEvent(element, event, handler, [], bindings);\n }\n continue;\n }\n if (key === 'class') {\n bindClassAttribute(element, val, bindings, disposers);\n continue;\n }\n bindPlainAttribute(element, key, val, bindings, disposers);\n }\n\n // Children reuse html's text-slot mounter: append a comment anchor per\n // child and let replaceMarkerWithBinding resolve its type in place.\n const flat: ElChild[] = [];\n flattenChildren(children, flat);\n for (const child of flat) {\n const anchor = document.createComment('');\n element.appendChild(anchor);\n replaceMarkerWithBinding(anchor, child, bindings, disposers);\n }\n\n host.appendChild(element);\n },\n\n dispose(): void {\n for (const d of disposers) {\n try { d(); } catch (_) { /* swallow */ }\n }\n disposers.length = 0;\n for (const b of bindings) {\n if ('dispose' in b && b.dispose) {\n try { b.dispose(); } catch (_) { /* swallow */ }\n }\n }\n bindings.length = 0;\n node?.parentNode?.removeChild(node);\n node = null;\n },\n };\n}\n\nfunction flattenChildren(children: ElChild | ElChild[] | undefined, out: ElChild[]): void {\n if (children === undefined) return;\n if (Array.isArray(children)) {\n for (const c of children) flattenChildren(c, out);\n } else {\n out.push(children);\n }\n}\n", "/**\n * projection.ts \u2014 First-class content projection (ADR 0025 item 1)\n *\n * `children(fallback?)` is a setup-context primitive that owns the light-DOM\n * projection machinery the registry currently hand-rolls\n * (captureChildren/projectChildren + per-component conditional-default swaps).\n *\n * ```ts\n * component('ui-button', (props, host) => {\n * transparentHost(host);\n * return html`<button class=\"${classes}\">${children()}</button>`;\n * });\n * ```\n *\n * Semantics:\n * - Returns a reactive slot value (a signal) that a template interpolates. The\n * slot resolves, in priority order: the factory `children` prop \u2192 the host's\n * captured light-DOM children \u2192 the fallback.\n * - Factory `children` route through the SAME slot: `children()` READS the\n * host's `children` prop signal (sugar over one path). Crucially it renders\n * them AT the slot position (not by relocating them to light DOM), so a\n * factory-composed child element is a DOM descendant of its parent when its\n * connectedCallback runs \u2014 `closest()`-based parent lookup keeps working.\n * - Plain-HTML light-DOM children are captured pre-setup by component.ts\n * (SEED \u2192 CAPTURE \u2192 CONTEXT) and projected here; late parser children are\n * swept in a microtask (the ADR 0023 streaming machinery, now in core).\n * - `children(fallback)` renders `fallback` when no MEANINGFUL children exist\n * (whitespace-only light DOM does not count) and REPLACES it reactively when\n * children arrive \u2014 including late parser children. This natively solves the\n * conditional-default class (message-scroller-button's default glyph).\n * - Single default slot only; named/multiple slots are a later design (v1 OUT).\n *\n * Zero-cost when unused: component.ts only snapshots childNodes when the host\n * has any, and only children() consumes them.\n */\n\nimport { getCurrentComponent } from './context.js';\nimport { onCleanup } from './lifecycle.js';\nimport { signal, computed, flush, type ReadonlySignal, type Signal } from './signal.js';\nimport type { TemplateResult } from './template.js';\n\n/** True if the nodes carry meaningful content (element or non-blank text). */\nfunction isMeaningful(nodes: Node[]): boolean {\n return nodes.some(\n (n) => n.nodeType === 1 || (n.nodeType === 3 && (n.textContent ?? '').trim() !== ''),\n );\n}\n\n/** A minimal TemplateResult that mounts pre-existing DOM nodes into the slot. */\nfunction nodesTemplate(nodes: Node[]): TemplateResult {\n return {\n __templateResult: true,\n mount(w: HTMLElement) {\n for (const node of nodes) w.appendChild(node);\n },\n dispose() { /* nodes are owned by the host tree; nothing to tear down */ },\n } as unknown as TemplateResult;\n}\n\n/** A re-mountable TemplateResult that renders a primitive as a fresh text node. */\nfunction textTemplate(text: string): TemplateResult {\n return {\n __templateResult: true,\n mount(w: HTMLElement) {\n w.appendChild(document.createTextNode(text));\n },\n dispose() { /* text node removed by the slot */ },\n } as unknown as TemplateResult;\n}\n\n/**\n * Normalize a slot value so the template ALWAYS sees a TemplateResult / factory\n * / array / null \u2014 never a bare primitive. Projection values may be detached\n * and reinserted as fallback/light-DOM ownership changes, so wrapping primitive\n * text keeps that projection value explicitly re-mountable.\n */\nfunction asSlot(value: unknown): unknown {\n if (value == null || value === '') return null;\n if (\n typeof value === 'object'\n && ('__templateResult' in (value as object) || '__type' in (value as object))\n ) {\n return value;\n }\n if (Array.isArray(value)) return value;\n return textTemplate(String(value));\n}\n\n/**\n * Project the host's children (factory `children` prop or light DOM) into this\n * slot, with an optional `fallback` rendered when empty. Must be called in\n * setup context. Interpolate the result in a template:\n * `html`<button>${children()}</button>``.\n */\nexport function children(fallback?: TemplateResult | string): ReadonlySignal<unknown> {\n const host = getCurrentComponent().element as HTMLElement & {\n __capturedChildren?: Node[];\n __nisliProjectionSweep?: () => void;\n _propSignal?(key: string): Signal<unknown>;\n };\n\n // Consume the pre-setup light-DOM capture; remove those nodes from the host\n // so the rendered template doesn't duplicate them.\n const captured = host.__capturedChildren ?? [];\n host.__capturedChildren = undefined;\n for (const node of captured) {\n if (node.parentNode === host) host.removeChild(node);\n }\n\n // The factory `children` prop, folded into the same slot (sugar over one path).\n const childrenProp = host._propSignal ? host._propSignal('children') : undefined;\n\n // Projected light-DOM nodes; grows when the late-parser sweep finds more.\n const projectedNodes = signal<Node[]>(captured);\n\n // True once this setup scope has been disposed (true disconnect, HMR\n // teardown, OR the containment boundary tearing down a failed mount). The\n // queued sweep below must then no-op: it would otherwise misread the\n // post-teardown host children (restored light DOM, or the error fallback)\n // as \"late\" and relocate them into a dead slot.\n let disposed = false;\n\n // A true disconnect/HMR teardown clears the component-owned rendered tree\n // before setup runs again. Hand the plain light-DOM nodes back to component.ts\n // so it can restore them as direct host children for the next capture.\n onCleanup(() => {\n disposed = true;\n const nodes = projectedNodes.value;\n host.__capturedChildren = nodes.length ? nodes : undefined;\n });\n\n // LATE-CHILDREN SWEEP \u2014 scheduled by component.ts's dedicated projection\n // phase (ADR 0030.2 \u00A73), which runs after the template is committed and\n // BEFORE any onMount callback. Pre-0030.2 this was registered via\n // children()'s own onMount, so the rendered-roots snapshot depended on\n // where children() sat relative to other onMount() registrations (the 0025\n // batch-3B ordering trap). Hoisting the SCHEDULING makes the rule\n // universal: the snapshot is exactly the rendered template roots, and\n // anything appearing after it \u2014 late parser/innerHTML children AND onMount\n // host-appends \u2014 classifies as projected content. Only scheduling moved;\n // the prop READ path (the computed below) is unchanged.\n host.__nisliProjectionSweep = () => {\n // The host's direct children at phase time are the rendered template\n // roots. Anything that appears later is late projected content.\n const renderedRoots = new Set<Node>(Array.from(host.childNodes));\n queueMicrotask(() => {\n if (disposed) return; // scope torn down before the sweep ran\n const late = Array.from(host.childNodes).filter((n) => !renderedRoots.has(n));\n if (late.length && isMeaningful(late)) {\n for (const node of late) host.removeChild(node);\n projectedNodes.value = [...projectedNodes.value, ...late];\n // Flush the slot effect NOW so the late children land in this same\n // microtask \u2014 the projectChildren() this replaces mutated the DOM\n // imperatively, so callers only await one microtask for the sweep.\n flush();\n }\n });\n };\n\n // Stable, RE-MOUNTABLE fallback slot: the same slot object is returned on\n // every empty render, and it can be mounted \u2192 unmounted \u2192 mounted again\n // (empty \u2192 filled \u2192 empty) without crashing. A string wraps to a fresh text\n // node each mount. A TemplateResult is mounted ONCE here into a detached\n // holder (its reactive bindings run in this component's context and dispose\n // with it); its rendered nodes are then exposed as a re-mountable node slot,\n // so the engine can detach and re-append them freely.\n let fallbackSlot: unknown = null;\n if (fallback != null) {\n if (typeof fallback === 'string') {\n fallbackSlot = textTemplate(fallback);\n } else {\n const holder = document.createDocumentFragment();\n fallback.mount(holder as unknown as HTMLElement);\n const fallbackNodes = Array.from(holder.childNodes);\n onCleanup(() => { try { fallback.dispose(); } catch (_) { /* ignore */ } });\n fallbackSlot = nodesTemplate(fallbackNodes);\n }\n }\n\n // Priority: factory children \u2192 captured/late light DOM \u2192 fallback. Reactive,\n // so late children (or a changing `children` prop) replace the fallback.\n return computed(() => {\n const kids = childrenProp?.value;\n if (kids != null && kids !== '') return asSlot(kids);\n const nodes = projectedNodes.value;\n if (isMeaningful(nodes)) return nodesTemplate(nodes);\n return fallbackSlot;\n });\n}\n", "/**\n * settle.ts \u2014 Awaitable async quiescence (ADR 0030.2 T2).\n *\n * `await settle()` resolves when every framework-started logical async\n * request has TERMINATED and the reactive graph is quiescent. Query runs\n * (query.ts) and resource loads (resource.ts) enroll here when they start\n * and deregister at *termination* \u2014 commit, terminal error after retries,\n * or abort \u2014 never at raw promise settlement. An abort-ignoring fetcher\n * whose run was superseded therefore cannot wedge `settle()`: the run's\n * registry entry closed at the abort even though the underlying promise\n * never resolves.\n *\n * ```ts\n * mount(app);\n * await settle();\n * expect(screen.textContent).toContain('loaded'); // no waitFor polling\n * ```\n *\n * Contract and bounds:\n * - This is a **test/verify primitive** (and the SSG pre-snapshot barrier).\n * Awaiting it in a live app with continuous background refetch/polling is\n * unbounded *by design* \u2014 each commit may legally schedule the next\n * request. A scope argument waits for a second consumer (ADR 0030.2 \u00A78).\n * - Each iteration awaits the pending registry, then `tick()` (signal.ts's\n * bounded microtask-drain contract). Timer-scheduled work is NOT awaited\n * beyond what a pending logical request itself spans.\n * - Iteration-capped at 50 like `tick()`; hitting the cap emits diagnostic\n * N603 and resolves \u2014 never a silent hang, never an unbounded loop.\n *\n * MERGE ITEM: `__resetPending()` should be folded into `resetInjector()`\n * (injector.ts is owned by another worktree); until then test teardown\n * calls it directly.\n */\n\nimport { tick } from './signal.js';\n\n// \u2500\u2500 Pending logical-request registry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * One entry per in-flight logical request. The promise is a *termination*\n * promise resolved by the enroller's `done()` callback \u2014 deliberately not\n * the fetcher/loader promise itself (see module doc).\n */\nconst pending = new Set<Promise<void>>();\n\n/**\n * Enroll a logical async request. Returns its `done()` terminator: call it\n * at commit, terminal error, or abort. Idempotent \u2014 a superseded run whose\n * terminator was already invoked by the superseding path may safely call\n * it again from its own settlement branch.\n *\n * @internal \u2014 called by query.ts runs and resource.ts loader generations.\n */\nexport function __enrollPending(): () => void {\n let resolve!: () => void;\n const entry = new Promise<void>((res) => { resolve = res; });\n pending.add(entry);\n let done = false;\n return () => {\n if (done) return;\n done = true;\n pending.delete(entry);\n resolve();\n };\n}\n\n/**\n * Reset the registry. Test-teardown escape hatch: entries orphaned by a\n * test that never terminated its fetchers would otherwise leak into the\n * next test's `settle()`.\n *\n * @internal\n */\nexport function __resetPending(): void {\n pending.clear();\n}\n\n/** Current number of enrolled (unterminated) logical requests. @internal */\nexport function __pendingCount(): number {\n return pending.size;\n}\n\n// \u2500\u2500 Diagnostics + test isolation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Reporting goes through the core diagnostics leaf. The pending registry\n// self-registers with resetInjector() so test teardown clears it without\n// an upside-down import (settle \u2192 injector, never the reverse).\nimport { diag, isDev } from './diagnostics.js';\nimport { registerResetHook } from './injector.js';\n\nregisterResetHook(__resetPending);\n\n// \u2500\u2500 settle() \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Await async quiescence: loop `tick()` \u2192 `Promise.allSettled(pending)`\n * until a full `tick()` leaves the pending registry empty.\n *\n * The `tick()` *first* ordering matters: observer effects created since\n * the last flush are what *start* runs (and enroll them) \u2014 the registry\n * can only be trusted empty after the reactive graph has flushed.\n */\nexport async function settle(): Promise<void> {\n for (let i = 0; i < 50; i++) {\n await tick();\n if (pending.size === 0) return;\n await Promise.allSettled([...pending]);\n }\n if (process.env.NODE_ENV !== 'production' && isDev()) diag(\n 'N603',\n 'settle() did not reach quiescence within 50 iterations \u2014 something '\n + 'keeps scheduling new async work (a self-invalidating query or a '\n + 'polling loop?). settle() is a test/verify primitive; under live '\n + 'background refetch it is unbounded by design. Returning anyway.',\n );\n}\n", "/**\n * query.ts \u2014 Keyed logical-request store (ADR 0030.2 T1).\n *\n * The cache unit is a per-key RECORD living in `QueryClient`:\n * `{data, error, status, fetchedAt}` as signals, plus exactly one `run()`\n * owning the retry loop, a per-run `AbortController` handed to the fetcher,\n * and the cache commit. `query()` is a thin OBSERVER: an effect keeps it\n * registered on the record its current key points at, and its outputs are\n * `computed()` views over that record. Dedup unit = logical request, by\n * construction (issues 0005\u20130009 close as a class).\n *\n * ```ts\n * const tasks = query(\n * () => ['tasks', scopeId.value],\n * (signal) => api.getTasks(scopeId.value, { signal }),\n * );\n * tasks.data // ReadonlySignal<Task[] | undefined>\n * tasks.loading // ReadonlySignal<boolean>\n * tasks.error // ReadonlySignal<Error | null>\n * tasks.status // ReadonlySignal<'idle' | 'loading' | 'success' | 'error'>\n * tasks.refetch() // force a refetch (joins an in-flight run)\n * tasks.dispose() // standalone callers; component setup auto-disposes\n * ```\n *\n * Ownership rules (ADR 0030.2 \u00A78, binding):\n * - The most-recently-mounted enabled observer's fetcher/options own the\n * next run for a shared key; `staleTime` freshness is per-observer POLICY\n * (it decides whether *that* observer triggers a run), while the record\n * state is shared truth.\n * - `invalidate()` marks records stale and reruns only records with \u22651\n * enabled observer; disabled observers revalidate on re-enable.\n * - A zero-observer record's in-flight run completes and commits.\n * - Records are NEVER garbage-collected: the cache is unbounded for the\n * life of the client (restates today's unbounded-cache bound). Bound it\n * operationally with `clear()` or a fresh client per app lifetime.\n *\n * Key contract: keys are FLAT \u2014 `readonly (string|number|boolean|null)[]`.\n * Objects and `undefined` are rejected with coded error N602 (`null` is\n * the optional sentinel). Flat keys are order-sensitive: prefer\n * per-endpoint key-builder helpers \u2014 a reordered key is a silent cache\n * *miss*, benign relative to a collision, but a miss.\n *\n * SSG stance (documented, not built): under core-render, records fetch\n * into the build-lifetime client and must TERMINATE before snapshot \u2014\n * `await settle()` is the barrier. Otherwise queries must be statically\n * disabled for the build.\n */\n\nimport {\n signal,\n effect,\n computed,\n untrack,\n type Signal,\n type ReadonlySignal,\n} from './signal.js';\nimport { hasContext, getCurrentComponent } from './context.js';\nimport { disposable, type DisposableResource } from './disposable.js';\nimport { inject } from './injector.js';\nimport { __enrollPending } from './settle.js';\nimport { formatDiag } from './diagnostics.js';\n\n// Diagnostics go through the core leaf (diagnostics.ts). Codes N602\u2013N603\n// belong to the query/async cluster (N601 retired before release \u2014 see\n// the eliminated-class note below).\n\n/** Build the coded error for key-contract violations. Always thrown \u2014\n * key validity is a contract, not an advisory diagnostic. */\nfunction keyError(detail: string): Error {\n return new Error(formatDiag(\n 'N602',\n `invalid query key: ${detail}. Keys must be flat `\n + 'readonly (string | number | boolean | null)[] arrays \u2014 spread '\n + 'object params into tuple elements; null is the optional sentinel.',\n ));\n}\n\n// \u2500\u2500 Key contract \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** A single query-key element. `null` is the optional sentinel. */\nexport type QueryKeyElement = string | number | boolean | null;\n\n/** The supported key contract: a flat, order-sensitive tuple. */\nexport type QueryKey = readonly QueryKeyElement[];\n\n/**\n * Validate a key against the flat contract and return a detached copy\n * (callers may mutate their array; records must not observe that).\n * Rejects objects, arrays, functions, undefined, and non-finite numbers\n * (NaN/Infinity JSON-serialize as null and would collide) with N602.\n */\nfunction validateKey(raw: unknown): QueryKey {\n if (!Array.isArray(raw)) {\n throw keyError(`expected an array, got ${typeof raw}`);\n }\n for (let i = 0; i < raw.length; i++) {\n const el: unknown = raw[i];\n if (el === null) continue;\n const t = typeof el;\n if (t === 'string' || t === 'boolean') continue;\n if (t === 'number') {\n if (Number.isFinite(el)) continue;\n throw keyError(`non-finite number at index ${i} (would collide with null)`);\n }\n if (el === undefined) {\n throw keyError(`undefined at index ${i}`);\n }\n throw keyError(`${t} at index ${i}`);\n }\n return raw.slice() as QueryKey;\n}\n\n/** THE one serializer: JSON.stringify of the validated flat array. */\nfunction serializeKey(key: QueryKey): string {\n return JSON.stringify(key);\n}\n\n/** Element-wise prefix match over validated keys (=== is sound: elements\n * are primitives and NaN is rejected by the contract). */\nfunction matchesPrefix(key: QueryKey, prefix: QueryKey): boolean {\n if (prefix.length > key.length) return false;\n for (let i = 0; i < prefix.length; i++) {\n if (key[i] !== prefix[i]) return false;\n }\n return true;\n}\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type QueryStatus = 'idle' | 'loading' | 'success' | 'error';\n\n/** Fetcher contract: receives the run's AbortSignal. Zero-arg fetchers\n * remain assignable. */\nexport type QueryFetcher<T> = (signal: AbortSignal) => Promise<T>;\n\nexport interface QueryResult<T> extends DisposableResource {\n /** The record's data, or `initialData`/undefined before first commit. */\n data: ReadonlySignal<T | undefined>;\n /** True while this observer is enabled and its record is fetching. */\n loading: ReadonlySignal<boolean>;\n /** The record's terminal error, or null. Cleared when a run starts. */\n error: ReadonlySignal<Error | null>;\n /** The record's lifecycle status. */\n status: ReadonlySignal<QueryStatus>;\n /** Force a refetch: bypasses staleTime freshness, but JOINS an in-flight\n * logical request rather than starting a second one (issue 0005). No-op\n * while disabled. */\n refetch(): void;\n /** Unregister this observer. Component setup calls this automatically at\n * teardown; standalone callers (tests, scripts) call it explicitly. The\n * record \u2014 and any in-flight run \u2014 survives: zero-observer runs complete\n * and commit (ADR 0030.2 \u00A78). */\n dispose(): void;\n}\n\nexport interface QueryOptions<T> {\n /** Cache freshness duration in ms for THIS observer. Default: 0 (a\n * registration/re-enable always revalidates). */\n staleTime?: number;\n /** Number of retries the run performs when this observer owns it. Default: 0 */\n retry?: number;\n /** Skip fetching while this returns false. Signal reads are tracked. */\n enabled?: () => boolean;\n /** Synchronous seed committed into an untouched (idle) record. */\n initialData?: T;\n}\n\n// \u2500\u2500 Record store \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface QueryRecord {\n readonly key: QueryKey;\n readonly serialized: string;\n readonly data: Signal<unknown>;\n readonly error: Signal<Error | null>;\n readonly status: Signal<QueryStatus>;\n /** Epoch ms of the last successful commit; 0 = never. */\n readonly fetchedAt: Signal<number>;\n /** Marked by invalidate(); cleared when a run starts. */\n stale: boolean;\n /** True while a run is in flight (status mirrors it reactively). */\n running: boolean;\n /** Increments per run start; a superseded run may never commit. */\n generation: number;\n controller: AbortController | null;\n /** The in-flight run (joinable by prefetch). */\n runPromise: Promise<void> | null;\n /** settle() terminator for the in-flight run. */\n terminate: (() => void) | null;\n readonly observers: Set<QueryObserver>;\n}\n\ninterface QueryObserver {\n readonly mountIndex: number;\n readonly fetcher: QueryFetcher<unknown>;\n readonly staleTime: number;\n readonly retry: number;\n enabled: boolean;\n record: QueryRecord | null;\n}\n\n/** Monotonic mount counter \u2014 \"most recently mounted\" is decided by\n * query() construction order, not re-registration order. */\nlet nextMountIndex = 0;\n\n/** Read a record signal without tracking it into the ambient observer \u2014\n * the observer effect must depend on keys/enabled/version ONLY, never on\n * record state (that is what keeps refetch loops unrepresentable). */\nfunction peek<T>(s: ReadonlySignal<T>): T {\n let v!: T;\n untrack(() => { v = s.value; });\n return v;\n}\n\nfunction toError(cause: unknown): Error {\n if (cause instanceof Error) return cause;\n try {\n return new Error(String(cause));\n } catch {\n return new Error('Unknown error');\n }\n}\n\n/**\n * Global keyed logical-request store. One per app: resolved via\n * `inject(QueryClient)` (auto-singleton; override with\n * `provide(QueryClient, ...)` BEFORE the first query() call).\n *\n * Records are never GC'd \u2014 see the module doc for the bound.\n */\nexport class QueryClient {\n /** @internal */ _records = new Map<string, QueryRecord>();\n /** @internal clear() bumps this; observer effects track it and re-resolve. */\n _version = signal(0);\n /** @internal live observer count (N601 mixed-client diagnostic). */\n _observers = 0;\n\n /**\n * Mark records matching the key prefix stale and rerun those with \u22651\n * enabled observer (using the owning observer's fetcher/options).\n * Disabled observers revalidate on re-enable; a record with only\n * disabled/no observers stays stale until one arrives. Returns the\n * number of records invalidated.\n *\n * invalidate(['tasks']) matches ['tasks'], ['tasks', '1'], ['tasks', '2', 'x'].\n */\n invalidate(keyPrefix: QueryKey): number {\n const prefix = validateKey(keyPrefix);\n let count = 0;\n for (const rec of this._records.values()) {\n if (!matchesPrefix(rec.key, prefix)) continue;\n count++;\n rec.stale = true;\n const owner = ownerOf(rec, /* requireEnabled */ true);\n if (owner) startRun(rec, owner.fetcher, owner.retry);\n }\n return count;\n }\n\n /**\n * Drop every record. In-flight runs are aborted (a settle() termination).\n * Live observers re-resolve fresh records on the version bump \u2014 enabled\n * ones revalidate immediately.\n */\n clear(): void {\n for (const rec of this._records.values()) {\n rec.generation++;\n rec.controller?.abort();\n rec.terminate?.();\n rec.controller = null;\n rec.terminate = null;\n rec.runPromise = null;\n rec.running = false;\n rec.observers.clear();\n }\n this._records.clear();\n this._version.value++;\n }\n\n /**\n * Imperatively warm a record. Joins an in-flight run; a fresh record\n * (per the given staleTime) is a no-op. Otherwise starts a run with THE\n * GIVEN fetcher \u2014 an explicit imperative is its own owner. The run\n * commits even with zero observers. Resolves at run termination.\n */\n prefetch<T>(key: QueryKey, fetcher: QueryFetcher<T>, staleTime = 0): Promise<void> {\n const rec = resolveRecord(this, key);\n if (rec.running) return rec.runPromise ?? Promise.resolve();\n if (!rec.stale && peek(rec.status) === 'success' && staleTime > 0\n && Date.now() - peek(rec.fetchedAt) < staleTime) {\n return Promise.resolve();\n }\n return startRun(rec, fetcher as QueryFetcher<unknown>, 0);\n }\n}\n\n/** Get-or-create the record for a key. Validation throws N602. */\nfunction resolveRecord(client: QueryClient, rawKey: unknown): QueryRecord {\n const key = validateKey(rawKey);\n const serialized = serializeKey(key);\n let rec = client._records.get(serialized);\n if (!rec) {\n rec = {\n key,\n serialized,\n data: signal<unknown>(undefined),\n error: signal<Error | null>(null),\n status: signal<QueryStatus>('idle'),\n fetchedAt: signal(0),\n stale: false,\n running: false,\n generation: 0,\n controller: null,\n runPromise: null,\n terminate: null,\n observers: new Set(),\n };\n client._records.set(serialized, rec); // never deleted \u2014 documented bound\n }\n return rec;\n}\n\n/** The observer whose fetcher/options own the next run: most recently\n * mounted, preferring enabled observers (a disabled observer asked not\n * to fetch \u2014 its fetcher should not fire). */\nfunction ownerOf(rec: QueryRecord, requireEnabled = false): QueryObserver | undefined {\n let best: QueryObserver | undefined;\n let bestDisabled: QueryObserver | undefined;\n for (const obs of rec.observers) {\n if (obs.enabled) {\n if (!best || obs.mountIndex > best.mountIndex) best = obs;\n } else if (!requireEnabled) {\n if (!bestDisabled || obs.mountIndex > bestDisabled.mountIndex) bestDisabled = obs;\n }\n }\n return best ?? bestDisabled;\n}\n\n/** Does this record need a run, per THIS observer's freshness policy?\n * Called only on real transitions (registration, re-enable, clear());\n * record reads are untracked, so commits never re-trigger observers. */\nfunction needsRun(rec: QueryRecord, observer: QueryObserver): boolean {\n if (rec.running) return false; // join the in-flight logical request\n if (rec.stale) return true;\n const status = peek(rec.status);\n if (status === 'idle' || status === 'error') return true;\n if (observer.staleTime <= 0) return true;\n return Date.now() - peek(rec.fetchedAt) >= observer.staleTime;\n}\n\n/**\n * THE run: one logical request owning the retry loop and the commit.\n * Supersedes (aborts) any in-flight run for the record. Enrolls in the\n * settle() registry on start and terminates it at commit, terminal error,\n * or abort \u2014 never at raw promise settlement.\n */\nfunction startRun(\n rec: QueryRecord,\n fetcher: QueryFetcher<unknown>,\n retry: number,\n): Promise<void> {\n // Supersede: abort IS the superseded run's termination.\n rec.controller?.abort();\n rec.terminate?.();\n\n const generation = ++rec.generation;\n const controller = new AbortController();\n const terminate = __enrollPending();\n rec.controller = controller;\n rec.terminate = terminate;\n rec.running = true;\n rec.stale = false;\n rec.status.value = 'loading';\n rec.error.value = null;\n\n const run = (async () => {\n try {\n let lastError: Error | null = null;\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (generation !== rec.generation) return; // superseded\n try {\n // The microtask hop makes a synchronous fetcher throw a normal\n // rejection \u2014 it enters the same retry/terminal path (issue 0008).\n const result = await Promise.resolve().then(() => fetcher(controller.signal));\n if (generation !== rec.generation) return;\n rec.data.value = result;\n rec.error.value = null;\n rec.fetchedAt.value = Date.now();\n rec.status.value = 'success';\n return; // commit\n } catch (cause) {\n lastError = toError(cause);\n }\n }\n if (generation !== rec.generation) return;\n rec.error.value = lastError;\n rec.status.value = 'error'; // terminal error after retries\n } finally {\n if (generation === rec.generation) {\n rec.running = false;\n rec.controller = null;\n rec.runPromise = null;\n rec.terminate = null;\n }\n terminate(); // idempotent \u2014 superseded runs already terminated at abort\n }\n })();\n rec.runPromise = run;\n return run;\n}\n\n// \u2500\u2500 Mixed clients: an eliminated class (formerly N601) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// With inject() as the single resolution path, the only way two clients\n// could mix was provide(QueryClient, ...) landing after queries already\n// bound the auto-created singleton. The injector now throws N501 at that\n// exact provide() (DI freeze, ADR 0030.2 T6), so the split-brain state is\n// unrepresentable in dev and was always silent in prod \u2014 the symptom-side\n// warning this block used to hold (N601) died with its cause. Retired\n// before release; the code number is not reused.\n\n// \u2500\u2500 query() \u2014 the thin observer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Observe the record the reactive key points at.\n *\n * @param keyFn - Returns the flat cache key. Signal reads are tracked; a\n * key change re-registers the observer on the new record.\n * @param fetcher - Fetches the data; receives the run's AbortSignal.\n * @param options - staleTime / retry / enabled / initialData.\n * @throws N602 synchronously when the initial key violates the contract.\n */\nexport function query<T>(\n keyFn: () => QueryKey,\n fetcher: QueryFetcher<T>,\n options: QueryOptions<T> = {},\n): QueryResult<T> {\n const { staleTime = 0, retry = 0, enabled, initialData } = options;\n\n const client = inject(QueryClient);\n\n // Surface key-contract violations at the call site: the observer effect\n // is error-contained (a later reactive key going invalid is logged with\n // the same coded message), so the construction-time key must be checked\n // synchronously. untrack: query() may run under an ambient observer\n // (component setup) and key signals must not widen its dependencies.\n untrack(() => { validateKey(keyFn()); });\n\n const observer: QueryObserver = {\n mountIndex: nextMountIndex++,\n fetcher: fetcher as QueryFetcher<unknown>,\n staleTime,\n retry,\n enabled: true,\n record: null,\n };\n client._observers++;\n\n const recSig = signal<QueryRecord | null>(null);\n const enabledSig = signal(true);\n let disposed = false;\n let prevEnabled: boolean | null = null;\n let prevVersion = -1;\n\n // The registration effect \u2014 depends on keyFn signals, enabled() signals,\n // and the client version. NEVER on record state (all record reads are\n // untracked), so commits cannot re-trigger it: run starts happen only on\n // the real transitions listed in needsRun()'s doc.\n const stopEffect = effect(() => {\n if (disposed) return;\n const version = client._version.value;\n const key = keyFn();\n const on = enabled ? !!enabled() : true;\n const rec = resolveRecord(client, key);\n\n observer.enabled = on;\n enabledSig.value = on;\n\n const moved = rec !== observer.record;\n if (moved) {\n observer.record?.observers.delete(observer);\n rec.observers.add(observer);\n observer.record = rec;\n if (initialData !== undefined && peek(rec.status) === 'idle'\n && peek(rec.data) === undefined) {\n rec.data.value = initialData; // seed; not a fetch \u2014 status stays idle\n }\n recSig.value = rec;\n }\n\n const reEnabled = prevEnabled === false && on;\n const versionChanged = version !== prevVersion;\n prevEnabled = on;\n prevVersion = version;\n\n if (on && (moved || reEnabled || versionChanged) && needsRun(rec, observer)) {\n const owner = ownerOf(rec) ?? observer;\n startRun(rec, owner.fetcher, owner.retry);\n }\n });\n\n const dispose = () => {\n if (disposed) return;\n disposed = true;\n observer.record?.observers.delete(observer);\n observer.record = null;\n client._observers--;\n stopEffect();\n // NOTE: no abort \u2014 a zero-observer in-flight run completes and commits.\n };\n\n if (hasContext()) {\n getCurrentComponent().addDisposer(dispose);\n }\n\n const refetch = () => {\n if (disposed) return;\n const rec = observer.record;\n if (!rec || !observer.enabled) return;\n if (rec.running) return; // join the in-flight logical request (dedup)\n const owner = ownerOf(rec) ?? observer;\n startRun(rec, owner.fetcher, owner.retry);\n };\n\n const result = {\n data: computed(() => {\n const rec = recSig.value;\n return (rec ? rec.data.value : initialData) as T | undefined;\n }),\n loading: computed(() => enabledSig.value && recSig.value?.status.value === 'loading'),\n error: computed(() => recSig.value?.error.value ?? null),\n status: computed<QueryStatus>(() => recSig.value?.status.value ?? 'idle'),\n refetch,\n dispose,\n };\n return disposable(result, dispose);\n}\n", "/**\n * resource.ts \u2014 Local async derivations with reactive source tracking.\n *\n * `resource()` is the async counterpart to a local computed value: source\n * dependencies are tracked synchronously, while the loader runs outside the\n * reactive observer and commits only the newest live generation.\n */\n\nimport { getCurrentComponent, hasContext } from './context.js';\nimport { disposable, type DisposableResource } from './disposable.js';\nimport { __enrollPending } from './settle.js';\nimport { effect, signal, type ReadonlySignal } from './signal.js';\n\nexport interface ResourceResult<T> extends DisposableResource {\n /** Latest successful value. Retained while a newer load is pending. */\n readonly data: ReadonlySignal<T | undefined>;\n /** True while the current generation is loading. */\n readonly loading: ReadonlySignal<boolean>;\n /** Error from the current generation, or null. */\n readonly error: ReadonlySignal<Error | null>;\n /** Re-run the loader for the current source value. */\n refresh(): void;\n /** Stop source tracking and invalidate/abort outstanding work. */\n dispose(): void;\n}\n\n/**\n * Derive local async state from a synchronously tracked source.\n *\n * Only signal reads inside `source` are dependencies. `loader` starts in a\n * microtask, outside the active observer, so signal reads before or after its\n * first await never accidentally widen the source set.\n */\nexport function resource<S, T>(\n source: () => S | undefined,\n loader: (source: S, signal: AbortSignal) => PromiseLike<T>,\n): ResourceResult<T> {\n const data = signal<T | undefined>(undefined);\n const loading = signal(false);\n const error = signal<Error | null>(null);\n const refreshVersion = signal(0);\n\n let generation = 0;\n let disposed = false;\n let stopEffect: () => void = () => {};\n\n const dispose = () => {\n if (disposed) return;\n disposed = true;\n generation++;\n stopEffect();\n loading.value = false;\n };\n\n // Register the full resource disposer before effect() registers its own\n // lower-level disposer, so component teardown first invalidates generations\n // and then performs the idempotent raw effect cleanup.\n if (hasContext()) {\n getCurrentComponent().addDisposer(dispose);\n }\n\n stopEffect = effect(() => {\n refreshVersion.value;\n const currentGeneration = ++generation;\n\n let sourceValue: S | undefined;\n try {\n sourceValue = source();\n } catch (cause) {\n loading.value = false;\n error.value = toError(cause);\n return;\n }\n\n // `undefined` is the single disabled sentinel. It covers the markdown\n // consumer's empty-content branch without growing an options surface.\n if (sourceValue === undefined) {\n data.value = undefined;\n loading.value = false;\n error.value = null;\n return;\n }\n\n const controller = new AbortController();\n loading.value = true;\n error.value = null;\n const enabledSource = sourceValue as S;\n const isStale = () => (\n disposed\n || controller.signal.aborted\n || currentGeneration !== generation\n );\n\n // settle() enrollment (ADR 0030.2 T2): this generation is a pending\n // logical request from here until COMMIT (data/error write) or ABORT\n // (the cleanup below) \u2014 never raw loader settlement, so an\n // abort-ignoring loader cannot wedge settle(). Idempotent.\n const settled = __enrollPending();\n\n // The microtask boundary is deliberate: loader signal reads are NOT source\n // dependencies, and synchronous loader throws become normal rejections.\n void Promise.resolve().then(async () => {\n if (isStale()) { settled(); return; }\n\n try {\n const value = await loader(enabledSource, controller.signal);\n if (isStale()) { settled(); return; }\n data.value = value;\n loading.value = false;\n settled();\n } catch (cause) {\n if (isStale()) { settled(); return; }\n error.value = toError(cause);\n loading.value = false;\n settled();\n }\n });\n\n return () => {\n if (currentGeneration === generation) generation++;\n controller.abort();\n settled();\n };\n });\n\n const result = {\n data,\n loading,\n error,\n refresh() {\n if (!disposed) refreshVersion.value++;\n },\n dispose,\n };\n return disposable(result, dispose);\n}\n\nfunction toError(cause: unknown): Error {\n if (cause instanceof Error) return cause;\n\n try {\n return new Error(String(cause));\n } catch {\n return new Error('Unknown error');\n }\n}\n", "/**\n * view-transition.ts \u2014 opt-in View Transitions over the synchronous flush.\n *\n * `viewTransition()` wraps a state update so the browser animates between the\n * before and after frames. It is a thin, opt-in wrapper: nothing here runs\n * unless you call it, and no scheduler behaviour changes.\n *\n * ```ts\n * viewTransition(() => { items.value = sorted; }, { types: ['reorder'] });\n * ```\n *\n * ## Why `flush()` is the whole trick\n *\n * `document.startViewTransition()` captures the OLD frame, runs the update\n * callback, then captures the NEW frame. Nisli coalesces signal writes onto a\n * microtask (ADR 0015), so a bare `items.value = sorted` inside that callback\n * would mutate the DOM *after* the capture window \u2014 the browser would animate\n * a frame to itself. Calling `flush()` inside the callback drains the effect\n * cascade synchronously, so the DOM mutation the browser snapshots is nisli's\n * own synchronous flush. `flush()` keeps its documented contract exactly\n * (\"effects executed before the next line\", ADR 0015); this is a consumer of\n * it, not a change to it. N303's cascade cap still applies inside the\n * callback \u2014 a runaway cascade degrades to a skipped transition, not a hang.\n *\n * ## Progressive enhancement\n *\n * Where `document.startViewTransition` is missing (no DOM at all, or an engine\n * without the API) the update still applies \u2014 synchronously, flushed, and\n * unanimated \u2014 and the return is `null`. Where the API exists but the\n * object/`types` form does not (Chrome 111\u2013124), the plain callback form is\n * used: the transition still runs, `:active-view-transition-type()` CSS simply\n * never matches. There is no polyfill and no UA sniffing.\n *\n * ## Companion CSS (author-side, core ships no stylesheet)\n *\n * The root crossfade is the UA default and needs no CSS; tune it, and cut\n * motion for users who ask, with:\n *\n * ```css\n * ::view-transition-old(root),\n * ::view-transition-new(root) { animation-duration: 200ms; }\n *\n * @media (prefers-reduced-motion: reduce) {\n * ::view-transition-group(*),\n * ::view-transition-old(*),\n * ::view-transition-new(*) { animation: none !important; }\n * }\n * ```\n *\n * Reduced motion is answered in CSS, not JS: `viewTransition()` is still\n * called, so the swap stays atomic and typed styles stay active \u2014 only the\n * motion is neutralised. `skipTransition()` on the returned handle is the hard\n * opt-out.\n */\n\nimport { flush } from './signal.js';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface ViewTransitionOptions {\n /** Transition types, surfaced to `:active-view-transition-type()` CSS. */\n types?: string[];\n}\n\n// \u2500\u2500 Feature detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Does this engine accept `startViewTransition({ update, types })`?\n *\n * The object form and the `ViewTransition.types` accessor shipped together,\n * so the accessor is the probe. Engines predating it take a bare callback \u2014\n * passing them an object would throw. A false negative costs only type-scoped\n * CSS, never the transition.\n */\nfunction supportsTransitionTypes(): boolean {\n return typeof ViewTransition !== 'undefined'\n && 'types' in ViewTransition.prototype;\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Run a state update inside a view transition.\n *\n * `update` must be synchronous: everything it does happens inside the\n * browser's capture window, where the page is frozen. Keep async work\n * (loaders, fetches) outside and wrap only the commit.\n *\n * @returns the live `ViewTransition` handle (`finished`, `ready`,\n * `skipTransition()`), or `null` when the platform has no support and the\n * update was applied directly.\n */\nexport function viewTransition(\n update: () => void,\n options: ViewTransitionOptions = {},\n): ViewTransition | null {\n // The commit the browser snapshots: apply the update, then settle the\n // reactive cascade now rather than on the next microtask.\n const commit = (): void => {\n update();\n flush();\n };\n\n if (typeof document === 'undefined'\n || typeof document.startViewTransition !== 'function') {\n commit();\n return null;\n }\n\n const types = options.types;\n return types !== undefined && types.length > 0 && supportsTransitionTypes()\n ? document.startViewTransition({ update: commit, types })\n : document.startViewTransition(commit);\n}\n"],
5
- "mappings": ";AAkEA,IAAI,WAA2B;AAGxB,SAAS,QAAiB;AAC/B,SAAiD,YAAY;AAC/D;AAMO,SAAS,WAAW,IAA0B;AACnD,MAAI,KAAuC,YAAW;AACxD;AAKO,SAAS,WAAW,MAAc,SAAyB;AAChE,SAAO,UAAU,IAAI,KAAK,OAAO;AACnC;AAOO,SAAS,KAAK,MAAc,SAAiB,QAAwC;AAC1F,MAAI,WAAW,QAAW;AACxB,YAAQ,MAAM,WAAW,MAAM,OAAO,CAAC;AAAA,EACzC,OAAO;AACL,YAAQ,MAAM,WAAW,MAAM,OAAO,GAAG,MAAM;AAAA,EACjD;AACF;;;ACrFA,IAAM,UAAU,OAAO;AAGhB,SAAS,WACd,OACA,SACwB;AACxB,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iB,MAAO,QAAO;AAEnC,MAAI;AACF,WAAO,IAAI,MAAM,OAAO,KAAK,CAAC;AAAA,EAChC,QAAQ;AACN,WAAO,IAAI,MAAM,eAAe;AAAA,EAClC;AACF;;;ACvEA,SAAS,0BAAmC;AAC1C,SAAO,OAAO,mBAAmB,eAC5B,WAAW,eAAe;AACjC;AAeO,SAAS,eACd,QACA,UAAiC,CAAC,GACX;AAGvB,QAAM,SAAS,MAAY;AACzB,WAAO;AACP,UAAM;AAAA,EACR;AAEA,MAAI,OAAO,aAAa,eACnB,OAAO,SAAS,wBAAwB,YAAY;AACvD,WAAO;AACP,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,QAAQ;AACtB,SAAO,UAAU,UAAa,MAAM,SAAS,KAAK,wBAAwB,IACtE,SAAS,oBAAoB,EAAE,QAAQ,QAAQ,MAAM,CAAC,IACtD,SAAS,oBAAoB,MAAM;AACzC;",
4
+ "sourcesContent": ["/**\n * diagnostics.ts \u2014 coded diagnostics leaf + the dev-mode gate (ADR 0030.2, Wave 1)\n *\n * The shared foundation every core layer reports through. Two rules keep it a\n * LEAF (ADR 0030.2 \u00A77): zero imports from other core modules (so signal.ts,\n * template.ts, component.ts, injector.ts can all use it without cycles), and\n * codes + a minimal payload emitter only \u2014 no docs prose.\n *\n * Contract:\n * - Every diagnostic carries a stable machine code `N<range><nn>` and renders\n * as ONE console.error line: `[nisli CODE] message` (+ structured detail as\n * the second console argument when given). Thrown coded errors reuse the\n * same `[nisli CODE]` prefix via {@link formatDiag} so `grep '\\[nisli '`\n * finds every framework-reported failure, logged or thrown.\n * - `diag()` itself is NOT dev-gated: gating is the CALL SITE's policy. Some\n * diagnostics are production facts (T6 containment N401/N402 \u2014 parity with\n * the pre-T6 unconditional console.error); others are dev-only attribution\n * (N201/N202/N501) and their callers guard with {@link isDev}.\n *\n * Availability belongs to the artifact (ADR 0048). Bundler ESM leaves standard\n * NODE_ENV guards at each optional work site; the native browser artifacts\n * resolve them at publication. No process global is needed in either browser\n * artifact. The runtime override controls available diagnostics only: it cannot\n * resurrect instrumentation removed from a production artifact.\n */\n\n// \u2500\u2500 Code registry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// The minimal central code table (0030.1 B2, landed as part of T6 per \u00A78).\n// `Nxyz` = concrete code; `Nxxx` range keys document ownership so parallel\n// waves allocate without collision. Ranges owned by other Wave-1 worktrees\n// (template, reactivity, async) are seeded here as placeholders only \u2014 their\n// concrete codes land with their waves.\nexport const codes: Record<string, string> = {\n // Range placeholders \u2014 owner module in parentheses.\n N1xx: 'template: parse/static-audit diagnostics (template.ts \u2014 template wave)',\n N2xx: 'define/props: registration and prop-contract diagnostics (component.ts)',\n N3xx: 'reactivity: scheduler/purity diagnostics (signal.ts \u2014 scheduler wave)',\n N4xx: 'lifecycle: setup/mount containment (component.ts, lifecycle.ts)',\n N5xx: 'dependency injection (injector.ts)',\n N6xx: 'async: query/resource/settle diagnostics (query.ts, resource.ts \u2014 async wave)',\n // Assigned codes.\n N201: 'duplicate component definition \u2014 tag already defined; first definition stays live',\n N202: 'unknown-prop echo \u2014 prop written after mount but never read by setup()',\n N401: 'setup failed \u2014 scope contained, host stamped data-nisli-error=\"N401\"',\n N402: 'onMount failed \u2014 scope contained, host stamped data-nisli-error=\"N402\"',\n N501: 'provide() after the token was already instantiated \u2014 resetInjector() first',\n N101: 'template audit \u2014 dash-tag never defined (misspelled or unimported component?)',\n N102: 'template audit \u2014 unknown @event name',\n N103: 'template audit \u2014 unknown event modifier',\n N104: 'template audit \u2014 undeclared attribute on a component with declared attrs',\n N105: 'template \u2014 remounting a live bound TemplateResult (shared-binding corruption)',\n N106: 'template \u2014 html:inner requires a branded value: raw(), sanitized(), or TrustedHTML',\n N107: 'template \u2014 html:inner sanitized() has no sink: no native Element.setHTML() and no setSanitizerFallback() hook',\n N301: 'reactivity \u2014 effect exceeded the consecutive re-schedule cap (loop); disposed',\n N302: 'reactivity \u2014 effect wrote a signal in its own dependency set (attribution)',\n N303: 'reactivity \u2014 flush()/tick() iteration cap reached before quiescence',\n N310: 'reactivity \u2014 effect callback returned a Promise; use resource() for async',\n N602: 'query \u2014 invalid key element (flat primitives only; null is the optional sentinel)',\n N603: 'settle() \u2014 no quiescence within the iteration cap; returning anyway',\n // N601 (mixed QueryClients) was retired before release: N501 makes that\n // state unrepresentable at its cause. The number is not reused.\n};\n\n// \u2500\u2500 Dev gate \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nlet override: boolean | null = null;\n\n/** Runtime preference within this artifact's development capability. */\nexport function isDev(): boolean {\n return process.env.NODE_ENV !== 'production' && (override ?? true);\n}\n\n/**\n * Enable/suppress available development diagnostics, or restore the artifact's\n * default (`null`). A production artifact cannot re-enable removed diagnostics.\n */\nexport function setDevMode(on: boolean | null): void {\n if (process.env.NODE_ENV !== 'production') override = on;\n}\n\n// \u2500\u2500 Emission \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The shared `[nisli CODE] message` line, for both logged and thrown paths. */\nexport function formatDiag(code: string, message: string): string {\n return `[nisli ${code}] ${message}`;\n}\n\n/**\n * Emit one coded diagnostic: a single console.error line\n * `[nisli CODE] message`, with `detail` attached as structured payload.\n * NOT dev-gated here \u2014 the caller owns the policy (see module doc).\n */\nexport function diag(code: string, message: string, detail?: Record<string, unknown>): void {\n if (detail === undefined) {\n console.error(formatDiag(code, message));\n } else {\n console.error(formatDiag(code, message), detail);\n }\n}\n", "/** A disposal surface that exposes ERM when the consumer's lib supports it. */\ntype DisposeSymbol = typeof Symbol extends {\n readonly dispose: infer Key extends symbol;\n} ? Key : never;\n\nexport type DisposableResource = {\n [Key in DisposeSymbol]: () => void;\n};\n\n/** Callable disposer returned by effects, subscriptions, and emitter handles. */\nexport interface Disposer extends DisposableResource {\n (): void;\n}\n\nconst DISPOSE = Symbol.dispose as typeof Symbol.dispose | undefined;\n\n/** Attach a guarded Symbol.dispose alias without polyfilling the platform. */\nexport function disposable<T extends object>(\n value: T,\n dispose: () => void,\n): T & DisposableResource {\n if (DISPOSE) (value as Record<symbol, () => void>)[DISPOSE] = dispose;\n return value as T & DisposableResource;\n}\n", "/**\n * signal.ts \u2014 Reactive primitives: signal(), computed(), effect()\n *\n * Push-pull hybrid model:\n * - Writes push dirty flags up the dependency graph in two flavors: a signal\n * write pushes Dirty (the value definitely changed), a computed propagates\n * MaybeDirty (recompute to find out). Flags never downgrade.\n * - Reads pull fresh values lazily (computed only recalculates when read)\n * - Multiple synchronous writes coalesce into one microtask flush\n *\n * Scheduler invariants (ADR 0030.2 T5):\n * - An effect re-runs iff a value it read changed. Before a MaybeDirty\n * effect runs, its computed sources are polled (recomputed via the\n * node\u2192impl back-pointer); if no source's change-epoch advanced past the\n * effect's last completed run, the run is skipped. A computed's\n * change-epoch also bumps on every error-state TRANSITION (enter and\n * exit), so effects never skip across error entry or equal-value recovery\n * (issue 0003 containment happens at the effect's own read).\n * - Pending effects flush in creation order (monotonic index), so identical\n * writes produce identical run order. Documented cost: a later-created\n * writer effect costs one deterministic extra run vs. topological order.\n * - The loop guard is clock-free: an effect that re-schedules ITSELF on\n * MAX_EFFECT_RERUNS consecutive runs is diagnosed (N301) and disposed.\n *\n * Dependency tracking is automatic: reading a signal inside a computed\n * or effect registers it as a dependency. Dependencies are re-tracked\n * on every execution (dynamic/conditional tracking).\n */\n\n// \u2500\u2500 Late-bound context hook for auto-disposal \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Avoids circular dependency: context.ts imports nothing from signal.ts,\n// but signal.ts needs to check for component context to auto-dispose effects.\n// component.ts wires this up at import time via `setContextHook()`.\n\nlet contextHook: (() => ((fn: () => void) => void) | null) | null = null;\n\n/**\n * Register the context hook. Called by component.ts at module init.\n * The hook returns an `addDisposer` function if inside setup context, null otherwise.\n */\nexport function setContextHook(hook: () => ((fn: () => void) => void) | null): void {\n contextHook = hook;\n}\n\n// \u2500\u2500 Brand symbol for signal detection in templates \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport const SIGNAL_BRAND = Symbol.for('backlog.signal');\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Readable reactive container. */\nexport interface ReadonlySignal<T> {\n readonly [SIGNAL_BRAND]: true;\n readonly value: T;\n /** Subscribe to value changes. Returns unsubscribe function. */\n subscribe(fn: (value: T) => void): Disposer;\n /**\n * Read the current value WITHOUT registering a dependency.\n * Equivalent to reading inside `untrack()`. On a computed this still\n * pulls a fresh value (and rethrows a cached error) \u2014 it only skips\n * dependency registration.\n */\n peek(): T;\n}\n\n/** Read-write reactive container. */\nexport interface Signal<T> extends ReadonlySignal<T> {\n value: T;\n}\n\n// \u2500\u2500 Internal tracking state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The currently executing reactive context (computed or effect).\n * When non-null, any signal read during execution is recorded as a dependency.\n */\nlet activeObserver: ReactiveNode | null = null;\n\n/**\n * The effect whose fn frame is currently executing. Unlike activeObserver\n * (which switches to a computed during its recompute, and to null under\n * untrack()), this stays pinned to the running effect \u2014 it exists solely to\n * attribute writes to the effect that performed them (N302).\n */\nlet runningEffect: EffectNode | null = null;\n\n/**\n * Global epoch counter. Incremented on every observable change: a signal\n * write, a computed recomputing to a different value, and a computed's\n * error-state transitions (enter and exit). A node's `lastChanged` epoch is\n * compared against an observer's last-validated/last-run epoch to decide\n * staleness.\n */\nlet globalEpoch = 0;\n\n/** Monotonic effect creation index \u2014 pending effects flush in this order. */\nlet nextEffectOrder = 0;\n\n// \u2500\u2500 Dev diagnostics \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Reporting goes through the diagnostics leaf (its dev gate governs);\n// guard BEHAVIOR (loop disposal, rejection containment) is never gated \u2014\n// only the reporting. Assigned codes: N301 effect loop, N302\n// write-in-own-effect, N303 flush/tick cap, N310 effect(async).\n\nimport { diag as emitDiag, isDev } from './diagnostics.js';\nimport { disposable, type Disposer } from './disposable.js';\n\nexport type { Disposer } from './disposable.js';\n\nfunction diag(code: string, message: string, detail?: object): void {\n if (!isDev()) return;\n emitDiag(code, message, detail as Record<string, unknown> | undefined);\n}\n\n// \u2500\u2500 Effect scheduling \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst pendingEffects = new Set<EffectNode>();\nlet flushScheduled = false;\n\nfunction scheduleFlush(): void {\n if (!flushScheduled) {\n flushScheduled = true;\n queueMicrotask(flushPendingEffects);\n }\n}\n\nfunction flushPendingEffects(): void {\n flushScheduled = false;\n // Copy to avoid mutation during iteration; sort by creation index so\n // identical writes produce identical run order forever (ADR 0030.2 T5).\n const effects = [...pendingEffects].sort((a, b) => a.order - b.order);\n pendingEffects.clear();\n for (const effect of effects) {\n if (!effect.disposed) {\n runEffect(effect);\n }\n }\n}\n\n// \u2500\u2500 Dependency graph node types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst enum NodeState {\n Clean = 0,\n MaybeDirty = 1, // A computed source may have changed \u2014 poll before acting\n Dirty = 2, // A signal source definitely changed \u2014 must recompute/run\n}\n\n/** Notification flavor: Dirty from signal writes, MaybeDirty through computeds. */\ntype DirtyFlavor = NodeState.MaybeDirty | NodeState.Dirty;\n\nconst NO_COMPUTED_ERROR = Symbol('no-computed-error');\n\ninterface ReactiveNode {\n state: NodeState;\n /** Signals/computeds this node reads from */\n sources: Set<SignalNode<unknown> | ComputedNode<unknown>>;\n /** Called when a source changes. Never downgrades an existing dirtier state. */\n notify(flavor: DirtyFlavor): void;\n}\n\n// \u2500\u2500 Signal (writable) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface SignalNode<T> {\n value: T;\n lastChanged: number;\n observers: Set<ReactiveNode>;\n}\n\nclass SignalImpl<T> implements Signal<T> {\n readonly [SIGNAL_BRAND] = true as const;\n /** @internal */\n _node: SignalNode<T>;\n\n constructor(initialValue: T) {\n this._node = {\n value: initialValue,\n lastChanged: globalEpoch,\n observers: new Set(),\n };\n }\n\n get value(): T {\n // Track dependency if inside a reactive context\n if (activeObserver) {\n activeObserver.sources.add(this._node);\n this._node.observers.add(activeObserver);\n }\n return this._node.value;\n }\n\n set value(newValue: T) {\n if (Object.is(this._node.value, newValue)) return;\n // N302: write-in-own-sources \u2014 the running effect wrote a signal it also\n // reads this run, so this write re-triggers it. Attribution-only (never\n // disposes; the loop guard owns disposal). Placed AFTER the Object.is\n // cutoff so certified converging writers \u2014 registry reflect effects,\n // each() item-signal reuse \u2014 never warn on equal-value writes.\n if (\n process.env.NODE_ENV !== 'production' && isDev() &&\n runningEffect !== null &&\n runningEffect.sources.has(this._node as SignalNode<unknown>)\n ) {\n diag(\n 'N302',\n 'Effect wrote to a signal it also reads \u2014 the write re-schedules the ' +\n 'effect. If this does not converge to an equal value it is an ' +\n 'infinite loop. Derive the value with computed() instead.',\n runningEffect.createdAt ? { effect: runningEffect.createdAt } : undefined,\n );\n }\n this._node.value = newValue;\n this._node.lastChanged = ++globalEpoch;\n notifyObservers(this._node.observers, NodeState.Dirty);\n }\n\n peek(): T {\n return this._node.value;\n }\n\n subscribe(fn: (value: T) => void): Disposer {\n return effect(() => {\n const value = this.value;\n // A subscription depends on THIS signal only. Reads performed by the\n // consumer callback are observational work, not reactive dependencies\n // of the subscription itself (issue 0004).\n untrack(() => fn(value));\n });\n }\n}\n\nfunction notifyObservers(observers: Set<ReactiveNode>, flavor: DirtyFlavor): void {\n for (const observer of observers) {\n observer.notify(flavor);\n }\n}\n\n// \u2500\u2500 Computed (derived, lazy, cached) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface ComputedNode<T> {\n value: T;\n lastChanged: number;\n observers: Set<ReactiveNode>;\n /**\n * Back-pointer into the owning ComputedImpl (ADR 0030.2 \u00A78 T5): recompute\n * this computed if stale, WITHOUT dependency tracking. Lets an effect's\n * pre-run poll refresh a computed source's change-epoch. Throws the\n * computed's (possibly cached) error.\n */\n pull(): void;\n}\n\nclass ComputedImpl<T> implements ReadonlySignal<T> {\n readonly [SIGNAL_BRAND] = true as const;\n /** @internal */\n _node: ComputedNode<T>;\n\n private compute: () => T;\n private state: NodeState = NodeState.Dirty; // Start dirty so first read computes\n private sources = new Set<SignalNode<unknown> | ComputedNode<unknown>>();\n private computing = false;\n private error: unknown = NO_COMPUTED_ERROR;\n /**\n * globalEpoch snapshot at the end of the last update()/validation pass.\n * A MaybeDirty computed recomputes only if some source's lastChanged\n * advanced past this \u2014 otherwise it revalidates to Clean for free.\n */\n private lastValidated = 0;\n\n constructor(fn: () => T) {\n this.compute = fn;\n this._node = {\n value: undefined as T,\n lastChanged: 0,\n observers: new Set(),\n pull: () => { this.peek(); },\n };\n }\n\n get value(): T {\n if (this.computing) {\n throw new Error('Circular dependency detected in computed()');\n }\n\n // Track dependency if inside a reactive context\n if (activeObserver) {\n activeObserver.sources.add(this._node as ComputedNode<unknown>);\n this._node.observers.add(activeObserver);\n }\n\n // Pull: recalculate if (maybe) dirty\n if (this.state !== NodeState.Clean) {\n this.update();\n }\n\n if (this.error !== NO_COMPUTED_ERROR) {\n throw this.error;\n }\n\n return this._node.value;\n }\n\n peek(): T {\n if (this.computing) {\n throw new Error('Circular dependency detected in computed()');\n }\n // Same pull as `get value`, minus dependency registration.\n if (this.state !== NodeState.Clean) {\n this.update();\n }\n if (this.error !== NO_COMPUTED_ERROR) {\n throw this.error;\n }\n return this._node.value;\n }\n\n /**\n * MaybeDirty validation: pull each source (computeds recompute lazily) and\n * report whether any source's change-epoch advanced past our last\n * validation. A pulled source may throw \u2014 its error-state transition\n * already bumped its change-epoch, so the epoch comparison decides.\n */\n private sourcesChanged(): boolean {\n for (const source of this.sources) {\n if ('pull' in source) {\n try { source.pull(); } catch (_) { /* transition bumped lastChanged */ }\n }\n if (source.lastChanged > this.lastValidated) return true;\n }\n return false;\n }\n\n private update(): void {\n // MaybeDirty means \"an upstream computed MAY have changed\". Validate\n // first: if no polled source advanced, revalidate to Clean without\n // recomputing (the half of push-pull that was previously unimplemented).\n if (this.state === NodeState.MaybeDirty && !this.sourcesChanged()) {\n this.state = NodeState.Clean;\n this.lastValidated = globalEpoch;\n return;\n }\n\n // Unsubscribe from previous sources (for dynamic dependency tracking)\n for (const source of this.sources) {\n source.observers.delete(this as unknown as ReactiveNode);\n }\n this.sources.clear();\n\n // Run compute with tracking\n const prevObserver = activeObserver;\n activeObserver = this as unknown as ReactiveNode;\n this.computing = true;\n const wasError = this.error !== NO_COMPUTED_ERROR;\n try {\n const newValue = this.compute();\n this.error = NO_COMPUTED_ERROR;\n if (!Object.is(this._node.value, newValue)) {\n this._node.value = newValue;\n this._node.lastChanged = ++globalEpoch;\n // NOTE: no notifyObservers() here. This update() is a *lazy* recompute\n // triggered by a read; every downstream observer was already marked\n // dirty / scheduled eagerly when the source signal changed (notify()\n // propagates through the computed chain). Re-notifying here would\n // re-schedule the very effect performing this read \u2014 a spurious\n // double-run that only surfaced once flush() began draining cascades.\n } else if (wasError) {\n // Error-state TRANSITION (exit) recovering to an EQUAL value: the\n // epoch must still advance, or downstream effects would skip the\n // recovery in their pre-run poll (ADR 0030.2 \u00A78 T5 error rule).\n this._node.lastChanged = ++globalEpoch;\n }\n } catch (error) {\n this.error = error;\n if (!wasError) {\n // Error-state TRANSITION (enter) counts as a change: polls must see\n // the epoch advance so the effect re-runs and its own read rethrows\n // into the effect's containment (issue 0003 semantics).\n this._node.lastChanged = ++globalEpoch;\n }\n throw error;\n } finally {\n this.computing = false;\n activeObserver = prevObserver;\n // A failed computed remains in an error state, but it must look clean to\n // notify(): the next dependency write then marks it dirty and propagates\n // to downstream observers so the computation can recover (issue 0003).\n this.state = NodeState.Clean;\n this.lastValidated = globalEpoch;\n }\n }\n\n /** @internal \u2014 called by the ReactiveNode interface when a source changes */\n notify(flavor: DirtyFlavor): void {\n // Never downgrade: a Dirty mark (definite signal change) survives a\n // later MaybeDirty from a parallel computed path.\n if (flavor > this.state) {\n const wasClean = this.state === NodeState.Clean;\n this.state = flavor;\n // Propagate once per dirty episode. Downstream observers always get\n // MaybeDirty \u2014 through a computed, \"changed\" is only knowable after a\n // recompute, which stays lazy (pull-based).\n if (wasClean) {\n notifyObservers(this._node.observers, NodeState.MaybeDirty);\n }\n }\n }\n\n subscribe(fn: (value: T) => void): Disposer {\n return effect(() => {\n const value = this.value;\n untrack(() => fn(value));\n });\n }\n\n // ReactiveNode interface \u2014 used by dependency tracking\n get sources_(): Set<SignalNode<unknown> | ComputedNode<unknown>> {\n return this.sources;\n }\n}\n\n// Make ComputedImpl satisfy ReactiveNode for the dependency tracker\nObject.defineProperty(ComputedImpl.prototype, 'sources', {\n enumerable: false,\n});\n\n// \u2500\u2500 Effect (side-effect, auto-tracks, auto-disposes) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Maximum CONSECUTIVE self-re-schedules before we assume an infinite loop.\n * An effect that writes to a signal it reads re-schedules itself on every\n * run; when that happens MAX_EFFECT_RERUNS times in a row (the counter\n * resets whenever a run does NOT re-schedule the effect), the effect is\n * diagnosed (N301) and disposed. Clock-free \u2014 deterministic under CI and\n * fake timers, and convergent clamps pass because their second run writes\n * an equal value (Object.is cutoff \u2192 no re-schedule \u2192 counter reset).\n * See ADR 0008 Gap 2 / ADR 0009 / ADR 0030.2 T5.\n */\nconst MAX_EFFECT_RERUNS = 100;\n\ninterface EffectNode extends ReactiveNode {\n fn: () => void | (() => void);\n cleanup: (() => void) | null;\n disposed: boolean;\n sources: Set<SignalNode<unknown> | ComputedNode<unknown>>;\n /** List of dispose callbacks registered by the component */\n disposers: (() => void)[];\n /** Monotonic creation index \u2014 flush order (deterministic scheduler) */\n order: number;\n /** globalEpoch snapshot at the end of the last completed run */\n lastRunEpoch: number;\n /** Consecutive runs that re-scheduled this effect (clock-free loop guard) */\n selfReschedules: number;\n /** Dev-captured creation-site stack \u2014 effect identity for N301/N302 */\n createdAt?: string;\n /** N310 (async effect) already reported for this effect */\n asyncWarned?: boolean;\n}\n\nfunction createEffectNode(fn: () => void | (() => void)): EffectNode {\n return {\n state: NodeState.Dirty,\n fn,\n cleanup: null,\n disposed: false,\n sources: new Set(),\n disposers: [],\n order: nextEffectOrder++,\n lastRunEpoch: 0,\n selfReschedules: 0,\n notify(flavor: DirtyFlavor) {\n if (this.disposed) return;\n // Never downgrade Dirty (definite signal change) to MaybeDirty.\n if (flavor > this.state) this.state = flavor;\n pendingEffects.add(this);\n scheduleFlush();\n },\n };\n}\n\n/**\n * Pre-run poll (ADR 0030.2 T5): the effect was notified MaybeDirty, meaning\n * only computed sources MAY have changed. Pull each computed source (via the\n * node back-pointer) so its change-epoch is fresh, then compare every\n * source's epoch against the effect's last completed run. A pull may throw:\n * the computed's error-state transition already bumped its epoch, so the\n * comparison decides \u2014 a NEW error re-runs the effect (whose own read\n * rethrows into its containment, issue 0003), while an error the effect\n * already observed does not.\n */\nfunction effectSourcesChanged(node: EffectNode): boolean {\n for (const source of node.sources) {\n if ('pull' in source) {\n try { source.pull(); } catch (_) { /* transition bumped lastChanged */ }\n }\n if (source.lastChanged > node.lastRunEpoch) return true;\n }\n return false;\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\nfunction runEffect(node: EffectNode): void {\n if (node.disposed) return;\n\n // MaybeDirty: poll sources \u2014 skip the run when no value the effect read\n // actually changed (equal recomputes through a computed chain stop here).\n if (node.state === NodeState.MaybeDirty && !effectSourcesChanged(node)) {\n node.state = NodeState.Clean;\n return;\n }\n\n // Run cleanup from previous execution\n if (node.cleanup) {\n try { node.cleanup(); } catch (_) { /* cleanup errors are swallowed */ }\n node.cleanup = null;\n }\n\n // Unsubscribe from previous sources\n for (const source of node.sources) {\n source.observers.delete(node);\n }\n node.sources.clear();\n\n // Reset state BEFORE running: a notify fired by the effect's own writes\n // must survive into the next flush pass, not be clobbered afterwards.\n node.state = NodeState.Clean;\n\n // Run effect with tracking\n const prevObserver = activeObserver;\n const prevRunning = process.env.NODE_ENV !== 'production' ? runningEffect : null;\n activeObserver = node;\n if (process.env.NODE_ENV !== 'production') runningEffect = node;\n try {\n const result: unknown = node.fn();\n if (typeof result === 'function') {\n node.cleanup = result as () => void;\n } else if (isThenable(result)) {\n // effect(async \u2026) \u2014 rejected at the type level, guarded at runtime for\n // JS callers (ADR 0030.2 \u00A73). The Promise is NOT a cleanup; route its\n // rejection into the effect error path so nothing goes unhandled.\n if (process.env.NODE_ENV !== 'production' && isDev() && !node.asyncWarned) {\n node.asyncWarned = true;\n diag(\n 'N310',\n 'effect() callback returned a Promise \u2014 effects must be synchronous. ' +\n 'Async state belongs in resource(). The returned Promise is not a ' +\n 'cleanup function; its rejection is contained by the effect error path.',\n node.createdAt ? { effect: node.createdAt } : undefined,\n );\n }\n result.then(undefined, (err: unknown) => {\n console.error('Effect error:', err);\n });\n }\n } catch (err) {\n // Effect errors: log but don't crash the system.\n // The effect is NOT disposed \u2014 it may succeed on next signal change.\n console.error('Effect error:', err);\n } finally {\n activeObserver = prevObserver;\n if (process.env.NODE_ENV !== 'production') runningEffect = prevRunning;\n // Everything observable up to now \u2014 including epochs bumped by this\n // run's own lazy computed pulls \u2014 counts as SEEN by this run.\n node.lastRunEpoch = globalEpoch;\n }\n\n // Clock-free loop guard: this run re-scheduled the effect iff the effect\n // is back in the pending set (only its own writes can do that mid-run).\n if (pendingEffects.has(node)) {\n if (++node.selfReschedules > MAX_EFFECT_RERUNS) {\n if (process.env.NODE_ENV !== 'production' && isDev()) diag(\n 'N301',\n `Effect exceeded maximum re-run limit (${MAX_EFFECT_RERUNS}). ` +\n `This usually means the effect writes to a signal it reads. ` +\n `The effect has been disposed to prevent a UI freeze.`,\n node.createdAt ? { effect: node.createdAt } : undefined,\n );\n // Dispose as today: unsubscribe everywhere and drop from the queue.\n node.disposed = true;\n for (const source of node.sources) {\n source.observers.delete(node);\n }\n node.sources.clear();\n pendingEffects.delete(node);\n }\n } else {\n node.selfReschedules = 0;\n }\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Create a writable reactive signal.\n *\n * ```ts\n * const count = signal(0);\n * count.value; // read (auto-tracks in reactive contexts)\n * count.value = 5; // write (notifies dependents)\n * count.peek(); // read WITHOUT tracking\n * ```\n */\nexport function signal<T>(initialValue: T): Signal<T> {\n return new SignalImpl(initialValue);\n}\n\n/**\n * Create a derived, lazy, cached computed signal.\n * Re-evaluates only when dependencies change AND the value is read.\n *\n * ```ts\n * const doubled = computed(() => count.value * 2);\n * doubled.value; // lazy evaluation\n * ```\n */\nexport function computed<T>(fn: () => T): ReadonlySignal<T> {\n return new ComputedImpl(fn);\n}\n\n/**\n * Type-level rejection of async callbacks: a Promise-returning fn makes the\n * call require an impossible second argument, so `effect(async () => {})`\n * fails to compile. Async work belongs in resource() (ADR 0030.2 \u00A73; N310).\n */\ntype SyncEffectGuard<R> = [R] extends [Promise<unknown>]\n ? [error: 'effect() callbacks must be synchronous \u2014 async work belongs in resource() (nisli N310)']\n : [];\n\n/**\n * Create a side-effect that re-runs when its dependencies change.\n * Returns a dispose function to stop the effect.\n *\n * The effect function may return a cleanup callback that runs\n * before each re-execution and on disposal. It must be SYNCHRONOUS \u2014\n * async functions are rejected at the type level and diagnosed at\n * runtime (N310); async state belongs in resource().\n *\n * ```ts\n * const dispose = effect(() => {\n * console.log('count is', count.value);\n * return () => { // cleanup\n * console.log('cleaning up');\n * };\n * });\n * dispose(); // stop the effect\n * ```\n */\nexport function effect<R>(fn: () => R, ..._rejectAsync: SyncEffectGuard<R>): Disposer {\n const node = createEffectNode(fn as unknown as () => void | (() => void));\n if (process.env.NODE_ENV !== 'production' && isDev()) {\n // Dev-captured effect identity: N301/N302 diagnostics name this site.\n node.createdAt = new Error('effect() created here').stack;\n }\n // Run immediately to establish initial dependencies\n runEffect(node);\n\n const dispose = () => {\n node.disposed = true;\n // Run final cleanup\n if (node.cleanup) {\n try { node.cleanup(); } catch (_) { /* swallow */ }\n node.cleanup = null;\n }\n // Unsubscribe from all sources\n for (const source of node.sources) {\n source.observers.delete(node);\n }\n node.sources.clear();\n pendingEffects.delete(node);\n };\n\n // Auto-dispose when inside component setup context\n if (contextHook) {\n const addDisposer = contextHook();\n if (addDisposer) {\n addDisposer(dispose);\n }\n }\n\n return disposable(dispose, dispose);\n}\n\n/**\n * Check if a value is a signal (writable or computed).\n * Used by the template engine to detect signals in expression slots.\n */\nexport function isSignal(value: unknown): value is ReadonlySignal<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n SIGNAL_BRAND in (value as Record<symbol, unknown>)\n );\n}\n\n// \u2500\u2500 Observer isolation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Run a function with activeObserver set to null, preventing any\n * signal reads inside `fn` from being tracked by an outer effect,\n * and return the function's result.\n *\n * Used by component.ts to isolate connectedCallback: child component\n * setup signal reads must not leak into a parent effect's dependency\n * set. See ADR 0008 Gap 1.\n */\nexport function untrack<T>(fn: () => T): T {\n const prev = activeObserver;\n activeObserver = null;\n try {\n return fn();\n } finally {\n activeObserver = prev;\n }\n}\n\n// \u2500\u2500 Synchronous flush \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Synchronously execute all pending effects.\n *\n * In normal usage, effects run automatically on the next microtask.\n * Use flush() only when you need effects to have executed before\n * the next line \u2014 e.g., imperative DOM measurement after state change.\n *\n * flush() is idempotent: calling it with no pending effects is a no-op.\n */\nexport function flush(): void {\n // Drain cascades: an effect may write a signal that schedules more effects\n // (e.g. A computes \u2192 B renders). Loop until the queue is empty so a single\n // flush() settles the whole synchronous cascade \u2014 no double-flush idiom.\n // Bounded to mirror the effect-loop guard; a runaway is a bug, not silence.\n let guard = 0;\n while (pendingEffects.size > 0) {\n flushPendingEffects();\n if (++guard > 100000) {\n if (process.env.NODE_ENV !== 'production' && isDev()) diag(\n 'N303',\n 'flush() cascade cap reached (100000 passes) \u2014 effects keep ' +\n 'scheduling more effects (a cross-effect write cycle?). Breaking out ' +\n 'to avoid a freeze; pending work remains unflushed.',\n );\n break;\n }\n }\n}\n\n/** Backward compat alias for tests. */\nexport { flush as flushEffects };\n\n/**\n * Settle the synchronous effect cascade AND all MICROTASK-scheduled work\n * pending at await time (content-projection sweeps, query/command initial\n * passes \u2014 at any queueMicrotask depth), plus the effects that work\n * schedules. Replaces the hand-rolled `flush(); await Promise.resolve();\n * flush()` and double-`flushEffects()` idioms.\n *\n * Bounded contract \u2014 deliberately NOT awaited: timers and other future\n * TASKS scheduled by that microtask work (e.g. a microtask calling\n * setTimeout) may fire after tick() resolves; awaiting arbitrary future\n * tasks is unbounded. Self-perpetuating schedulers are cut off at the\n * iteration cap (loudly \u2014 N303).\n *\n * ```ts\n * host.setProp('x', 1);\n * await tick();\n * expect(el.textContent).toBe('1');\n * ```\n */\nexport async function tick(): Promise<void> {\n flush(); // drain the synchronous effect cascade first\n // Each iteration crosses a MACROTASK boundary (setTimeout 0). Doing so runs\n // the ENTIRE microtask queue to completion first \u2014 including microtasks a\n // microtask schedules, at any depth \u2014 so a 3-deep `queueMicrotask` chain is\n // fully drained before the timer fires. After the drain we flush the effects\n // that work scheduled. When a full iteration schedules no effects, the queue\n // is quiescent and we return. Contract: microtask-scheduled work + effect\n // cascades pending at await time settle; TIMER-scheduled work does not\n // (see the doc above \u2014 bounded by design). The iteration cap is a\n // documented backstop for self-perpetuating schedulers, not a silent hang.\n for (let i = 0; i < 50; i++) {\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n if (pendingEffects.size === 0) return; // the microtask drain scheduled nothing\n flush();\n }\n if (process.env.NODE_ENV !== 'production' && isDev()) diag(\n 'N303',\n 'tick() iteration cap (50) reached with effects still pending \u2014 ' +\n 'something keeps scheduling reactive work every task (a ' +\n 'self-perpetuating scheduler?). Returning with work still queued.',\n );\n}\n", "/**\n * context.ts \u2014 Setup context for pure function DI\n *\n * The setup context lets pure functions (inject(), listen(), effect())\n * access the component they belong to without needing `this`.\n *\n * The context exists ONLY during component initialization (setup()).\n * It is NOT a runtime thing \u2014 it's a synchronous initialization-time concept.\n *\n * Same pattern as Angular's inject(), Solid's createSignal(), Vue's setup().\n */\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Minimal interface for a component host. component.ts provides the\n * full implementation; this file only needs the disposal hook.\n */\nexport interface ComponentHost {\n /** Register a cleanup function to run on disconnectedCallback */\n addDisposer(fn: () => void): void;\n /** The raw HTMLElement */\n element: HTMLElement;\n}\n\n// \u2500\u2500 Context state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nlet currentComponent: ComponentHost | null = null;\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Run a function with a component as the active context.\n * Pure functions called during `fn` can access the component via\n * `getCurrentComponent()`.\n *\n * Context is strictly synchronous \u2014 it does NOT survive across\n * await boundaries or microtasks.\n */\nexport function runWithContext(component: ComponentHost, fn: () => void): void {\n const prev = currentComponent;\n currentComponent = component;\n try {\n fn();\n } finally {\n currentComponent = prev;\n }\n}\n\n/**\n * Get the currently active component host.\n * Throws if called outside a setup() context.\n *\n * This is framework-internal \u2014 component authors use inject(), effect(),\n * etc., which call this internally.\n */\nexport function getCurrentComponent(): ComponentHost {\n if (!currentComponent) {\n throw new Error(\n 'getCurrentComponent() called outside setup(). ' +\n 'inject(), effect(), and other context-dependent functions ' +\n 'can only be called during component initialization.'\n );\n }\n return currentComponent;\n}\n\n/**\n * Check if there is an active setup context.\n * Returns true during component setup, false otherwise.\n */\nexport function hasContext(): boolean {\n return currentComponent !== null;\n}\n", "/**\n * emitter.ts \u2014 Typed pub/sub base class for services.\n *\n * Replaces `document.dispatchEvent(new CustomEvent(...))` with typed,\n * scoped event emitters. Services extend Emitter<T> where T defines\n * the event contract as a record of event names \u2192 payload types.\n *\n * ```ts\n * class NavigationEvents extends Emitter<{\n * select: { id: string };\n * filter: { filter: string };\n * }> {}\n *\n * const nav = inject(NavigationEvents);\n * nav.emit('select', { id: 'TASK-1' }); // typed\n * nav.on('select', ({ id }) => console.log(id)); // typed\n * const selectedId = nav.toSignal('select', e => e.id, null);\n * ```\n */\n\nimport { signal, type Signal } from './signal.js';\nimport { hasContext, getCurrentComponent } from './context.js';\nimport { disposable, type Disposer } from './disposable.js';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ntype EventMap = Record<string, unknown>;\ntype Listener<T> = (payload: T) => void;\n\n// \u2500\u2500 Emitter base class \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport class Emitter<Events extends EventMap> {\n private listeners = new Map<keyof Events, Set<Listener<any>>>();\n\n /**\n * Emit a typed event. All subscribers for this event name are called\n * synchronously. If a subscriber throws, other subscribers still fire.\n */\n emit<K extends keyof Events>(event: K, payload: Events[K]): void {\n const set = this.listeners.get(event);\n if (!set) return;\n\n // Iterate a copy to allow unsubscribe during callback\n for (const fn of [...set]) {\n try {\n fn(payload);\n } catch (err) {\n console.error(`Emitter: subscriber for '${String(event)}' threw:`, err);\n }\n }\n }\n\n /**\n * Subscribe to a typed event. Returns an unsubscribe function.\n *\n * If called during component setup, the subscription is automatically\n * disposed on disconnectedCallback.\n */\n on<K extends keyof Events>(event: K, fn: Listener<Events[K]>): Disposer {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(fn);\n\n const unsubscribe = () => {\n set!.delete(fn);\n if (set!.size === 0) {\n this.listeners.delete(event);\n }\n };\n\n // Auto-dispose if inside component setup context\n if (hasContext()) {\n getCurrentComponent().addDisposer(unsubscribe);\n }\n\n return disposable(unsubscribe, unsubscribe);\n }\n\n /**\n * Bridge an event into the signal system.\n * Returns a signal that updates whenever the event fires.\n *\n * @param event - Event name to subscribe to\n * @param selector - Transform the payload into the signal value\n * @param initial - Initial signal value before any event fires\n */\n toSignal<K extends keyof Events, V>(\n event: K,\n selector: (payload: Events[K]) => V,\n initial: V,\n ): Signal<V> {\n const s = signal(initial);\n this.on(event, (payload) => {\n s.value = selector(payload);\n });\n return s;\n }\n\n /**\n * Remove all subscribers. Useful for testing cleanup.\n */\n clear(): void {\n this.listeners.clear();\n }\n}\n", "/**\n * injector.ts \u2014 Dependency injection: inject(), provide(), class-as-token\n *\n * Two key insights from Angular's evolution:\n * 1. The class IS the token \u2014 no createToken() needed for 99% of cases\n * 2. provide() is optional \u2014 inject() auto-creates singletons on first call\n *\n * ```ts\n * class BacklogAPI {\n * async getTasks(): Promise<Task[]> { ... }\n * }\n *\n * // In component setup:\n * const api = inject(BacklogAPI); // auto-created singleton\n *\n * // In tests:\n * provide(BacklogAPI, () => new MockAPI());\n * ```\n */\n\nimport { hasContext, getCurrentComponent } from './context.js';\nimport { formatDiag, isDev } from './diagnostics.js';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Any class constructor \u2014 used as both the token and the type. */\nexport type Constructor<T = unknown> = new (...args: any[]) => T;\n\n/** Opaque token for non-class dependencies (config objects, primitives). */\nexport interface InjectionToken<T> {\n readonly __brand: 'InjectionToken';\n readonly name: string;\n /** @internal default factory */\n _factory?: () => T;\n}\n\n// \u2500\u2500 Global singleton registry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Stores singleton instances keyed by constructor or token. */\nconst singletonCache = new Map<Constructor | InjectionToken<unknown>, unknown>();\n\n/** Stores factory overrides from provide(). */\nconst factoryOverrides = new Map<Constructor | InjectionToken<unknown>, () => unknown>();\n\n/** Tracks which constructors are currently being instantiated (circular detection). */\nconst instantiating = new Set<Constructor | InjectionToken<unknown>>();\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Get or create a singleton instance of the given class.\n *\n * On first call: creates the instance via `new Class()` (or the\n * factory from provide(), if one exists). On subsequent calls:\n * returns the same instance.\n *\n * Can be called inside or outside component setup context.\n * When inside, the inject result is available for the component's lifetime.\n */\nexport function inject<T>(token: Constructor<T>): T;\nexport function inject<T>(token: InjectionToken<T>): T;\nexport function inject<T>(token: Constructor<T> | InjectionToken<T>): T {\n // Check cache first\n if (singletonCache.has(token)) {\n return singletonCache.get(token) as T;\n }\n\n // Circular dependency detection\n if (instantiating.has(token)) {\n const name = typeof token === 'function' ? token.name : (token as InjectionToken<T>).name;\n throw new Error(\n `Circular dependency detected when instantiating '${name}'. ` +\n 'Check your service constructors for circular inject() calls.'\n );\n }\n\n instantiating.add(token);\n try {\n let instance: T;\n\n // Check for factory override\n const factory = factoryOverrides.get(token as Constructor | InjectionToken<unknown>);\n if (factory) {\n instance = factory() as T;\n } else if (typeof token === 'function') {\n // Class token \u2014 auto-create via constructor\n instance = new (token as Constructor<T>)();\n } else {\n // InjectionToken with default factory\n const injToken = token as InjectionToken<T>;\n if (injToken._factory) {\n instance = injToken._factory();\n } else {\n throw new Error(\n `No provider found for token '${injToken.name}'. ` +\n 'Use provide() to register a factory before calling inject().'\n );\n }\n }\n\n singletonCache.set(token as Constructor | InjectionToken<unknown>, instance);\n return instance;\n } finally {\n instantiating.delete(token);\n }\n}\n\n/**\n * Register a factory override for a class or token.\n * The factory will be called on the next inject() if no cached instance exists.\n *\n * Call provide() before the first inject() of that token. Once a token has\n * been instantiated the injector is FROZEN for it (dev, coded error N501):\n * everything that already injected holds the old instance while later\n * inject() calls would get the new one \u2014 a silent mixed-instance split\n * (ADR 0030.2 \u00A73). `resetInjector()` is the escape hatch (tests use it).\n * Production keeps the historical silent replace so a live page never breaks\n * over an ordering issue that dev already surfaced.\n */\nexport function provide<T>(token: Constructor<T>, factory: () => T): void;\nexport function provide<T>(token: InjectionToken<T>, factory: () => T): void;\nexport function provide<T>(token: Constructor<T> | InjectionToken<T>, factory: () => T): void {\n if (process.env.NODE_ENV !== 'production' && isDev() && singletonCache.has(token as Constructor | InjectionToken<unknown>)) {\n const name = typeof token === 'function' ? token.name : (token as InjectionToken<T>).name;\n throw new Error(formatDiag(\n 'N501',\n `provide(${name}) after '${name}' was already instantiated \u2014 existing `\n + `consumers keep the old instance while new inject() calls would get the `\n + `new one (mixed-instance split). Call resetInjector() first (tests), or `\n + `provide() before the first inject().`,\n ));\n }\n factoryOverrides.set(token as Constructor | InjectionToken<unknown>, factory);\n // Remove cached instance so next inject() uses the new factory\n singletonCache.delete(token as Constructor | InjectionToken<unknown>);\n}\n\n/**\n * Create an injection token for non-class dependencies.\n * Use this for config objects, primitives, or interfaces.\n *\n * ```ts\n * const AppConfig = createToken<{ apiUrl: string }>('AppConfig');\n * provide(AppConfig, () => ({ apiUrl: '/api' }));\n * const config = inject(AppConfig);\n * ```\n */\nexport function createToken<T>(name: string, defaultFactory?: () => T): InjectionToken<T> {\n return {\n __brand: 'InjectionToken' as const,\n name,\n _factory: defaultFactory,\n };\n}\n\n// Hooks run by resetInjector() \u2014 module-level caches elsewhere (settle's\n// pending registry) stay test-isolated without upside-down imports: those\n// modules import the injector and self-register, never the reverse.\nconst resetHooks = new Set<() => void>();\n\n/** @internal Register a hook run by every resetInjector() call. */\nexport function registerResetHook(hook: () => void): void {\n resetHooks.add(hook);\n}\n\n/**\n * Reset the injector \u2014 clears all singletons and factory overrides.\n * Used in tests to ensure isolation between test cases.\n */\nexport function resetInjector(): void {\n singletonCache.clear();\n factoryOverrides.clear();\n instantiating.clear();\n for (const hook of resetHooks) hook();\n}\n", "/**\n * element-context.ts \u2014 subtree-scoped context (provide / inject).\n *\n * The DOM-native equivalent of React/Radix context: a provider publishes a\n * typed value on its host element, and descendant components `inject()` it by\n * walking up the element tree. It replaces the userland `host.__uiX = state` +\n * `host.closest('ui-x')` convention (stringly-typed, invisible to TypeScript,\n * re-implemented per family) with an identity-keyed, end-to-end-typed primitive.\n *\n * ```ts\n * interface TabsState { value: ReadonlySignal<string>; setValue(v: string): void }\n * const TabsContext = createContext<TabsState>('Tabs');\n *\n * // provider setup:\n * TabsContext.provide(host, state);\n *\n * // descendant setup:\n * const tabs = TabsContext.inject(); // throws (error boundary) if absent\n * const maybe = TabsContext.inject.optional(); // TabsState | undefined\n * ```\n *\n * Design (see ADR 0025 \u00A72):\n *\n * - **Typed, no string keys.** Each `createContext` mints a private `Symbol`\n * used as the storage key; consumers reference the context object, never a\n * string. Two contexts never collide even with the same `name` (name is for\n * diagnostics only).\n *\n * - **Capture at setup, not at lookup.** `inject()` resolves during component\n * setup, while the injecting host is still a DOM descendant of its provider.\n * It returns the value *once*; because provider values carry signals,\n * reactivity flows through them with no further tree-walks. This is what makes\n * it **portal-safe**: after a subtree is reparented to `<body>` (dialog, menu,\n * \u2026) the injected value is already held, so the component keeps resolving its\n * ORIGINAL provider \u2014 a later walk from the portaled host would find nothing.\n * `inject()` therefore requires an active setup context when no host is passed.\n *\n * - **Zero cost for non-users.** Providing sets one symbol property on the host;\n * injecting is a `parentElement` walk. Components that use neither pay nothing,\n * and there is no global registry to maintain.\n */\n\nimport { getCurrentComponent, hasContext } from './context.js';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface Inject<T> {\n /**\n * Resolve the nearest provider's value by walking up from `host` (default:\n * the current component's host, requiring a setup context). Throws if no\n * provider is found \u2014 in a component this surfaces via the error boundary.\n */\n (host?: HTMLElement): T;\n /** Like `inject()` but returns `undefined` instead of throwing when absent. */\n optional(host?: HTMLElement): T | undefined;\n}\n\nexport interface Context<T> {\n /** Diagnostic label (error messages); not an identity key. */\n readonly name: string;\n /** Publish `value` on `host` so descendants can `inject()` it. */\n provide(host: HTMLElement, value: T): void;\n /** Resolve this context from a descendant (see {@link Inject}). */\n readonly inject: Inject<T>;\n /**\n * Read the value provided on THIS host only \u2014 no ancestor walk. `undefined`\n * if `host` is not a provider of this context. The low-level primitive for\n * bespoke walks (e.g. \"nearest provider of context A OR context B\", which\n * `inject` can't express in one pass); prefer `inject`/`inject.optional`\n * for ordinary descendant resolution.\n */\n peek(host: HTMLElement): T | undefined;\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Create a subtree-scoped context. `name` is used only in diagnostics; the\n * context's identity (a private symbol) is what keys storage and lookup.\n *\n * Pass `{ providerTag }` to name the provider element so a missing-provider\n * `inject()` produces an ACTIONABLE, element-language error \u2014\n * `<injecting-tag> must be used inside <provider-tag>.` \u2014 instead of naming the\n * private context object. Set it whenever consumers are DOM elements (the whole\n * registry): it's the difference between a message a plain-HTML user can act on\n * and one they can't.\n */\nexport function createContext<T>(\n name: string,\n options: { providerTag?: string } = {},\n): Context<T> {\n const { providerTag } = options;\n // Private per-context storage key. Not derived from `name`, so same-named\n // contexts stay distinct, and it never appears in userland.\n const KEY = Symbol(`nisli.context:${name}`);\n\n const store = (el: Element): Record<symbol, unknown> =>\n el as unknown as Record<symbol, unknown>;\n\n const provide = (host: HTMLElement, value: T): void => {\n store(host)[KEY] = value;\n };\n\n const peek = (host: HTMLElement): T | undefined =>\n KEY in host ? (store(host)[KEY] as T) : undefined;\n\n // Walk up the element tree (inclusive of `start`) to the nearest provider.\n // `parentElement` transparently crosses `display: contents` hosts.\n const find = (start: HTMLElement): T | undefined => {\n let el: Element | null = start;\n while (el) {\n if (KEY in el) return store(el)[KEY] as T;\n el = el.parentElement;\n }\n return undefined;\n };\n\n const startHost = (host: HTMLElement | undefined, caller: string): HTMLElement | null => {\n if (host) return host;\n if (!hasContext()) {\n throw new Error(\n `${caller} for context \"${name}\" was called without a host and outside component ` +\n `setup. Call it during setup (so the provider is resolved before any portal move), ` +\n `or pass an explicit host.`,\n );\n }\n return getCurrentComponent().element;\n };\n\n const inject = ((host?: HTMLElement): T => {\n const start = startHost(host, 'inject()')!;\n const found = find(start);\n if (found === undefined) {\n const injectingTag = start.tagName.toLowerCase();\n // With a declared provider tag, speak element-language the consumer can\n // act on; otherwise fall back to the generic (provider named by API).\n throw new Error(\n providerTag\n ? `Context \"${name}\": <${injectingTag}> must be used inside <${providerTag}>.`\n : `Context \"${name}\" not found: <${injectingTag}> must be rendered ` +\n `inside a provider that calls ${name}Context.provide(host, \u2026).`,\n );\n }\n return found;\n }) as Inject<T>;\n\n inject.optional = (host?: HTMLElement): T | undefined => {\n // Outside setup with no host: there is nothing to resolve from \u2014 undefined.\n if (!host && !hasContext()) return undefined;\n return find(startHost(host, 'inject.optional()')!);\n };\n\n return { name, provide, inject, peek };\n}\n", "/**\n * lifecycle.ts \u2014 Post-mount and cleanup lifecycle hooks\n *\n * `onMount()` registers a callback that runs after the component's\n * template is mounted to the DOM. If the callback returns a function,\n * that function runs on disconnect (cleanup).\n *\n * `onCleanup()` registers a standalone cleanup callback that runs\n * on disconnect \u2014 for cases where you need cleanup without mount logic.\n *\n * Both must be called synchronously during component setup.\n *\n * ```ts\n * component('my-el', (props, host) => {\n * onMount(() => {\n * host.querySelector('input')?.focus();\n * return () => console.log('unmounted');\n * });\n *\n * onCleanup(() => clearInterval(timerId));\n *\n * return html`<input />`;\n * });\n * ```\n */\n\nimport { hasContext, getCurrentComponent } from './context.js';\n\n// \u2500\u2500 Mount callback storage \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Mount callbacks are stored on the component host and called after template mount. */\nconst mountCallbacks = new WeakMap<object, (() => void | (() => void))[]>();\n\n/**\n * Register a callback to run after the component's template is mounted.\n * If the callback returns a function, it will be called on disconnect.\n *\n * Must be called synchronously during component setup.\n */\nexport function onMount(callback: () => void | (() => void)): void {\n if (!hasContext()) {\n throw new Error(\n 'onMount() called outside setup(). ' +\n 'It can only be called during component initialization.'\n );\n }\n const comp = getCurrentComponent();\n let callbacks = mountCallbacks.get(comp);\n if (!callbacks) {\n callbacks = [];\n mountCallbacks.set(comp, callbacks);\n }\n callbacks.push(callback);\n}\n\n/**\n * Register a cleanup callback to run on disconnect.\n * This is a convenience for cases where you need cleanup without mount logic.\n *\n * Must be called synchronously during component setup.\n */\nexport function onCleanup(callback: () => void): void {\n if (!hasContext()) {\n throw new Error(\n 'onCleanup() called outside setup(). ' +\n 'It can only be called during component initialization.'\n );\n }\n getCurrentComponent().addDisposer(callback);\n}\n\n/**\n * Listen for a DOM event on a target and auto-dispose the listener when the\n * component disconnects. Works with any EventTarget (host element, document,\n * window, etc.). Must be called during component setup.\n *\n * ```ts\n * useHostEvent(host, 'click', (e) => {\n * // Runs on each click\n * });\n * ```\n */\nexport function useHostEvent<E extends Event = Event>(\n target: EventTarget,\n eventName: string,\n handler: (event: E) => void,\n): void {\n if (!hasContext()) {\n throw new Error(\n 'useHostEvent() called outside setup(). ' +\n 'It can only be called during component initialization.'\n );\n }\n target.addEventListener(eventName, handler as EventListener);\n getCurrentComponent().addDisposer(() => {\n target.removeEventListener(eventName, handler as EventListener);\n });\n}\n\n/**\n * Run all registered mount callbacks for a component host.\n * Called by component.ts after the template is mounted to the DOM.\n *\n * A throw here PROPAGATES to component.ts's containment boundary \u2014 the SAME\n * boundary as a setup throw (ADR 0030.2 T6, code N402): remaining callbacks\n * are skipped, the partial scope (including cleanups already registered by\n * earlier callbacks) is disposed, the error fallback renders, and the host is\n * stamped `data-nisli-error`. The pre-T6 behavior (console-and-limp per\n * callback) left a half-mounted component alive with no machine-readable\n * trace and no teardown \u2014 the one containment semantics setup already had\n * (issue 0010) now covers mount too.\n * @internal\n */\nexport function runMountCallbacks(comp: object): void {\n const callbacks = mountCallbacks.get(comp);\n if (!callbacks) return;\n\n try {\n for (const cb of callbacks) {\n const cleanup = cb();\n if (typeof cleanup === 'function') {\n // Register cleanup as a disposer on the component\n (comp as any).addDisposer(cleanup);\n }\n }\n } finally {\n // Clear \u2014 mount callbacks run once (also when a throw contains the scope:\n // the boundary re-runs setup from scratch on the next mount, which\n // re-registers a fresh callback list).\n mountCallbacks.delete(comp);\n }\n}\n", "/**\n * component.ts \u2014 Web component shell with typed props and factory composition\n *\n * `component()` is the single entry point for defining components.\n * It registers a custom element and returns a typed factory function.\n *\n * Component authors write a setup function that receives typed props\n * (each wrapped as a Signal) and optionally the host element.\n * The setup function returns a TemplateResult from html`...`.\n *\n * The class internals (connectedCallback, etc.) are completely hidden.\n */\n\nimport { signal, effect, setContextHook, isSignal, untrack, type Signal, type ReadonlySignal } from './signal.js';\nimport { runWithContext, hasContext, getCurrentComponent, type ComponentHost } from './context.js';\nimport type { TemplateResult } from './template.js';\nimport { runMountCallbacks } from './lifecycle.js';\nimport { diag, formatDiag, isDev } from './diagnostics.js';\n\n// Diagnostic state is external to production component/props objects. Each\n// allocation and use is statically gated so the entire maps disappear (0048).\nconst propsReadKeys = process.env.NODE_ENV !== 'production'\n ? new WeakMap<object, Set<string>>() : undefined;\nconst completedSetups = process.env.NODE_ENV !== 'production'\n ? new WeakSet<HTMLElement>() : undefined;\nconst echoedProps = process.env.NODE_ENV !== 'production'\n ? new WeakMap<HTMLElement, Set<string>>() : undefined;\n\n// Wire up effect auto-disposal: when effect() is called during component setup,\n// auto-register the dispose function with the component host.\nsetContextHook(() => {\n if (hasContext()) {\n const comp = getCurrentComponent();\n return (disposer: () => void) => comp.addDisposer(disposer);\n }\n return null;\n});\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Narrows one prop's reactive value to the runtime type its `attrs`\n * declaration guarantees (ADR 0025 candidate (b)). Only the two kinds core\n * reconciles to a NON-`undefined` runtime value narrow; everything else is\n * left as the author's `T` (= `P[K]`):\n *\n * - `'boolean'` / `{ type:'boolean' }` (any default) \u2192 `boolean` \u2014 a declared\n * boolean is absent\u2192`false`, never `undefined`.\n * - `{ type:'number'; default }` \u2192 `number` \u2014 the default guarantees a value.\n * - `'number'` / `{ type:'number' }` WITHOUT a default \u2192 `number | undefined`.\n * - `'string'` / `{ type:'string' }` / `'forward'` / undeclared \u2192 `T` unchanged\n * (a string attr is genuinely absent\u2192`undefined`; forwarding does not touch\n * the value type).\n *\n * SOUND FALLBACK on an incompatible declaration: the narrowed runtime type is\n * applied ONLY when the declared kind and `NonNullable<T>` (the prop's author\n * type) agree EXACTLY \u2014 mutual assignability, BOTH directions. A one-way check\n * (`boolean extends NonNullable<T>`) is unsound: it would still narrow a\n * `boolean | string` prop to `boolean` (silently dropping `string`), and a\n * one-way check the other way would widen a literal `true`/`1` prop. So a\n * declaration is honored only when `NonNullable<T>` IS the kind \u2014 `boolean` for\n * a boolean declaration, `number` for a numeric one \u2014 via {@link IsExactKind}.\n * Every genuine mismatch or partial overlap (`boolean | string` declared\n * `'boolean'`, `'boolean'` on a `string` prop, a numeric decl on a boolean prop,\n * a literal `true`/`1` prop) falls back to `T` unchanged \u2014 never a compile-time\n * lie about the value. The whole registry declares props as exactly `boolean` /\n * `number`, so it narrows as before; only unions/literals/mismatches are refused.\n *\n * `D` is the declaration at that key (or `undefined` when the key is absent\n * from the `attrs` map, in which case the caller passes `T` through directly).\n */\nexport type AttrValueType<T, D> =\n D extends 'boolean' ? (IsExactKind<T, boolean> extends true ? boolean : T)\n : D extends { type: 'boolean' } ? (IsExactKind<T, boolean> extends true ? boolean : T)\n : D extends { type: 'number'; default: number } ? (IsExactKind<T, number> extends true ? number : T)\n : D extends 'number' ? (IsExactKind<T, number> extends true ? number | undefined : T)\n : D extends { type: 'number' } ? (IsExactKind<T, number> extends true ? number | undefined : T)\n : T;\n\n/**\n * `true` iff `NonNullable<T>` is EXACTLY `K` \u2014 mutually assignable in both\n * directions (`NonNullable<T> extends K` AND `K extends NonNullable<T>`). The\n * tuple wrappers block distribution so `boolean` (`= true | false`) is compared\n * whole: `boolean | string` is NOT exactly `boolean` (fails the first arm), and\n * `true` is NOT exactly `boolean` (fails the second), so both are refused.\n */\ntype IsExactKind<T, K> =\n [NonNullable<T>] extends [K] ? ([K] extends [NonNullable<T>] ? true : false) : false;\n\n/**\n * Maps a props interface to reactive signals, narrowed by the `attrs`\n * declaration `A` (ADR 0025 candidate (b)).\n *\n * Each prop `P[K]` becomes `Signal<AttrValueType<P[K], A[K]>>` when `K` is\n * declared in `A`, otherwise `Signal<P[K]>`. So a declared `'boolean'` types as\n * `Signal<boolean>` (not `Signal<boolean | undefined>`), retiring the\n * registry's `as boolean` stopgap. `A` defaults to `{}` (no declared keys \u2192\n * every prop unchanged), so `ReactiveProps<P>` keeps its pre-candidate-(b)\n * meaning and existing single-argument uses are unaffected.\n *\n * Optionality is stripped (`-?`): the props Proxy always returns a signal,\n * even for props never set \u2014 an optional prop `variant?: T` is\n * `Signal<T | undefined>`, not `Signal<T> | undefined`.\n */\nexport type ReactiveProps<P, A extends ComponentAttrs<P> = {}> = {\n readonly [K in keyof P]-?: Signal<K extends keyof A ? AttrValueType<P[K], A[K]> : P[K]>;\n};\n\n/**\n * The setup function signature. Receives reactive props (narrowed by the\n * `attrs` declaration `A`) and the host element. Returns a TemplateResult to be\n * mounted into the component.\n */\nexport type SetupFunction<P, A extends ComponentAttrs<P> = {}> = (\n props: ReactiveProps<P, A>,\n host: HTMLElement,\n) => TemplateResult;\n\n/**\n * Accepts either a Signal<T> (reactive) or a plain T (static, auto-wrapped).\n * This eliminates the need to wrap static values in `signal()` at call sites.\n * See ADR 0009 Gap 4.\n */\nexport type PropInput<T> = T | Signal<T> | ReadonlySignal<T>;\n\n/**\n * Host-level attributes that every factory accepts, independent of component props.\n * `class` is applied to the host element via classList \u2014 it does not collide with\n * the component's own class attribute or class:name directives.\n * See ADR 0009 Gap 3.\n */\nexport interface HostAttrs {\n class?: PropInput<string>;\n}\n\n/**\n * A factory function for type-safe component composition.\n * Props accept both Signal<T> (reactive) and plain T (static, auto-wrapped).\n * An optional second argument provides host-level attributes (class).\n */\nexport type ComponentFactory<P> = (\n props: { [K in keyof P]: PropInput<P[K]> },\n hostAttrs?: HostAttrs,\n) => TemplateResult;\n\n/**\n * Opt-in attribute reactivity declaration (ADR 0025 item 3).\n *\n * Declares how a host attribute maps onto a prop signal, subsuming userland\n * `attr()`/`boolAttr()`/`forwardedAttr()`. Unlike those (which read the\n * attribute once at setup), a declared attribute is `observedAttributes`-wired,\n * so `setAttribute()` AFTER mount writes the prop signal LIVE.\n *\n * - `'string'` \u2014 the attribute's string value (absent \u2192 `undefined`).\n * - `'boolean'` \u2014 OUR boolean semantics: bare/any value \u2192 `true`, literal\n * `\"false\"` \u2192 `false`, absent \u2192 `false`.\n * - `'number'` \u2014 `Number(raw)`; absent \u2192 the default (else `undefined`); a\n * non-numeric value behaves as absent \u2192 the default (else `undefined`), so a\n * garbage attribute never propagates `NaN` into layout math.\n * - `{ type: 'boolean', default: true }` \u2014 as above but absent \u2192 the default\n * (so a default-`true` flag can be opted out with `attr=\"false\"`).\n * - `{ type: 'string', default: '\u2026' }` \u2014 string with an absent-value default.\n * - `{ type: 'number', default: 0 }` \u2014 number with an absent-value default.\n * - `'forward'` \u2014 string semantics PLUS relocation: the attribute is removed\n * from the (layout-transparent) host so `id`/`name` live only on the inner\n * control (native form participation), matching `forwardedAttr()`.\n *\n * The observed attribute name is the kebab-case of the prop key (`className` \u2194\n * `class-name`, `showOutsideDays` \u2194 `show-outside-days`, `id` \u2194 `id`). The\n * object forms accept an `attr` override for props whose native attribute is\n * NOT the kebab derivation \u2014 e.g. `readOnly: { type: 'boolean', attr: 'readonly' }`\n * (the native boolean attribute is `readonly`, not `read-only`). (v1.1)\n */\nexport type AttrDecl =\n | 'string'\n | 'boolean'\n | 'number'\n | 'forward'\n | { type: 'boolean'; default?: boolean; attr?: string }\n | { type: 'string'; default?: string; attr?: string }\n | { type: 'number'; default?: number; attr?: string };\n\n/**\n * The `attrs` declaration map for a props interface `P`: prop keys \u2192 attribute\n * behavior. This is the type an `attrs` object satisfies; capture its literal\n * type with `typeof` and pass it as `component`'s second type argument to\n * unlock declared-type narrowing (ADR 0025 candidate (b)):\n *\n * ```ts\n * const attrs = { checked: 'boolean' } satisfies ComponentAttrs<SwitchProps>;\n * const Switch = component<SwitchProps, typeof attrs>('ui-switch', setup, { attrs });\n * // inside setup: props.checked.value is `boolean`, not `boolean | undefined`\n * ```\n */\nexport type ComponentAttrs<P> = Partial<Record<Extract<keyof P, string>, AttrDecl>>;\n\n/** Options for component() registration */\nexport interface ComponentOptions<P = unknown> {\n /** Custom error fallback renderer */\n onError?: (error: Error, host: HTMLElement) => TemplateResult | string;\n /**\n * Opt-in attribute reactivity (ADR 0025 item 3). Maps prop keys\n * to attribute declarations. Omitted entirely \u2192 zero cost (empty\n * `observedAttributes`, no `attributeChangedCallback` work).\n */\n attrs?: ComponentAttrs<P>;\n}\n\n// \u2500\u2500 Attribute-reactivity helpers (ADR 0025 item 3) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface AttrEntry {\n /** camelCase prop key. */\n key: string;\n /** kebab-case observed attribute name. */\n attrName: string;\n decl: AttrDecl;\n}\n\nconst camelToKebab = (s: string): string =>\n s.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n\nconst declType = (decl: AttrDecl): 'string' | 'boolean' | 'number' | 'forward' =>\n typeof decl === 'string' ? decl : decl.type;\n\n/** The observed attribute name: an explicit `attr` override, else kebab(key). */\nconst declAttrName = (key: string, decl: AttrDecl): string =>\n typeof decl === 'object' && decl.attr ? decl.attr : camelToKebab(key);\n\n/** Resolve a raw attribute string (or null when absent) to the prop value. */\nfunction resolveAttrValue(decl: AttrDecl, raw: string | null): unknown {\n const t = declType(decl);\n if (t === 'boolean') {\n const def =\n typeof decl === 'object' && 'default' in decl && decl.default !== undefined\n ? decl.default\n : false;\n if (raw === null) return def; // absent \u2192 declared default (else false)\n return raw !== 'false'; // bare/any \u2192 true, literal \"false\" \u2192 false\n }\n if (t === 'number') {\n const def = typeof decl === 'object' && 'default' in decl ? decl.default : undefined;\n if (raw === null) return def; // absent \u2192 declared default (else undefined)\n const n = Number(raw);\n // Garbage behaves as ABSENT \u2192 the declared default (else undefined). A\n // default exists to guarantee non-undefined; letting garbage fall to\n // literal undefined would reintroduce exactly what the default prevents.\n return Number.isNaN(n) ? def : n;\n }\n // 'string' | 'forward'\n if (raw === null) {\n return typeof decl === 'object' && 'default' in decl ? decl.default : undefined;\n }\n return raw;\n}\n\n// \u2500\u2500 Internal component host \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass ComponentHostImpl implements ComponentHost {\n element: HTMLElement;\n private disposers: (() => void)[] = [];\n private setupComplete = false;\n\n constructor(element: HTMLElement) {\n this.element = element;\n }\n\n addDisposer(fn: () => void): void {\n this.disposers.push(fn);\n }\n\n dispose(): void {\n for (const fn of this.disposers) {\n try { fn(); } catch (_) { /* swallow disposal errors */ }\n }\n this.disposers.length = 0;\n }\n}\n\n// \u2500\u2500 Prop signal management via Proxy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Creates a Proxy-based props object that lazily creates signals\n * for each property on first access. When a parent sets a property\n * on the element, the Proxy intercepts it and updates (or creates)\n * the backing signal.\n */\nfunction createPropsProxy<P>(): {\n props: ReactiveProps<P>;\n setProperty: (key: string, value: unknown) => void;\n} {\n const signals = new Map<string, Signal<unknown>>();\n\n // Keys the component has READ through the proxy, accumulated over the\n // COMPONENT LIFETIME (the proxy is constructor-owned and survives\n // remounts/HMR swaps, so a re-setup never false-positives). This is the\n // truth source for the unknown-prop echo (N202, ADR 0030.2): a post-mount\n // write to a never-read key is attribution noise, not state. A component\n // that stashes `props` and reads a key dynamically AFTER such a write gets\n // one stale echo \u2014 accepted; the echo is attribution-only. The dev-only\n // propsReadKeys map above owns this bookkeeping, outside production objects.\n const getOrCreate = (key: string, initialValue?: unknown): Signal<unknown> => {\n let s = signals.get(key);\n if (!s) {\n s = signal(initialValue);\n signals.set(key, s);\n }\n return s;\n };\n\n const props = new Proxy({} as ReactiveProps<P>, {\n get(_target, key) {\n // Symbol probes (well-known symbols, thenable checks) are not props.\n if (typeof key !== 'string') return undefined;\n if (process.env.NODE_ENV !== 'production') propsReadKeys!.get(props)!.add(key);\n return getOrCreate(key);\n },\n });\n\n if (process.env.NODE_ENV !== 'production') propsReadKeys!.set(props, new Set());\n\n const setProperty = (key: string, value: unknown) => {\n const s = getOrCreate(key, value);\n s.value = value;\n };\n\n return { props, setProperty };\n}\n\n// \u2500\u2500 Duplicate-define attribution (N201, dev only) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** First definition site per tag, captured in dev for N201 attribution. */\nconst firstDefineSites = process.env.NODE_ENV !== 'production'\n ? new Map<string, string>() : undefined;\n\n/**\n * Best-effort caller frame for N201: the first stack line that is neither the\n * Error header nor a frame inside this module. Dev-only; a user file that is\n * itself named `component.ts` gets skipped too (best-effort attribution, never\n * behavior).\n */\nfunction captureDefineSite(): string {\n const stack = new Error().stack;\n if (!stack) return '(site unavailable)';\n const lines = stack.split('\\n');\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i]!.trim();\n if (!line) continue;\n if (line.includes('captureDefineSite') || /[/\\\\]component\\.(?:ts|js)\\b/.test(line)) continue;\n return line;\n }\n return '(site unavailable)';\n}\n\n// \u2500\u2500 component() \u2014 the main entry point \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Define a web component with typed props and a setup function.\n *\n * Returns a typed factory function for compile-time-safe composition.\n *\n * ```ts\n * interface TaskItemProps {\n * task: Task;\n * selected: boolean;\n * }\n *\n * const TaskItem = component<TaskItemProps>('task-item', (props, host) => {\n * const title = computed(() => props.task.value.title);\n * return html`<div>${title}</div>`;\n * });\n *\n * // Factory usage:\n * TaskItem({ task: taskSignal, selected: isSelected })\n * ```\n */\nexport function component<\n P extends object = Record<string, never>,\n A extends ComponentAttrs<P> = {},\n>(\n tagName: string,\n setup: SetupFunction<P, A>,\n // When `A` is explicitly given a non-empty attrs literal (the narrowing\n // opt-in), the options argument \u2014 carrying `attrs: A` \u2014 is REQUIRED: a\n // `component<P, typeof attrs>(tag, setup)` that types the props as narrowed but\n // never actually wires the attrs at runtime would be a compile-time lie. When\n // `A` is `{}` (the legacy default, no second type arg), options stays optional\n // exactly as before. `attrs` in that legacy branch is still validated as\n // `ComponentAttrs<P>` via `ComponentOptions<P>`.\n ...[options]: [keyof A] extends [never]\n ? [options?: ComponentOptions<P>]\n : [options: ComponentOptions<P> & { attrs: A }]\n): ComponentFactory<P> {\n // Attribute-reactivity wiring (ADR 0025 item 3). Computed once\n // per component definition; empty when no `attrs` declared (\u2192 zero cost).\n const attrEntries = new Map<string, AttrEntry>(); // by attrName\n const attrEntriesByKey = new Map<string, AttrEntry>(); // by prop key\n if (options?.attrs) {\n for (const key of Object.keys(options.attrs)) {\n const decl = (options.attrs as Record<string, AttrDecl>)[key]!;\n const attrName = declAttrName(key, decl);\n const entry: AttrEntry = { key, attrName, decl };\n attrEntries.set(attrName, entry);\n attrEntriesByKey.set(key, entry);\n }\n }\n const observedList = Array.from(attrEntries.keys());\n\n // The custom element class\n class FrameworkComponent extends HTMLElement {\n private _host: ComponentHostImpl | null = null;\n private _propsProxy: ReturnType<typeof createPropsProxy<P>> | null = null;\n private _mounted = false;\n private _templateResult: TemplateResult | null = null;\n private _errorTemplateResult: TemplateResult | null = null;\n private _teardownScheduled = false;\n // Props explicitly set via _setProp (factory / direct assignment) are\n // \"pinned\": an explicit prop wins, so attribute writes no longer overwrite\n // it. (Precedence ruling: prop-pins.)\n private _pinned = new Set<string>();\n // Guards our own removeAttribute() during 'forward' relocation from\n // re-entering attributeChangedCallback.\n private _relocating = false;\n\n /** The browser reads this once at define time. Empty \u2192 no callbacks. */\n static get observedAttributes(): string[] {\n return observedList;\n }\n\n constructor() {\n super();\n this._propsProxy = createPropsProxy<P>();\n }\n\n /** Write one declared attribute onto its prop signal, honoring pinning. */\n private _applyAttr(entry: AttrEntry, raw: string | null): void {\n if (declType(entry.decl) === 'forward') {\n // Relocate off the layout-transparent host (no duplicate id/name), but\n // only adopt the attribute's value when no explicit prop pinned it. A\n // null `raw` here (absent OR already-relocated) is a NO-OP: the seed\n // and attributeChangedCallback must not clobber an adopted value. The\n // explicit unpin path (in _setProp) handles clearing.\n if (raw !== null) {\n if (!this._pinned.has(entry.key)) {\n this._propsProxy!.setProperty(entry.key, raw);\n }\n this._relocating = true;\n this.removeAttribute(entry.attrName);\n this._relocating = false;\n }\n return;\n }\n if (this._pinned.has(entry.key)) return; // explicit prop wins\n this._propsProxy!.setProperty(entry.key, resolveAttrValue(entry.decl, raw));\n }\n\n /** Seed initial prop values from current attributes (incl. defaults). */\n private _seedAttrs(): void {\n for (const entry of attrEntries.values()) {\n this._applyAttr(entry, this.getAttribute(entry.attrName));\n }\n }\n\n attributeChangedCallback(name: string, _old: string | null, next: string | null): void {\n if (this._relocating) return;\n const entry = attrEntries.get(name);\n if (entry) this._applyAttr(entry, next);\n }\n\n connectedCallback() {\n if (this._mounted) return; // guard against re-connection\n this._mounted = true;\n\n // Isolate activeObserver: child component setup signal reads must NOT\n // leak into a parent effect's dependency set. Without this, a parent\n // effect running replaceChildren/appendChild triggers child\n // connectedCallback synchronously, and child signal reads would be\n // tracked as parent dependencies \u2014 causing infinite re-render loops.\n // See ADR 0008 Gap 1 / ADR 0009.\n untrack(() => {\n const host = new ComponentHostImpl(this);\n this._host = host;\n\n // Canonical pre-setup order: SEED \u2192 CAPTURE \u2192 CONTEXT (then setup).\n //\n // SEED (ADR 0025 item 3): write prop signals from current\n // attributes (incl. declared defaults and 'forward' relocation) so setup\n // sees correct initial values. No-op when no attrs are declared.\n if (attrEntries.size) this._seedAttrs();\n\n // CAPTURE (ADR 0025 item 1): snapshot the host's light-DOM\n // children so children() can project them. Snapshot only \u2014 children()\n // removes/projects on demand \u2014 so non-projecting components are\n // untouched. Zero-cost when the host has no light DOM.\n if (this.childNodes.length) {\n (this as unknown as { __capturedChildren?: Node[] }).__capturedChildren =\n Array.from(this.childNodes);\n }\n\n // Phase attribution for the SHARED containment boundary (ADR 0030.2\n // T6): 'setup' (N401) until the template is committed, 'mount' (N402)\n // once onMount callbacks begin. Both phases route through the ONE\n // catch below \u2014 runMountCallbacks no longer swallows (lifecycle.ts).\n let phase: 'setup' | 'mount' = 'setup';\n try {\n // CONTEXT is established by runWithContext(host, \u2026) below; setup then\n // runs with seed + capture already in place.\n runWithContext(host, () => {\n // The Proxy is runtime-untyped; the declared narrowing (A) is a\n // compile-time view the setup function requested (ADR 0025 (b)).\n this._templateResult = setup(\n this._propsProxy!.props as ReactiveProps<P, A>,\n this,\n );\n });\n\n // Mount the template result\n if (this._templateResult) {\n mountTemplate(this, this._templateResult, host);\n }\n\n // PROJECTION PHASE (ADR 0030.2 \u00A73): if setup called children(), run\n // its late-children sweep scheduling NOW \u2014 after the template\n // committed, BEFORE any onMount callback. The rendered-roots\n // snapshot therefore never depends on where children() sat relative\n // to onMount() registrations (the 0025 batch-3B ordering trap), and\n // the rule becomes universal: any host child appearing after this\n // point \u2014 late parser/innerHTML content OR an onMount host-append \u2014\n // classifies as projected content.\n const sweepHost = this as unknown as { __nisliProjectionSweep?: () => void };\n if (sweepHost.__nisliProjectionSweep) {\n const sweep = sweepHost.__nisliProjectionSweep;\n sweepHost.__nisliProjectionSweep = undefined; // consumed once per cycle\n sweep();\n }\n\n // Run onMount() callbacks \u2014 DOM is now committed\n phase = 'mount';\n runMountCallbacks(host);\n\n if (process.env.NODE_ENV !== 'production') completedSetups!.add(this);\n // T6: a SUCCESSFUL (re-)setup \u2014 including _remount(), the documented\n // boundary reset \u2014 removes the failure stamp.\n this.removeAttribute('data-nisli-error');\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n const code = phase === 'setup' ? 'N401' : 'N402';\n diag(code, `<${tagName}> ${phase} failed: ${error.message}`, {\n tag: tagName,\n phase,\n error,\n });\n\n // Setup may already have registered effects/lifecycle cleanup, or\n // mountTemplate() may have partially installed bindings before\n // throwing \u2014 and a mount-phase throw arrives with the whole scope\n // live. Tear the partial scope down BEFORE mounting the error\n // fallback so no hidden work survives behind it (issue 0010; the\n // onMount phase now shares these exact semantics per T6). An\n // unconsumed projection sweep hook is part of that partial scope.\n (this as unknown as { __nisliProjectionSweep?: () => void }).__nisliProjectionSweep =\n undefined;\n if (this._templateResult?.dispose) {\n this._templateResult.dispose();\n }\n this._templateResult = null;\n host.dispose();\n this._host = null;\n this.replaceChildren();\n\n // T6 \u2014 failure is a DOM fact. The attribute is the DURABLE channel:\n // `querySelectorAll('[data-nisli-error]')` answers \"which component\n // failed\" long after the fact, with no listener installed in\n // advance. Client-runtime only \u2014 SSG failures stay build failures.\n this.setAttribute('data-nisli-error', code);\n\n if (options?.onError) {\n try {\n const fallback = options.onError(error, this);\n if (typeof fallback === 'string') {\n this.innerHTML = fallback;\n } else {\n this._errorTemplateResult = fallback;\n mountTemplate(this, fallback);\n }\n } catch (_) {\n if (this._errorTemplateResult?.dispose) {\n this._errorTemplateResult.dispose();\n }\n this._errorTemplateResult = null;\n this.innerHTML = `<div style=\"color:red;padding:4px\">Error in &lt;${tagName}&gt;</div>`;\n }\n } else {\n this.innerHTML = `<div style=\"color:red;padding:4px\">Error in &lt;${tagName}&gt;</div>`;\n }\n\n // T6 \u2014 the EVENT is the live channel: one document-level listener\n // observes every contained failure as it happens. Dispatched LAST so\n // listeners see the settled DOM (stamp + fallback). Bubbling is a\n // DOM-tree walk, so CSS (display:contents transparent hosts) never\n // affects delivery \u2014 but a component mounted into a DETACHED\n // fragment has no path to document and the event is swallowed; the\n // attribute above is the durable record for those (ADR 0030.2 \u00A78).\n this.dispatchEvent(\n new CustomEvent('nisli-error', {\n bubbles: true,\n composed: true,\n detail: { code, tag: tagName, phase, message: error.message },\n }),\n );\n }\n });\n }\n\n disconnectedCallback() {\n // A same-tick remove+reinsert is a MOVE, not a removal: per WHATWG,\n // append-based moves fire disconnected+connected (only moveBefore()\n // preserves state). Moves happen routinely inside the framework \u2014\n // each() keyed reorders, light-DOM projection of nested components \u2014\n // and re-running setup on them duplicates rendered output and loses\n // state. Defer teardown one microtask and skip it if the element is\n // connected again; connectedCallback's _mounted guard then makes the\n // whole move a no-op. True removals still dispose, one microtask\n // later. See ADR 0023.\n if (this._teardownScheduled) return;\n this._teardownScheduled = true;\n queueMicrotask(() => {\n this._teardownScheduled = false;\n if (this.isConnected) return;\n this._teardownNow();\n });\n }\n\n /**\n * Atomic DOM moves preserve this component's position-independent state,\n * so the platform-level lifecycle is a no-op. ADR 0023's deferred\n * disconnect teardown remains the fallback for append-based moves.\n */\n connectedMoveCallback(): void {}\n\n /**\n * Synchronously dispose the current component scope and restore any\n * projected light-DOM children as direct host children. Normal disconnect\n * calls this after the move-detection microtask; HMR calls it directly so\n * reconnect cannot be defeated by the `_mounted` guard (issues 0001/0002).\n */\n private _teardownNow(): void {\n this._mounted = false;\n if (process.env.NODE_ENV !== 'production') completedSetups!.delete(this);\n if (this._templateResult?.dispose) {\n this._templateResult.dispose();\n }\n this._templateResult = null;\n if (this._errorTemplateResult?.dispose) {\n this._errorTemplateResult.dispose();\n }\n this._errorTemplateResult = null;\n if (this._host) {\n this._host.dispose();\n this._host = null;\n }\n\n // children() records the plain light-DOM nodes it owns during cleanup.\n // Replacing the rendered tree with those nodes preserves author content\n // for a later true reconnect/HMR setup; components without projection\n // simply become empty before the fresh setup appends its new subtree.\n const captured = (this as unknown as { __capturedChildren?: Node[] })\n .__capturedChildren ?? [];\n this.replaceChildren(...captured);\n }\n\n /** @internal \u2014 transport-agnostic HMR in-place remount hook. */\n _remount(): void {\n this._teardownScheduled = false;\n this._teardownNow();\n this.connectedCallback();\n }\n\n /**\n * Set a prop value. Called by the factory and by direct property assignment.\n * The Proxy intercepts and creates/updates backing signals.\n *\n * Precedence = DEFINED-write-pins (ADR 0025 item 3): a defined\n * value pins the key so a declared attribute no longer overwrites it. An\n * explicit `undefined` (e.g. a factory spreading an unset optional prop \u2014\n * `{...opts}` fires _setProp(key, undefined) per the Object.entries walk)\n * must NOT pin; it falls back to the declared attribute/default, matching\n * attr()'s coalesce. For a declared attribute, that fallback re-resolves\n * from the current attribute, keeping declared-default booleans\n * non-undefined.\n */\n _setProp(key: string, value: unknown): void {\n // Unknown-prop echo (N202, dev, ADR 0030.2): post-mount, a DEFINED write\n // to a key setup() never read is attribution noise \u2014 a misspelled prop\n // (`varian=`) arriving through the factory or the template\n // auto-resolution path (both funnel through _setProp). `undefined`\n // writes are exempt BY CONTRACT: a factory spreading unset optional\n // props fires _setProp(key, undefined) per the Object.entries walk (see\n // the pinning doc above). Attribution-only \u2014 the write still lands\n // exactly as before; deduped per key per element.\n if (\n process.env.NODE_ENV !== 'production'\n && completedSetups!.has(this)\n && value !== undefined\n && isDev()\n // A declared attrs key is contract, not a typo \u2014 'forward' especially,\n // where CORE owns the read and setup() never touches the prop. Gate\n // ruling on ADR 0030.2 \u00A78 T6 Q3: declared keys are exempt.\n && !attrEntriesByKey.has(key)\n && !propsReadKeys!.get(this._propsProxy!.props)!.has(key)\n && !echoedProps!.get(this)?.has(key)\n ) {\n const echoed = echoedProps!.get(this) ?? new Set<string>();\n echoed.add(key);\n echoedProps!.set(this, echoed);\n diag(\n 'N202',\n `<${tagName}> prop '${key}' was set but setup() never read it \u2014 misspelled or unsupported prop?`,\n { tag: tagName, key },\n );\n }\n if (value === undefined) {\n this._pinned.delete(key);\n const entry = attrEntriesByKey.get(key);\n if (entry) {\n const raw = this.getAttribute(entry.attrName);\n // A 'forward' attribute is removed from the host on adoption, so an\n // unpin can't re-read it \u2014 resolve the absent value directly to CLEAR\n // a previously pinned id/name (rev audit fix). _applyAttr's forward\n // branch deliberately no-ops on absent (so the seed/attr callback\n // never clobber an adopted value); the explicit unpin does not.\n if (raw === null && declType(entry.decl) === 'forward') {\n this._propsProxy?.setProperty(key, resolveAttrValue(entry.decl, null));\n } else {\n this._applyAttr(entry, raw);\n }\n return;\n }\n } else {\n this._pinned.add(key);\n }\n this._propsProxy?.setProperty(key, value);\n }\n\n /**\n * Read a prop's backing signal (framework-internal). Used by children()\n * to fold the factory `children` prop into the projection slot (ADR 0025\n * item 1) without a new public read API.\n */\n _propSignal(key: string): Signal<unknown> {\n return (this._propsProxy!.props as Record<string, Signal<unknown>>)[key]!;\n }\n\n /**\n * Whether a prop is currently pinned by a defined factory/property write\n * (framework-internal, like _propSignal). The attribute-as-truth open-state\n * pattern needs this as its controlled-mode discriminator: a declared\n * 'boolean' prop is never undefined (absent \u2192 false), so pin state is the\n * ONLY way a component can tell \"parent drives this\" from \"the attribute\n * drives this\" \u2014 e.g. setOpen() must not write the open attribute while a\n * controlled parent has it pinned, or the DOM attribute diverges from the\n * pinned state until the next prop write.\n */\n _isPinned(key: string): boolean {\n return this._pinned.has(key);\n }\n }\n\n // Register the custom element. A DUPLICATE definition is a coded dev error\n // (N201, ADR 0030.2 \u00A73/\u00A78): first-wins-silently rendered the WRONG component\n // while the second factory typechecked against the wrong props. The error\n // names both definition sites and is thrown to the SECOND definer; the\n // first definition stays live (first-wins preserved). Exemptions:\n // - HMR re-evaluations arrive with the registry's marked indirection thunk\n // (hmr/registry.ts __register) \u2014 the live thunk already swapped setup, so\n // re-registration is the mechanism working, not a collision.\n // - Production keeps the historical SILENT first-wins: a name clash must\n // not take down a live page (redefine-as-swap stays HMR/dev-only because\n // the copy-in registry model makes genuine duplicate tags structural).\n if (!customElements.get(tagName)) {\n customElements.define(tagName, FrameworkComponent);\n if (process.env.NODE_ENV !== 'production' && isDev()) firstDefineSites!.set(tagName, captureDefineSite());\n } else if (process.env.NODE_ENV !== 'production' && isDev() && !(setup as { __nisliHmr?: boolean }).__nisliHmr) {\n const first = firstDefineSites!.get(tagName)\n ?? '(unknown site \u2014 defined outside component(), or before dev mode was enabled)';\n throw new Error(formatDiag(\n 'N201',\n `duplicate define for <${tagName}>. First defined ${first}; the second `\n + `definition site is this error's own stack. The first definition stays `\n + `live (first-wins) \u2014 rename one of the components.`,\n ));\n }\n\n // Return the typed factory function\n const factory: ComponentFactory<P> = (props, hostAttrs?) => {\n return {\n __type: 'factory' as const,\n tagName,\n props: props as Record<string, PropInput<unknown>>,\n hostAttrs,\n } as unknown as TemplateResult;\n };\n\n return factory;\n}\n\n/**\n * Ensure a value is a signal. If it already is, return as-is.\n * If it's a plain value, wrap it in signal().\n * Used by factory mount to support PropInput<T> = T | Signal<T>.\n */\nfunction ensureSignal<T>(value: PropInput<T>): ReadonlySignal<T> {\n if (isSignal(value)) return value as ReadonlySignal<T>;\n return signal(value as T);\n}\n\n/**\n * Mount a TemplateResult into a host element.\n * This is the bridge between component.ts and template.ts.\n * Template.ts will provide the actual implementation via the\n * TemplateResult.mount() method.\n *\n * @param hostImpl \u2014 optional ComponentHostImpl for registering disposers\n */\nfunction mountTemplate(host: HTMLElement, result: TemplateResult, hostImpl?: ComponentHostImpl): void {\n if (result && typeof result === 'object' && 'mount' in result && typeof result.mount === 'function') {\n result.mount(host);\n } else if (result && typeof result === 'object' && '__type' in result) {\n // Factory result \u2014 create the child element\n const factoryResult = result as unknown as {\n __type: 'factory';\n tagName: string;\n props: Record<string, PropInput<unknown>>;\n hostAttrs?: HostAttrs;\n };\n const el = document.createElement(factoryResult.tagName);\n\n // Forward props as signals (auto-wrap plain values)\n for (const [key, raw] of Object.entries(factoryResult.props)) {\n const sig = ensureSignal(raw);\n (el as any)._setProp(key, sig.value);\n // Subscribe to signal changes to update the child's props\n const unsub = sig.subscribe((newVal: unknown) => {\n (el as any)._setProp(key, newVal);\n });\n // Register unsub for cleanup on disconnect\n if (hostImpl) {\n hostImpl.addDisposer(unsub);\n }\n }\n\n // Apply host-level attributes (class)\n if (factoryResult.hostAttrs?.class != null) {\n const classSig = ensureSignal(factoryResult.hostAttrs.class);\n // Apply initial value\n applyHostClass(el, '', classSig.value);\n // Subscribe to reactive changes\n let prevClass = classSig.value;\n const unsub = classSig.subscribe((newClass: string) => {\n applyHostClass(el, prevClass, newClass);\n prevClass = newClass;\n });\n if (hostImpl) {\n hostImpl.addDisposer(unsub);\n }\n }\n\n host.appendChild(el);\n }\n}\n\n/**\n * Apply a class string to an element via classList, replacing the previous\n * class string's classes. Uses add/remove to avoid interfering with classes\n * set by the component's own template (class:name directives, etc.).\n */\nfunction applyHostClass(el: Element, prev: string, next: string): void {\n const prevClasses = prev ? prev.split(/\\s+/).filter(Boolean) : [];\n const nextClasses = next ? next.split(/\\s+/).filter(Boolean) : [];\n for (const cls of prevClasses) {\n if (!nextClasses.includes(cls)) el.classList.remove(cls);\n }\n for (const cls of nextClasses) {\n if (!prevClasses.includes(cls)) el.classList.add(cls);\n }\n}\n", "/**\n * ref.ts \u2014 Element reference primitive for imperative DOM access\n *\n * `ref()` creates a container that receives a DOM element reference\n * after the template is mounted. Use it for focus management, DOM\n * measurement, scroll management, and third-party library init.\n *\n * ```ts\n * const inputRef = ref<HTMLInputElement>();\n *\n * onMount(() => inputRef.current?.focus());\n *\n * return html`<input ref=\"${inputRef}\" @keydown.enter=${onSubmit} />`;\n * ```\n *\n * The template engine detects `Ref` objects in `ref=\"${...}\"`\n * attribute bindings and assigns the referenced element.\n */\n\n// \u2500\u2500 Brand for ref detection in templates \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport const REF_BRAND = Symbol.for('backlog.ref');\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface Ref<T extends Element = Element> {\n readonly [REF_BRAND]: true;\n /** The DOM element, or null before mount / after unmount */\n current: T | null;\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Create a ref container for imperative DOM access.\n *\n * After the template is mounted, `ref.current` holds the element.\n * After dispose, `ref.current` is set back to null.\n */\nexport function ref<T extends Element = Element>(): Ref<T> {\n return {\n [REF_BRAND]: true as const,\n current: null,\n };\n}\n\n/**\n * Check if a value is a Ref.\n * Used by the template engine to detect refs in expression slots.\n */\nexport function isRef(value: unknown): value is Ref {\n return (\n value !== null &&\n typeof value === 'object' &&\n REF_BRAND in (value as Record<symbol, unknown>)\n );\n}\n", "/**\n * template-audit.ts \u2014 First-parse static template audit (ADR 0030.2 T4).\n *\n * Attached to the parse-once cache in template.ts: runs ONCE per `html`\n * callsite (keyed by TemplateStringsArray identity) at the first parse, and\n * walks the parsed-but-never-mounted template element checking its STATIC\n * parts. The silent-static-typo class \u2014 the no-build equivalent of a compile\n * error \u2014 dies in the engine, amortized free.\n *\n * Checks (per ADR 0030.2 \u00A72 T4 as amended by \u00A78 \"T4 (template)\"):\n * - N101 \u2014 a dash-tag with no customElements definition. Races\n * `customElements.whenDefined` against a microtask + macrotask grace so\n * ordinary lazy definition (module import order) never warns.\n * - N102 \u2014 an `@event` name that is neither a known native event nor an\n * allowlisted component-dispatched event (`ui-*`, `nisli-*`).\n * - N103 \u2014 an unknown `@event.modifier`.\n * - N104 \u2014 an attribute on a component tag that declares attributes\n * (non-empty `static observedAttributes`) which is neither declared nor a\n * global HTML attribute. Components WITHOUT declared attributes get NO\n * attribute audit: pre-schema (T3) there is no truth source \u2014 auto-resolved\n * props are deliberately not attributes (\u00A78).\n *\n * Suppression escape (designed for lazy islands, \u00A78): a comment directive as\n * the template's FIRST node (leading whitespace allowed):\n *\n * html`<!-- nisli-audit off --><my-island>\u2026</my-island>`\n * \u2014 disables the whole audit for this template.\n *\n * html`<!-- nisli-audit allow-undefined: my-island other-tag --><\u2026>`\n * \u2014 suppresses only N101 for the named tags (other checks stay live).\n *\n * The directive comment is static content: it survives into the mounted DOM\n * (and SSG output) as an inert HTML comment. Documented, accepted for the\n * prototype; the design gate may choose to strip it at parse.\n *\n * Calls AND module allocations are statically gated (ADR 0048). The runtime\n * override can suppress or restore available audits, never restore removed code.\n * No SSG/happy-dom detection is attempted; production rendering uses NODE_ENV\n * or the native production artifact.\n */\n\n// Reporting goes through the diagnostics leaf. The audit keeps its own\n// enable override (tests, SSG environments) and otherwise follows the\n// leaf's dev gate \u2014 under NODE_ENV=production builds it is silent.\nimport { diag as emitDiag, isDev } from './diagnostics.js';\n\nlet enabledOverride: boolean | null = null;\n\n/**\n * Enable/disable the first-parse audit (and its callsite capture);\n * `null` restores the dev-gate default.\n */\nexport function setTemplateAuditEnabled(enabled: boolean | null): void {\n if (process.env.NODE_ENV !== 'production') enabledOverride = enabled;\n}\n\n/** Current audit gate state (exposed for template.ts and tests). */\nexport function isTemplateAuditEnabled(): boolean {\n return process.env.NODE_ENV !== 'production' && (enabledOverride ?? isDev());\n}\n\n/** Emit a coded audit diagnostic through the diagnostics leaf (audit-gated). */\nexport function diag(code: string, message: string, detail?: unknown): void {\n if (!isTemplateAuditEnabled()) return;\n emitDiag(code, message, detail === undefined ? undefined : { detail });\n}\n\n// \u2500\u2500 Callsite capture \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** First-seen authoring callsite per template identity (dev only). */\nconst callsites = process.env.NODE_ENV !== 'production'\n ? new WeakMap<TemplateStringsArray, string>() : undefined;\n\n/**\n * Remember the authoring callsite of an `html` template the first time its\n * strings identity is seen. Must be called from `html()` itself \u2014 by the\n * time the first parse happens (first mount), the authoring frame is gone\n * from the stack. No-op when the audit is disabled or already captured.\n */\nexport function captureCallsite(strings: TemplateStringsArray): void {\n if (!isTemplateAuditEnabled() || callsites!.has(strings)) return;\n const stack = new Error().stack ?? '';\n const frame = stack\n .split('\\n')\n .slice(1)\n .find(line => line.includes('at ') && !/template(-audit)?\\.(ts|js|mjs|cjs)/.test(line));\n callsites!.set(strings, frame ? frame.trim() : '(unknown callsite)');\n}\n\n// \u2500\u2500 Audit \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst audited = process.env.NODE_ENV !== 'production'\n ? new WeakSet<TemplateStringsArray>() : undefined;\n\n/** Modifiers understood by bindEvent (template.ts). */\nconst KNOWN_MODIFIERS = process.env.NODE_ENV !== 'production'\n ? new Set(['stop', 'prevent', 'once', 'enter', 'escape', 'space', 'tab']) : undefined;\n\n/** Component-dispatched event prefixes exempt from the native-event check (\u00A78). */\nconst COMPONENT_EVENT_PREFIXES = ['ui-', 'nisli-'];\n\n/** Real native events with no `on*` IDL attribute (the `in`-check misses them). */\nconst NATIVE_EVENTS_WITHOUT_IDL = process.env.NODE_ENV !== 'production'\n ? new Set(['focusin', 'focusout']) : undefined;\n\n/**\n * Global HTML attributes legal on ANY component tag. Mirrors (and must stay a\n * superset of) template.ts's auto-resolution exclusion list \u2014 these reach the\n * element as plain attributes, never `_setProp`.\n */\nconst GLOBAL_ATTRS = process.env.NODE_ENV !== 'production' ? new Set([\n 'id', 'class', 'style', 'slot', 'title', 'role', 'tabindex', 'name',\n 'part', 'hidden', 'dir', 'lang', 'is',\n]) : undefined;\n\ninterface AuditDirectives {\n off: boolean;\n allowUndefined: Set<string>;\n}\n\n/** Parse the leading `<!-- nisli-audit \u2026 -->` directive comment, if any. */\nfunction parseDirectives(content: DocumentFragment): AuditDirectives {\n const directives: AuditDirectives = { off: false, allowUndefined: new Set() };\n for (const node of content.childNodes) {\n if (node.nodeType === Node.TEXT_NODE) {\n if ((node.textContent ?? '').trim() === '') continue; // leading whitespace\n break;\n }\n if (node.nodeType === Node.COMMENT_NODE) {\n const body = (node.textContent ?? '').trim();\n if (!body.startsWith('nisli-audit')) break;\n const rest = body.slice('nisli-audit'.length).trim();\n if (rest === 'off') {\n directives.off = true;\n } else if (rest.startsWith('allow-undefined')) {\n const tags = rest\n .slice('allow-undefined'.length)\n .replace(/^[:\\s]+/, '')\n .split(/[\\s,]+/)\n .filter(Boolean);\n for (const tag of tags) directives.allowUndefined.add(tag.toLowerCase());\n }\n }\n break; // only the FIRST non-whitespace node may carry the directive\n }\n return directives;\n}\n\n/**\n * N101 \u2014 dash-tag with no definition. Rather than warning synchronously (the\n * defining module may simply import later in the same task), race\n * `customElements.whenDefined(tag)` against a microtask + macrotask grace;\n * warn only if the tag is still undefined after the grace elapses.\n */\nfunction checkDashTag(tag: string, site: string): void {\n let registry: CustomElementRegistry | undefined;\n try {\n registry = customElements;\n } catch {\n return; // no registry in this environment \u2014 nothing to check\n }\n if (!registry || registry.get(tag)) return;\n\n let defined = false;\n try {\n registry.whenDefined(tag).then(\n () => { defined = true; },\n () => { /* invalid name \u2014 the synchronous throw below already covers it */ },\n );\n } catch {\n diag('N101', `<${tag}> is not a valid custom element name \u2014 at ${site}`);\n return;\n }\n\n // Grace: one microtask hop (whenDefined settlements for definitions made\n // earlier in this task) + one macrotask hop (definitions made later in the\n // same task, e.g. module evaluation order). Under fake timers the macrotask\n // may never fire \u2014 the warning is simply skipped, never wrong.\n queueMicrotask(() => {\n if (defined) return;\n setTimeout(() => {\n try {\n if (!isTemplateAuditEnabled() || defined || registry!.get(tag)) return;\n diag(\n 'N101',\n `<${tag}> is used in a template but never defined (customElements.get returned ` +\n `undefined after grace) \u2014 at ${site}. If this tag is a lazily-loaded island, ` +\n `suppress with a leading <!-- nisli-audit allow-undefined: ${tag} --> comment.`,\n );\n } catch { /* environment torn down during grace \u2014 nothing to report */ }\n }, 0);\n });\n}\n\n/** N102/N103 \u2014 event-name and modifier checks for one `@event.mods` attribute. */\nfunction checkEvent(el: Element, attrName: string, site: string): void {\n const parts = attrName.slice(1).split('.');\n const eventName = parts[0] ?? '';\n const modifiers = parts.slice(1);\n\n const isNative = `on${eventName}` in el || NATIVE_EVENTS_WITHOUT_IDL!.has(eventName);\n const isComponentEvent = COMPONENT_EVENT_PREFIXES.some(p => eventName.startsWith(p));\n if (eventName && !isNative && !isComponentEvent) {\n diag(\n 'N102',\n `@${eventName} on <${el.tagName.toLowerCase()}> is not a known native event ` +\n `(and not an allowlisted ${COMPONENT_EVENT_PREFIXES.join('/')} component event) \u2014 at ${site}`,\n );\n }\n for (const mod of modifiers) {\n if (!KNOWN_MODIFIERS!.has(mod)) {\n diag(\n 'N103',\n `unknown event modifier \".${mod}\" in \"${attrName}\" \u2014 known: ` +\n `${[...KNOWN_MODIFIERS!].join(', ')} \u2014 at ${site}`,\n );\n }\n }\n}\n\n/** N104 \u2014 undeclared attribute on a component that DECLARES attributes. */\nfunction checkComponentAttr(tag: string, name: string, observed: string[], site: string): void {\n if (name.startsWith('data-') || name.startsWith('aria-')) return;\n if (GLOBAL_ATTRS!.has(name) || observed.includes(name)) return;\n diag(\n 'N104',\n `<${tag}> declares attributes [${observed.join(', ')}] but the template sets ` +\n `unknown \"${name}\" \u2014 at ${site}. Undeclared names route through _setProp and are ` +\n `silently dead as attributes.`,\n );\n}\n\n/**\n * Run the one-time static audit over a freshly parsed template. Called by\n * template.ts's parse-once cache on cache miss; idempotent per template\n * identity, no-op when the audit is disabled. Read-only over the cached\n * template element \u2014 mounting state is never touched.\n */\nexport function auditTemplate(strings: TemplateStringsArray, template: HTMLTemplateElement): void {\n if (!isTemplateAuditEnabled() || audited!.has(strings)) return;\n audited!.add(strings);\n\n const site = callsites!.get(strings) ?? '(unknown callsite)';\n const content = template.content;\n const directives = parseDirectives(content);\n if (directives.off) return;\n\n for (const el of content.querySelectorAll('*')) {\n const tag = el.tagName.toLowerCase();\n const isDashTag = tag.includes('-');\n\n if (isDashTag && !directives.allowUndefined.has(tag)) {\n checkDashTag(tag, site);\n }\n\n // Attribute audit ONLY for components with declared attrs (\u00A78): a\n // non-empty static observedAttributes is the single pre-T3 truth source.\n let observed: string[] | undefined;\n if (isDashTag) {\n const ctor = customElements.get(tag) as { observedAttributes?: unknown } | undefined;\n const list = ctor?.observedAttributes;\n if (Array.isArray(list) && list.length > 0) observed = list as string[];\n }\n\n for (const attr of [...el.attributes]) {\n const name = attr.name;\n if (name.startsWith('@')) {\n checkEvent(el, name, site);\n continue;\n }\n // Directive positions with their own semantics \u2014 never attributes.\n if (name.startsWith('class:') || name === 'ref' || name === 'html:inner') continue;\n if (observed) checkComponentAttr(tag, name, observed, site);\n }\n }\n}\n", "/**\n * template.ts \u2014 Tagged template engine with targeted DOM binding\n *\n * The html tagged template literal parses HTML with expression slots,\n * creates bindings for signals, and produces a TemplateResult that\n * can be mounted into the DOM with surgical updates.\n *\n * Two phases:\n * 1. First render: parse template, clone, create bindings, mount\n * 2. Updates: signal changes trigger individual binding updates (O(1))\n */\n\nimport {\n signal,\n isSignal,\n effect,\n computed,\n untrack,\n type Signal,\n type ReadonlySignal,\n} from './signal.js';\nimport { isRef, type Ref } from './ref.js';\n// First-parse audit (ADR 0030.2 T4). The import is static \u2014 core has no\n// build-time dev/prod define yet (a named Wave-1 deliverable, \u00A78) \u2014 but every\n// entry point is a no-op behind template-audit's own dev flag.\nimport { auditTemplate, captureCallsite } from './template-audit.js';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface TemplateResult {\n /** Mount this template into a host element */\n mount(host: HTMLElement): void;\n /** Dispose all bindings and effects */\n dispose(): void;\n /** Brand for type checking */\n __templateResult: true;\n}\n\n// TypeScript's DOM library does not expose moveBefore() yet.\ninterface MoveCapableParent extends ParentNode {\n moveBefore(node: Node, child: Node | null): void;\n}\n\nconst canMoveWithin = (parent: ParentNode): parent is MoveCapableParent =>\n typeof (parent as Partial<MoveCapableParent>).moveBefore === 'function';\n\n/** A DOM event handler whose event type is inferred from its native event name. */\nexport type TypedEventHandler<K extends keyof HTMLElementEventMap> = (\n event: HTMLElementEventMap[K],\n) => void;\n\n/**\n * Value-returning untrack. signal.ts's `untrack` is `(fn: () => void) => void`\n * (the value-returning form is a 0030.2 \u00A73 papercut owned elsewhere); this\n * local wrapper closes over the result until that lands.\n */\nfunction untracked<T>(fn: () => T): T {\n let result!: T;\n untrack(() => { result = fn(); });\n return result;\n}\n\n// \u2500\u2500 Trusted HTML brand (raw) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Branded trusted-HTML value accepted by `html:inner` (and by @nisli/ssg's\n * static renderer, which re-exports this brand \u2014 core owns it, ADR 0030.2 \u00A78).\n * Structural, not nominal: cross-package/cross-realm values with the same\n * shape stay valid.\n */\nexport interface RawHtml {\n value: string;\n __raw: true;\n}\n\n/**\n * Mark a string as trusted raw HTML. `html:inner` accepts ONLY branded\n * values \u2014 a bare string throws N106 (the accidental-XSS-sink class closes,\n * ADR 0030.2 \u00A73). NEVER wrap user-generated input.\n */\nexport function raw(value: string): RawHtml {\n return { __raw: true as const, value };\n}\n\nfunction isRawHtml(value: unknown): value is RawHtml {\n return (\n typeof value === 'object'\n && value !== null\n && '__raw' in value\n && (value as RawHtml).__raw === true\n && typeof (value as RawHtml).value === 'string'\n );\n}\n\n// \u2500\u2500 Sanitized HTML brand (untrusted markup) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Branded UNTRUSTED-HTML value accepted by `html:inner`. The mirror image of\n * {@link RawHtml}: where `raw()` is the author asserting markup is already\n * trustworthy, this brand asserts the opposite \u2014 the string is untrusted and\n * MUST pass a sanitizer before it reaches the DOM (ADR 0019:124\u2013128, executed\n * by bet-09(c)). Structural, not nominal, on the same rule as RawHtml.\n */\nexport interface SanitizedHtml {\n value: string;\n __sanitize: true;\n}\n\n/**\n * Mark a string as untrusted markup to be sanitized at the sink \u2014 the brand\n * for user-generated HTML, which must NEVER go through `raw()`.\n *\n * `html:inner` writes it with the platform's `Element.setHTML()` (the spec's\n * XSS-safe default sanitizer) when the engine has one, otherwise with the hook\n * registered by {@link setSanitizerFallback}. With NEITHER available the\n * binding throws N107: it never falls back to `innerHTML`. nisli bundles no\n * sanitizer \u2014 the trust decision, and its bytes, stay in the app.\n */\nexport function sanitized(value: string): SanitizedHtml {\n return { __sanitize: true as const, value };\n}\n\nfunction isSanitizedHtml(value: unknown): value is SanitizedHtml {\n return (\n typeof value === 'object'\n && value !== null\n && '__sanitize' in value\n && (value as SanitizedHtml).__sanitize === true\n && typeof (value as SanitizedHtml).value === 'string'\n );\n}\n\n// \u2500\u2500 Sanitizer sinks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** A sanitizing writer: sanitize `html`, then put the result inside `el`. */\nexport type SanitizerFallback = (el: Element, html: string) => void;\n\nlet sanitizerFallback: SanitizerFallback | null = null;\n\n/**\n * Register the sanitizing writer used for `sanitized()` values on engines\n * WITHOUT native `Element.setHTML()` (Safari today, older Chromium/Firefox),\n * or `null` to unregister. Native `setHTML()` always wins where it exists, so\n * modern engines never pay the hook. nisli ships no sanitizer; wire one:\n *\n * setSanitizerFallback((el, html) => {\n * el.innerHTML = DOMPurify.sanitize(html);\n * });\n */\nexport function setSanitizerFallback(fn: SanitizerFallback | null): void {\n sanitizerFallback = fn;\n}\n\n// TypeScript's DOM library does not expose Element.setHTML() yet.\ninterface SanitizeCapableElement extends Element {\n setHTML(html: string): void;\n}\n\nconst nativeSetHtml: SanitizerFallback = (el, html) => {\n (el as SanitizeCapableElement).setHTML(html);\n};\n\n/**\n * The sanitizing writer for this element, or `null` when the engine has none\n * and the app registered none \u2014 the fail-closed signal N107 is thrown on.\n *\n * The method must be the one on `Element.prototype`, not merely *a* callable\n * named `setHTML`. A duck-typed check here is a sanitizer bypass: an element\n * carrying its own `setHTML` \u2014 DOM clobbering, an unsafe polyfill, a library\n * shim \u2014 would be trusted as the platform sanitizer and would preempt the\n * fallback the app explicitly registered as safe. Verified: with an\n * own-property `setHTML`, the registered fallback was never called and\n * `<img src=x onerror=\u2026>` reached innerHTML intact.\n *\n * Read from the prototype per write rather than captured at module load, so a\n * late polyfill or a test's stub is still honoured; identity is what is\n * checked, not existence. Replacing `Element.prototype.setHTML` wholesale is\n * out of scope \u2014 an attacker who can do that owns the realm regardless.\n */\nfunction sanitizerFor(el: Element): SanitizerFallback | null {\n const platform = typeof Element === 'function'\n ? (Element.prototype as Partial<SanitizeCapableElement>).setHTML\n : undefined;\n return typeof platform === 'function'\n && (el as Partial<SanitizeCapableElement>).setHTML === platform\n ? nativeSetHtml\n : sanitizerFallback;\n}\n\n// \u2500\u2500 Trusted Types pass-through \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The native `TrustedHTML` shape \u2014 also missing from TypeScript's DOM library.\n * Only `isHTML()` recognition is needed: under CSP\n * `require-trusted-types-for 'script'` the raw sink's plain-string `innerHTML`\n * assignment throws, so policy-created values pass through `html:inner`\n * unwrapped instead of being re-wrapped in `raw()`.\n */\ninterface TrustedHtml {\n toJSON(): string;\n}\n\ninterface TrustedTypeChecker {\n isHTML(value: unknown): boolean;\n}\n\nfunction isTrustedHtml(value: unknown): value is TrustedHtml {\n const tt = (globalThis as { trustedTypes?: TrustedTypeChecker }).trustedTypes;\n return tt !== undefined && tt.isHTML(value);\n}\n\n// TODO(diagnostics): replace with the core diagnostics leaf (parallel\n// worktree); template-layer codes N101\u2013N107 register there. N105\u2013N107 are\n// thrown (correctness/security guards), unlike the warn-level audit codes.\nfunction nisliError(code: string, message: string): Error {\n return new Error(`[nisli] ${code}: ${message}`);\n}\n\n// \u2500\u2500 Template cache \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Cache parsed templates by their static string parts.\n * Since tagged templates always produce the same static strings array\n * reference per call site, we use WeakMap for efficient caching.\n */\nconst templateCache = new WeakMap<TemplateStringsArray, HTMLTemplateElement>();\n\n/** Parses performed since module load \u2014 test-only regression hook (issue 0015). */\nlet parseCount = 0;\n\n/** @internal Test-only: number of actual `<template>` parses performed. */\nexport function __templateParseCount(): number {\n return parseCount;\n}\n\n/**\n * Parse-once (ADR 0030.2 T4, issue 0015): build the marker HTML string and\n * parse it into a `<template>` exactly once per callsite, keyed by\n * TemplateStringsArray identity. The string depends only on the static\n * `strings` (marker indices are positional), so every TemplateResult from the\n * same callsite shares one parsed template and clones per mount.\n *\n * The first parse also runs the one-time static audit (template-audit.ts)\n * over the pristine parsed element \u2014 it still carries the raw `@event`/\n * `class:`/marker attributes that processAttributes later strips from clones.\n */\nfunction parseTemplate(strings: TemplateStringsArray, valueCount: number): HTMLTemplateElement {\n let template = templateCache.get(strings);\n if (template) return template;\n\n // Build the HTML string with markers.\n // Track HTML parsing state to auto-quote markers in unquoted\n // attribute positions where the > in --> would close the tag.\n // See ADR 0069.\n let htmlStr = '';\n let inTag = false;\n let quoteChar: string | null = null;\n\n for (let i = 0; i < strings.length; i++) {\n const s = strings[i] ?? '';\n for (let c = 0; c < s.length; c++) {\n const ch = s.charAt(c);\n if (quoteChar) { if (ch === quoteChar) quoteChar = null; }\n else if (inTag) {\n if (ch === '>') inTag = false;\n else if (ch === '\"' || ch === \"'\") quoteChar = ch;\n } else { if (ch === '<') inTag = true; }\n }\n htmlStr += s;\n if (i < valueCount) {\n const needsQuotes = inTag && !quoteChar && /=\\s*$/.test(s);\n htmlStr += needsQuotes ? `\"${createMarker(i)}\"` : createMarker(i);\n }\n }\n\n parseCount++;\n template = document.createElement('template');\n template.innerHTML = htmlStr;\n templateCache.set(strings, template);\n\n // Dev-only first-parse audit (N101\u2013N104); no-op when disabled.\n if (process.env.NODE_ENV !== 'production') auditTemplate(strings, template);\n\n return template;\n}\n\n// \u2500\u2500 Marker for expression slots \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst MARKER_PREFIX = '<!--bk-';\nconst MARKER_SUFFIX = '-->';\nconst ATTR_MARKER = 'bk-';\n\n/**\n * Generate a unique marker for each expression slot.\n * We use HTML comments as markers in text positions and\n * special attribute prefixes for attribute positions.\n */\nfunction createMarker(index: number): string {\n return `${MARKER_PREFIX}${index}${MARKER_SUFFIX}`;\n}\n\n// \u2500\u2500 Binding types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface TextBinding {\n type: 'text';\n node: Text;\n dispose?: () => void;\n}\n\ninterface AttributeBinding {\n type: 'attribute';\n element: Element;\n name: string;\n dispose?: () => void;\n}\n\ninterface ClassBinding {\n type: 'class';\n element: Element;\n className: string;\n dispose?: () => void;\n}\n\ninterface EventBinding {\n type: 'event';\n element: Element;\n eventName: string;\n handler: EventListener;\n modifiers: string[];\n dispose?: () => void;\n}\n\ninterface InnerHtmlBinding {\n type: 'innerHtml';\n element: Element;\n dispose?: () => void;\n}\n\ninterface ChildBinding {\n type: 'child';\n startMarker: Comment;\n endMarker: Comment;\n currentNodes: Node[];\n dispose?: () => void;\n}\n\ntype Binding = TextBinding | AttributeBinding | ClassBinding | EventBinding | InnerHtmlBinding | ChildBinding;\n\n// \u2500\u2500 html tagged template \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Tagged template literal for creating reactive DOM templates.\n *\n * ```ts\n * const name = signal('World');\n * const greeting = html`<h1>Hello, ${name}!</h1>`;\n * ```\n *\n * Signals in expression slots are detected automatically and\n * create fine-grained bindings. When the signal changes, only\n * the specific text node or attribute updates \u2014 no diffing needed.\n */\nexport function html(\n strings: TemplateStringsArray,\n ...values: unknown[]\n): TemplateResult {\n const bindings: Binding[] = [];\n const disposers: (() => void)[] = [];\n // Dev-only: remember the authoring callsite for first-parse audit\n // diagnostics \u2014 by first-mount time this frame is gone from the stack.\n if (process.env.NODE_ENV !== 'production') captureCallsite(strings);\n let mounted = false;\n\n return {\n __templateResult: true as const,\n\n mount(host: HTMLElement): void {\n // Single-mount guard (ADR 0030.2 T4 + \u00A78): a second mount of a live,\n // un-disposed result with value bindings would attach a second set of\n // bindings to the same shared arrays \u2014 shared-binding corruption.\n // Zero-binding templates (the registry's shared static icon pattern)\n // stay multi-mountable; dispose() \u2192 mount() stays legal.\n if (mounted && values.length > 0) {\n throw nisliError(\n 'N105',\n `mount() on an already-mounted TemplateResult with ${values.length} value ` +\n `binding(s) \u2014 dispose() it first or create a fresh template per mount. ` +\n `Template starts: ${JSON.stringify((strings[0] ?? '').slice(0, 60))}`,\n );\n }\n mounted = true;\n\n // Parse-once: the parsed template is cached per callsite; each mount\n // only pays the clone + binding walk. The per-mount processNode walk\n // below REMAINS by design until the ADR 0014-class work \u2014 caching\n // removes the *parse*, not the walk (ADR 0030.2 \u00A78).\n const template = parseTemplate(strings, values.length);\n const fragment = template.content.cloneNode(true) as DocumentFragment;\n const afterMount: (() => void)[] = [];\n\n // Walk the DOM tree and replace markers with bindings\n processNode(fragment, values, bindings, disposers, afterMount);\n\n // Mount into host\n host.appendChild(fragment);\n for (const sync of afterMount) sync();\n },\n\n dispose(): void {\n for (const d of disposers) {\n try { d(); } catch (_) {}\n }\n disposers.length = 0;\n for (const b of bindings) {\n if ('dispose' in b && b.dispose) {\n try { b.dispose(); } catch (_) {}\n }\n }\n bindings.length = 0;\n mounted = false;\n },\n };\n}\n\n// \u2500\u2500 DOM walking and binding creation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction processNode(\n node: Node,\n values: unknown[],\n bindings: Binding[],\n disposers: (() => void)[],\n afterMount: (() => void)[],\n): void {\n let afterChildren: (() => void)[] | undefined;\n // Process element attributes\n if (node.nodeType === Node.ELEMENT_NODE) {\n const el = node as Element;\n afterChildren = processAttributes(el, values, bindings, disposers, afterMount);\n }\n\n // Process text nodes and comments (markers)\n if (node.nodeType === Node.COMMENT_NODE) {\n const comment = node as Comment;\n const text = comment.textContent || '';\n // Check if this is one of our markers\n if (text.startsWith('bk-') && !isNaN(Number(text.slice(3)))) {\n const index = Number(text.slice(3));\n const value = values[index];\n replaceMarkerWithBinding(comment, value, bindings, disposers);\n return; // Don't recurse into replaced content\n }\n }\n\n // Process child nodes (make a copy since we may mutate)\n const children = [...node.childNodes];\n for (const child of children) {\n processNode(child, values, bindings, disposers, afterMount);\n }\n // Native state must see resolved type/name attributes and mounted options.\n // These are still synchronous setup-owned bindings, not delayed effects.\n if (afterChildren) for (const bind of afterChildren) bind();\n}\n\nfunction processAttributes(\n el: Element,\n values: unknown[],\n bindings: Binding[],\n disposers: (() => void)[],\n afterMount: (() => void)[],\n): (() => void)[] | undefined {\n // We need to find attributes that contain markers\n const attrsToRemove: string[] = [];\n let afterChildren: (() => void)[] | undefined;\n\n for (const attr of [...el.attributes]) {\n const name = attr.name;\n const attrValue = attr.value;\n\n // Check for @event bindings\n if (name.startsWith('@')) {\n const eventParts = name.slice(1).split('.');\n const eventName = eventParts[0] ?? '';\n const modifiers = eventParts.slice(1);\n\n // The value should be a marker containing the handler\n const markerMatch = attrValue.match(/<!--bk-(\\d+)-->/);\n if (markerMatch) {\n const index = Number(markerMatch[1]);\n const handler = values[index];\n if (typeof handler === 'function') {\n // Cleanup is registered on the EventBinding (removes the installed\n // safeHandler); a manual removeEventListener here would target the\n // original handler and no-op. See bindEvent (UI-33-R).\n bindEvent(el, eventName, handler as EventListener, modifiers, bindings);\n }\n }\n attrsToRemove.push(name);\n continue;\n }\n\n // Check for class:name bindings\n if (name.startsWith('class:')) {\n const className = name.slice(6);\n const markerMatch = attrValue.match(/<!--bk-(\\d+)-->/);\n if (markerMatch) {\n const index = Number(markerMatch[1]);\n const value = values[index];\n bindClass(el, className, value, bindings, disposers);\n }\n attrsToRemove.push(name);\n continue;\n }\n\n // Check for html:inner binding (trusted HTML rendering)\n if (name === 'html:inner') {\n const markerMatch = attrValue.match(/<!--bk-(\\d+)-->/);\n if (markerMatch) {\n const index = Number(markerMatch[1]);\n const value = values[index];\n bindInnerHtml(el, value, bindings, disposers);\n }\n attrsToRemove.push(name);\n continue;\n }\n\n // Check for ref binding: ref=\"${myRef}\"\n if (name === 'ref' && attrValue.includes(MARKER_PREFIX)) {\n const markerMatch = attrValue.match(/<!--bk-(\\d+)-->/);\n if (markerMatch) {\n const index = Number(markerMatch[1]);\n const value = values[index];\n if (isRef(value)) {\n (value as Ref).current = el;\n disposers.push(() => { (value as Ref).current = null; });\n }\n }\n attrsToRemove.push(name);\n continue;\n }\n\n // Check for regular attribute bindings with markers\n if (attrValue.includes(MARKER_PREFIX)) {\n const markers = [...attrValue.matchAll(/<!--bk-(\\d+)-->/g)];\n if (markers.length) {\n const first = markers[0];\n let value: unknown;\n // Single expression = entire value: preserve raw type and signal\n if (markers.length === 1 && first && attrValue === first[0]) {\n value = values[Number(first[1])];\n } else {\n // Mixed static + dynamic: resolve markers into string\n const resolve = () => attrValue.replace(/<!--bk-(\\d+)-->/g, (_, i) => {\n const v = values[Number(i)];\n const raw = isSignal(v) ? (v as ReadonlySignal<unknown>).value : v;\n return raw == null || raw === false ? '' : String(raw);\n });\n const hasSignals = markers.some(m => isSignal(values[Number(m[1])]));\n value = hasSignals ? computed(resolve) : resolve();\n }\n if (nativeFormProperty(el, name)) {\n (afterChildren ??= []).push(() => bindAttribute(el, name, value, bindings, disposers, afterMount));\n } else {\n bindAttribute(el, name, value, bindings, disposers, afterMount);\n }\n }\n continue;\n }\n }\n\n for (const name of attrsToRemove) {\n el.removeAttribute(name);\n }\n return afterChildren;\n}\n\n/**\n * Mount a factory result (from component() factory functions) into a DOM element.\n * Handles prop forwarding (with signal subscriptions) and host-level class attrs.\n */\nfunction mountFactoryResult(\n factory: { tagName: string; props: Record<string, unknown>; hostAttrs?: { class?: unknown } },\n): { element: HTMLElement; dispose: () => void } {\n const el = document.createElement(factory.tagName);\n const localDisposers: (() => void)[] = [];\n for (const [key, raw] of Object.entries(factory.props)) {\n if (isSignal(raw)) {\n const sig = raw as ReadonlySignal<unknown>;\n const unsub = sig.subscribe((newVal: unknown) => {\n (el as any)._setProp?.(key, newVal);\n });\n localDisposers.push(unsub);\n } else {\n (el as any)._setProp?.(key, raw);\n }\n }\n if (factory.hostAttrs?.class != null) {\n const classVal = factory.hostAttrs.class;\n if (isSignal(classVal)) {\n const sig = classVal as ReadonlySignal<string>;\n let prevClasses: string[] = [];\n const applyClasses = (raw: string) => {\n const next = raw ? raw.split(/\\s+/).filter(Boolean) : [];\n for (const cls of prevClasses) {\n if (!next.includes(cls)) el.classList.remove(cls);\n }\n for (const cls of next) {\n if (!prevClasses.includes(cls)) el.classList.add(cls);\n }\n prevClasses = next;\n };\n const unsub = sig.subscribe(applyClasses);\n localDisposers.push(unsub);\n } else if (typeof classVal === 'string' && classVal) {\n for (const cls of classVal.split(/\\s+/).filter(Boolean)) {\n el.classList.add(cls);\n }\n }\n }\n return {\n element: el,\n dispose() {\n for (const dispose of localDisposers.splice(0)) {\n try { dispose(); } catch (_) { /* swallow */ }\n }\n },\n };\n}\n\nfunction replaceMarkerWithBinding(\n comment: Comment,\n value: unknown,\n bindings: Binding[],\n disposers: (() => void)[],\n): void {\n const parent = comment.parentNode;\n if (!parent) return;\n\n if (isSignal(value)) {\n // Every reactive child is a slot because its future values may have any\n // documented child type. The slot still keeps a single Text node alive for\n // primitive-to-primitive updates, preserving the O(1) text fast path.\n const startMarker = document.createComment('slot-start');\n const endMarker = document.createComment('slot-end');\n parent.replaceChild(endMarker, comment);\n parent.insertBefore(startMarker, endMarker);\n\n let currentResults: TemplateResult[] = [];\n let currentNodes: Node[] = [];\n let currentFactoryDisposers: (() => void)[] = [];\n let currentText: Text | null = null;\n // Sentinel distinct from any resolvable value (including null/undefined)\n // so the FIRST effect run always mounts. See ADR 0008.1.\n const NOT_RENDERED = Symbol('not-rendered');\n let lastValue: unknown = NOT_RENDERED;\n\n const dispose = effect(() => {\n const newValue = (value as ReadonlySignal<unknown>).value;\n // Use endMarker.parentNode \u2014 the captured `parent` may be a\n // DocumentFragment that was already appended to the real DOM,\n // leaving the markers reparented under the actual DOM element.\n const liveParent = endMarker.parentNode;\n if (!liveParent) return;\n\n // Memoize by referential identity. A computed/signal only notifies\n // when its value changes by Object.is, so an EQUAL value here means\n // this effect was re-triggered by some OTHER dependency (a tracking\n // leak), not by an actual change to this slot. Re-mounting identical\n // content would destroy live DOM (and reset scroll/focus) for nothing.\n // See ADR 0008.1.\n if (newValue === lastValue) return;\n lastValue = newValue;\n\n const isTemplate = Boolean(\n newValue\n && typeof newValue === 'object'\n && '__templateResult' in newValue,\n );\n const isFactory = Boolean(\n newValue\n && typeof newValue === 'object'\n && '__type' in newValue\n && (newValue as any).__type === 'factory',\n );\n const isPrimitive = newValue != null\n && newValue !== false\n && !Array.isArray(newValue)\n && !isTemplate\n && !isFactory;\n\n if (isPrimitive && currentText) {\n currentText.data = String(newValue);\n return;\n }\n\n // Dispose and remove the previous slot value before mounting the next.\n // Ownership is per VALUE, not per outer template lifetime: factory prop\n // subscriptions must stop as soon as their child leaves (issue 0011).\n for (const r of currentResults) {\n try { r.dispose(); } catch (_) {}\n }\n for (const dispose of currentFactoryDisposers) {\n try { dispose(); } catch (_) {}\n }\n for (const node of currentNodes) {\n node.parentNode?.removeChild(node);\n }\n currentNodes = [];\n currentResults = [];\n currentFactoryDisposers = [];\n currentText = null;\n\n if (newValue == null) {\n // null/undefined \u2014 nothing to mount\n } else if (Array.isArray(newValue)) {\n // Array of TemplateResults (or mixed content)\n for (const item of newValue) {\n if (item && typeof item === 'object' && '__templateResult' in item) {\n const tpl = item as TemplateResult;\n const wrapper = document.createDocumentFragment();\n tpl.mount(wrapper as unknown as HTMLElement);\n const nodes = [...wrapper.childNodes];\n currentNodes.push(...nodes);\n currentResults.push(tpl);\n liveParent.insertBefore(wrapper, endMarker);\n } else if (item && typeof item === 'object' && '__type' in item && (item as any).__type === 'factory') {\n const mounted = mountFactoryResult(item as any);\n currentNodes.push(mounted.element);\n currentFactoryDisposers.push(mounted.dispose);\n liveParent.insertBefore(mounted.element, endMarker);\n } else if (item != null && item !== false) {\n const textNode = document.createTextNode(String(item));\n currentNodes.push(textNode);\n liveParent.insertBefore(textNode, endMarker);\n }\n }\n } else if (isTemplate) {\n // Single TemplateResult\n const tpl = newValue as TemplateResult;\n const wrapper = document.createDocumentFragment();\n tpl.mount(wrapper as unknown as HTMLElement);\n currentNodes = [...wrapper.childNodes];\n currentResults.push(tpl);\n liveParent.insertBefore(wrapper, endMarker);\n } else if (isFactory) {\n // Factory result \u2014 create child element\n const mounted = mountFactoryResult(newValue as any);\n currentNodes.push(mounted.element);\n currentFactoryDisposers.push(mounted.dispose);\n liveParent.insertBefore(mounted.element, endMarker);\n } else if (newValue !== false) {\n currentText = document.createTextNode(String(newValue));\n currentNodes.push(currentText);\n liveParent.insertBefore(currentText, endMarker);\n }\n });\n disposers.push(dispose);\n // TemplateResult.dispose() intentionally leaves mounted DOM in place, but\n // it must still dispose bindings owned by the CURRENT reactive slot value.\n disposers.push(() => {\n for (const r of currentResults.splice(0)) {\n try { r.dispose(); } catch (_) {}\n }\n for (const factoryDispose of currentFactoryDisposers.splice(0)) {\n try { factoryDispose(); } catch (_) {}\n }\n currentNodes = [];\n currentText = null;\n });\n } else if (value && typeof value === 'object' && '__templateResult' in value) {\n // Nested template result \u2014 mount it\n const result = value as TemplateResult;\n const startMarker = document.createComment('tpl-start');\n const endMarker = document.createComment('tpl-end');\n parent.replaceChild(endMarker, comment);\n parent.insertBefore(startMarker, endMarker);\n\n // Create a wrapper element to mount into\n const wrapper = document.createDocumentFragment();\n result.mount(wrapper as unknown as HTMLElement);\n parent.insertBefore(wrapper, endMarker);\n\n disposers.push(() => result.dispose());\n } else if (value && typeof value === 'object' && '__type' in value && (value as any).__type === 'factory') {\n // Factory result \u2014 create child element\n const mounted = mountFactoryResult(value as any);\n parent.replaceChild(mounted.element, comment);\n disposers.push(mounted.dispose);\n } else if (Array.isArray(value)) {\n // Array of template results\n const startMarker = document.createComment('list-start');\n const endMarker = document.createComment('list-end');\n parent.replaceChild(endMarker, comment);\n parent.insertBefore(startMarker, endMarker);\n\n for (const item of value) {\n if (item && typeof item === 'object' && '__templateResult' in item) {\n const wrapper = document.createDocumentFragment();\n (item as TemplateResult).mount(wrapper as unknown as HTMLElement);\n parent.insertBefore(wrapper, endMarker);\n disposers.push(() => (item as TemplateResult).dispose());\n } else if (item && typeof item === 'object' && '__type' in item && (item as any).__type === 'factory') {\n const mounted = mountFactoryResult(item as any);\n parent.insertBefore(mounted.element, endMarker);\n disposers.push(mounted.dispose);\n } else {\n const textNode = document.createTextNode(String(item));\n parent.insertBefore(textNode, endMarker);\n }\n }\n } else if (value == null || value === false) {\n // null, undefined, false \u2014 render nothing\n parent.removeChild(comment);\n } else {\n // Primitive value \u2014 render as text\n const textNode = document.createTextNode(String(value));\n parent.replaceChild(textNode, comment);\n }\n}\n\nfunction bindAttribute(\n el: Element,\n name: string,\n value: unknown,\n bindings: Binding[],\n disposers: (() => void)[],\n afterMount: (() => void)[],\n): void {\n // class attribute gets special handling to avoid conflicts with\n // class:name directives (see bindClassAttribute for details).\n if (name === 'class') {\n bindClassAttribute(el, value, bindings, disposers);\n return;\n }\n\n // Auto-resolution: framework components get _setProp for custom props\n // (preserves types). Standard HTML attributes (id, style, data-*, aria-*,\n // and \u2014 ADR 0030.2 \u00A78 \u2014 title/role/tabindex/name) always use setAttribute\n // even on framework components: routed through _setProp they were silently\n // dead (no component declares them as props).\n const isHtmlAttr = name === 'id' || name === 'style'\n || name === 'slot' || name === 'title' || name === 'role'\n || name === 'tabindex' || name === 'name'\n || name.startsWith('data-') || name.startsWith('aria-');\n const hasPropSetter = !isHtmlAttr && typeof (el as any)._setProp === 'function';\n\n if (hasPropSetter) {\n if (isSignal(value)) {\n const binding: AttributeBinding = { type: 'attribute', element: el, name };\n bindings.push(binding);\n const dispose = effect(() => {\n (el as any)._setProp(name, (value as ReadonlySignal<unknown>).value);\n });\n binding.dispose = dispose;\n disposers.push(dispose);\n } else {\n (el as any)._setProp(name, value);\n }\n return;\n }\n\n bindPlainAttribute(el, name, value, bindings, disposers, afterMount);\n}\n\n/**\n * Bind an HTML attribute, reactive when it is a signal, with `html`'s\n * boolean/null semantics (true \u2192 present empty, false/null/undefined \u2192 absent).\n * Native form state additionally updates its live property (ADR 0049).\n * NEVER uses `_setProp` \u2014 this is the shared\n * attribute path used by both `bindAttribute` (its non-component branch) and\n * `el()`, whose contract is *plain-HTML authoring*: a framework component tag\n * reached this way receives its values as attributes and resolves them through\n * its `attr()`/`boolAttr()` fallbacks, not typed prop setters.\n */\nfunction bindPlainAttribute(\n el: Element,\n name: string,\n value: unknown,\n bindings: Binding[],\n disposers: (() => void)[],\n afterMount: (() => void)[],\n): void {\n const property = nativeFormProperty(el, name);\n let current: unknown;\n const apply = (v: unknown) => {\n current = v;\n if (v == null || v === false) {\n el.removeAttribute(name);\n } else {\n el.setAttribute(name, v === true ? '' : String(v));\n }\n if (property) syncFormProperty(el, property, v);\n };\n\n if (isSignal(value)) {\n const binding: AttributeBinding = { type: 'attribute', element: el, name };\n bindings.push(binding);\n\n const dispose = effect(() => apply((value as ReadonlySignal<unknown>).value));\n binding.dispose = dispose;\n disposers.push(dispose);\n } else {\n apply(value);\n }\n\n if (property === 'value' && el.localName === 'select') {\n // Option lists can change independently of the desired value, including\n // async/slot content and option values derived from other signals. Observe\n // the native subtree rather than coupling bindings to a particular list API.\n // Only the live property is reapplied here: writing attributes would feed\n // this observer and would change native reset defaults.\n let active = true;\n const sync = () => { if (active) syncFormProperty(el, 'value', current); };\n const observer = new MutationObserver(sync);\n observer.observe(el, {\n childList: true, subtree: true, characterData: true,\n attributes: true, attributeFilter: ['value', 'selected'],\n });\n disposers.push(() => { active = false; observer.disconnect(); });\n // Insertion can normalize selectedness again (especially no-match values).\n // The microtask also covers connection by a surrounding template's mount.\n afterMount.push(sync);\n queueMicrotask(sync);\n }\n}\n\ntype NativeFormProperty = 'value' | 'checked' | 'selected';\n\n/** Deliberate native-only allowlist; never assign arbitrary/custom properties. */\nfunction nativeFormProperty(el: Element, name: string): NativeFormProperty | undefined {\n const attribute = name.toLowerCase();\n if (attribute !== 'value' && attribute !== 'checked' && attribute !== 'selected') return;\n if (el.namespaceURI !== 'http://www.w3.org/1999/xhtml') return;\n const tag = el.localName;\n if (attribute === 'value' && (tag === 'input' || tag === 'textarea' || tag === 'select')) return attribute;\n if (attribute === 'checked' && tag === 'input') return attribute;\n if (attribute === 'selected' && tag === 'option') return attribute;\n}\n\nfunction syncFormProperty(el: Element, property: NativeFormProperty, value: unknown): void {\n if (property === 'value') {\n const control = el as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;\n const next = value == null || typeof value === 'boolean' ? '' : String(value);\n // HTML file inputs cannot be populated by script. Preserve their native\n // attribute behavior for nonempty values; an empty binding may clear files.\n if (el.localName === 'input' && (el as HTMLInputElement).type === 'file' && next !== '') return;\n // Echoing the value already entered must not move the user's caret.\n // A scalar select value also clears extra selections on a multiple select.\n if (el.localName === 'select' || control.value !== next) control.value = next;\n } else {\n const control = el as HTMLInputElement & HTMLOptionElement;\n const next = value != null && value !== false;\n if (control[property] !== next) control[property] = next;\n }\n}\n\n/**\n * Bind a reactive class attribute using classList.add/remove instead of\n * setAttribute('class', ...). This prevents the class attribute binding\n * from overwriting classes toggled by class:name directives.\n *\n * The problem: setAttribute('class', 'foo bar') replaces ALL classes,\n * wiping out any classes added by classList.toggle() from class:name\n * bindings. By tracking which classes \"belong\" to the class attribute\n * and using classList operations, we only manage our own classes.\n */\nfunction bindClassAttribute(\n el: Element,\n value: unknown,\n bindings: Binding[],\n disposers: (() => void)[],\n): void {\n // On first call, we must clear the parser-set class attribute which\n // contains raw marker text (e.g. \"badge status-<!--bk-0-->\").\n // We snapshot any non-marker classes set by the parser before clearing.\n let initialized = false;\n let prevClasses: string[] = [];\n\n const applyClasses = (raw: unknown) => {\n if (!initialized) {\n // Clear the parser's class attribute (contains marker text)\n el.setAttribute('class', '');\n initialized = true;\n }\n const str = raw == null || raw === false ? '' : String(raw);\n const next = str.split(/\\s+/).filter(Boolean);\n\n // Remove classes no longer in the attribute value\n for (const cls of prevClasses) {\n if (!next.includes(cls)) {\n el.classList.remove(cls);\n }\n }\n // Add new classes\n for (const cls of next) {\n if (!prevClasses.includes(cls)) {\n el.classList.add(cls);\n }\n }\n prevClasses = next;\n };\n\n if (isSignal(value)) {\n const binding: AttributeBinding = { type: 'attribute', element: el, name: 'class' };\n bindings.push(binding);\n\n const dispose = effect(() => {\n applyClasses((value as ReadonlySignal<unknown>).value);\n });\n binding.dispose = dispose;\n disposers.push(dispose);\n } else {\n applyClasses(value);\n }\n}\n\nfunction bindClass(\n el: Element,\n className: string,\n value: unknown,\n bindings: Binding[],\n disposers: (() => void)[],\n): void {\n if (isSignal(value)) {\n const binding: ClassBinding = { type: 'class', element: el, className };\n bindings.push(binding);\n\n const dispose = effect(() => {\n const v = (value as ReadonlySignal<unknown>).value;\n el.classList.toggle(className, !!v);\n });\n binding.dispose = dispose;\n disposers.push(dispose);\n } else {\n el.classList.toggle(className, !!value);\n }\n}\n\n/**\n * Bind branded HTML content to an element's inner markup.\n *\n * Never a bare string \u2014 a brand is the author's explicit decision about where\n * the markup came from, which is what closes the accidental-XSS-sink class\n * (ADR 0030.2 \u00A73/\u00A78). Three shapes resolve, in the order they are checked:\n *\n * - `raw()` (core owns the `__raw` brand; @nisli/ssg re-exports it):\n * author-asserted trust \u2192 today's `innerHTML` sink, unchanged.\n * NEVER wrap user-generated input in raw().\n * - `sanitized()` \u2192 the sanitizer sink: native `Element.setHTML()`, else the\n * `setSanitizerFallback()` hook, else N107. It NEVER reaches `innerHTML`\n * (ADR 0019:124\u2013128, bet-09(c)).\n * - A native `TrustedHTML` object \u2192 the same `innerHTML` sink as `raw()`,\n * passed through unwrapped so Trusted-Types-enforcing apps can assign\n * policy output directly.\n *\n * Anything else throws N106. Supports both static values and reactive\n * `Signal`s of them; when the signal changes the content is rewritten through\n * the same branch. null/undefined (branded or not) clears the content.\n *\n * Usage in templates:\n * html`<span html:inner=\"${raw(highlightedHtml)}\"></span>`\n * html`<span html:inner=\"${sanitized(userComment)}\"></span>`\n */\nfunction bindInnerHtml(\n el: Element,\n value: unknown,\n bindings: Binding[],\n disposers: (() => void)[],\n): void {\n // PURE \u2014 validates the brand and proves a sink exists without writing\n // anything, so the eager signal check below can run it for its throw alone.\n // A SanitizedHtml resolves to ITSELF (the writer routes it to the\n // sanitizer); everything else resolves to the innerHTML payload.\n const resolveHtml = (v: unknown): string | SanitizedHtml | TrustedHtml => {\n if (v == null) return '';\n if (isRawHtml(v)) {\n // Both brands at once: trust is not resolvable in favour of the raw\n // sink, so reject rather than guess which one the author meant.\n if (isSanitizedHtml(v)) {\n throw nisliError(\n 'N106',\n `html:inner rejects a value branded both raw() and sanitized() \u2014 the ` +\n `trust decision is ambiguous. Pick one brand.`,\n );\n }\n return v.value;\n }\n if (isSanitizedHtml(v)) {\n // FAIL CLOSED. Untrusted markup is only ever eligible to be written once\n // a sanitizing sink is proven to exist; no native setHTML() and no\n // registered hook is a hard error, because silently downgrading to\n // innerHTML would reopen the exact XSS hole this brand closes.\n if (sanitizerFor(el) === null) {\n throw nisliError(\n 'N107',\n `html:inner cannot render sanitized() markup: this engine has no native ` +\n `Element.setHTML() and no fallback is registered. Wire one at startup \u2014 ` +\n `setSanitizerFallback((el, html) => { el.innerHTML = DOMPurify.sanitize(html) }) ` +\n `\u2014 nisli ships no sanitizer and will not fall back to innerHTML.`,\n );\n }\n return v;\n }\n if (isTrustedHtml(v)) return v;\n throw nisliError(\n 'N106',\n `html:inner rejects unbranded values (got ${typeof v}). Wrap trusted markup ` +\n `in raw(html), untrusted markup in sanitized(html) \u2014 and never wrap ` +\n `user-generated input in raw().`,\n );\n };\n\n const writeHtml = (v: unknown): void => {\n const resolved = resolveHtml(v);\n if (isSanitizedHtml(resolved)) {\n // The sanitizer sink. resolveHtml has already proven a writer exists,\n // and `el.innerHTML` is unreachable from this branch by construction.\n sanitizerFor(el)?.(el, resolved.value);\n return;\n }\n // The raw sink, unchanged: a plain string, or a TrustedHTML object handed\n // over WITHOUT stringifying it (stringifying would defeat the CSP check).\n // The cast only satisfies the DOM library's `string` typing.\n el.innerHTML = resolved as string;\n };\n\n if (isSignal(value)) {\n // Validate the INITIAL value untracked and eagerly so an unbranded or\n // unsanitizable signal throws synchronously out of mount(); later invalid\n // values throw inside the effect and land in effect error containment\n // (console.error, element content untouched).\n untracked(() => resolveHtml((value as ReadonlySignal<unknown>).value));\n\n const binding: InnerHtmlBinding = { type: 'innerHtml', element: el };\n bindings.push(binding);\n\n const dispose = effect(() => {\n writeHtml((value as ReadonlySignal<unknown>).value);\n });\n binding.dispose = dispose;\n disposers.push(dispose);\n } else {\n writeHtml(value);\n }\n}\n\nfunction bindEvent(\n el: Element,\n eventName: string,\n handler: EventListener,\n modifiers: string[],\n bindings: Binding[],\n): void {\n // One canonical INSTALLED identity that every removal path references \u2014 the\n // EventBinding `dispose` below AND the `once` self-removal. Forward-declared\n // so the modifier wrappers close over it before it is assigned; it is only\n // ever *called* after addEventListener, so the reference always resolves.\n // This identity-mismatch class bit el() dispose, html dispose, and once \u2014 a\n // single installed handler that all removals target closes it (UI-33-R2).\n let safeHandler!: EventListener;\n\n // Compose the modifier chain (inner); safeHandler wraps it in try/catch below.\n let composed: EventListener = handler;\n\n if (modifiers.includes('stop')) {\n const inner = composed;\n composed = (e: Event) => {\n e.stopPropagation();\n inner(e);\n };\n }\n if (modifiers.includes('prevent')) {\n const inner = composed;\n composed = (e: Event) => {\n e.preventDefault();\n inner(e);\n };\n }\n if (modifiers.includes('once')) {\n const inner = composed;\n composed = (e: Event) => {\n // Remove the ACTUALLY-INSTALLED listener, not this intermediate wrapper.\n el.removeEventListener(eventName, safeHandler);\n inner(e);\n };\n }\n\n // Keyboard modifiers\n for (const mod of modifiers) {\n if (['enter', 'escape', 'space', 'tab'].includes(mod)) {\n const keyMap: Record<string, string> = {\n enter: 'Enter',\n escape: 'Escape',\n space: ' ',\n tab: 'Tab',\n };\n const inner = composed;\n composed = (e: Event) => {\n if ((e as KeyboardEvent).key === keyMap[mod]) {\n inner(e);\n }\n };\n }\n }\n\n // Wrap in try/catch for error containment \u2014 THIS is the installed handler.\n // Handler bodies run UNTRACKED (ADR 0030.2 \u00A78, surfaced by the T5 review):\n // synchronous dispatchEvent from inside an effect would otherwise run the\n // handler under that effect's observer \u2014 widening the effect's dependency\n // set with every signal the handler reads and mis-attributing its writes.\n safeHandler = (e: Event) => {\n try {\n untrack(() => composed(e));\n } catch (err) {\n console.error(`Event handler error for '${eventName}':`, err);\n }\n };\n\n el.addEventListener(eventName, safeHandler);\n\n // Register cleanup of the ACTUALLY-INSTALLED handler (safeHandler), not the\n // caller's original \u2014 their identities differ, so a removeEventListener with\n // the original is a silent no-op (the UI-33-R leak). Both `html` dispose and\n // `el()` dispose iterate bindings and call `dispose`, so this is the single\n // correct cleanup path for event listeners.\n bindings.push({\n type: 'event',\n element: el,\n eventName,\n handler: safeHandler,\n modifiers,\n dispose: () => el.removeEventListener(eventName, safeHandler),\n });\n}\n\n// \u2500\u2500 each() reactive list rendering \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Brand for each result detection */\nconst EACH_BRAND = Symbol.for('backlog.each');\n\ninterface EachEntry<T> {\n key: string | number;\n itemSignal: Signal<T>;\n indexSignal: Signal<number>;\n templateResult: TemplateResult;\n /** Stable wrapper element that survives inner reactive content changes. */\n wrapper: HTMLElement;\n}\n\n/**\n * Reactive list rendering with keyed reconciliation.\n *\n * Renders a list of items from a signal, tracking each item by key.\n * When the array changes, only affected DOM nodes are added, removed,\n * or reordered \u2014 existing items update in-place via their signals.\n *\n * ```ts\n * const tasks = signal([{ id: '1', title: 'A' }, { id: '2', title: 'B' }]);\n * html`<ul>${each(tasks, t => t.id, (task, index) =>\n * html`<li>${computed(() => task.value.title)}</li>`\n * )}</ul>`\n * ```\n */\n/**\n * Adapt whatever a template callback returned into a mountable TemplateResult.\n * Factory descriptors (the value `component()` factories actually return) are\n * mounted through the same path every other slot uses (issue 0021).\n */\nfunction asTemplateResult(result: unknown): TemplateResult {\n if (result && typeof result === 'object' && '__templateResult' in result) {\n return result as TemplateResult;\n }\n if (result && typeof result === 'object' && (result as any).__type === 'factory') {\n let mounted: { element: HTMLElement; dispose: () => void } | null = null;\n return {\n __templateResult: true as const,\n mount(host: HTMLElement) {\n mounted = mountFactoryResult(result as any);\n host.appendChild(mounted.element);\n },\n dispose() {\n mounted?.dispose();\n mounted?.element.remove();\n mounted = null;\n },\n };\n }\n throw new TypeError(\n `each(): template callback must return a TemplateResult or a component factory result, got ${\n result === null ? 'null' : typeof result\n }`,\n );\n}\n\nexport function each<T>(\n items: ReadonlySignal<T[]>,\n keyFn: (item: T, index: number) => string | number,\n templateFn: (item: ReadonlySignal<T>, index: ReadonlySignal<number>) => TemplateResult | { __type: 'factory' },\n): TemplateResult {\n let startMarker: Comment;\n let endMarker: Comment;\n let entries: EachEntry<T>[] = [];\n let effectDispose: (() => void) | null = null;\n\n return {\n __templateResult: true as const,\n\n mount(host: HTMLElement) {\n startMarker = document.createComment('each-start');\n endMarker = document.createComment('each-end');\n host.appendChild(startMarker);\n host.appendChild(endMarker);\n\n effectDispose = effect(() => {\n const newItems = items.value;\n reconcile(newItems);\n });\n },\n\n dispose() {\n if (effectDispose) {\n effectDispose();\n effectDispose = null;\n }\n for (const entry of entries) {\n entry.templateResult.dispose();\n }\n entries = [];\n },\n };\n\n function reconcile(newItems: T[]) {\n const parent = endMarker.parentNode;\n if (!parent) return;\n\n // Validate the whole key set before updating item signals, mounting new\n // entries, or touching DOM. A duplicate update must leave the last valid\n // reconciliation intact so a later corrected array can recover normally.\n const keyedItems: Array<{ item: T; index: number; key: string | number }> = [];\n const keyIndices = new Map<string | number, number>();\n for (let i = 0; i < newItems.length; i++) {\n const item = newItems[i];\n if (item === undefined) continue;\n const key = keyFn(item, i);\n const previousIndex = keyIndices.get(key);\n if (previousIndex !== undefined) {\n const formattedKey = typeof key === 'string' ? JSON.stringify(key) : String(key);\n console.error(\n `each() requires unique keys. Duplicate key ${formattedKey} ` +\n `found at indices ${previousIndex} and ${i}; reconciliation skipped.`,\n );\n return;\n }\n keyIndices.set(key, i);\n keyedItems.push({ item, index: i, key });\n }\n\n // Build old key \u2192 entry map\n const oldMap = new Map<string | number, EachEntry<T>>();\n for (const entry of entries) {\n oldMap.set(entry.key, entry);\n }\n\n // Build new entries list\n const newEntries: EachEntry<T>[] = [];\n const newKeys = new Set<string | number>();\n\n for (const { item, index, key } of keyedItems) {\n newKeys.add(key);\n\n const existing = oldMap.get(key);\n if (existing) {\n // Reuse \u2014 update signals in place\n existing.itemSignal.value = item;\n existing.indexSignal.value = index;\n newEntries.push(existing);\n } else {\n // Create new entry with a stable wrapper element.\n // Using display:contents so the wrapper is invisible to layout \u2014\n // inner reactive content can freely swap DOM nodes without\n // invalidating the each() reconciler's node tracking.\n const itemSignal = signal(item) as Signal<T>;\n const indexSignal = signal(index);\n const wrapper = document.createElement('each-item');\n wrapper.style.display = 'contents';\n const templateResult = asTemplateResult(templateFn(itemSignal, indexSignal));\n templateResult.mount(wrapper);\n newEntries.push({ key, itemSignal, indexSignal, templateResult, wrapper });\n }\n }\n\n // Remove entries whose key is gone\n for (const entry of entries) {\n if (!newKeys.has(entry.key)) {\n entry.templateResult.dispose();\n entry.wrapper.parentNode?.removeChild(entry.wrapper);\n }\n }\n\n // Reorder DOM nodes to match new order.\n // Each entry has exactly one stable wrapper element, so positioning\n // is simple and immune to inner reactive content swaps.\n const atomic = canMoveWithin(parent);\n // insertBefore disconnects an existing subtree and can blur its focused\n // descendant. On the fallback path, leave that row attached and position\n // its siblings around it. Consult the containing root so shadow DOM works\n // too (its activeElement may itself be a shadow host).\n let focusedIndex = -1;\n if (!atomic) {\n const root = parent.getRootNode();\n let active = 'activeElement' in root\n ? (root as Document | ShadowRoot).activeElement\n : null;\n while (active && active.parentNode !== parent) active = active.parentElement;\n if (active) focusedIndex = newEntries.findIndex(entry => entry.wrapper === active);\n }\n if (focusedIndex !== -1) {\n let next: Node = newEntries[focusedIndex]!.wrapper;\n for (let i = focusedIndex - 1; i >= 0; i--) {\n const wrapper = newEntries[i]!.wrapper;\n if (wrapper.nextSibling !== next) parent.insertBefore(wrapper, next);\n next = wrapper;\n }\n }\n let cursor: Node = focusedIndex === -1 ? startMarker : newEntries[focusedIndex]!.wrapper;\n for (let i = focusedIndex + 1; i < newEntries.length; i++) {\n const entry = newEntries[i]!;\n const nextSibling = cursor.nextSibling;\n if (nextSibling !== entry.wrapper) {\n if (entry.wrapper.parentNode === parent && atomic) {\n // Already attached under this parent: atomic move preconditions hold.\n parent.moveBefore(entry.wrapper, nextSibling);\n } else {\n // Fresh wrapper, or a browser without moveBefore().\n parent.insertBefore(entry.wrapper, nextSibling);\n }\n }\n cursor = entry.wrapper;\n }\n\n entries = newEntries;\n }\n}\n\n/**\n * Conditional rendering helper (ADR 0030.2 \u00A73, boolean-gated with `else`).\n *\n * Shows `template` when the condition is truthy, `elseTemplate` (optional)\n * when falsy. Both arms accept a TemplateResult or a lazy callback\n * `() => TemplateResult`; callbacks are only evaluated for the active arm.\n *\n * Semantics for signal conditions:\n * - The gate is `!!condition.value` \u2014 a truthy\u2192truthy (or falsy\u2192falsy)\n * transition returns the memoized previous result, so the live branch is\n * NEVER rebuilt (no state/scroll/focus loss) and callbacks never re-run.\n * - Branch callbacks evaluate UNTRACKED: a signal read during branch\n * construction does not subscribe the when() computed, so it cannot\n * trigger a rebuild. Reactive parts inside a branch must be interpolated\n * as signals/computeds (values), not read raw at construction time.\n */\nexport function when(\n condition: unknown,\n template: TemplateResult | (() => TemplateResult),\n elseTemplate?: TemplateResult | (() => TemplateResult),\n): TemplateResult | ReadonlySignal<TemplateResult | null> | null {\n const resolveBranch = (\n branch: TemplateResult | (() => TemplateResult) | undefined,\n ): TemplateResult | null => {\n if (branch === undefined) return null;\n if (typeof branch === 'function') return untracked(branch);\n return branch;\n };\n\n if (isSignal(condition)) {\n // Boolean-gated memo: notify() marks observers dirty EAGERLY (before\n // value-equality is known), so a computed chain alone cannot stop a\n // truthy\u2192truthy recompute from re-evaluating the branch. The memo pins\n // branch evaluation to actual boolean FLIPS; equal gates return the\n // cached result, which the slot then memoizes by identity (ADR 0008.1).\n let lastGate: boolean | undefined;\n let lastResult: TemplateResult | null = null;\n return computed(() => {\n const gate = !!(condition as ReadonlySignal<unknown>).value;\n if (gate === lastGate) return lastResult;\n const next = gate ? resolveBranch(template) : resolveBranch(elseTemplate);\n // Commit the memo only after a successful resolve so a throwing branch\n // callback retries on the next read (computed error containment).\n lastGate = gate;\n lastResult = next;\n return next;\n });\n }\n return condition ? resolveBranch(template) : resolveBranch(elseTemplate);\n}\n\n// \u2500\u2500 el(): dynamic tag names (ADR 0025 item 11) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** A value bindable to an `el()` attribute \u2014 static or reactive. */\ntype ElAttrValue = string | number | boolean | null | undefined | ReadonlySignal<unknown>;\n\nexport interface ElProps {\n /** Assigned to `.current` on mount, nulled on dispose. */\n ref?: Ref;\n /** Event handlers by native event name; auto-removed on dispose. */\n on?: Record<string, EventListener>;\n /** Any other key is an HTML attribute (static or signal \u2192 reactive). */\n [attr: string]: ElAttrValue | Ref | Record<string, EventListener> | undefined;\n}\n\n/** A child accepted by `el()` \u2014 anything an `html` text slot accepts, plus arrays. */\nexport type ElChild =\n | string\n | number\n | boolean\n | null\n | undefined\n | TemplateResult\n | ReadonlySignal<unknown>\n | { __type: 'factory' }\n | ElChild[];\n\n/**\n * Build a DOM element by a (possibly *dynamic*) tag name with reactive\n * attributes, event handlers, and children, returned as a mountable/disposable\n * `TemplateResult` \u2014 so it composes in an `html` slot:\n * `` html`${el(tag, { class: cls }, children)}` ``.\n *\n * `el()` is the \"author plain HTML programmatically\" primitive. It exists for\n * the one thing `html` cannot express \u2014 a tag name chosen at runtime \u2014 while\n * the `html` PARSER STAYS 100% STATIC: `el()` is a separate construction path\n * that shares `html`'s binding helpers (`bindPlainAttribute`, `bindClassAttribute`,\n * `bindEvent`, and the `replaceMarkerWithBinding` slot mounter). Prefer `html`\n * for static tags and typed factories for typed composition.\n *\n * Semantics (ADR 0025 item 11):\n * - Props are **HTML attributes**: `class` uses the reactive class binder, every\n * other key uses `setAttribute` with `html`'s boolean/null rules. Native\n * value/checked/selected also update live form state (ADR 0049) \u2014 NEVER\n * `_setProp`. A framework component tag reached via `el()` receives its values\n * as attributes and resolves them through its `attr()`/`boolAttr()` fallbacks.\n * - `ref` assigns `.current`; `on: { event: handler }` adds auto-removed listeners.\n * - Children accept the full `html` text-slot range \u2014 string/number, signals\n * (reactive text or reactive template slot), `TemplateResult`, factory results,\n * and arrays \u2014 via the shared slot mounter.\n * - v1 is HTML-only: SVG/namespaced tags (`createElementNS`) are deferred until a\n * real consumer needs them.\n */\nexport function el(\n tag: string,\n props: ElProps = {},\n children?: ElChild | ElChild[],\n): TemplateResult {\n let node: HTMLElement | null = null;\n const bindings: Binding[] = [];\n const disposers: (() => void)[] = [];\n\n return {\n __templateResult: true,\n\n mount(host: HTMLElement): void {\n const element = document.createElement(tag);\n node = element;\n let afterChildren: (() => void)[] | undefined;\n const afterMount: (() => void)[] = [];\n\n for (const [key, val] of Object.entries(props)) {\n const formProperty = nativeFormProperty(element, key);\n if (val === undefined && !formProperty) continue;\n if (key === 'ref') {\n if (isRef(val)) {\n (val as Ref).current = element;\n disposers.push(() => { (val as Ref).current = null; });\n }\n continue;\n }\n if (key === 'on') {\n // bindEvent registers correct disposal on the EventBinding (removes\n // the installed safeHandler); no manual removeEventListener (UI-33-R).\n for (const [event, handler] of Object.entries(val as Record<string, EventListener>)) {\n bindEvent(element, event, handler, [], bindings);\n }\n continue;\n }\n if (key === 'class') {\n bindClassAttribute(element, val, bindings, disposers);\n continue;\n }\n if (formProperty) {\n (afterChildren ??= []).push(() => bindPlainAttribute(element, key, val, bindings, disposers, afterMount));\n } else {\n bindPlainAttribute(element, key, val, bindings, disposers, afterMount);\n }\n }\n\n // Children reuse html's text-slot mounter: append a comment anchor per\n // child and let replaceMarkerWithBinding resolve its type in place.\n const flat: ElChild[] = [];\n flattenChildren(children, flat);\n for (const child of flat) {\n const anchor = document.createComment('');\n element.appendChild(anchor);\n replaceMarkerWithBinding(anchor, child, bindings, disposers);\n }\n\n if (afterChildren) for (const bind of afterChildren) bind();\n\n host.appendChild(element);\n for (const sync of afterMount) sync();\n },\n\n dispose(): void {\n for (const d of disposers) {\n try { d(); } catch (_) { /* swallow */ }\n }\n disposers.length = 0;\n for (const b of bindings) {\n if ('dispose' in b && b.dispose) {\n try { b.dispose(); } catch (_) { /* swallow */ }\n }\n }\n bindings.length = 0;\n node?.parentNode?.removeChild(node);\n node = null;\n },\n };\n}\n\nfunction flattenChildren(children: ElChild | ElChild[] | undefined, out: ElChild[]): void {\n if (children === undefined) return;\n if (Array.isArray(children)) {\n for (const c of children) flattenChildren(c, out);\n } else {\n out.push(children);\n }\n}\n", "/**\n * projection.ts \u2014 First-class content projection (ADR 0025 item 1)\n *\n * `children(fallback?)` is a setup-context primitive that owns the light-DOM\n * projection machinery the registry currently hand-rolls\n * (captureChildren/projectChildren + per-component conditional-default swaps).\n *\n * ```ts\n * component('ui-button', (props, host) => {\n * transparentHost(host);\n * return html`<button class=\"${classes}\">${children()}</button>`;\n * });\n * ```\n *\n * Semantics:\n * - Returns a reactive slot value (a signal) that a template interpolates. The\n * slot resolves, in priority order: the factory `children` prop \u2192 the host's\n * captured light-DOM children \u2192 the fallback.\n * - Factory `children` route through the SAME slot: `children()` READS the\n * host's `children` prop signal (sugar over one path). Crucially it renders\n * them AT the slot position (not by relocating them to light DOM), so a\n * factory-composed child element is a DOM descendant of its parent when its\n * connectedCallback runs \u2014 `closest()`-based parent lookup keeps working.\n * - Plain-HTML light-DOM children are captured pre-setup by component.ts\n * (SEED \u2192 CAPTURE \u2192 CONTEXT) and projected here; late parser children are\n * swept in a microtask (the ADR 0023 streaming machinery, now in core).\n * - `children(fallback)` renders `fallback` when no MEANINGFUL children exist\n * (whitespace-only light DOM does not count) and REPLACES it reactively when\n * children arrive \u2014 including late parser children. This natively solves the\n * conditional-default class (message-scroller-button's default glyph).\n * - Single default slot only; named/multiple slots are a later design (v1 OUT).\n *\n * Zero-cost when unused: component.ts only snapshots childNodes when the host\n * has any, and only children() consumes them.\n */\n\nimport { getCurrentComponent } from './context.js';\nimport { onCleanup } from './lifecycle.js';\nimport { signal, computed, flush, type ReadonlySignal, type Signal } from './signal.js';\nimport type { TemplateResult } from './template.js';\n\n/** True if the nodes carry meaningful content (element or non-blank text). */\nfunction isMeaningful(nodes: Node[]): boolean {\n return nodes.some(\n (n) => n.nodeType === 1 || (n.nodeType === 3 && (n.textContent ?? '').trim() !== ''),\n );\n}\n\n/** A minimal TemplateResult that mounts pre-existing DOM nodes into the slot. */\nfunction nodesTemplate(nodes: Node[]): TemplateResult {\n return {\n __templateResult: true,\n mount(w: HTMLElement) {\n for (const node of nodes) w.appendChild(node);\n },\n dispose() { /* nodes are owned by the host tree; nothing to tear down */ },\n } as unknown as TemplateResult;\n}\n\n/** A re-mountable TemplateResult that renders a primitive as a fresh text node. */\nfunction textTemplate(text: string): TemplateResult {\n return {\n __templateResult: true,\n mount(w: HTMLElement) {\n w.appendChild(document.createTextNode(text));\n },\n dispose() { /* text node removed by the slot */ },\n } as unknown as TemplateResult;\n}\n\n/**\n * Normalize a slot value so the template ALWAYS sees a TemplateResult / factory\n * / array / null \u2014 never a bare primitive. Projection values may be detached\n * and reinserted as fallback/light-DOM ownership changes, so wrapping primitive\n * text keeps that projection value explicitly re-mountable.\n */\nfunction asSlot(value: unknown): unknown {\n if (value == null || value === '') return null;\n if (\n typeof value === 'object'\n && ('__templateResult' in (value as object) || '__type' in (value as object))\n ) {\n return value;\n }\n if (Array.isArray(value)) return value;\n return textTemplate(String(value));\n}\n\n/**\n * Project the host's children (factory `children` prop or light DOM) into this\n * slot, with an optional `fallback` rendered when empty. Must be called in\n * setup context. Interpolate the result in a template:\n * `html`<button>${children()}</button>``.\n */\nexport function children(fallback?: TemplateResult | string): ReadonlySignal<unknown> {\n const host = getCurrentComponent().element as HTMLElement & {\n __capturedChildren?: Node[];\n __nisliProjectionSweep?: () => void;\n _propSignal?(key: string): Signal<unknown>;\n };\n\n // Consume the pre-setup light-DOM capture; remove those nodes from the host\n // so the rendered template doesn't duplicate them.\n const captured = host.__capturedChildren ?? [];\n host.__capturedChildren = undefined;\n for (const node of captured) {\n if (node.parentNode === host) host.removeChild(node);\n }\n\n // The factory `children` prop, folded into the same slot (sugar over one path).\n const childrenProp = host._propSignal ? host._propSignal('children') : undefined;\n\n // Projected light-DOM nodes; grows when the late-parser sweep finds more.\n const projectedNodes = signal<Node[]>(captured);\n\n // True once this setup scope has been disposed (true disconnect, HMR\n // teardown, OR the containment boundary tearing down a failed mount). The\n // queued sweep below must then no-op: it would otherwise misread the\n // post-teardown host children (restored light DOM, or the error fallback)\n // as \"late\" and relocate them into a dead slot.\n let disposed = false;\n\n // A true disconnect/HMR teardown clears the component-owned rendered tree\n // before setup runs again. Hand the plain light-DOM nodes back to component.ts\n // so it can restore them as direct host children for the next capture.\n onCleanup(() => {\n disposed = true;\n const nodes = projectedNodes.value;\n host.__capturedChildren = nodes.length ? nodes : undefined;\n });\n\n // LATE-CHILDREN SWEEP \u2014 scheduled by component.ts's dedicated projection\n // phase (ADR 0030.2 \u00A73), which runs after the template is committed and\n // BEFORE any onMount callback. Pre-0030.2 this was registered via\n // children()'s own onMount, so the rendered-roots snapshot depended on\n // where children() sat relative to other onMount() registrations (the 0025\n // batch-3B ordering trap). Hoisting the SCHEDULING makes the rule\n // universal: the snapshot is exactly the rendered template roots, and\n // anything appearing after it \u2014 late parser/innerHTML children AND onMount\n // host-appends \u2014 classifies as projected content. Only scheduling moved;\n // the prop READ path (the computed below) is unchanged.\n host.__nisliProjectionSweep = () => {\n // The host's direct children at phase time are the rendered template\n // roots. Anything that appears later is late projected content.\n const renderedRoots = new Set<Node>(Array.from(host.childNodes));\n queueMicrotask(() => {\n if (disposed) return; // scope torn down before the sweep ran\n const late = Array.from(host.childNodes).filter((n) => !renderedRoots.has(n));\n if (late.length && isMeaningful(late)) {\n for (const node of late) host.removeChild(node);\n projectedNodes.value = [...projectedNodes.value, ...late];\n // Flush the slot effect NOW so the late children land in this same\n // microtask \u2014 the projectChildren() this replaces mutated the DOM\n // imperatively, so callers only await one microtask for the sweep.\n flush();\n }\n });\n };\n\n // Stable, RE-MOUNTABLE fallback slot: the same slot object is returned on\n // every empty render, and it can be mounted \u2192 unmounted \u2192 mounted again\n // (empty \u2192 filled \u2192 empty) without crashing. A string wraps to a fresh text\n // node each mount. A TemplateResult is mounted ONCE here into a detached\n // holder (its reactive bindings run in this component's context and dispose\n // with it); its rendered nodes are then exposed as a re-mountable node slot,\n // so the engine can detach and re-append them freely.\n let fallbackSlot: unknown = null;\n if (fallback != null) {\n if (typeof fallback === 'string') {\n fallbackSlot = textTemplate(fallback);\n } else {\n const holder = document.createDocumentFragment();\n fallback.mount(holder as unknown as HTMLElement);\n const fallbackNodes = Array.from(holder.childNodes);\n onCleanup(() => { try { fallback.dispose(); } catch (_) { /* ignore */ } });\n fallbackSlot = nodesTemplate(fallbackNodes);\n }\n }\n\n // Priority: factory children \u2192 captured/late light DOM \u2192 fallback. Reactive,\n // so late children (or a changing `children` prop) replace the fallback.\n return computed(() => {\n const kids = childrenProp?.value;\n if (kids != null && kids !== '') return asSlot(kids);\n const nodes = projectedNodes.value;\n if (isMeaningful(nodes)) return nodesTemplate(nodes);\n return fallbackSlot;\n });\n}\n", "/**\n * settle.ts \u2014 Awaitable async quiescence (ADR 0030.2 T2).\n *\n * `await settle()` resolves when every framework-started logical async\n * request has TERMINATED and the reactive graph is quiescent. Query runs\n * (query.ts) and resource loads (resource.ts) enroll here when they start\n * and deregister at *termination* \u2014 commit, terminal error after retries,\n * or abort \u2014 never at raw promise settlement. An abort-ignoring fetcher\n * whose run was superseded therefore cannot wedge `settle()`: the run's\n * registry entry closed at the abort even though the underlying promise\n * never resolves.\n *\n * ```ts\n * mount(app);\n * await settle();\n * expect(screen.textContent).toContain('loaded'); // no waitFor polling\n * ```\n *\n * Contract and bounds:\n * - This is a **test/verify primitive** (and the SSG pre-snapshot barrier).\n * Awaiting it in a live app with continuous background refetch/polling is\n * unbounded *by design* \u2014 each commit may legally schedule the next\n * request. A scope argument waits for a second consumer (ADR 0030.2 \u00A78).\n * - Each iteration awaits the pending registry, then `tick()` (signal.ts's\n * bounded microtask-drain contract). Timer-scheduled work is NOT awaited\n * beyond what a pending logical request itself spans.\n * - Iteration-capped at 50 like `tick()`; hitting the cap emits diagnostic\n * N603 and resolves \u2014 never a silent hang, never an unbounded loop.\n *\n * MERGE ITEM: `__resetPending()` should be folded into `resetInjector()`\n * (injector.ts is owned by another worktree); until then test teardown\n * calls it directly.\n */\n\nimport { tick } from './signal.js';\n\n// \u2500\u2500 Pending logical-request registry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * One entry per in-flight logical request. The promise is a *termination*\n * promise resolved by the enroller's `done()` callback \u2014 deliberately not\n * the fetcher/loader promise itself (see module doc).\n */\nconst pending = new Set<Promise<void>>();\n\n/**\n * Enroll a logical async request. Returns its `done()` terminator: call it\n * at commit, terminal error, or abort. Idempotent \u2014 a superseded run whose\n * terminator was already invoked by the superseding path may safely call\n * it again from its own settlement branch.\n *\n * @internal \u2014 called by query.ts runs and resource.ts loader generations.\n */\nexport function __enrollPending(): () => void {\n let resolve!: () => void;\n const entry = new Promise<void>((res) => { resolve = res; });\n pending.add(entry);\n let done = false;\n return () => {\n if (done) return;\n done = true;\n pending.delete(entry);\n resolve();\n };\n}\n\n/**\n * Reset the registry. Test-teardown escape hatch: entries orphaned by a\n * test that never terminated its fetchers would otherwise leak into the\n * next test's `settle()`.\n *\n * @internal\n */\nexport function __resetPending(): void {\n pending.clear();\n}\n\n/** Current number of enrolled (unterminated) logical requests. @internal */\nexport function __pendingCount(): number {\n return pending.size;\n}\n\n// \u2500\u2500 Diagnostics + test isolation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Reporting goes through the core diagnostics leaf. The pending registry\n// self-registers with resetInjector() so test teardown clears it without\n// an upside-down import (settle \u2192 injector, never the reverse).\nimport { diag, isDev } from './diagnostics.js';\nimport { registerResetHook } from './injector.js';\n\nregisterResetHook(__resetPending);\n\n// \u2500\u2500 settle() \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Await async quiescence: loop `tick()` \u2192 `Promise.allSettled(pending)`\n * until a full `tick()` leaves the pending registry empty.\n *\n * The `tick()` *first* ordering matters: observer effects created since\n * the last flush are what *start* runs (and enroll them) \u2014 the registry\n * can only be trusted empty after the reactive graph has flushed.\n */\nexport async function settle(): Promise<void> {\n for (let i = 0; i < 50; i++) {\n await tick();\n if (pending.size === 0) return;\n await Promise.allSettled([...pending]);\n }\n if (process.env.NODE_ENV !== 'production' && isDev()) diag(\n 'N603',\n 'settle() did not reach quiescence within 50 iterations \u2014 something '\n + 'keeps scheduling new async work (a self-invalidating query or a '\n + 'polling loop?). settle() is a test/verify primitive; under live '\n + 'background refetch it is unbounded by design. Returning anyway.',\n );\n}\n", "/**\n * query.ts \u2014 Keyed logical-request store (ADR 0030.2 T1).\n *\n * The cache unit is a per-key RECORD living in `QueryClient`:\n * `{data, error, status, fetchedAt}` as signals, plus exactly one `run()`\n * owning the retry loop, a per-run `AbortController` handed to the fetcher,\n * and the cache commit. `query()` is a thin OBSERVER: an effect keeps it\n * registered on the record its current key points at, and its outputs are\n * `computed()` views over that record. Dedup unit = logical request, by\n * construction (issues 0005\u20130009 close as a class).\n *\n * ```ts\n * const tasks = query(\n * () => ['tasks', scopeId.value],\n * (signal) => api.getTasks(scopeId.value, { signal }),\n * );\n * tasks.data // ReadonlySignal<Task[] | undefined>\n * tasks.loading // ReadonlySignal<boolean>\n * tasks.error // ReadonlySignal<Error | null>\n * tasks.status // ReadonlySignal<'idle' | 'loading' | 'success' | 'error'>\n * tasks.refetch() // force a refetch (joins an in-flight run)\n * tasks.dispose() // standalone callers; component setup auto-disposes\n * ```\n *\n * Ownership rules (ADR 0030.2 \u00A78, binding):\n * - The most-recently-mounted enabled observer's fetcher/options own the\n * next run for a shared key; `staleTime` freshness is per-observer POLICY\n * (it decides whether *that* observer triggers a run), while the record\n * state is shared truth.\n * - `invalidate()` marks records stale and reruns only records with \u22651\n * enabled observer; disabled observers revalidate on re-enable.\n * - A zero-observer record's in-flight run completes and commits.\n * - Records are NEVER garbage-collected: the cache is unbounded for the\n * life of the client (restates today's unbounded-cache bound). Bound it\n * operationally with `clear()` or a fresh client per app lifetime.\n *\n * Key contract: keys are FLAT \u2014 `readonly (string|number|boolean|null)[]`.\n * Objects and `undefined` are rejected with coded error N602 (`null` is\n * the optional sentinel). Flat keys are order-sensitive: prefer\n * per-endpoint key-builder helpers \u2014 a reordered key is a silent cache\n * *miss*, benign relative to a collision, but a miss.\n *\n * SSG stance (documented, not built): under core-render, records fetch\n * into the build-lifetime client and must TERMINATE before snapshot \u2014\n * `await settle()` is the barrier. Otherwise queries must be statically\n * disabled for the build.\n */\n\nimport {\n signal,\n effect,\n computed,\n untrack,\n type Signal,\n type ReadonlySignal,\n} from './signal.js';\nimport { hasContext, getCurrentComponent } from './context.js';\nimport { disposable, type DisposableResource } from './disposable.js';\nimport { inject } from './injector.js';\nimport { __enrollPending } from './settle.js';\nimport { formatDiag } from './diagnostics.js';\n\n// Diagnostics go through the core leaf (diagnostics.ts). Codes N602\u2013N603\n// belong to the query/async cluster (N601 retired before release \u2014 see\n// the eliminated-class note below).\n\n/** Build the coded error for key-contract violations. Always thrown \u2014\n * key validity is a contract, not an advisory diagnostic. */\nfunction keyError(detail: string): Error {\n return new Error(formatDiag(\n 'N602',\n `invalid query key: ${detail}. Keys must be flat `\n + 'readonly (string | number | boolean | null)[] arrays \u2014 spread '\n + 'object params into tuple elements; null is the optional sentinel.',\n ));\n}\n\n// \u2500\u2500 Key contract \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** A single query-key element. `null` is the optional sentinel. */\nexport type QueryKeyElement = string | number | boolean | null;\n\n/** The supported key contract: a flat, order-sensitive tuple. */\nexport type QueryKey = readonly QueryKeyElement[];\n\n/**\n * Validate a key against the flat contract and return a detached copy\n * (callers may mutate their array; records must not observe that).\n * Rejects objects, arrays, functions, undefined, and non-finite numbers\n * (NaN/Infinity JSON-serialize as null and would collide) with N602.\n */\nfunction validateKey(raw: unknown): QueryKey {\n if (!Array.isArray(raw)) {\n throw keyError(`expected an array, got ${typeof raw}`);\n }\n for (let i = 0; i < raw.length; i++) {\n const el: unknown = raw[i];\n if (el === null) continue;\n const t = typeof el;\n if (t === 'string' || t === 'boolean') continue;\n if (t === 'number') {\n if (Number.isFinite(el)) continue;\n throw keyError(`non-finite number at index ${i} (would collide with null)`);\n }\n if (el === undefined) {\n throw keyError(`undefined at index ${i}`);\n }\n throw keyError(`${t} at index ${i}`);\n }\n return raw.slice() as QueryKey;\n}\n\n/** THE one serializer: JSON.stringify of the validated flat array. */\nfunction serializeKey(key: QueryKey): string {\n return JSON.stringify(key);\n}\n\n/** Element-wise prefix match over validated keys (=== is sound: elements\n * are primitives and NaN is rejected by the contract). */\nfunction matchesPrefix(key: QueryKey, prefix: QueryKey): boolean {\n if (prefix.length > key.length) return false;\n for (let i = 0; i < prefix.length; i++) {\n if (key[i] !== prefix[i]) return false;\n }\n return true;\n}\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type QueryStatus = 'idle' | 'loading' | 'success' | 'error';\n\n/** Fetcher contract: receives the run's AbortSignal. Zero-arg fetchers\n * remain assignable. */\nexport type QueryFetcher<T> = (signal: AbortSignal) => Promise<T>;\n\nexport interface QueryResult<T> extends DisposableResource {\n /** The record's data, or `initialData`/undefined before first commit. */\n data: ReadonlySignal<T | undefined>;\n /** True while this observer is enabled and its record is fetching. */\n loading: ReadonlySignal<boolean>;\n /** The record's terminal error, or null. Cleared when a run starts. */\n error: ReadonlySignal<Error | null>;\n /** The record's lifecycle status. */\n status: ReadonlySignal<QueryStatus>;\n /** Force a refetch: bypasses staleTime freshness, but JOINS an in-flight\n * logical request rather than starting a second one (issue 0005). No-op\n * while disabled. */\n refetch(): void;\n /** Unregister this observer. Component setup calls this automatically at\n * teardown; standalone callers (tests, scripts) call it explicitly. The\n * record \u2014 and any in-flight run \u2014 survives: zero-observer runs complete\n * and commit (ADR 0030.2 \u00A78). */\n dispose(): void;\n}\n\nexport interface QueryOptions<T> {\n /** Cache freshness duration in ms for THIS observer. Default: 0 (a\n * registration/re-enable always revalidates). */\n staleTime?: number;\n /** Number of retries the run performs when this observer owns it. Default: 0 */\n retry?: number;\n /** Skip fetching while this returns false. Signal reads are tracked. */\n enabled?: () => boolean;\n /** Synchronous seed committed into an untouched (idle) record. */\n initialData?: T;\n}\n\n// \u2500\u2500 Record store \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface QueryRecord {\n readonly key: QueryKey;\n readonly serialized: string;\n readonly data: Signal<unknown>;\n readonly error: Signal<Error | null>;\n readonly status: Signal<QueryStatus>;\n /** Epoch ms of the last successful commit; 0 = never. */\n readonly fetchedAt: Signal<number>;\n /** Marked by invalidate(); cleared when a run starts. */\n stale: boolean;\n /** True while a run is in flight (status mirrors it reactively). */\n running: boolean;\n /** Increments per run start; a superseded run may never commit. */\n generation: number;\n controller: AbortController | null;\n /** The in-flight run (joinable by prefetch). */\n runPromise: Promise<void> | null;\n /** settle() terminator for the in-flight run. */\n terminate: (() => void) | null;\n readonly observers: Set<QueryObserver>;\n}\n\ninterface QueryObserver {\n readonly mountIndex: number;\n readonly fetcher: QueryFetcher<unknown>;\n readonly staleTime: number;\n readonly retry: number;\n enabled: boolean;\n record: QueryRecord | null;\n}\n\n/** Monotonic mount counter \u2014 \"most recently mounted\" is decided by\n * query() construction order, not re-registration order. */\nlet nextMountIndex = 0;\n\n/** Read a record signal without tracking it into the ambient observer \u2014\n * the observer effect must depend on keys/enabled/version ONLY, never on\n * record state (that is what keeps refetch loops unrepresentable). */\nfunction peek<T>(s: ReadonlySignal<T>): T {\n let v!: T;\n untrack(() => { v = s.value; });\n return v;\n}\n\nfunction toError(cause: unknown): Error {\n if (cause instanceof Error) return cause;\n try {\n return new Error(String(cause));\n } catch {\n return new Error('Unknown error');\n }\n}\n\n/**\n * Global keyed logical-request store. One per app: resolved via\n * `inject(QueryClient)` (auto-singleton; override with\n * `provide(QueryClient, ...)` BEFORE the first query() call).\n *\n * Records are never GC'd \u2014 see the module doc for the bound.\n */\nexport class QueryClient {\n /** @internal */ _records = new Map<string, QueryRecord>();\n /** @internal clear() bumps this; observer effects track it and re-resolve. */\n _version = signal(0);\n /** @internal live observer count (N601 mixed-client diagnostic). */\n _observers = 0;\n\n /**\n * Mark records matching the key prefix stale and rerun those with \u22651\n * enabled observer (using the owning observer's fetcher/options).\n * Disabled observers revalidate on re-enable; a record with only\n * disabled/no observers stays stale until one arrives. Returns the\n * number of records invalidated.\n *\n * invalidate(['tasks']) matches ['tasks'], ['tasks', '1'], ['tasks', '2', 'x'].\n */\n invalidate(keyPrefix: QueryKey): number {\n const prefix = validateKey(keyPrefix);\n let count = 0;\n for (const rec of this._records.values()) {\n if (!matchesPrefix(rec.key, prefix)) continue;\n count++;\n rec.stale = true;\n const owner = ownerOf(rec, /* requireEnabled */ true);\n if (owner) startRun(rec, owner.fetcher, owner.retry);\n }\n return count;\n }\n\n /**\n * Drop every record. In-flight runs are aborted (a settle() termination).\n * Live observers re-resolve fresh records on the version bump \u2014 enabled\n * ones revalidate immediately.\n */\n clear(): void {\n for (const rec of this._records.values()) {\n rec.generation++;\n rec.controller?.abort();\n rec.terminate?.();\n rec.controller = null;\n rec.terminate = null;\n rec.runPromise = null;\n rec.running = false;\n rec.observers.clear();\n }\n this._records.clear();\n this._version.value++;\n }\n\n /**\n * Imperatively warm a record. Joins an in-flight run; a fresh record\n * (per the given staleTime) is a no-op. Otherwise starts a run with THE\n * GIVEN fetcher \u2014 an explicit imperative is its own owner. The run\n * commits even with zero observers. Resolves at run termination.\n */\n prefetch<T>(key: QueryKey, fetcher: QueryFetcher<T>, staleTime = 0): Promise<void> {\n const rec = resolveRecord(this, key);\n if (rec.running) return rec.runPromise ?? Promise.resolve();\n if (!rec.stale && peek(rec.status) === 'success' && staleTime > 0\n && Date.now() - peek(rec.fetchedAt) < staleTime) {\n return Promise.resolve();\n }\n return startRun(rec, fetcher as QueryFetcher<unknown>, 0);\n }\n}\n\n/** Get-or-create the record for a key. Validation throws N602. */\nfunction resolveRecord(client: QueryClient, rawKey: unknown): QueryRecord {\n const key = validateKey(rawKey);\n const serialized = serializeKey(key);\n let rec = client._records.get(serialized);\n if (!rec) {\n rec = {\n key,\n serialized,\n data: signal<unknown>(undefined),\n error: signal<Error | null>(null),\n status: signal<QueryStatus>('idle'),\n fetchedAt: signal(0),\n stale: false,\n running: false,\n generation: 0,\n controller: null,\n runPromise: null,\n terminate: null,\n observers: new Set(),\n };\n client._records.set(serialized, rec); // never deleted \u2014 documented bound\n }\n return rec;\n}\n\n/** The observer whose fetcher/options own the next run: most recently\n * mounted, preferring enabled observers (a disabled observer asked not\n * to fetch \u2014 its fetcher should not fire). */\nfunction ownerOf(rec: QueryRecord, requireEnabled = false): QueryObserver | undefined {\n let best: QueryObserver | undefined;\n let bestDisabled: QueryObserver | undefined;\n for (const obs of rec.observers) {\n if (obs.enabled) {\n if (!best || obs.mountIndex > best.mountIndex) best = obs;\n } else if (!requireEnabled) {\n if (!bestDisabled || obs.mountIndex > bestDisabled.mountIndex) bestDisabled = obs;\n }\n }\n return best ?? bestDisabled;\n}\n\n/** Does this record need a run, per THIS observer's freshness policy?\n * Called only on real transitions (registration, re-enable, clear());\n * record reads are untracked, so commits never re-trigger observers. */\nfunction needsRun(rec: QueryRecord, observer: QueryObserver): boolean {\n if (rec.running) return false; // join the in-flight logical request\n if (rec.stale) return true;\n const status = peek(rec.status);\n if (status === 'idle' || status === 'error') return true;\n if (observer.staleTime <= 0) return true;\n return Date.now() - peek(rec.fetchedAt) >= observer.staleTime;\n}\n\n/**\n * THE run: one logical request owning the retry loop and the commit.\n * Supersedes (aborts) any in-flight run for the record. Enrolls in the\n * settle() registry on start and terminates it at commit, terminal error,\n * or abort \u2014 never at raw promise settlement.\n */\nfunction startRun(\n rec: QueryRecord,\n fetcher: QueryFetcher<unknown>,\n retry: number,\n): Promise<void> {\n // Supersede: abort IS the superseded run's termination.\n rec.controller?.abort();\n rec.terminate?.();\n\n const generation = ++rec.generation;\n const controller = new AbortController();\n const terminate = __enrollPending();\n rec.controller = controller;\n rec.terminate = terminate;\n rec.running = true;\n rec.stale = false;\n rec.status.value = 'loading';\n rec.error.value = null;\n\n const run = (async () => {\n try {\n let lastError: Error | null = null;\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (generation !== rec.generation) return; // superseded\n try {\n // The microtask hop makes a synchronous fetcher throw a normal\n // rejection \u2014 it enters the same retry/terminal path (issue 0008).\n const result = await Promise.resolve().then(() => fetcher(controller.signal));\n if (generation !== rec.generation) return;\n rec.data.value = result;\n rec.error.value = null;\n rec.fetchedAt.value = Date.now();\n rec.status.value = 'success';\n return; // commit\n } catch (cause) {\n lastError = toError(cause);\n }\n }\n if (generation !== rec.generation) return;\n rec.error.value = lastError;\n rec.status.value = 'error'; // terminal error after retries\n } finally {\n if (generation === rec.generation) {\n rec.running = false;\n rec.controller = null;\n rec.runPromise = null;\n rec.terminate = null;\n }\n terminate(); // idempotent \u2014 superseded runs already terminated at abort\n }\n })();\n rec.runPromise = run;\n return run;\n}\n\n// \u2500\u2500 Mixed clients: an eliminated class (formerly N601) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// With inject() as the single resolution path, the only way two clients\n// could mix was provide(QueryClient, ...) landing after queries already\n// bound the auto-created singleton. The injector now throws N501 at that\n// exact provide() (DI freeze, ADR 0030.2 T6), so the split-brain state is\n// unrepresentable in dev and was always silent in prod \u2014 the symptom-side\n// warning this block used to hold (N601) died with its cause. Retired\n// before release; the code number is not reused.\n\n// \u2500\u2500 query() \u2014 the thin observer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Observe the record the reactive key points at.\n *\n * @param keyFn - Returns the flat cache key. Signal reads are tracked; a\n * key change re-registers the observer on the new record.\n * @param fetcher - Fetches the data; receives the run's AbortSignal.\n * @param options - staleTime / retry / enabled / initialData.\n * @throws N602 synchronously when the initial key violates the contract.\n */\nexport function query<T>(\n keyFn: () => QueryKey,\n fetcher: QueryFetcher<T>,\n options: QueryOptions<T> = {},\n): QueryResult<T> {\n const { staleTime = 0, retry = 0, enabled, initialData } = options;\n\n const client = inject(QueryClient);\n\n // Surface key-contract violations at the call site: the observer effect\n // is error-contained (a later reactive key going invalid is logged with\n // the same coded message), so the construction-time key must be checked\n // synchronously. untrack: query() may run under an ambient observer\n // (component setup) and key signals must not widen its dependencies.\n untrack(() => { validateKey(keyFn()); });\n\n const observer: QueryObserver = {\n mountIndex: nextMountIndex++,\n fetcher: fetcher as QueryFetcher<unknown>,\n staleTime,\n retry,\n enabled: true,\n record: null,\n };\n client._observers++;\n\n const recSig = signal<QueryRecord | null>(null);\n const enabledSig = signal(true);\n let disposed = false;\n let prevEnabled: boolean | null = null;\n let prevVersion = -1;\n\n // The registration effect \u2014 depends on keyFn signals, enabled() signals,\n // and the client version. NEVER on record state (all record reads are\n // untracked), so commits cannot re-trigger it: run starts happen only on\n // the real transitions listed in needsRun()'s doc.\n const stopEffect = effect(() => {\n if (disposed) return;\n const version = client._version.value;\n const key = keyFn();\n const on = enabled ? !!enabled() : true;\n const rec = resolveRecord(client, key);\n\n observer.enabled = on;\n enabledSig.value = on;\n\n const moved = rec !== observer.record;\n if (moved) {\n observer.record?.observers.delete(observer);\n rec.observers.add(observer);\n observer.record = rec;\n if (initialData !== undefined && peek(rec.status) === 'idle'\n && peek(rec.data) === undefined) {\n rec.data.value = initialData; // seed; not a fetch \u2014 status stays idle\n }\n recSig.value = rec;\n }\n\n const reEnabled = prevEnabled === false && on;\n const versionChanged = version !== prevVersion;\n prevEnabled = on;\n prevVersion = version;\n\n if (on && (moved || reEnabled || versionChanged) && needsRun(rec, observer)) {\n const owner = ownerOf(rec) ?? observer;\n startRun(rec, owner.fetcher, owner.retry);\n }\n });\n\n const dispose = () => {\n if (disposed) return;\n disposed = true;\n observer.record?.observers.delete(observer);\n observer.record = null;\n client._observers--;\n stopEffect();\n // NOTE: no abort \u2014 a zero-observer in-flight run completes and commits.\n };\n\n if (hasContext()) {\n getCurrentComponent().addDisposer(dispose);\n }\n\n const refetch = () => {\n if (disposed) return;\n const rec = observer.record;\n if (!rec || !observer.enabled) return;\n if (rec.running) return; // join the in-flight logical request (dedup)\n const owner = ownerOf(rec) ?? observer;\n startRun(rec, owner.fetcher, owner.retry);\n };\n\n const result = {\n data: computed(() => {\n const rec = recSig.value;\n return (rec ? rec.data.value : initialData) as T | undefined;\n }),\n loading: computed(() => enabledSig.value && recSig.value?.status.value === 'loading'),\n error: computed(() => recSig.value?.error.value ?? null),\n status: computed<QueryStatus>(() => recSig.value?.status.value ?? 'idle'),\n refetch,\n dispose,\n };\n return disposable(result, dispose);\n}\n", "/**\n * resource.ts \u2014 Local async derivations with reactive source tracking.\n *\n * `resource()` is the async counterpart to a local computed value: source\n * dependencies are tracked synchronously, while the loader runs outside the\n * reactive observer and commits only the newest live generation.\n */\n\nimport { getCurrentComponent, hasContext } from './context.js';\nimport { disposable, type DisposableResource } from './disposable.js';\nimport { __enrollPending } from './settle.js';\nimport { effect, signal, type ReadonlySignal } from './signal.js';\n\nexport interface ResourceResult<T> extends DisposableResource {\n /** Latest successful value. Retained while a newer load is pending. */\n readonly data: ReadonlySignal<T | undefined>;\n /** True while the current generation is loading. */\n readonly loading: ReadonlySignal<boolean>;\n /** Error from the current generation, or null. */\n readonly error: ReadonlySignal<Error | null>;\n /** Re-run the loader for the current source value. */\n refresh(): void;\n /** Stop source tracking and invalidate/abort outstanding work. */\n dispose(): void;\n}\n\n/**\n * Derive local async state from a synchronously tracked source.\n *\n * Only signal reads inside `source` are dependencies. `loader` starts in a\n * microtask, outside the active observer, so signal reads before or after its\n * first await never accidentally widen the source set.\n */\nexport function resource<S, T>(\n source: () => S | undefined,\n loader: (source: S, signal: AbortSignal) => PromiseLike<T>,\n): ResourceResult<T> {\n const data = signal<T | undefined>(undefined);\n const loading = signal(false);\n const error = signal<Error | null>(null);\n const refreshVersion = signal(0);\n\n let generation = 0;\n let disposed = false;\n let stopEffect: () => void = () => {};\n\n const dispose = () => {\n if (disposed) return;\n disposed = true;\n generation++;\n stopEffect();\n loading.value = false;\n };\n\n // Register the full resource disposer before effect() registers its own\n // lower-level disposer, so component teardown first invalidates generations\n // and then performs the idempotent raw effect cleanup.\n if (hasContext()) {\n getCurrentComponent().addDisposer(dispose);\n }\n\n stopEffect = effect(() => {\n refreshVersion.value;\n const currentGeneration = ++generation;\n\n let sourceValue: S | undefined;\n try {\n sourceValue = source();\n } catch (cause) {\n loading.value = false;\n error.value = toError(cause);\n return;\n }\n\n // `undefined` is the single disabled sentinel. It covers the markdown\n // consumer's empty-content branch without growing an options surface.\n if (sourceValue === undefined) {\n data.value = undefined;\n loading.value = false;\n error.value = null;\n return;\n }\n\n const controller = new AbortController();\n loading.value = true;\n error.value = null;\n const enabledSource = sourceValue as S;\n const isStale = () => (\n disposed\n || controller.signal.aborted\n || currentGeneration !== generation\n );\n\n // settle() enrollment (ADR 0030.2 T2): this generation is a pending\n // logical request from here until COMMIT (data/error write) or ABORT\n // (the cleanup below) \u2014 never raw loader settlement, so an\n // abort-ignoring loader cannot wedge settle(). Idempotent.\n const settled = __enrollPending();\n\n // The microtask boundary is deliberate: loader signal reads are NOT source\n // dependencies, and synchronous loader throws become normal rejections.\n void Promise.resolve().then(async () => {\n if (isStale()) { settled(); return; }\n\n try {\n const value = await loader(enabledSource, controller.signal);\n if (isStale()) { settled(); return; }\n data.value = value;\n loading.value = false;\n settled();\n } catch (cause) {\n if (isStale()) { settled(); return; }\n error.value = toError(cause);\n loading.value = false;\n settled();\n }\n });\n\n return () => {\n if (currentGeneration === generation) generation++;\n controller.abort();\n settled();\n };\n });\n\n const result = {\n data,\n loading,\n error,\n refresh() {\n if (!disposed) refreshVersion.value++;\n },\n dispose,\n };\n return disposable(result, dispose);\n}\n\nfunction toError(cause: unknown): Error {\n if (cause instanceof Error) return cause;\n\n try {\n return new Error(String(cause));\n } catch {\n return new Error('Unknown error');\n }\n}\n", "/**\n * view-transition.ts \u2014 opt-in View Transitions over the synchronous flush.\n *\n * `viewTransition()` wraps a state update so the browser animates between the\n * before and after frames. It is a thin, opt-in wrapper: nothing here runs\n * unless you call it, and no scheduler behaviour changes.\n *\n * ```ts\n * viewTransition(() => { items.value = sorted; }, { types: ['reorder'] });\n * ```\n *\n * ## Why `flush()` is the whole trick\n *\n * `document.startViewTransition()` captures the OLD frame, runs the update\n * callback, then captures the NEW frame. Nisli coalesces signal writes onto a\n * microtask (ADR 0015), so a bare `items.value = sorted` inside that callback\n * would mutate the DOM *after* the capture window \u2014 the browser would animate\n * a frame to itself. Calling `flush()` inside the callback drains the effect\n * cascade synchronously, so the DOM mutation the browser snapshots is nisli's\n * own synchronous flush. `flush()` keeps its documented contract exactly\n * (\"effects executed before the next line\", ADR 0015); this is a consumer of\n * it, not a change to it. N303's cascade cap still applies inside the\n * callback \u2014 a runaway cascade degrades to a skipped transition, not a hang.\n *\n * ## Progressive enhancement\n *\n * Where `document.startViewTransition` is missing (no DOM at all, or an engine\n * without the API) the update still applies \u2014 synchronously, flushed, and\n * unanimated \u2014 and the return is `null`. Where the API exists but the\n * object/`types` form does not (Chrome 111\u2013124), the plain callback form is\n * used: the transition still runs, `:active-view-transition-type()` CSS simply\n * never matches. There is no polyfill and no UA sniffing.\n *\n * ## Companion CSS (author-side, core ships no stylesheet)\n *\n * The root crossfade is the UA default and needs no CSS; tune it, and cut\n * motion for users who ask, with:\n *\n * ```css\n * ::view-transition-old(root),\n * ::view-transition-new(root) { animation-duration: 200ms; }\n *\n * @media (prefers-reduced-motion: reduce) {\n * ::view-transition-group(*),\n * ::view-transition-old(*),\n * ::view-transition-new(*) { animation: none !important; }\n * }\n * ```\n *\n * Reduced motion is answered in CSS, not JS: `viewTransition()` is still\n * called, so the swap stays atomic and typed styles stay active \u2014 only the\n * motion is neutralised. `skipTransition()` on the returned handle is the hard\n * opt-out.\n */\n\nimport { flush } from './signal.js';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface ViewTransitionOptions {\n /** Transition types, surfaced to `:active-view-transition-type()` CSS. */\n types?: string[];\n}\n\n// \u2500\u2500 Feature detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Does this engine accept `startViewTransition({ update, types })`?\n *\n * The object form and the `ViewTransition.types` accessor shipped together,\n * so the accessor is the probe. Engines predating it take a bare callback \u2014\n * passing them an object would throw. A false negative costs only type-scoped\n * CSS, never the transition.\n */\nfunction supportsTransitionTypes(): boolean {\n return typeof ViewTransition !== 'undefined'\n && 'types' in ViewTransition.prototype;\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Run a state update inside a view transition.\n *\n * `update` must be synchronous: everything it does happens inside the\n * browser's capture window, where the page is frozen. Keep async work\n * (loaders, fetches) outside and wrap only the commit.\n *\n * @returns the live `ViewTransition` handle (`finished`, `ready`,\n * `skipTransition()`), or `null` when the platform has no support and the\n * update was applied directly.\n */\nexport function viewTransition(\n update: () => void,\n options: ViewTransitionOptions = {},\n): ViewTransition | null {\n // The commit the browser snapshots: apply the update, then settle the\n // reactive cascade now rather than on the next microtask.\n const commit = (): void => {\n update();\n flush();\n };\n\n if (typeof document === 'undefined'\n || typeof document.startViewTransition !== 'function') {\n commit();\n return null;\n }\n\n const types = options.types;\n return types !== undefined && types.length > 0 && supportsTransitionTypes()\n ? document.startViewTransition({ update: commit, types })\n : document.startViewTransition(commit);\n}\n"],
5
+ "mappings": ";AAkEA,IAAI,WAA2B;AAGxB,SAAS,QAAiB;AAC/B,SAAiD,YAAY;AAC/D;AAMO,SAAS,WAAW,IAA0B;AACnD,MAAI,KAAuC,YAAW;AACxD;AAKO,SAAS,WAAW,MAAc,SAAyB;AAChE,SAAO,UAAU,IAAI,KAAK,OAAO;AACnC;AAOO,SAAS,KAAK,MAAc,SAAiB,QAAwC;AAC1F,MAAI,WAAW,QAAW;AACxB,YAAQ,MAAM,WAAW,MAAM,OAAO,CAAC;AAAA,EACzC,OAAO;AACL,YAAQ,MAAM,WAAW,MAAM,OAAO,GAAG,MAAM;AAAA,EACjD;AACF;;;ACrFA,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AO;AAEnC,MAAI;AACF,WAAO,IAAI,MAAM,OAAO,KAAK,CAAC;AAAA,EAChC,QAAQ;AACN,WAAO,IAAI,MAAM,eAAe;AAAA,EAClC;AACF;;;ACvEA,SAAS,0BAAmC;AAC1C,SAAO,OAAO,mBAAmB,eAC5B,WAAW,eAAe;AACjC;AAeO,SAAS,eACd,QACA,UAAiC,CAAC,GACX;AAGvB,QAAM,SAAS,MAAY;AACzB,WAAO;AACP,UAAM;AAAA,EACR;AAEA,MAAI,OAAO,aAAa,eACnB,OAAO,SAAS,wBAAwB,YAAY;AACvD,WAAO;AACP,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,QAAQ;AACtB,SAAO,UAAU,UAAa,MAAM,SAAS,KAAK,wBAAwB,IACtE,SAAS,oBAAoB,EAAE,QAAQ,QAAQ,MAAM,CAAC,IACtD,SAAS,oBAAoB,MAAM;AACzC;",
6
6
  "names": ["diag", "effect", "diag", "diag", "component", "el", "provide", "peek", "inject", "raw", "el", "diag", "el", "el", "html", "el", "children", "raw", "dispose", "children", "raw", "el", "toError"]
7
7
  }