{"version":3,"sources":["../src/core/reactive.ts","../src/core/feature-flags.ts","../src/core/use.ts"],"names":["REACTIVE_SIGNAL","targetMap","reactiveMap","reactive","target","existingProxy","proxy","key","receiver","res","track","value","oldValue","result","hasChanged","trigger","getActiveEffect","depsMap","dep","PackedDepSet","trackEffect","triggerEffects","isReactive","REACTIVITY_V2","globalRegistry","releaseGlobalKeyImpl","entry","setGlobalKeyReleaseHandler","releaseGlobalKey","serializeKey","makeResourceControl","container","params","NOOP_RESOURCE_CONTAINER","use","input","depsOrOptions","thirdArg","isUseable","source","currentValue","hook","v2Container","makeSignalContainer","hybrid","trackV2","v","triggerV2","scheduleEffect","newValue","s","actions","deps","options","_component","getComponent","stateRef","_hi","currentKey","serializedKey","keyChanged","fn","memoState","d","i","ctx","control","newContainer","state","run","data","err","unsafeEffect","createSignalV2","newEntry"],"mappings":"uOAiBO,IAAMA,CAAAA,CAAkB,MAAA,CAAO,kBAAkB,CAAA,CAIlDC,CAAAA,CAAY,IAAI,OAAA,CAGhBC,CAAAA,CAAc,IAAI,OAAA,CAEjB,SAASC,CAAAA,CAA2BC,EAAc,CACrD,GAAIA,CAAAA,EAAWA,CAAAA,CAAmCJ,CAAe,CAAA,CAC7D,OAAOI,CAAAA,CAGX,IAAMC,CAAAA,CAAgBH,CAAAA,CAAY,GAAA,CAAIE,CAAM,CAAA,CAC5C,GAAIC,CAAAA,CACA,OAAOA,CAAAA,CAGX,IAAMC,CAAAA,CAAQ,IAAI,MAAMF,CAAAA,CAAQ,CAC5B,GAAA,CAAIA,CAAAA,CAAQG,CAAAA,CAAKC,CAAAA,CAAU,CACvB,GAAID,CAAAA,GAAQP,CAAAA,CAAiB,OAAO,KAAA,CAEpC,IAAMS,CAAAA,CAAM,OAAA,CAAQ,GAAA,CAAIL,CAAAA,CAAQG,CAAAA,CAAKC,CAAQ,CAAA,CAI7C,OAFAE,EAAMN,CAAAA,CAAQG,CAAG,CAAA,CAEbE,CAAAA,GAAQ,IAAA,EAAQ,OAAOA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CAAAA,CAAW,UAAA,CAAW,IAAA,CAAKK,GAAa,CAAA,EAE5C,CAEAH,CAAAA,CAAS,SAAA,CAAYW,EACvB,CAGF,IAAMpC,CAAAA,CAAYyB,CAAAA,CAAS,SAAA,CAGrBhB,CAAAA,CAAeT,CAAAA,CAAU,KAAA,CAE/B,GAAIA,CAAAA,CAAU,IAAA,GAAS,QAAA,CAmBrB,OAAO,CAACS,CAAAA,CAfkB,SAAsBS,CAAAA,CAAU,CACpDlB,CAAAA,CAAU,GAAA,EAAOA,CAAAA,CAAU,OAAA,CAE7BA,CAAAA,CAAU,QAAQkB,CAAQ,CAAA,CAEtB,OAAOA,CAAAA,EAAa,UAAA,CACtBlB,CAAAA,CAAU,KAAA,CAASkB,CAAAA,CAA4BlB,CAAAA,CAAU,KAAK,CAAA,CAE9DA,CAAAA,CAAU,KAAA,CAAQkB,EAMxB,CAC4B,CAAA,CACvB,CAEL,IAAMiB,CAAAA,CAAUpC,CAAAA,CAAuBC,CAAqC,CAAA,CAC5E,OAAO,CAACS,CAAAA,CAAc0B,CAAO,CAC/B,CACF","file":"chunk-6DXVUFAW.mjs","sourcesContent":["import { getActiveEffect, trackEffect, triggerEffects } from './lifecycle'\nimport { PackedDepSet } from './packed-dep-set'\n\n/**\n * @deprecated V1 Proxy reactivity — scheduled for removal after V2 stabilization.\n *\n * V2 (getter/setter via `./reactive-v2`) is the default since Phase 1 of the\n * 2026-05-16 performance overhaul. This file is kept callable so that setting\n * `FLEXIUM_REACTIVITY_V2=0` provides an emergency rollback during the soak\n * period; see Plan Phase D Task 26 in\n * `docs/superpowers/plans/2026-05-16-perf-phase1-reactivity-core.md` for the\n * removal timeline.\n *\n * Phase 4: Dep storage was migrated from `Set<ReactiveEffect>` to\n * `PackedDepSet` (Uint32Array of effect IDs) for cache-locality and memory wins.\n */\n\nexport const REACTIVE_SIGNAL = Symbol('flexium.reactive')\n\ntype Dep = PackedDepSet\ntype KeyToDepMap = Map<unknown, Dep>\nconst targetMap = new WeakMap<object, KeyToDepMap>()\n\n// WeakMap to store existing proxies to avoid duplicates\nconst reactiveMap = new WeakMap<object, object>()\n\nexport function reactive<T extends object>(target: T): T {\n    if (target && (target as Record<symbol, unknown>)[REACTIVE_SIGNAL]) {\n        return target\n    }\n\n    const existingProxy = reactiveMap.get(target)\n    if (existingProxy) {\n        return existingProxy as T\n    }\n\n    const proxy = new Proxy(target, {\n        get(target, key, receiver) {\n            if (key === REACTIVE_SIGNAL) return true\n\n            const res = Reflect.get(target, key, receiver)\n\n            track(target, key)\n\n            if (res !== null && typeof res === 'object') {\n                return reactive(res)\n            }\n\n            return res\n        },\n        set(target, key, value, receiver) {\n            const oldValue = (target as Record<string | symbol, unknown>)[key]\n            const result = Reflect.set(target, key, value, receiver)\n\n            if (result && hasChanged(value, oldValue)) {\n                trigger(target, key)\n            }\n\n            return result\n        }\n    })\n\n    reactiveMap.set(target, proxy)\n    return proxy\n}\n\nexport function track(target: object, key: unknown) {\n    if (!getActiveEffect()) return\n\n    let depsMap = targetMap.get(target)\n    if (!depsMap) {\n        targetMap.set(target, (depsMap = new Map()))\n    }\n\n    let dep = depsMap.get(key)\n    if (!dep) {\n        depsMap.set(key, (dep = new PackedDepSet()))\n    }\n\n    trackEffect(dep)\n}\n\nexport function trigger(target: object, key: unknown) {\n    const depsMap = targetMap.get(target)\n    if (!depsMap) return\n\n    const dep = depsMap.get(key)\n    if (dep) {\n        triggerEffects(dep)\n    }\n}\n\nfunction hasChanged(value: unknown, oldValue: unknown): boolean {\n    return !Object.is(value, oldValue)\n}\n\nexport function isReactive(value: unknown): boolean {\n    return !!(value && (value as Record<symbol, unknown>)[REACTIVE_SIGNAL])\n}\n","/**\n * Runtime feature flags for flexium internals.\n *\n * FLEXIUM_REACTIVITY_V2=0  — Emergency rollback to V1 Proxy reactivity.\n *\n * How to disable (rollback):\n *   - Node / Vitest:  FLEXIUM_REACTIVITY_V2=0 vitest\n *   - Vite build:     define: { 'process.env.FLEXIUM_REACTIVITY_V2': '\"0\"' }\n *\n * Default: '1' (V2 getter/setter path — enabled after Phase 1 soak).\n *\n * The V1 Proxy path remains callable until the Task 26 soak-period deletion;\n * see `docs/superpowers/plans/2026-05-16-perf-phase1-reactivity-core.md` §Task 26\n * for the removal timeline.\n */\nexport const REACTIVITY_V2 = (\n    typeof process !== 'undefined'\n        ? (process.env.FLEXIUM_REACTIVITY_V2 ?? '1')   // default: '1' (V2)\n        : '1'\n) !== '0'\n","import { reactive } from './reactive'\nimport { unsafeEffect } from './lifecycle'\nimport { hook, getComponent, setGlobalKeyReleaseHandler } from './hook'\nimport { registerSignal, updateSignal } from './devtools'\nimport { Context } from './context'\nimport { Useable, isUseable } from './useable'\nimport { REACTIVITY_V2 } from './feature-flags'\nimport { createSignalV2, makeSignalContainer, trackV2, triggerV2 } from './reactive-v2'\nimport { scheduleEffect } from './scheduler'\n\n// Re-export Context and Useable\nexport { Context } from './context'\nexport { Useable, isUseable } from './useable'\n\n// Types\nexport type Setter<T> = (newValue: T | ((prev: T) => T)) => void\n\nexport type ResourceControl<P = void> = {\n  refetch: (params?: P) => Promise<void>\n  readonly loading: boolean\n  readonly error: unknown\n  readonly status: 'idle' | 'loading' | 'success' | 'error'\n}\n\nexport interface UseContext<P = void> {\n  onCleanup: (fn: () => void) => void\n  params?: P\n}\n\nexport interface UseOptions {\n  key?: unknown[]\n  name?: string\n}\n\n// Phase 6C: plain-object stateRef shape — replaces reactive({}) Proxy allocation.\n// stateRef is purely internal bookkeeping across renders; it never needs reactivity\n// (no effect or computed reads its fields — verified Task 11 grep). V8 can\n// monomorphize all stateRef reads/writes since every instance has this exact shape.\ninterface StateRef {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- runtime container, type narrowed below via .type discriminant\n  container: any\n  serializedKey: string | undefined\n}\n\n// Global State Registry\n\ninterface RegistryEntry {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- dynamic runtime containers require any for heterogeneous signal/resource storage\n  container: any\n  refCount: number\n}\n\nconst globalRegistry = new Map<string, RegistryEntry>()\n\nfunction releaseGlobalKeyImpl(key: string): void {\n  const entry = globalRegistry.get(key)\n  if (!entry) return\n  entry.refCount--\n  if (entry.refCount <= 0) {\n    globalRegistry.delete(key)\n  }\n}\n\n// Register the release handler with hook.ts (avoids circular import — hook.ts\n// never imports from use.ts; use.ts calls this at module-init time).\nsetGlobalKeyReleaseHandler(releaseGlobalKeyImpl)\n\n/**\n * Force-evict a globally-keyed signal from the registry.\n *\n * Normally registry entries are reference-counted: each component reading a global\n * key increments refCount on mount and decrements on unmount. The entry is auto-evicted\n * when refCount reaches 0.\n *\n * Use this only when you need to explicitly clear cached state (e.g., invalidating a\n * cache, logout flow). Active subscribers will be left with a dangling reference if\n * you force-evict — call this only when you're sure nothing reads the key anymore.\n *\n * @example\n * releaseGlobalKey(JSON.stringify(['user', userId]))\n */\nexport const releaseGlobalKey = releaseGlobalKeyImpl\n\nfunction serializeKey(key: unknown[]): string {\n  return JSON.stringify(key)\n}\n\n// ---------------------------------------------------------------------------\n// Module-scope factories — eliminate per-call closure allocation. (Phase 5D)\n// ---------------------------------------------------------------------------\n\n/**\n * Shape of a resource/computed container that the public ResourceControl\n * exposes via accessors. `loading`, `error`, `status` are read every render;\n * `run` is invoked on `.refetch()`.\n */\ninterface ResourceContainerLike<P> {\n  loading: boolean\n  error: unknown\n  status: string\n  run: (params?: P) => void\n}\n\n/**\n * @internal — module-scope factory used by every use(fn,...) path. Returns a\n * fresh ResourceControl wrapper whose accessors delegate to the underlying\n * container by closure. The accessor functions are NOT shared across calls,\n * but moving the body here keeps use() smaller and lets V8 share the IC for\n * this construction site across all components.\n */\nfunction makeResourceControl<P>(\n  container: ResourceContainerLike<P>\n): ResourceControl<P> {\n  return {\n    refetch: async (params?: P) => { container.run(params) },\n    get loading() { return container.loading },\n    get error() { return container.error },\n    get status() { return container.status as 'idle' | 'loading' | 'success' | 'error' },\n  }\n}\n\n/** No-op container for the sync deps-mode path (loading=false, status='success'). */\nconst NOOP_RESOURCE_CONTAINER: ResourceContainerLike<unknown> = {\n  loading: false,\n  error: null,\n  status: 'success',\n  run: () => {},\n}\n\n// Overloads\n\n/**\n * Consume a Context value provided by an ancestor Provider.\n *\n * @example\n * const [theme] = use(ThemeContext);\n *\n * @param ctx - The Context object created with `createContext`\n * @returns Tuple of [contextValue, undefined]\n */\nexport function use<T>(ctx: Context<T>): [T, undefined]\n\n/**\n * Subscribe to a Useable data source (Stream, Shared, or any custom Useable).\n *\n * @example\n * const [messages, send] = use(chatStream, { roomId });\n *\n * @param source - A Useable object (e.g. Stream, Shared)\n * @param params - Optional parameters forwarded to the Useable's subscribe call\n * @returns Tuple of [currentValue, ...actions] where actions come from the Useable\n */\nexport function use<T, P, A extends unknown[]>(source: Useable<T, P, A>, params?: P): [T, ...A]\n\n/**\n * Create an async resource that fetches data and tracks loading/error state.\n *\n * @example\n * const [user, ctrl] = use(async () => fetchUser(id));\n * if (ctrl.loading) return html`<spinner />`;\n * ctrl.refetch();\n *\n * @param fn - Async function (optionally using `ctx.onCleanup`) that returns a Promise\n * @param depsOrOptions - Dependency array or UseOptions (key, name)\n * @param options - UseOptions when `depsOrOptions` is a deps array\n * @returns Tuple of [resolvedValue | undefined, ResourceControl]\n */\nexport function use<T, P = void>(\n  fn: (ctx: UseContext<P>) => Promise<T>,\n  depsOrOptions?: unknown[] | UseOptions,\n  options?: UseOptions\n): [T | undefined, ResourceControl<P>]\n\n/**\n * Create a computed (derived) value that re-runs when its deps change.\n *\n * @example\n * const [doubled, ctrl] = use((ctx) => count() * 2, [count]);\n *\n * @param fn - Sync computation function; receives a UseContext for cleanup registration\n * @param depsOrOptions - Dependency array that controls when `fn` re-runs, or UseOptions\n * @param options - UseOptions when `depsOrOptions` is a deps array\n * @returns Tuple of [computedValue, ResourceControl]\n */\nexport function use<T>(\n  fn: (ctx: UseContext) => T,\n  depsOrOptions?: unknown[] | UseOptions,\n  options?: UseOptions\n): [T, ResourceControl]\n\n/**\n * Create a local reactive signal with an initial value.\n *\n * @example\n * const [count, setCount] = use(0);\n * setCount(c => c + 1);\n *\n * @param initialValue - Initial value of the signal (must not be a function)\n * @param options - Optional UseOptions (key for global registry, name for DevTools)\n * @returns Tuple of [currentValue, setter]\n */\nexport function use<T>(\n  initialValue: T extends (...args: unknown[]) => unknown ? never : T,\n  options?: UseOptions\n): [T, Setter<T>]\n\nexport function use<T, P = void>(\n  input: T | Useable<T, P> | ((ctx: UseContext<P>) => T) | ((ctx: UseContext<P>) => Promise<T>),\n  depsOrOptions?: unknown[] | UseOptions | P,\n  thirdArg?: UseOptions\n): unknown {\n  // Useable mode: use(SomeUseable, params?) returns [value, undefined] or [value, send] for sendable\n  // This handles Context, Stream, Shared, and any custom Useable\n  if (isUseable(input)) {\n    const source = input as Useable<T, P>\n    const params = depsOrOptions as P | undefined\n\n    // Hook to store subscription state\n    const state = hook(() => {\n      if (REACTIVITY_V2) {\n        // V2: backing signal container + non-reactive cleanup slot.\n        const v2Container = makeSignalContainer<T>(source.getInitial(params))\n        const hybrid = {\n          _v2: true as const,\n          _v2Container: v2Container,\n          cleanup: undefined as (() => void) | undefined,\n          get value(): T { trackV2(v2Container); return v2Container.value },\n          set value(v: T) {\n            if (!Object.is(v, v2Container.value)) {\n              v2Container.value = v\n              triggerV2(v2Container, scheduleEffect)\n            }\n          },\n        }\n\n        // Subscribe to updates — writes go through hybrid.value setter\n        hybrid.cleanup = source.subscribe(params, (newValue) => {\n          hybrid.value = newValue\n        })\n\n        return hybrid\n      } else {\n        const s = reactive({\n          value: source.getInitial(params),\n          cleanup: undefined as (() => void) | undefined\n        })\n\n        // Subscribe to updates\n        s.cleanup = source.subscribe(params, (newValue) => {\n          s.value = newValue\n        })\n\n        return s\n      }\n    })\n\n    // Access value to track dependency\n    const currentValue = state.value\n\n    // Get additional actions from the source (if any)\n    const actions = source.getActions()\n    if (actions && actions.length > 0) {\n      return [currentValue, ...actions]\n    }\n\n    return [currentValue, undefined]\n  }\n\n  // Normalize arguments:\n  // - use(value, { key }) → options only\n  // - use(fn, [deps]) → deps only\n  // - use(fn, [deps], { key }) → deps + options\n  let deps: unknown[] | undefined\n  let options: UseOptions | undefined\n\n  if (Array.isArray(depsOrOptions)) {\n    deps = depsOrOptions\n    options = thirdArg  // third arg is options when second is deps array\n  } else if (depsOrOptions && typeof depsOrOptions === 'object') {\n    options = depsOrOptions as UseOptions\n  }\n\n  // Validate key if provided\n  if (options?.key && !Array.isArray(options.key)) {\n    throw new Error('State key must be an array')\n  }\n\n  // Phase 6B: resolve current component once; reuse for inlined stateRef\n  // bookkeeping + the globalKeys tracking calls below. Eliminates 2-3 redundant\n  // getComponent() calls per use() invocation in the signal path.\n  const _component = getComponent()\n\n  // Phase 6B: inline hook() bookkeeping for the stateRef slot.\n  // Avoids hook() function call + arrow-function allocation on every render.\n  // Phase 6C: stateRef is a plain object — no reactive() Proxy. V8 can\n  // monomorphize all stateRef reads/writes since the shape is fixed at\n  // construction (container + serializedKey, both initialized to undefined).\n  let stateRef: StateRef\n  if (_component) {\n    // DEV hook-order signature — push on EVERY render (matches hook()'s\n    // semantics: hookSignatures must contain one entry per hook call so\n    // checkHookOrder's prev.length === curr.length invariant holds).\n    if (import.meta.env.DEV) {\n      _component.hookSignatures!.push('stateRef')\n    }\n    const _hi = _component.hookIndex\n    if (_hi < _component.hooks.length) {\n      // Re-render: return cached stateRef without running factory\n      stateRef = _component.hooks[_hi] as StateRef\n      _component.hookIndex = _hi + 1\n    } else {\n      // First render: create and store. Plain object literal — V8-friendly\n      // stable shape, no Proxy allocation.\n      stateRef = { container: undefined, serializedKey: undefined }\n      _component.hooks.push(stateRef)\n      _component.hookIndex = _hi + 1\n    }\n  } else {\n    // Outside component context — create ephemeral ref (no caching).\n    stateRef = { container: undefined, serializedKey: undefined }\n  }\n\n  // Compute serialized key\n  const currentKey = options?.key\n  const serializedKey = currentKey ? serializeKey(currentKey) : undefined\n\n  // Check if key has changed\n  const keyChanged = serializedKey !== stateRef.serializedKey\n\n  // DEPS MODE: Function with explicit deps array\n  if (typeof input === 'function' && deps !== undefined) {\n    const fn = input as (ctx: UseContext<P>) => T | Promise<T>\n\n    const memoState = hook(() => ({\n      value: undefined as T | undefined,\n      prevDeps: undefined as unknown[] | undefined,\n      cleanup: undefined as (() => void) | undefined,\n      hasRun: false,\n      params: undefined as P | undefined\n    }))\n\n    let hasChanged = true\n    if (memoState.hasRun && memoState.prevDeps) {\n      hasChanged = deps.length !== memoState.prevDeps.length ||\n        deps.some((d, i) => d !== memoState.prevDeps![i])\n    }\n\n    if (hasChanged) {\n      // Run previous cleanup\n      if (memoState.cleanup) {\n        memoState.cleanup()\n        memoState.cleanup = undefined\n      }\n\n      // Create context with onCleanup\n      const ctx: UseContext<P> = {\n        onCleanup: (fn) => {\n          memoState.cleanup = fn\n        },\n        params: memoState.params\n      }\n\n      const result = fn(ctx)\n\n      if (result instanceof Promise) {\n        throw new Error('deps with async functions is not supported. Use use(asyncFn) without deps for async resources.')\n      }\n\n      memoState.value = result\n      memoState.prevDeps = [...deps]\n      memoState.hasRun = true\n    }\n\n    const control = makeResourceControl<P>(NOOP_RESOURCE_CONTAINER as ResourceContainerLike<P>)\n\n    return [memoState.value, control]\n  }\n\n  // If key changed or first time, get/create container\n  if (!stateRef.container || keyChanged) {\n    stateRef.serializedKey = serializedKey\n\n    // Check Registry FIRST\n    if (serializedKey && globalRegistry.has(serializedKey)) {\n      const entry = globalRegistry.get(serializedKey)!\n      entry.refCount++\n      stateRef.container = entry.container\n      // Track this key on the component for later release.\n      // Reuse Phase 6B hoisted _component — no second getComponent() call.\n      if (_component) {\n        if (!_component.globalKeys) _component.globalKeys = []\n        _component.globalKeys.push(serializedKey)\n      }\n    } else {\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any -- runtime container, type narrowed below via .type discriminant\n      let newContainer: any\n\n      // Function (Computed or Resource)\n      if (typeof input === 'function') {\n        const fn = input as (ctx: UseContext<P>) => T | Promise<T>\n\n        // State for async/computed\n        const state = reactive({\n          type: 'resource',\n          value: undefined as T | undefined,\n          loading: true,\n          error: null as unknown,\n          status: 'idle' as 'idle' | 'loading' | 'success' | 'error',\n          cleanup: undefined as (() => void) | undefined,\n          params: undefined as P | undefined,\n          run: () => {}\n        })\n\n        const run = (params?: P) => {\n          // Run previous cleanup\n          if (state.cleanup) {\n            state.cleanup()\n            state.cleanup = undefined\n          }\n\n          // Store params for context\n          state.params = params\n\n          try {\n            // Create context\n            const ctx: UseContext<P> = {\n              onCleanup: (fn) => {\n                state.cleanup = fn\n              },\n              params: state.params\n            }\n\n            const result = fn(ctx)\n\n            if (result instanceof Promise) {\n              state.loading = true\n              state.status = 'loading'\n              state.error = null\n\n              result\n                .then(data => {\n                  state.value = data\n                  state.status = 'success'\n                  state.loading = false\n                })\n                .catch(err => {\n                  state.error = err\n                  state.status = 'error'\n                  state.loading = false\n                })\n            } else {\n              state.value = result\n              state.status = 'success'\n              state.loading = false\n              state.error = null\n            }\n          } catch (err) {\n            state.error = err\n            state.status = 'error'\n            state.loading = false\n          }\n        }\n\n        state.run = run\n\n        // Make it reactive! Plain unsafeEffect (not .detached) so the effect is\n        // auto-registered with the enclosing component and stopped on unmount,\n        // preventing the async resource from leaking reactive subscriptions.\n        unsafeEffect(() => run())\n\n        newContainer = state\n      } else {\n        // Value (Signal)\n        if (REACTIVITY_V2) {\n          // V2: createSignalV2 returns a SignalContainerV2 with the same shape\n          // as the former `hybrid` object literal — single allocation, stable\n          // hidden class, prototype-level value accessor. (Phase 5B)\n          newContainer = createSignalV2(input, scheduleEffect)\n        } else {\n          newContainer = reactive({\n            type: 'signal',\n            value: input\n          })\n        }\n\n        // Register with DevTools (DEV-only — folded away in production builds)\n        if (import.meta.env.DEV) {\n          registerSignal(newContainer, options?.name)\n        }\n      }\n\n      // Register in global registry if needed\n      if (serializedKey) {\n        const newEntry: RegistryEntry = { container: newContainer, refCount: 1 }\n        globalRegistry.set(serializedKey, newEntry)\n        // Track this key on the component for later release.\n        // Reuse Phase 6B hoisted _component — no second getComponent() call.\n        if (_component) {\n          if (!_component.globalKeys) _component.globalKeys = []\n          _component.globalKeys.push(serializedKey)\n        }\n      }\n\n      stateRef.container = newContainer\n    }\n  }\n\n  const container = stateRef.container\n\n  // Access container.value to track dependency\n  const currentValue = container.value\n\n  if (container.type === 'signal') {\n    // Phase 4: use a named function expression rather than an arrow. The name\n    // gives V8 a stable identity for inline-cache specialization across the\n    // many setter invocations during a component's lifetime.\n    const setter: Setter<T> = function signalSetter(newValue) {\n      if (container._v2 && container._setter) {\n        // V2 setter: handles functional updates + Object.is dedup + trigger internally\n        container._setter(newValue)\n      } else {\n        if (typeof newValue === 'function') {\n          container.value = (newValue as (prev: T) => T)(container.value)\n        } else {\n          container.value = newValue\n        }\n      }\n      if (import.meta.env.DEV) {\n        updateSignal(container, container.value)\n      }\n    }\n    return [currentValue, setter]\n  } else {\n    // Resource / Computed\n    const control = makeResourceControl<P>(container as ResourceContainerLike<P>)\n    return [currentValue, control]\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Test helpers (not intended for production use)\n// ---------------------------------------------------------------------------\n\n/** @internal — for tests only */\nexport function __registrySize(): number {\n  return globalRegistry.size\n}\n\n/** @internal — for tests only */\nexport function __registryHas(key: string): boolean {\n  return globalRegistry.has(key)\n}\n"]}