react-fine-grained-signals 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jsx-P6volZdr.js","names":[],"sources":["../src/core/deep-signal-engine.ts","../src/core/deep-signal.ts","../src/core/readable-subscription.ts","../src/react/hooks.ts","../src/runtime/jsx.ts"],"sourcesContent":["import {\r\n attachReadableInterop,\r\n getReadableInterop,\r\n getSharedInteropContext,\r\n isInteropSpeculative,\r\n markInteropSpeculativeDeepRead,\r\n} from \"./interop.js\";\r\nimport { hasActiveRenderCollector } from \"./render-tracking.js\";\nimport { SIGNAL_BRAND } from \"./signal-brand.js\";\n\r\nexport interface DeepSignalSource<T> {\n value: T;\n peek(): T;\n}\n\r\nexport interface DeepSignalLike<T extends object> {\r\n value: T;\r\n peek(): T;\r\n}\r\n\r\nexport interface DeepSignalRuntimeAdapter {\n /** Creates the root source behind the public DeepSignal wrapper. */\n createSignal<T>(initial: T): DeepSignalSource<T>;\n /** Creates an internal property/existence/iteration version source. */\n createVersionSignal<T>(initial: T): DeepSignalSource<T>;\n markWatched(source: DeepSignalSource<unknown>): void;\n hasSubscribers(source: DeepSignalSource<unknown>): boolean;\n batch<T>(callback: () => T): T;\r\n /** Runs a callback without collecting dependencies, as the public `untracked`. */\n untracked<T>(callback: () => T): T;\n isSignal(value: unknown): boolean;\r\n hasActiveSubscriber(): boolean;\r\n getBatchDepth(): number;\r\n registerDeepSignal?(value: DeepSignalLike<object>): void;\r\n /** Optional execution-owner hooks for alternate internal runtime adapters. */\n isSpeculative?(): boolean;\n markSpeculativeDeepRead?(): void;\n}\r\n\r\ninterface PropertyMetadata {\r\n properties: Map<PropertyKey, VersionSignal>;\r\n existence: Map<PropertyKey, VersionSignal>;\r\n propertyIndices: Set<number>;\r\n existenceIndices: Set<number>;\r\n iteration?: DeepSignalSource<number>;\r\n arrayMethods: Map<PropertyKey, { method: (...args: unknown[]) => unknown; wrapper: (...args: unknown[]) => unknown }>;\r\n prunable?: Set<PropertyKey> | undefined;\r\n proxy: object;\r\n}\r\n\r\ntype VersionSignal = DeepSignalSource<number>;\n\nfunction isObjectLike(value: unknown): value is object {\n return (typeof value === \"object\" && value !== null) || typeof value === \"function\";\n}\n\nfunction assertExtensible(value: object): void {\n if (!Object.isExtensible(value)) {\n throw new TypeError(\"deepSignal() cannot proxy a non-extensible object or array\");\n }\n}\n\nfunction assertDataProperties(value: object): void {\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Reflect.getOwnPropertyDescriptor(value, key);\n if (descriptor !== undefined && !(\"value\" in descriptor)) {\n throw new TypeError(\"deepSignal() does not support accessor properties\");\n }\n }\n}\n\nfunction emptyArrayOfLength(length: number): unknown[] {\n const result: unknown[] = [];\n result.length = length;\n return result;\n}\n\nfunction isArrayIndex(key: PropertyKey): key is string {\n if (typeof key !== \"string\" || key === \"\") return false;\n const index = Number(key);\n return Number.isInteger(index) && index >= 0 && index < 0xffff_ffff && String(index) === key;\n}\n\nconst notify = (versions: Map<PropertyKey, VersionSignal>, key: PropertyKey): void => {\n const version = versions.get(key);\n if (version !== undefined) version.value += 1;\n};\n\nconst markPrunable = (metadata: PropertyMetadata, key: PropertyKey): void => {\n if (!metadata.properties.has(key) && !metadata.existence.has(key)) return;\n (metadata.prunable ??= new Set()).add(key);\n};\n\nconst notifyIteration = (metadata: PropertyMetadata): void => {\n if (metadata.iteration !== undefined) metadata.iteration.value += 1;\n};\n\r\nexport function createDeepSignalFactory(adapter: DeepSignalRuntimeAdapter) {\r\n const ARRAY_MUTATORS = new Set<PropertyKey>([\r\n \"copyWithin\",\r\n \"fill\",\r\n \"pop\",\r\n \"push\",\r\n \"reverse\",\r\n \"shift\",\r\n \"sort\",\r\n \"splice\",\r\n \"unshift\",\r\n ]);\r\n const ARRAY_SEARCHES = new Set<PropertyKey>([\"includes\", \"indexOf\", \"lastIndexOf\"]);\n const proxyToRaw = new WeakMap<object, object>();\r\n const rawToMetadata = new WeakMap<object, PropertyMetadata>();\r\n const readonlyMapViews = new WeakMap<Map<unknown, unknown>, ReadonlyMap<unknown, unknown>>();\r\n const readonlySetViews = new WeakMap<Set<unknown>, ReadonlySet<unknown>>();\r\n const readonlyCollectionViewToRaw = new WeakMap<object, Map<unknown, unknown> | Set<unknown>>();\r\n // A carrier that contains one of our proxies has to be copied before it can be\r\n // stored. Remember that copy so assigning the same carrier again preserves the\r\n // same identity and aliases, just like assigning an ordinary raw object does.\r\n const normalizedProxyCarriers = new WeakMap<object, object>();\r\n const isSpeculative = adapter.isSpeculative ?? isInteropSpeculative;\n const markSpeculativeDeepRead = adapter.markSpeculativeDeepRead ?? markInteropSpeculativeDeepRead;\n\r\n function shouldTrackDeepRead(): boolean {\r\n if (isSpeculative()) {\n // No per-key metadata during speculation; the computed's speculative\r\n // result must therefore not be promoted as a complete graph cache.\r\n markSpeculativeDeepRead();\n return false;\r\n }\r\n const shared = getSharedInteropContext();\r\n return adapter.hasActiveSubscriber() ||\r\n hasActiveRenderCollector() ||\r\n shared.graphCollector !== undefined ||\r\n shared.renderCollector !== undefined;\r\n }\r\n\r\n /**\r\n * The realm's built-in prototype objects, rejected deliberately rather than by\r\n * accident. Several of them look exactly like plain data to the rest of this\r\n * module: `Array.prototype` is array-exotic (so `Array.isArray` short-circuits\r\n * the prototype check below), while `Error.prototype`, `Date.prototype`,\r\n * `Promise.prototype`, `String.prototype`, ... all inherit straight from\r\n * `Object.prototype` and expose only extensible, writable data properties, so\r\n * neither `assertExtensible` nor `assertDataProperties` stops them. Adopting\r\n * one as deep state would let the `set` trap `Reflect.set` onto the real,\r\n * globally shared intrinsic. Some of them (`Object.prototype.__proto__`,\r\n * `Map.prototype.size`, ...) happen to be caught today by the accessor check,\r\n * but that protection is incidental and asymmetric; this set makes it uniform.\r\n *\r\n * Built from `globalThis` so an engine missing a builtin simply contributes\r\n * nothing. Only this realm's intrinsics are listed: an object from another\r\n * realm already fails the `Object.prototype` identity check below (the one\r\n * exception being a cross-realm array, which stays accepted as it is today).\r\n */\r\n const INTRINSIC_PROTOTYPES: ReadonlySet<object> = (() => {\r\n const prototypes = new Set<object>();\r\n for (const name of [\r\n \"Object\",\r\n \"Array\",\r\n \"Function\",\r\n \"Boolean\",\r\n \"Number\",\r\n \"String\",\r\n \"Symbol\",\r\n \"BigInt\",\r\n \"Date\",\r\n \"RegExp\",\r\n \"Error\",\r\n \"AggregateError\",\r\n \"EvalError\",\r\n \"RangeError\",\r\n \"ReferenceError\",\r\n \"SyntaxError\",\r\n \"TypeError\",\r\n \"URIError\",\r\n \"Map\",\r\n \"Set\",\r\n \"WeakMap\",\r\n \"WeakSet\",\r\n \"WeakRef\",\r\n \"FinalizationRegistry\",\r\n \"Promise\",\r\n \"ArrayBuffer\",\r\n \"SharedArrayBuffer\",\r\n \"DataView\",\r\n ]) {\r\n const intrinsic = (globalThis as unknown as Record<string, unknown>)[name];\r\n if (typeof intrinsic !== \"function\") continue;\r\n const prototype: unknown = (intrinsic as { prototype?: unknown }).prototype;\r\n if ((typeof prototype === \"object\" && prototype !== null) || typeof prototype === \"function\") {\r\n prototypes.add(prototype as object);\r\n }\r\n }\r\n return prototypes;\r\n })();\r\n\r\n const isIntrinsicPrototype = (value: unknown): boolean =>\r\n isObjectLike(value) && INTRINSIC_PROTOTYPES.has(value);\r\n\r\n function isPlainObjectOrArray(value: unknown): value is object {\r\n if (typeof value !== \"object\" || value === null || adapter.isSignal(value)) return false;\r\n // Before `Array.isArray`, which would otherwise wave `Array.prototype`\r\n // through: it is array-exotic, extensible, and carries only data properties.\r\n if (INTRINSIC_PROTOTYPES.has(value)) return false;\r\n if (Array.isArray(value)) return true;\r\n const prototype = Object.getPrototypeOf(value);\r\n return prototype === Object.prototype || prototype === null;\r\n }\r\n\r\n /**\r\n * Resolves a value that may be one of our proxies or one of our readonly\r\n * collection views back to the raw object it wraps. Returns `undefined` when\r\n * `value` is not object-like or is not a value this module has wrapped, so\r\n * callers can fall back to using it as-is.\r\n */\r\n function toRaw(value: unknown): object | undefined {\r\n if (!isObjectLike(value)) return undefined;\r\n const directRaw = proxyToRaw.get(value);\r\n if (directRaw !== undefined) return directRaw;\r\n return readonlyCollectionViewToRaw.get(value);\r\n }\r\n\r\n type RejectMutation = (operation: string) => () => never;\r\n\r\n /**\r\n * Shared scaffolding for `readonlyMapView`/`readonlySetView`: cache lookup,\r\n * the \"reject this mutation\" factory, defining the descriptors, the\r\n * feature-detected extras loop, and the dual-WeakMap registration. Only the\r\n * per-type descriptor bodies (which truly differ between Map and Set) and\r\n * the extras list are supplied by the caller.\r\n */\r\n function createReadonlyCollectionView<Raw extends object, View extends object>(\r\n raw: Raw,\r\n cache: WeakMap<Raw, View>,\r\n prototype: object,\r\n kind: string,\r\n buildCore: (raw: Raw, view: View, rejectMutation: RejectMutation) => Record<PropertyKey, PropertyDescriptor>,\r\n buildExtras: (raw: Raw, rejectMutation: RejectMutation) => Array<[string, (...args: unknown[]) => unknown]>,\r\n ): View {\r\n const cached = cache.get(raw);\r\n if (cached !== undefined) return cached;\r\n\r\n const view = Object.create(prototype) as View;\r\n const rejectMutation: RejectMutation = (operation: string) => () => {\r\n throw new TypeError(\r\n `deepSignal() ${kind}#${operation}() is not allowed through .value; replace the ${kind} immutably`,\r\n );\r\n };\r\n Object.defineProperties(view, buildCore(raw, view, rejectMutation));\r\n for (const [name, impl] of buildExtras(raw, rejectMutation)) {\r\n Object.defineProperty(view, name, { enumerable: false, configurable: false, value: impl });\r\n }\r\n\r\n cache.set(raw, view);\r\n readonlyCollectionViewToRaw.set(view, raw as Map<unknown, unknown> | Set<unknown>);\r\n return view;\r\n }\r\n\r\n function readonlyMapView<Key, Value>(raw: Map<Key, Value>): ReadonlyMap<Key, Value> {\r\n return createReadonlyCollectionView(\r\n raw as Map<unknown, unknown>,\r\n readonlyMapViews,\r\n Map.prototype,\r\n \"Map\",\r\n (target, view, rejectMutation) => ({\r\n size: { enumerable: false, configurable: false, get: () => target.size },\r\n get: { enumerable: false, configurable: false, value: (key: unknown) => target.get(key) },\r\n has: { enumerable: false, configurable: false, value: (key: unknown) => target.has(key) },\r\n entries: {\r\n enumerable: false,\r\n configurable: false,\r\n value: () => Map.prototype.entries.call(target),\r\n },\r\n keys: {\r\n enumerable: false,\r\n configurable: false,\r\n value: () => Map.prototype.keys.call(target),\r\n },\r\n values: {\r\n enumerable: false,\r\n configurable: false,\r\n value: () => Map.prototype.values.call(target),\r\n },\r\n forEach: {\r\n enumerable: false,\r\n configurable: false,\r\n value: (\r\n callback: (value: unknown, key: unknown, map: ReadonlyMap<unknown, unknown>) => void,\r\n thisArg?: unknown,\r\n ) => {\r\n Map.prototype.forEach.call(target, (value, key) => callback.call(thisArg, value, key, view));\r\n },\r\n },\r\n [Symbol.iterator]: {\r\n enumerable: false,\r\n configurable: false,\r\n value: () => Map.prototype.entries.call(target),\r\n },\r\n set: { enumerable: false, configurable: false, value: rejectMutation(\"set\") },\r\n delete: { enumerable: false, configurable: false, value: rejectMutation(\"delete\") },\r\n clear: { enumerable: false, configurable: false, value: rejectMutation(\"clear\") },\r\n }),\r\n (_target, rejectMutation) => {\r\n const extras: Array<[string, (...args: unknown[]) => unknown]> = [];\r\n // Keep future mutating Map proposals from becoming an integrity bypass when\r\n // they are present in the running JavaScript engine.\r\n for (const operation of [\"getOrInsert\", \"getOrInsertComputed\", \"emplace\"]) {\r\n if (typeof (Map.prototype as unknown as Record<string, unknown>)[operation] === \"function\") {\r\n extras.push([operation, rejectMutation(operation)]);\r\n }\r\n }\r\n return extras;\r\n },\r\n ) as ReadonlyMap<Key, Value>;\r\n }\r\n\r\n function readonlySetView<Value>(raw: Set<Value>): ReadonlySet<Value> {\r\n return createReadonlyCollectionView(\r\n raw as Set<unknown>,\r\n readonlySetViews,\r\n Set.prototype,\r\n \"Set\",\r\n (target, view, rejectMutation) => ({\r\n size: { enumerable: false, configurable: false, get: () => target.size },\r\n has: { enumerable: false, configurable: false, value: (value: unknown) => target.has(value) },\r\n entries: {\r\n enumerable: false,\r\n configurable: false,\r\n value: () => Set.prototype.entries.call(target),\r\n },\r\n keys: {\r\n enumerable: false,\r\n configurable: false,\r\n value: () => Set.prototype.keys.call(target),\r\n },\r\n values: {\r\n enumerable: false,\r\n configurable: false,\r\n value: () => Set.prototype.values.call(target),\r\n },\r\n forEach: {\r\n enumerable: false,\r\n configurable: false,\r\n value: (\r\n callback: (value: unknown, key: unknown, set: ReadonlySet<unknown>) => void,\r\n thisArg?: unknown,\r\n ) => {\r\n Set.prototype.forEach.call(target, (value) => callback.call(thisArg, value, value, view));\r\n },\r\n },\r\n [Symbol.iterator]: {\r\n enumerable: false,\r\n configurable: false,\r\n value: () => Set.prototype.values.call(target),\r\n },\r\n add: { enumerable: false, configurable: false, value: rejectMutation(\"add\") },\r\n delete: { enumerable: false, configurable: false, value: rejectMutation(\"delete\") },\r\n clear: { enumerable: false, configurable: false, value: rejectMutation(\"clear\") },\r\n }),\r\n (target) => {\r\n const extras: Array<[string, (...args: unknown[]) => unknown]> = [];\r\n const forwardSetOperation = (operation: string) => (other: unknown) => {\r\n const method = (Set.prototype as unknown as Record<string, unknown>)[operation];\r\n if (typeof method !== \"function\") {\r\n throw new TypeError(`Set#${operation}() is unavailable in this JavaScript engine`);\r\n }\r\n const collection =\r\n isObjectLike(other) ? readonlyCollectionViewToRaw.get(other) ?? other : other;\r\n return Reflect.apply(method, target, [collection]);\r\n };\r\n // ES2025's Set operations are non-mutating. Forward them to the raw Set so\r\n // native methods receive their required internal-slot receiver. A second\r\n // deepSignal read-only view is unwrapped first because it is also set-like.\r\n for (const operation of [\r\n \"union\",\r\n \"intersection\",\r\n \"difference\",\r\n \"symmetricDifference\",\r\n \"isSubsetOf\",\r\n \"isSupersetOf\",\r\n \"isDisjointFrom\",\r\n ]) {\r\n if (typeof (Set.prototype as unknown as Record<string, unknown>)[operation] === \"function\") {\r\n extras.push([operation, forwardSetOperation(operation)]);\r\n }\r\n }\r\n return extras;\r\n },\r\n ) as ReadonlySet<Value>;\r\n }\r\n\r\n function assertRootValue(value: unknown): asserts value is object {\r\n if (!isPlainObjectOrArray(value)) {\r\n throw new TypeError(\"deepSignal() only accepts a plain object or array root\");\r\n }\r\n }\r\n\r\n function assertDeepDataGraph(value: unknown): boolean {\r\n if (!isObjectLike(value)) return false;\r\n // A value can be reachable both as reactive plain data and through an opaque\r\n // value. A proxy beneath an opaque value cannot be unwrapped without changing\r\n // that value's observable identity, so reject it instead of leaking a proxy\r\n // into the raw tree.\r\n const seen = new WeakMap<object, number>();\r\n const pending: Array<{ value: object; insideOpaque: boolean }> = [\r\n { value, insideOpaque: false },\r\n ];\r\n let needsNormalization = false;\r\n\r\n while (pending.length > 0) {\r\n const { value: current, insideOpaque } = pending.pop() as {\r\n value: object;\r\n insideOpaque: boolean;\r\n };\r\n const wrapperRaw = toRaw(current);\r\n if (wrapperRaw !== undefined) {\r\n if (insideOpaque) {\r\n throw new TypeError(\r\n proxyToRaw.has(current)\r\n ? \"deepSignal() cannot store a deep proxy inside an opaque value\"\r\n : \"deepSignal() cannot store a deep collection view inside an opaque value\",\r\n );\r\n }\r\n // The raw graph was validated when this proxy (or collection view) was\r\n // created. Do not walk it again: this makes `{ inner: state.value.large }`\r\n // proportional to the new carrier rather than the already-known subtree.\r\n needsNormalization = true;\r\n continue;\r\n }\r\n const raw = current;\r\n const visitedAs = seen.get(raw) ?? 0;\r\n const visitFlag = insideOpaque ? 2 : 1;\r\n if ((visitedAs & visitFlag) !== 0) continue;\r\n seen.set(raw, visitedAs | visitFlag);\r\n\r\n // A built-in prototype adopted as reactive data would be written through\r\n // by the `set` trap, landing on the realm's shared intrinsic. Reject it\r\n // here, ahead of every branch below, so the diagnosis is the same for\r\n // `Array.prototype` (which nothing else catches) and for `Object.prototype`\r\n // (which only trips the accessor check by accident). Values reached\r\n // *through* an opaque one are exempt: they are never proxied and never\r\n // written to, and `{ ctor: Array }` reaches `Array.prototype` that way.\r\n if (!insideOpaque && isIntrinsicPrototype(raw)) {\r\n throw new TypeError(\"deepSignal() cannot store a built-in prototype object in deep state\");\r\n }\r\n\r\n if (raw instanceof Map) {\r\n for (const [key, entry] of raw) {\r\n if (isObjectLike(key)) {\r\n pending.push({ value: key, insideOpaque: true });\r\n }\r\n if (isObjectLike(entry)) {\r\n pending.push({ value: entry, insideOpaque: true });\r\n }\r\n }\r\n continue;\r\n }\r\n if (raw instanceof Set) {\r\n for (const entry of raw) {\r\n if (isObjectLike(entry)) {\r\n pending.push({ value: entry, insideOpaque: true });\r\n }\r\n }\r\n continue;\r\n }\r\n if (!isPlainObjectOrArray(raw)) {\r\n // Class instances, Date, functions, and other opaque values retain their\r\n // identity. Inspect their own data descriptors without invoking getters\r\n // so a contained deep proxy cannot enter the raw graph.\r\n for (const key of Reflect.ownKeys(raw)) {\r\n const descriptor = Reflect.getOwnPropertyDescriptor(raw, key);\r\n if (descriptor !== undefined && \"value\" in descriptor && isObjectLike(descriptor.value)) {\r\n pending.push({ value: descriptor.value, insideOpaque: true });\r\n }\r\n }\r\n continue;\r\n }\r\n\r\n if (!insideOpaque) {\r\n assertExtensible(raw);\r\n assertDataProperties(raw);\r\n }\r\n for (const key of Reflect.ownKeys(raw)) {\r\n const descriptor = Reflect.getOwnPropertyDescriptor(raw, key);\r\n if (descriptor !== undefined && \"value\" in descriptor) {\r\n const child = descriptor.value;\r\n if (isObjectLike(child)) {\r\n pending.push({ value: child, insideOpaque });\r\n }\r\n }\r\n }\r\n }\r\n\r\n return needsNormalization;\r\n }\r\n\r\n function matchesNormalizedGraph(source: object, normalized: object): boolean {\r\n const sources = new WeakMap<object, object>();\r\n const targets = new WeakMap<object, object>();\r\n const pending: Array<[unknown, unknown]> = [[source, normalized]];\r\n\r\n while (pending.length > 0) {\r\n const [currentSource, currentTarget] = pending.pop() as [unknown, unknown];\r\n if (typeof currentSource !== \"object\" || currentSource === null) {\r\n if (!Object.is(currentSource, currentTarget)) return false;\r\n continue;\r\n }\r\n\r\n const wrapperRaw = toRaw(currentSource);\r\n if (wrapperRaw !== undefined) {\r\n if (wrapperRaw !== currentTarget) return false;\r\n continue;\r\n }\r\n if (!isPlainObjectOrArray(currentSource)) {\r\n if (currentSource !== currentTarget) return false;\r\n continue;\r\n }\r\n if (\r\n typeof currentTarget !== \"object\" ||\r\n currentTarget === null ||\r\n !isPlainObjectOrArray(currentTarget)\r\n ) {\r\n return false;\r\n }\r\n\r\n const knownTarget = sources.get(currentSource);\r\n if (knownTarget !== undefined) {\r\n if (knownTarget !== currentTarget) return false;\r\n continue;\r\n }\r\n const knownSource = targets.get(currentTarget);\r\n if (knownSource !== undefined && knownSource !== currentSource) return false;\r\n sources.set(currentSource, currentTarget);\r\n targets.set(currentTarget, currentSource);\r\n\r\n if (\r\n Array.isArray(currentSource) !== Array.isArray(currentTarget) ||\r\n Object.getPrototypeOf(currentSource) !== Object.getPrototypeOf(currentTarget)\r\n ) {\r\n return false;\r\n }\r\n const sourceKeys = Reflect.ownKeys(currentSource);\r\n const targetKeys = Reflect.ownKeys(currentTarget);\r\n if (sourceKeys.length !== targetKeys.length) return false;\r\n // `entries()` rather than a plain index read so `key` is typed as a key\r\n // rather than `key | undefined`: `Reflect.ownKeys` returns a dense array,\r\n // so every index in range holds one, but only iteration says that in types.\r\n for (const [index, key] of sourceKeys.entries()) {\r\n if (key !== targetKeys[index]) return false;\r\n const sourceDescriptor = Reflect.getOwnPropertyDescriptor(currentSource, key);\r\n const targetDescriptor = Reflect.getOwnPropertyDescriptor(currentTarget, key);\r\n if (\r\n sourceDescriptor === undefined ||\r\n targetDescriptor === undefined ||\r\n !(\"value\" in sourceDescriptor) ||\r\n !(\"value\" in targetDescriptor) ||\r\n sourceDescriptor.configurable !== targetDescriptor.configurable ||\r\n sourceDescriptor.enumerable !== targetDescriptor.enumerable ||\r\n sourceDescriptor.writable !== targetDescriptor.writable\r\n ) {\r\n return false;\r\n }\r\n pending.push([sourceDescriptor.value, targetDescriptor.value]);\r\n }\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * An array of `length` with no own index properties — holes, not `undefined`s.\r\n * `Array.from({ length })` would materialize every index as an own property,\r\n * so cloning a sparse carrier produced an array with strictly more own keys\r\n * than its source. `matchesNormalizedGraph` compares own keys one-for-one, so\r\n * that clone could never match its source again: the carrier cache missed on\r\n * every re-assignment, breaking the documented guarantee that assigning the\r\n * same carrier twice preserves identity and aliasing.\r\n */\r\n function cloneWithoutProxies<T>(value: T): T {\r\n const wrapperRaw = toRaw(value);\r\n if (wrapperRaw !== undefined) return wrapperRaw as T;\r\n if (!isObjectLike(value)) return value;\r\n\r\n const cachedRoot = normalizedProxyCarriers.get(value);\r\n if (\r\n cachedRoot !== undefined &&\r\n matchesNormalizedGraph(value, cachedRoot)\r\n ) {\r\n return cachedRoot as T;\r\n }\r\n\r\n const clones = new WeakMap<object, object>();\r\n const created: Array<[object, object]> = [];\r\n const pending: object[] = [];\r\n\r\n const resolve = (current: unknown): unknown => {\r\n const resolvedRaw = toRaw(current);\r\n if (resolvedRaw !== undefined) return resolvedRaw;\r\n if (!isPlainObjectOrArray(current)) return current;\r\n\r\n const local = clones.get(current);\r\n if (local !== undefined) return local;\r\n\r\n const result: object = Array.isArray(current)\r\n ? emptyArrayOfLength(current.length)\r\n : Object.create(Object.getPrototypeOf(current));\r\n clones.set(current, result);\r\n created.push([current, result]);\r\n pending.push(current);\r\n return result;\r\n };\r\n\r\n const root = resolve(value) as T;\r\n while (pending.length > 0) {\r\n const source = pending.pop() as object;\r\n const target = clones.get(source) as object;\r\n for (const key of Reflect.ownKeys(source)) {\r\n if (Array.isArray(source) && key === \"length\") continue;\r\n const descriptor = Reflect.getOwnPropertyDescriptor(source, key);\r\n if (descriptor === undefined) continue;\r\n // Validation has already rejected accessors, before any clone is exposed.\r\n if (!(\"value\" in descriptor)) {\r\n throw new TypeError(\"deepSignal() does not support accessor properties\");\r\n }\r\n descriptor.value = resolve(descriptor.value);\r\n Reflect.defineProperty(target, key, descriptor);\r\n }\r\n }\r\n\r\n for (const [source, target] of created) {\r\n normalizedProxyCarriers.set(source, target);\r\n }\r\n return root;\r\n }\r\n\r\n function prepareDeepValue<T>(value: T): T {\r\n // Reassigning a value obtained from this deep signal is already known-good.\r\n // Avoid validating its entire graph again on this common O(1) path.\r\n const wrapperRaw = toRaw(value);\r\n if (wrapperRaw !== undefined) return wrapperRaw as T;\r\n const containsProxy = assertDeepDataGraph(value);\r\n return containsProxy ? cloneWithoutProxies(value) : value;\r\n }\r\n\r\n // The graph and caches are factory-local, so runtimes keep independent\n // proxies and version sources while sharing this single Proxy implementation.\n\r\n const unwrap = <T>(value: T): T => {\r\n return prepareDeepValue(value);\r\n };\r\n\r\n // Inherited members of the two prototypes a deep-signal target can have.\r\n // Reading one of these through the proxy (`list.map`, `list[Symbol.iterator]`,\r\n // `state.constructor`, ...) used to mint a permanent version signal for a key\r\n // that can never change, so a single `.map()` per render leaked one entry per\r\n // method name for the lifetime of the page. They are only skipped while the\r\n // key is *not* an own property, so a real data property named `map` or\r\n // `toString` — and an array's own `length` — stays fully reactive, and a\r\n // null-prototype object (which inherits nothing) is never affected.\r\n const OBJECT_PROTOTYPE_KEYS: ReadonlySet<PropertyKey> = new Set(\r\n Reflect.ownKeys(Object.prototype),\r\n );\r\n const ARRAY_PROTOTYPE_KEYS: ReadonlySet<PropertyKey> = new Set([\r\n ...Reflect.ownKeys(Object.prototype),\r\n ...Reflect.ownKeys(Array.prototype),\r\n ]);\r\n\r\n const isInheritedPrototypeMember = (target: object, key: PropertyKey): boolean => {\r\n if (Object.prototype.hasOwnProperty.call(target, key)) return false;\r\n const prototype = Object.getPrototypeOf(target) as object | null;\r\n if (prototype === Object.prototype) return OBJECT_PROTOTYPE_KEYS.has(key);\r\n if (prototype === Array.prototype) return ARRAY_PROTOTYPE_KEYS.has(key);\r\n return false;\r\n };\r\n\r\n const getVersion = (\r\n versions: Map<PropertyKey, VersionSignal>,\r\n key: PropertyKey,\r\n ): VersionSignal => {\r\n let version = versions.get(key);\r\n if (version === undefined) {\r\n version = adapter.createVersionSignal<number>(0);\n versions.set(key, version);\r\n }\r\n return version;\r\n };\r\n\r\n const track = (\r\n metadata: PropertyMetadata,\n target: object,\r\n versions: Map<PropertyKey, VersionSignal>,\r\n indices: Set<number>,\r\n key: PropertyKey,\r\n ): void => {\r\n if (!shouldTrackDeepRead()) return;\r\n if (isInheritedPrototypeMember(target, key)) {\n // An inherited member can only change by becoming (or ceasing to be) an\n // own property, which is exactly what the iteration version reports.\n // Plain objects subscribe to that, so dictionary-style state keyed by\n // \"constructor\" or \"toString\" stays reactive without minting a version\n // per inherited name. Arrays keep skipping: their inherited members are\n // the methods every `.map()` reads, and an own data property named after\n // one is not a supported shape.\n if (!Array.isArray(target)) trackIterationOf(metadata);\n return;\n }\n if (isArrayIndex(key)) indices.add(Number(key));\r\n const version = getVersion(versions, key);\r\n // Records that something reactive depends on this key right now, which is\r\n // what keeps `sweepPrunedKeys` from dropping it out from under a subscriber.\r\n adapter.markWatched(version);\n version.value;\r\n };\r\n\r\n /**\r\n * Queues `key`'s version signals for removal once nothing depends on them.\r\n * Only called for a key that has just been removed *and* notified, which is\r\n * what makes the eventual removal safe: the notification forces every\r\n * subscriber to re-run, so one that still cares re-reads the key (re-arming\r\n * `markWatched`) and one that does not has already been unlinked.\r\n */\r\n /**\r\n * Drops the version signals of removed keys once they have no subscribers\r\n * left, so a virtualized or repeatedly-spliced list stops accumulating one\r\n * entry per key that ever existed.\r\n *\r\n * Runs only at batch depth 0, where the write that queued these keys has\r\n * already flushed its effects; before that, `hasSubscribers()` would still\r\n * report the pre-flush picture. A key that is still subscribed (typically a\r\n * React store whose re-render has not committed yet) stays queued and is\r\n * reconsidered on the next sweep rather than being dropped early.\r\n */\r\n const sweepPrunedKeys = (metadata: PropertyMetadata, target: object): void => {\r\n const prunable = metadata.prunable;\r\n if (prunable === undefined || prunable.size === 0) return;\r\n if (adapter.getBatchDepth() !== 0) return;\r\n\r\n for (const key of prunable) {\r\n // The key came back (an index was written again, a property re-added):\r\n // its version signals are live metadata again, not garbage.\r\n if (Object.prototype.hasOwnProperty.call(target, key)) {\r\n prunable.delete(key);\r\n continue;\r\n }\r\n const property = metadata.properties.get(key);\r\n const existence = metadata.existence.get(key);\r\n if ((property !== undefined && adapter.hasSubscribers(property)) ||\n (existence !== undefined && adapter.hasSubscribers(existence))) {\n continue;\r\n }\r\n metadata.properties.delete(key);\r\n metadata.existence.delete(key);\r\n if (isArrayIndex(key)) {\r\n const index = Number(key);\r\n metadata.propertyIndices.delete(index);\r\n metadata.existenceIndices.delete(index);\r\n }\r\n prunable.delete(key);\r\n }\r\n\r\n if (prunable.size === 0) metadata.prunable = undefined;\r\n };\r\n\r\n const trackIterationOf = (metadata: PropertyMetadata): void => {\n metadata.iteration ??= adapter.createVersionSignal(0);\n metadata.iteration.value;\n };\n\n const trackIteration = (metadata: PropertyMetadata): void => {\r\n if (!shouldTrackDeepRead()) return;\r\n trackIterationOf(metadata);\n };\r\n\r\n const notifyTruncatedIndices = (\r\n metadata: PropertyMetadata,\r\n currentLength: number,\r\n oldLength: number,\r\n ): void => {\r\n const truncatedCount = oldLength - currentLength;\r\n const trackedCount =\r\n metadata.propertyIndices.size + metadata.existenceIndices.size;\r\n if (trackedCount === 0) return;\r\n\r\n if (truncatedCount <= trackedCount) {\r\n for (let index = currentLength; index < oldLength; index++) {\r\n const key = String(index);\r\n notify(metadata.properties, key);\r\n notify(metadata.existence, key);\r\n markPrunable(metadata, key);\r\n }\r\n return;\r\n }\r\n for (const index of metadata.propertyIndices) {\r\n if (index >= currentLength && index < oldLength) {\r\n const key = String(index);\r\n notify(metadata.properties, key);\r\n markPrunable(metadata, key);\r\n }\r\n }\r\n for (const index of metadata.existenceIndices) {\r\n if (index >= currentLength && index < oldLength) {\r\n const key = String(index);\r\n notify(metadata.existence, key);\r\n markPrunable(metadata, key);\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Whether `wrap()` would hand back something other than `value` itself — a\r\n * deep proxy for a plain object/array, or a readonly view for a Map/Set. The\r\n * `get` trap uses this to reject a non-configurable, non-writable property\r\n * whose value cannot be substituted, before `wrap()` performs the swap.\r\n */\r\n const isWrappedByValue = (value: unknown): boolean =>\r\n isPlainObjectOrArray(value) || value instanceof Map || value instanceof Set;\r\n\r\n const wrap = <T>(value: T): T => {\r\n const rawValue = (toRaw(value) as T | undefined) ?? value;\r\n if (rawValue instanceof Map) return readonlyMapView(rawValue) as T;\r\n if (rawValue instanceof Set) return readonlySetView(rawValue) as T;\r\n if (!isPlainObjectOrArray(rawValue)) return rawValue;\r\n assertExtensible(rawValue);\r\n\r\n const cached = rawToMetadata.get(rawValue);\r\n if (cached !== undefined) return cached.proxy as T;\r\n assertDataProperties(rawValue);\r\n\r\n const metadata: PropertyMetadata = {\r\n properties: new Map(),\r\n existence: new Map(),\r\n propertyIndices: new Set(),\r\n existenceIndices: new Set(),\r\n arrayMethods: new Map(),\r\n proxy: undefined as unknown as object,\r\n };\r\n\r\n const proxy = new Proxy(rawValue, {\r\n get(target, key, receiver) {\r\n // Deep state is raw data, never a signal. Answering the identity probe\r\n // up front keeps `isSignal()` on a nested proxy from allocating a\r\n // version signal for a key that can never change. An own brand only\r\n // exists if a raw reference bypassed this proxy, and it is reported so\r\n // the proxy invariants hold.\r\n if (key === SIGNAL_BRAND && !Object.prototype.hasOwnProperty.call(target, key)) {\r\n return undefined;\r\n }\r\n track(metadata, target, metadata.properties, metadata.propertyIndices, key);\n const result = Reflect.get(target, key, receiver);\r\n\r\n if (\r\n Array.isArray(target) &&\r\n ARRAY_MUTATORS.has(key) &&\r\n typeof result === \"function\"\r\n ) {\r\n const cachedMethod = metadata.arrayMethods.get(key);\r\n if (cachedMethod?.method === result) return cachedMethod.wrapper;\r\n\r\n const method = result as (...args: unknown[]) => unknown;\r\n // A mutator's own reads (`length`, the indices it shifts) are an\n // implementation detail of the write, not something the caller\n // depends on: tracked, `push` inside an effect would subscribe that\n // effect to `length` and re-run it on every later push. Vue 3.6's\n // array instrumentations pause tracking the same way. The writes\n // still go through the proxy (`this`), so they notify as usual.\n const wrapper = function (this: unknown, ...args: unknown[]) {\r\n try {\r\n return adapter.batch(() => adapter.untracked(() => Reflect.apply(method, this, args)));\n } finally {\r\n sweepPrunedKeys(metadata, target);\r\n }\r\n };\r\n metadata.arrayMethods.set(key, { method, wrapper });\r\n return wrapper;\r\n }\r\n\r\n if (\n Array.isArray(target) &&\n ARRAY_SEARCHES.has(key) &&\n typeof result === \"function\"\n ) {\n const cachedMethod = metadata.arrayMethods.get(key);\n if (cachedMethod?.method === result) return cachedMethod.wrapper;\n\n const method = result as (...args: unknown[]) => unknown;\n // Elements read through the proxy as proxies, so an identity search\n // for the raw object that was stored misses (and `splice(indexOf(a),\n // 1)` then removes the last element). The proxied search runs first,\n // keeping its reads tracked and native results unchanged; only an\n // object it missed is searched again, as raw, in the raw array --\n // elements are stored raw. Vue 3.6's `searchProxy` does the same.\n const wrapper = function (this: unknown, ...args: unknown[]) {\n const found = Reflect.apply(method, this, args);\n if ((found !== -1 && found !== false) || !isObjectLike(args[0])) return found;\n args[0] = toRaw(args[0]) ?? args[0];\n return Reflect.apply(method, toRaw(this) ?? this, args);\n };\n metadata.arrayMethods.set(key, { method, wrapper });\n return wrapper;\n }\n\n // Checked before `wrap()` substitutes anything: `wrap()` also swaps a\r\n // Map/Set for a readonly view, and those views are just as unassignable\r\n // back through a non-configurable, non-writable slot as a nested proxy\r\n // is. Gating this on `isPlainObjectOrArray(result)` let a frozen\r\n // Map/Set-valued property past the friendly error and into a raw engine\r\n // `TypeError` later on.\r\n if (isWrappedByValue(result)) {\r\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key);\r\n if (\r\n descriptor !== undefined &&\r\n \"value\" in descriptor &&\r\n descriptor.configurable === false &&\r\n descriptor.writable === false\r\n ) {\r\n throw new TypeError(\r\n \"deepSignal() cannot wrap a non-configurable, non-writable object property\",\r\n );\r\n }\r\n }\r\n\r\n return wrap(result);\r\n },\r\n\r\n set(target, key, nextValue, receiver) {\n // A write that only reaches this proxy through the prototype chain\n // (`Object.create(state).x = 1`) defines `x` on that receiver, as an\n // ordinary [[Set]] would; it changes nothing in this deep state.\n if (receiver !== metadata.proxy) return Reflect.set(target, key, nextValue, receiver);\n if (key === \"__proto__\") {\r\n throw new TypeError(\"deepSignal() does not support prototype mutation\");\r\n }\r\n // Storing the brand would make this subtree answer `isSignal()`, which\r\n // silently stops it from being wrapped and kills its reactivity.\r\n if (key === SIGNAL_BRAND) {\r\n throw new TypeError(\"deepSignal() does not support branding state as a signal\");\r\n }\r\n const oldValue = Reflect.get(target, key, target);\r\n const existed = Reflect.has(target, key);\r\n const owned = Object.prototype.hasOwnProperty.call(target, key);\r\n const oldLength = Array.isArray(target) ? target.length : undefined;\r\n const rawNextValue = unwrap(nextValue);\r\n const succeeded = Reflect.set(target, key, rawNextValue, target);\r\n if (!succeeded) return false;\r\n\r\n const currentValue = Reflect.get(target, key, target);\r\n const existsNow = Reflect.has(target, key);\r\n const ownedNow = Object.prototype.hasOwnProperty.call(target, key);\r\n\r\n adapter.batch(() => {\r\n if (!Object.is(oldValue, currentValue) || owned !== ownedNow) {\r\n notify(metadata.properties, key);\r\n }\r\n // Existence versions back both `in` (any key in the chain) and own-key\n // checks such as `Object.hasOwn` (see `getOwnPropertyDescriptor`), so\n // either kind of change notifies them.\n if (existed !== existsNow || owned !== ownedNow) notify(metadata.existence, key);\n if (owned !== ownedNow) notifyIteration(metadata);\r\n\r\n if (Array.isArray(target) && oldLength !== undefined) {\r\n const currentLength = target.length;\r\n if (key !== \"length\" && oldLength !== currentLength) {\r\n notify(metadata.properties, \"length\");\r\n }\r\n if (key === \"length\" && currentLength < oldLength) {\r\n notifyTruncatedIndices(metadata, currentLength, oldLength);\r\n notifyIteration(metadata);\r\n }\r\n }\r\n });\r\n sweepPrunedKeys(metadata, target);\r\n\r\n return true;\r\n },\r\n\r\n deleteProperty(target, key) {\r\n const owned = Object.prototype.hasOwnProperty.call(target, key);\r\n const succeeded = Reflect.deleteProperty(target, key);\r\n if (!succeeded || !owned) return succeeded;\r\n\r\n adapter.batch(() => {\r\n notify(metadata.properties, key);\r\n // An own key was removed, which own-key existence checks observe even\n // when `in` still finds the key on the prototype.\n notify(metadata.existence, key);\n notifyIteration(metadata);\r\n markPrunable(metadata, key);\r\n });\r\n sweepPrunedKeys(metadata, target);\r\n return true;\r\n },\r\n\r\n getOwnPropertyDescriptor(target, key) {\r\n // [[GetOwnProperty]] is what `Object.hasOwn`, `hasOwnProperty.call`,\n // and the enumerability check inside `Object.keys`/`for...in` use, so it\n // subscribes to the key's *existence*, not its value: tracking the value\n // here made a keys-only reader re-run on every property write. Reads\n // that need the value (`Object.entries`, spread, JSON) also go through\n // [[Get]] and track it there; a value read through a descriptor alone\n // (`Object.getOwnPropertyDescriptor(state, key).value`) does not re-run\n // on value changes. The value is still wrapped so no raw nested object\n // escapes through `Object.getOwnPropertyDescriptors`.\n track(metadata, target, metadata.existence, metadata.existenceIndices, key);\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key);\r\n if (descriptor === undefined || !(\"value\" in descriptor)) return descriptor;\r\n\r\n // The one value that cannot be substituted. [[GetOwnProperty]] requires\r\n // the reported descriptor to be compatible with the target's, and for a\r\n // non-configurable, non-writable data property that means reporting the\r\n // very same value — a proxy may not lie about it, so the engine throws\r\n // at the call site if we swap in a wrapper. `get` refuses such a\r\n // property outright rather than hand back an unwrapped reference; here\r\n // refusing would break `Object.getOwnPropertyDescriptors()` for the\r\n // whole object, so report it exactly as it is, which is also all the\r\n // invariant ever lets a caller observe.\r\n if (descriptor.configurable === false && descriptor.writable === false) {\r\n return descriptor;\r\n }\r\n\r\n descriptor.value = wrap(descriptor.value);\r\n return descriptor;\r\n },\r\n\r\n has(target, key) {\r\n track(metadata, target, metadata.existence, metadata.existenceIndices, key);\n return Reflect.has(target, key);\r\n },\r\n\r\n ownKeys(target) {\r\n trackIteration(metadata);\r\n return Reflect.ownKeys(target);\r\n },\r\n\r\n defineProperty() {\r\n throw new TypeError(\"deepSignal() does not support property descriptors\");\r\n },\r\n\r\n preventExtensions() {\r\n throw new TypeError(\"deepSignal() state must remain extensible\");\r\n },\r\n\r\n setPrototypeOf() {\r\n throw new TypeError(\"deepSignal() does not support prototype mutation\");\r\n },\r\n });\r\n\r\n metadata.proxy = proxy;\r\n rawToMetadata.set(rawValue, metadata);\r\n proxyToRaw.set(proxy, rawValue);\r\n return proxy as T;\r\n };\r\n\r\n class DeepSignalImpl<T extends object> implements DeepSignalLike<T> {\n readonly #source: DeepSignalSource<T>;\r\n\r\n constructor(source: DeepSignalSource<T>) {\r\n this.#source = source;\r\n const protocol = getReadableInterop(this.#source);\r\n if (protocol !== undefined) attachReadableInterop(this, protocol);\r\n }\r\n\r\n get value(): T {\r\n // Runtime collection views intentionally keep the established `.value: T`\r\n // public type. `DeepSignal<T>` must remain assignable to `Signal<T>`.\r\n return wrap(this.#source.value) as T;\r\n }\r\n\r\n set value(nextValue: T) {\r\n const rawValue = unwrap(nextValue);\r\n assertRootValue(rawValue);\r\n this.#source.value = rawValue as T;\r\n }\r\n\r\n peek(): T {\r\n return this.#source.peek();\r\n }\r\n }\r\n\r\n /**\r\n * Reports the per-key reactive metadata currently retained for a deep proxy\r\n * (or for the raw object behind it). Exposed for this package's own tests\r\n * only — it is deliberately absent from every published entry point, and the\r\n * shape it returns is internal detail, not API.\r\n */\r\n function inspectDeepSignalMetadata(value: object): {\r\n properties: PropertyKey[];\r\n existence: PropertyKey[];\r\n propertyIndices: number[];\r\n existenceIndices: number[];\r\n } | undefined {\r\n const metadata = rawToMetadata.get(toRaw(value) ?? value);\r\n if (metadata === undefined) return undefined;\r\n return {\r\n properties: [...metadata.properties.keys()],\r\n existence: [...metadata.existence.keys()],\r\n propertyIndices: [...metadata.propertyIndices],\r\n existenceIndices: [...metadata.existenceIndices],\r\n };\r\n }\r\n\r\n /**\r\n * Creates a signal that lazily tracks nested plain-object and array properties.\r\n * Mutations must go through `.value`; changes made through the original raw\r\n * object are intentionally not observable.\r\n */\r\n function deepSignal<T extends object>(initialValue: T): DeepSignalLike<T> {\r\n const rawInitialValue = prepareDeepValue(initialValue);\r\n assertRootValue(rawInitialValue);\r\n\r\n wrap(rawInitialValue);\r\n const root = adapter.createSignal(rawInitialValue as T);\r\n const result = new DeepSignalImpl(root);\r\n adapter.registerDeepSignal?.(result);\r\n return result;\r\n }\r\n return { deepSignal, inspectDeepSignalMetadata };\r\n}\r\n","import { coreRuntime } from \"./core-runtime.js\";\nimport { executionContext, UNTRACKED_OWNER } from \"./execution-owner.js\";\nimport { createDeepSignalFactory } from \"./deep-signal-engine.js\";\nimport {\n batch,\n isSignal,\n registerSignal,\n untracked,\n} from \"./base.js\";\nimport type { Signal } from \"./base.js\";\n\ndeclare const deepSignalBrand: unique symbol;\n\n/** A signal whose plain-object and array values are reactive by property. */\nexport interface DeepSignal<T extends object> extends Signal<T> {\n /**\n * Type-only marker; never present at runtime. It lets positions that only\n * observe a signal's root value reject a deep signal at compile time,\n * because they would not re-render on nested mutations.\n */\n readonly [deepSignalBrand]: true;\n}\n\n/**\n * Package-internal: intersected with `ReadonlySignal<T>` where only root\n * replacement is observed (`useSignalValue`, JSX children and host props), so\n * passing a `DeepSignal` there is a type error instead of a silently stale UI.\n */\nexport type NotDeepSignal = { readonly [deepSignalBrand]?: never };\n\nlet productionDeepSignals: ReturnType<typeof createDeepSignalFactory> | undefined;\n\nfunction getProductionDeepSignals(): NonNullable<typeof productionDeepSignals> {\n return productionDeepSignals ??= createDeepSignalFactory({\n createSignal<T>(initial: T) {\n return coreRuntime.createDeepSignal(initial);\n },\n createVersionSignal<T>(initial: T) {\n return coreRuntime.createDeepSignalVersion(initial);\n },\n markWatched(source) { coreRuntime.markDeepSignalWatched(source); },\n hasSubscribers(source) { return coreRuntime.hasDeepSignalSubscribers(source); },\n batch,\n untracked,\n isSignal,\n hasActiveSubscriber: () => {\n const owner = executionContext.owner;\n // Another copy's `untracked()` only clears that copy's subscriber; the\n // shared owner is what says this read must not be tracked by anyone.\n if (owner === UNTRACKED_OWNER) return false;\n return coreRuntime.hasActiveSubscriber() ||\n (owner !== undefined && typeof owner !== \"symbol\" &&\n (owner.kind === \"graph\" || owner.kind === \"render\"));\n },\n getBatchDepth: () => coreRuntime.getBatchDepth(),\n isSpeculative: () => coreRuntime.isSpeculative(),\n markSpeculativeDeepRead: () => coreRuntime.markSpeculativeDeepRead(),\n registerDeepSignal(value) {\n registerSignal(value as DeepSignal<object>);\n },\n });\n}\n\n/**\n * Reports the per-key reactive metadata currently retained for a deep proxy\n * (or for the raw object behind it). This package-internal helper is not part\n * of any published entry point.\n */\nexport function inspectDeepSignalMetadata(value: object): ReturnType<\n ReturnType<typeof createDeepSignalFactory>[\"inspectDeepSignalMetadata\"]\n> {\n return getProductionDeepSignals().inspectDeepSignalMetadata(value);\n}\n\n/**\n * Creates a signal that lazily tracks nested plain-object and array properties.\n * Mutations must go through `.value`; changes made through the original raw\n * object are intentionally not observable.\n */\nexport function deepSignal<T extends object>(\n initialValue: T,\n): DeepSignal<T> {\n return getProductionDeepSignals().deepSignal(initialValue) as DeepSignal<T>;\n}\n","import { getReadableInterop } from \"./interop.js\";\nimport { notifyListener } from \"./render-tracking.js\";\n\n/** Subscribe through the private V1 boundary without creating an EffectNode. */\nexport function subscribeReadableV1(\n readable: object,\n listener: () => void,\n): (() => void) | undefined {\n const protocol = getReadableInterop(readable);\n if (protocol === undefined) return undefined;\n const subscription = protocol.subscribe(() => notifyListener(listener));\n return () => subscription.unsubscribe();\n}\n","import {\n useCallback,\n useEffect as useReactEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\nimport { computed, deepSignal, signal, untracked } from \"../core/index.js\";\nimport { detachedEffect } from \"../core/base.js\";\nimport type {\n DeepSignal,\n ReadonlySignal,\n Signal,\n} from \"../core/index.js\";\nimport type { NotDeepSignal } from \"../core/deep-signal.js\";\nimport { untrackedRender } from \"../core/render-tracking.js\";\nimport { subscribeReadableV1 } from \"../core/readable-subscription.js\";\nimport type { DependencyList } from \"react\";\nexport { useSignalTracking } from \"./use-signals.js\";\n\nconst EMPTY_DEPENDENCIES: DependencyList = [];\n\n/** Which of `useComputed`'s two mutually exclusive modes a call site uses. */\ntype ComputedMode = \"without a dependency array\" | \"with a dependency array\";\n\n/** An immutable value that React can safely compare as an external-store snapshot. */\nexport type SignalSnapshot =\n | string\n | number\n | boolean\n | bigint\n | symbol\n | null\n | undefined;\n\ntype SelectorResult<S extends SignalSnapshot> =\n | { readonly kind: \"value\"; readonly value: S }\n | { readonly kind: \"error\"; readonly error: unknown };\n\nfunction assertSignalSnapshot(value: unknown): asserts value is SignalSnapshot {\n if ((typeof value === \"object\" && value !== null) || typeof value === \"function\") {\n throw new TypeError(\n \"useDeepSignalValue selector must return a primitive snapshot; objects, Proxies, and functions are not supported\",\n );\n }\n}\n\n/**\n * Shared `useSyncExternalStore` wiring for effect-backed subscriptions only:\n * the dynamic deep-selector store and structural-readable compatibility\n * fallback. Package readables with ReadableInterop V1 use a direct watcher.\n * On `subscribe`, starts an `effect()` that reruns `onEvaluate` on relevant\n * writes and notifies React when it reports a change.\n *\n * `getSnapshot` is intentionally not this helper's concern — the caller\n * wires its own, whether that means recomputing fresh each call\n * (`useSignalValue`) or returning a cached result (the deep-selector store).\n *\n * An exception thrown by `onEvaluate` is swallowed here and treated as a\n * change worth notifying about. That leaves the next render-time snapshot\n * read to surface the error to an Error Boundary rather than letting the\n * background effect's exception escape through the signal writer.\n */\nfunction createEffectBackedStoreSubscription(\n onEvaluate: () => boolean,\n): (notify: () => void) => () => void {\n return (notify: () => void): (() => void) => {\n let isInitialRun = true;\n return detachedEffect(() => {\n let changed: boolean;\n try {\n changed = onEvaluate();\n } catch {\n changed = true;\n }\n if (isInitialRun) {\n isInitialRun = false;\n return;\n }\n if (changed) notify();\n });\n };\n}\n\n/**\n * Holds a selector result outside the reactive graph. A selector error must\n * not escape from the signal write that caused a reactive re-evaluation:\n * React needs to observe it during its next render so an Error Boundary can\n * handle it. The cached result also avoids rerunning the selector on every\n * render.\n */\nfunction createDeepSelectorStore<T extends object, S extends SignalSnapshot>(\n source: DeepSignal<T>,\n selector: (value: T) => S,\n) {\n const evaluate = (): SelectorResult<S> => {\n try {\n const value = untrackedRender(() => selector(source.value));\n assertSignalSnapshot(value);\n return { kind: \"value\", value };\n } catch (error) {\n return { kind: \"error\", error };\n }\n };\n\n let result = evaluate();\n\n const hasChanged = (next: SelectorResult<S>): boolean => {\n if (result.kind !== next.kind) return true;\n return result.kind === \"value\" && next.kind === \"value\"\n ? !Object.is(result.value, next.value)\n : result.kind === \"error\" && next.kind === \"error\"\n ? !Object.is(result.error, next.error)\n : false;\n };\n\n return {\n // Notify only when the primitive result or error identity changes; this\n // is the same Object.is rule used by useSyncExternalStore snapshots.\n subscribe: createEffectBackedStoreSubscription(() => {\n const next = evaluate();\n if (!hasChanged(next)) return false;\n result = next;\n return true;\n }),\n getSnapshot(): S {\n if (result.kind === \"error\") throw result.error;\n return result.value;\n },\n };\n}\n\n/** Creates a signal whose identity is stable for the lifetime of this component. */\nexport function useSignal<T>(initialValue: T): Signal<T> {\n const signalRef = useRef<Signal<T> | undefined>(undefined);\n\n if (signalRef.current === undefined) {\n signalRef.current = signal(initialValue);\n }\n\n return signalRef.current;\n}\n\n/**\n * Creates a deep signal whose identity is stable for the component lifetime.\n * A factory is evaluated only while initializing a mounted component instance;\n * it must remain pure because React Strict Mode may replay initial rendering.\n */\nexport function useDeepSignal<T extends object>(\n initialValue: T | (() => T),\n): DeepSignal<T> {\n const signalRef = useRef<DeepSignal<T> | undefined>(undefined);\n\n if (signalRef.current === undefined) {\n signalRef.current = deepSignal(\n typeof initialValue === \"function\" ? initialValue() : initialValue,\n );\n }\n\n return signalRef.current;\n}\n\n/**\n * Selects a property-level primitive snapshot from a deep signal.\n *\n * Every non-signal value captured by `selector` must be listed in\n * `dependencies`. Object and proxy results are intentionally rejected because\n * mutable snapshots cannot satisfy `useSyncExternalStore` identity semantics.\n *\n * `dependencies` must keep a fixed length across this component's lifetime,\n * matching `useMemo`'s own rule (its length feeds a `useMemo` deps array\n * below via `[source, ...dependencies]`). A length change is caught and\n * thrown as a clear error rather than left to degrade into React's silent\n * \"changed size between renders\" dev warning, mirroring `useComputed`'s\n * dependency-mode-switch guard.\n */\nexport function useDeepSignalValue<\n T extends object,\n S extends SignalSnapshot,\n>(\n source: DeepSignal<T>,\n selector: (value: T) => S,\n dependencies: DependencyList,\n): S {\n // A variable-length `dependencies` would otherwise only surface as React's\n // dev-mode \"changed size between renders\" warning on the `useMemo` call\n // below, while silently recreating the store (and losing selector/error\n // history) on every subsequent render. Mirrors `useComputed`'s mode-switch\n // guard below: a violation is a loud, actionable error instead of a\n // silently degraded memo.\n const initialDependencyLengthRef = useRef<number | undefined>(undefined);\n initialDependencyLengthRef.current ??= dependencies.length;\n if (dependencies.length !== initialDependencyLengthRef.current) {\n const error = new Error(\n `useDeepSignalValue: the \\`dependencies\\` array length changed between renders (from ${initialDependencyLengthRef.current} to ${dependencies.length}) for this call site. Keep \\`dependencies\\` a fixed length across the component's lifetime, matching useMemo's rules.`,\n );\n error.name = \"UseDeepSignalValueDependencyLengthChangeError\";\n throw error;\n }\n\n const store = useMemo(\n () => createDeepSelectorStore(source, selector),\n [source, ...dependencies],\n );\n return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);\n}\n\n/**\n * Creates a computed signal with a stable identity.\n *\n * When `dependencies` is omitted, the getter must only read signals. Its initial\n * closure is retained for the component lifetime, so props, state, and other\n * non-signal values must not be captured in that mode.\n *\n * When the getter captures props, state, or any other non-signal value, list all\n * of those values in `dependencies`. React memoization then creates a separate\n * computed when they change, rather than replacing the getter of an existing\n * computed during render. An abandoned render therefore cannot change the\n * closure used by the previously committed computed. Choose one mode for a\n * component's lifetime.\n */\nexport function useComputed<T>(\n getValue: () => T,\n dependencies?: DependencyList,\n): ReadonlySignal<T> {\n const dependencyComputed = useMemo(\n () =>\n dependencies === undefined\n ? undefined\n : computed(getValue),\n dependencies ?? EMPTY_DEPENDENCIES,\n );\n\n const initialModeRef = useRef<ComputedMode | undefined>(undefined);\n const signalOnlyComputedRef = useRef<ReadonlySignal<T> | undefined>(undefined);\n\n // Both directions of a mode switch are silently destructive, so neither is\n // allowed to reach the caller as a mystery. Going deps -> no-deps used to\n // hand back `undefined` typed as `ReadonlySignal<T>`, so the crash surfaced\n // at the call site as \"Cannot read properties of undefined (reading\n // 'value')\" with nothing pointing back here. Going no-deps -> deps quietly\n // built a *second* computed with a new identity mid-lifetime, invalidating\n // every subscription already made to the first.\n const mode: ComputedMode =\n dependencies === undefined ? \"without a dependency array\" : \"with a dependency array\";\n initialModeRef.current ??= mode;\n if (initialModeRef.current !== mode) {\n const error = new Error(\n `useComputed: the dependency-array mode changed between renders (from ${initialModeRef.current} to ${mode}) for this call site. Keep passing deps consistently, matching useMemo's rules.`,\n );\n error.name = \"UseComputedModeChangeError\";\n throw error;\n }\n\n // Defined exactly when `dependencies` is, per the memo above; checking the\n // result rather than the argument is what removes the old `!` assertion.\n if (dependencyComputed !== undefined) return dependencyComputed;\n\n if (signalOnlyComputedRef.current === undefined) {\n signalOnlyComputedRef.current = computed(getValue);\n }\n\n return signalOnlyComputedRef.current;\n}\n\n/**\n * Runs a reactive effect after this component has committed, disposing it when\n * the component unmounts (and during React Strict Mode's development replay).\n *\n * When `dependencies` is omitted, the callback must only capture signals. Its\n * initial closure is retained for the component lifetime, so unrelated React\n * renders do not restart the effect.\n *\n * When the callback captures props, state, or any other non-signal value, list\n * all of those values in `dependencies`. The effect is then reconnected after\n * those dependencies change. Choose one mode for a component's lifetime.\n */\nexport function useSignalEffect(\n callback: () => void | (() => void),\n dependencies?: DependencyList,\n): void {\n useReactEffect(() => detachedEffect(callback), dependencies ?? EMPTY_DEPENDENCIES);\n}\n\n/**\n * Reads a signal and subscribes the component to subsequent changes through\n * ReadableInterop V1 when available.\n *\n * `useSyncExternalStore` owns the initial consistency check after subscribing.\n * For V1 readables, its watcher tracks revisions without an EffectNode. A\n * read that throws (a computed whose cached error `.value` rethrows) remains\n * for the render-time `getSnapshot` to surface to an Error Boundary; only the\n * structural-readable fallback needs an effect to contain background errors.\n *\n * A `deepSignal` is rejected at compile time: this subscribes to root\n * replacement only, so nested mutations would never re-render. Read deep state\n * with `useDeepSignalValue` or inside a tracked component instead.\n */\nexport function useSignalValue<T>(source: ReadonlySignal<T> & NotDeepSignal): T {\n const subscribe = useCallback((notify: () => void) => {\n const unsubscribe = subscribeReadableV1(source, notify);\n if (unsubscribe !== undefined) return unsubscribe;\n // Preserve the legacy bridge for structural readables without V1.\n return createEffectBackedStoreSubscription(() => {\n source.value;\n return true;\n })(notify);\n }, [source]);\n\n // A leaf subscription owns this read. An unmanaged useSignalTracking() scope may\n // still be open for an ancestor or earlier sibling until React commits, so\n // do not also register the source with that component's render collector.\n // `untrackedRender()` clears only render dependency collection.\n // `untracked()` also suppresses dependency collection in RFSG's runtime,\n // whose runtime-local `activeSub` is owned by `createReactiveRuntime()`.\n // A snapshot read during an RFSG effect or computed evaluation must use\n // `untracked()` so it cannot graft this source onto that subscriber.\n const getSnapshot = useCallback(\n () => untracked(() => source.value),\n [source],\n );\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n","import { isSignal, untracked } from \"../core/index.js\";\nimport { detachedEffect } from \"../core/base.js\";\nimport { subscribeReadableV1 } from \"../core/readable-subscription.js\";\nimport { notifyListener } from \"../core/render-tracking.js\";\nimport type { ReadonlySignal } from \"../core/index.js\";\nimport type { NotDeepSignal } from \"../core/deep-signal.js\";\nimport { useSignalValue } from \"../react/hooks.js\";\nimport { createElement, Fragment } from \"react\";\nimport type * as React from \"react\";\n\n/** The small set of DOM properties that support direct signal bindings. */\nconst REACTIVE_PROP_NAMES = new Set([\n \"title\",\n \"id\",\n \"className\",\n \"hidden\",\n \"disabled\",\n \"style\",\n \"value\",\n \"checked\",\n]);\n\n// `value`/`checked` are two-way bound only on these tags — the ones where React\n// itself treats them as a controlled/uncontrolled input. Elsewhere (`<li value>`,\n// `<option value>`, `<meter value>`, ...) they are plain, write-only attributes,\n// so those keep the same peek-and-substitute treatment as `title`/`disabled`/etc.\nfunction isControlledTwoWayProp(tagName: string, name: string): boolean {\n if (name === \"value\") return tagName === \"input\" || tagName === \"textarea\" || tagName === \"select\";\n if (name === \"checked\") return tagName === \"input\";\n return false;\n}\n\n/**\n * The concrete strategy a direct binding is mounted with. Resolved once, in\n * `findHostBindings`, from the JSX tag string that is already on hand at\n * element-creation time — `\"select\"` needs `bindSelectValue`'s MutationObserver\n * workaround, `\"input\"`/`\"textarea\"` need `bindTextValue`'s IME handling, and\n * `<input checked>` is the only other two-way case — so `mountBinding` later\n * only has to dispatch on this already-known value instead of re-deriving the\n * same facts from the mounted DOM node's `tagName`. It is also half of a\n * binding's identity for `NodeBinder`'s re-attach diff.\n */\ntype BindingKind = \"style\" | \"select-value\" | \"text-value\" | \"checked\" | \"prop\";\n\nfunction resolveBindingKind(tagName: string, name: string): BindingKind {\n if (name === \"style\") return \"style\";\n if (isControlledTwoWayProp(tagName, name)) {\n if (name === \"value\") return tagName === \"select\" ? \"select-value\" : \"text-value\";\n return \"checked\";\n }\n return \"prop\";\n}\n\nfunction isTwoWayBindingKind(kind: BindingKind): boolean {\n return kind === \"select-value\" || kind === \"text-value\" || kind === \"checked\";\n}\n\n// The uncontrolled counterpart React reads only at mount, used in place of the\n// controlled prop so React's own input reconciliation never re-asserts a stale\n// signal snapshot over what the direct-binding subscription just wrote.\nconst UNCONTROLLED_PROP_NAMES: Record<string, string> = {\n value: \"defaultValue\",\n checked: \"defaultChecked\",\n};\n\n// CSS properties React also treats as unitless: a bound number is written as-is\n// instead of getting a \"px\" suffix. Not exhaustive (SVG-only properties are\n// omitted since style binding is HTML-host-only), but covers the common cases.\nconst UNITLESS_CSS_PROPERTIES = new Set([\n \"animationIterationCount\", \"aspectRatio\", \"borderImageOutset\", \"borderImageSlice\",\n \"borderImageWidth\", \"boxFlex\", \"boxFlexGroup\", \"boxOrdinalGroup\", \"columnCount\",\n \"columns\", \"flex\", \"flexGrow\", \"flexPositive\", \"flexShrink\", \"flexNegative\",\n \"flexOrder\", \"gridArea\", \"gridColumn\", \"gridColumnEnd\", \"gridColumnSpan\",\n \"gridColumnStart\", \"gridRow\", \"gridRowEnd\", \"gridRowSpan\", \"gridRowStart\",\n \"fontWeight\", \"lineClamp\", \"lineHeight\", \"opacity\", \"order\", \"orphans\",\n \"scale\", \"tabSize\", \"WebkitLineClamp\", \"widows\", \"zIndex\", \"zoom\",\n]);\n\n// SVG has a different property model (for example, className is an SVGAnimatedString).\n// Keeping it out of the host fast path makes the supported surface explicit.\nconst SVG_ELEMENTS = [\n \"svg\", \"animate\", \"animateMotion\", \"animateTransform\", \"circle\", \"clipPath\",\n \"defs\", \"desc\", \"ellipse\", \"feBlend\", \"feColorMatrix\", \"feComponentTransfer\",\n \"feComposite\", \"feConvolveMatrix\", \"feDiffuseLighting\", \"feDisplacementMap\",\n \"feDistantLight\", \"feDropShadow\", \"feFlood\", \"feFuncA\", \"feFuncB\", \"feFuncG\",\n \"feFuncR\", \"feGaussianBlur\", \"feImage\", \"feMerge\", \"feMergeNode\", \"feMorphology\",\n \"feOffset\", \"fePointLight\", \"feSpecularLighting\", \"feSpotLight\", \"feTile\",\n \"feTurbulence\", \"filter\", \"foreignObject\", \"g\", \"image\", \"line\", \"linearGradient\",\n \"marker\", \"mask\", \"metadata\", \"mpath\", \"path\", \"pattern\", \"polygon\", \"polyline\",\n \"radialGradient\", \"rect\", \"set\", \"stop\", \"switch\", \"symbol\", \"text\", \"textPath\",\n \"tspan\", \"use\", \"view\",\n] as const;\n\ntype SvgElement = (typeof SVG_ELEMENTS)[number];\n\n// MathML properties do not share the HTML DOM property model either. React\n// currently types only SVG separately, but custom JSX factories can still\n// receive these host tags at runtime.\nconst MATHML_ELEMENTS = [\n \"annotation\", \"annotation-xml\", \"maction\", \"math\", \"merror\", \"mfrac\",\n \"mi\", \"mmultiscripts\", \"mn\", \"mo\", \"mover\", \"mpadded\", \"mphantom\",\n \"mprescripts\", \"mroot\", \"mrow\", \"ms\", \"mspace\", \"msqrt\", \"mstyle\",\n \"msub\", \"msubsup\", \"msup\", \"mtable\", \"mtd\", \"mtext\", \"mtr\", \"munder\",\n \"munderover\", \"semantics\",\n] as const;\n\ntype MathMlElement = (typeof MATHML_ELEMENTS)[number];\ntype NonHtmlHostElement = SvgElement | MathMlElement;\n// Built without array spread: a bundler has to assume spreading may run an\n// iterator with side effects, which kept this module's tag lists in every\n// bundle that imports the package root (it re-exports `createElement` from\n// here) even when nothing from this module is used.\nconst NON_HTML_HOST_ELEMENTS: ReadonlySet<string> = /* @__PURE__ */ (() => {\n const tags = new Set<string>(SVG_ELEMENTS);\n for (const tag of MATHML_ELEMENTS) tags.add(tag);\n return tags;\n})();\n\n// A deep signal is excluded from every position here: a child or host prop\n// observes root replacement only, so nested mutations would never show.\ntype SignalChild = React.ReactNode | (ReadonlySignal<SignalChild> & NotDeepSignal) | readonly SignalChild[];\ntype HostProps = Record<string, unknown>;\n// `snapshot` is the value React itself was handed for the prop at render (see\n// `transformHostProps`); a binding hands the node back to it on detach.\ntype Binding = readonly [name: string, source: ReadonlySignal<unknown>, kind: BindingKind, snapshot: unknown];\nconst HTML_NAMESPACE = \"http://www.w3.org/1999/xhtml\";\n\n/**\n * A leaf that lets React own reconciliation while its signal dependency stays\n * local to the leaf. A signal resolving to another signal/array is normalized\n * again so nested reactive children also work.\n */\nexport function SignalValue({ source }: { source: ReadonlySignal<SignalChild> }): React.ReactNode {\n return normalizeChild(useSignalValue(source));\n}\n\nfunction normalizeChild(value: unknown): React.ReactNode {\n if (isSignal(value)) {\n return createElement(SignalValue, { source: value as ReadonlySignal<SignalChild> });\n }\n\n if (Array.isArray(value)) {\n return value.map(normalizeArrayItem);\n }\n\n return value as React.ReactNode;\n}\n\n/**\n * A signal inside an array child has no way to carry a key of its own, so the\n * leaf it becomes is keyed by position. That is the identity such an array\n * already has (a literal `[a, b]` never reorders), and it keeps React's\n * missing-key warning for genuinely dynamic element lists intact. The prefix\n * keeps these keys out of the way of keys on the array's other elements.\n */\nfunction normalizeArrayItem(value: unknown, index: number): React.ReactNode {\n if (isSignal(value)) {\n return createElement(SignalValue, {\n source: value as ReadonlySignal<SignalChild>,\n key: `rfgs-signal:${index}`,\n });\n }\n return normalizeChild(value);\n}\n\nfunction isReactiveHostProp(name: string, value: unknown): value is ReadonlySignal<unknown> {\n if (!isSignal(value)) return false;\n return REACTIVE_PROP_NAMES.has(name) || name.startsWith(\"data-\") || name.startsWith(\"aria-\");\n}\n\nfunction readInitialValue(source: ReadonlySignal<unknown>, kind: BindingKind): unknown {\n const value = source.peek();\n // React DOM freezes the style object it is given in development. The signal\n // keeps owning its object (a `deepSignal`'s raw state, for one), so React gets\n // a shallow copy rather than a reference it would freeze out from under it.\n if (kind === \"style\" && typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n return { ...value };\n }\n return value;\n}\n\n/**\n * Per-binding \"already reported this episode\" latch for `readBoundSignal`.\n * Owned by the same closure that already holds a binding's other local state\n * (`previousKeys`, `composing`, ...) — never module-level — so two bindings\n * failing independently each still get their own first-failure log instead of\n * one silencing the other.\n */\ntype FailureEpisode = { hasReported: boolean };\n\n/**\n * Reads a signal on behalf of one of this module's direct DOM bindings (see\n * the module doc: these write straight to the DOM from a subscription mounted\n * alongside the element's ref, bypassing React's render, so the owning\n * component never re-renders). A `computed()` whose getter throws caches and\n * rethrows that error on every read (see `updateComputed` in\n * src/core/alien-derived-runtime-core.mts) —\n * if `source` is such a computed and it starts failing after the binding is\n * already mounted, an unguarded read here could throw from the subscription's\n * update callback while processing the write. The direct V1 watcher contains\n * computed dirty-check errors, but this binding read is a separate operation;\n * catching it here also keeps the structural-readable effect fallback local.\n *\n * Catching here keeps a failure local to this one binding: the DOM write for\n * this cycle is skipped (the DOM is left at its last successful value) and\n * the failure is reported with `console.error(message, { cause: error })` —\n * assert against `mock.calls[i][1].cause` in tests, the same shape used by\n * `effect()`'s failure report (`reportFailure` in\n * src/core/alien-derived-runtime-core.mts) and by `render-tracking.ts`. Reporting is intentional here too: a direct binding\n * has no Error Boundary or other surface to fall back on, and silence would\n * mean a binding that mysteriously stops updating with zero trace.\n *\n * Reported at most once per contiguous run of failures (\"episode\"): `episode`\n * latches after the first report and is cleared the moment a read next\n * succeeds, so a later, distinct failure episode logs again. This keeps a\n * `computed()` that fails on every keystroke from spamming one `console.error`\n * per keystroke.\n */\nfunction readBoundSignal<T>(\n read: () => T,\n episode: FailureEpisode,\n): { ok: true; value: T } | { ok: false } {\n try {\n const value = read();\n episode.hasReported = false;\n return { ok: true, value };\n } catch (error) {\n if (!episode.hasReported) {\n episode.hasReported = true;\n console.error(\n \"react-fine-grained-signals: a direct signal binding's read threw; skipping this update and leaving the DOM at its last value.\",\n { cause: error },\n );\n }\n return { ok: false };\n }\n}\n\n/**\n * Reads via `readBoundSignal` and, on success, hands the value to `apply`; a\n * failed read is already reported by `readBoundSignal`, so this just skips\n * the write. Shared by every read-and-apply call site below, including the\n * one that isn't itself a subscription callback — the MutationObserver-triggered\n * re-apply in `bindSelectValue`, which reads outside the reactive graph via\n * `.peek()`.\n */\nfunction applyBoundSignal<T>(\n read: () => T,\n apply: (value: T) => void,\n episode: FailureEpisode,\n): void {\n const result = readBoundSignal(read, episode);\n if (result.ok) apply(result.value);\n}\n\n/**\n * The common case built on `applyBoundSignal`: subscribe to a readable and\n * re-run `apply` whenever it changes. V1 readables use a direct protocol\n * subscription; structural readables retain the effect bridge. Centralizes\n * the pattern that used to be hand-rolled at each binding site — declare an\n * `episode`, then `effect(() => { const read = readBoundSignal(...); if\n * (!read.ok) return; <apply the value> })` — so the read-and-skip contract\n * can't drift between sites. An `episode` may be passed in to share a\n * failure latch with a sibling read site (see `bindSelectValue`); otherwise\n * each binding gets its own.\n */\n/**\n * A live binding subscription; `refresh` re-applies the current value. A\n * `\"style\"` binding also takes the render snapshot it is re-attached for (see\n * `subscribeBinding`); every other kind ignores it.\n */\ntype BindingSubscription = { readonly dispose: () => void; readonly refresh: (snapshot?: unknown) => void };\n\nfunction createBindingSubscription<T>(\n source: ReadonlySignal<T>,\n apply: (value: T) => void,\n episode: FailureEpisode = { hasReported: false },\n): BindingSubscription {\n const update = () => applyBoundSignal(() => source.value, apply, episode);\n const refresh = () => untracked(update);\n const unsubscribe = subscribeReadableV1(source, update);\n if (unsubscribe !== undefined) {\n // Subscribe before the initial read/apply so setup cannot miss an update.\n untracked(() => notifyListener(update));\n return { dispose: unsubscribe, refresh };\n }\n return { dispose: detachedEffect(update), refresh };\n}\n\nfunction setAttribute(node: Element, name: string, value: unknown): void {\n if (value == null) {\n node.removeAttribute(name);\n } else {\n node.setAttribute(name, String(value));\n }\n}\n\nfunction setDomProp(node: Element, name: string, value: unknown): void {\n // Tags such as `a`, `script`, `style`, and `title` exist in both HTML and\n // SVG. The JSX factory only sees the tag name, so defer the final namespace\n // decision until React gives us the actual DOM node.\n if (node.namespaceURI !== HTML_NAMESPACE) {\n setAttribute(node, name === \"className\" ? \"class\" : name, value);\n return;\n }\n\n switch (name) {\n case \"title\":\n (node as HTMLElement).title = value == null ? \"\" : String(value);\n return;\n case \"id\":\n (node as HTMLElement).id = value == null ? \"\" : String(value);\n return;\n case \"className\":\n (node as HTMLElement).className = value == null ? \"\" : String(value);\n return;\n case \"hidden\":\n // The `hidden` content attribute also accepts the DOM-native keyword\n // `\"until-found\"` (a collapsible, find-in-page-revealable hidden\n // state) — coercing every value through `Boolean(...)` and the\n // `.hidden` IDL property would turn that truthy string into a plain\n // `true`, downgrading it to a hard hide. Writing it as the attribute\n // directly instead preserves the keyword; every other value keeps\n // going through `.hidden` so `disabled`-style boolean semantics\n // (including the false/null/undefined-removes-the-attribute cases)\n // are unchanged.\n if (value === \"until-found\") setAttribute(node, \"hidden\", value);\n else (node as HTMLElement).hidden = Boolean(value);\n return;\n case \"disabled\":\n // Only controls expose this property, but the runtime remains safe when\n // JSX places it on another HTML element.\n if (\"disabled\" in node) (node as HTMLButtonElement).disabled = Boolean(value);\n else if (value == null || value === false) node.removeAttribute(name);\n else setAttribute(node, name, value);\n return;\n default:\n setAttribute(node, name, value);\n }\n}\n\n/**\n * Writes `value`/`checked` on a controlled-two-way element, skipping the DOM\n * write when it already holds the value being written. A binding update\n * follows signal writes, including keystrokes written by `onChange`, so without\n * this guard every keystroke would re-set a property the DOM already has,\n * moving the caret and disrupting IME composition for no reason.\n */\nfunction setControlledProp(node: Element, name: string, value: unknown): void {\n if (name === \"value\") {\n const select = node as HTMLSelectElement;\n if (select.tagName === \"SELECT\") {\n setSelectValue(select, value);\n return;\n }\n const next = value == null ? \"\" : String(value);\n const input = node as HTMLInputElement | HTMLTextAreaElement;\n if (input.value !== next) input.value = next;\n // The default is what a form reset restores (`form.reset()`, a reset\n // button, React 19's reset after a form action). Keeping it equal to the\n // bound value makes a reset land on the signal's value, as React does for a\n // controlled input by syncing its `value` attribute, instead of reverting to\n // the first render's value and leaving the DOM and the signal disagreeing.\n if (input.defaultValue !== next) input.defaultValue = next;\n return;\n }\n const next = Boolean(value);\n const input = node as HTMLInputElement;\n if (input.checked !== next) input.checked = next;\n if (input.defaultChecked !== next) input.defaultChecked = next;\n}\n\n/**\n * `<select multiple>` does not support assigning `.value` directly — the DOM\n * setter only ever selects a single option, silently corrupting the\n * selection instead of erroring. Its documented API for a multi-value select\n * is per-`<option>` `.selected`, so an array-valued signal (React's own\n * typing for a multi-select) is applied that way instead.\n */\nfunction setSelectValue(select: HTMLSelectElement, value: unknown): void {\n const multiple = select.multiple;\n const values = new Set(\n Array.isArray(value) && multiple ? value.map(String) : value == null ? (multiple ? [] : [\"\"]) : [String(value)],\n );\n // A single select keeps going through `.value`, which also handles a value\n // no option matches (nothing selected).\n if (!multiple) {\n const next = [...values][0]!;\n if (select.value !== next) select.value = next;\n }\n for (const option of select.options) {\n const selected = values.has(option.value);\n if (multiple && option.selected !== selected) option.selected = selected;\n // See `setControlledProp`: a form reset restores `defaultSelected`.\n if (option.defaultSelected !== selected) option.defaultSelected = selected;\n }\n}\n\n/**\n * A `<select>` whose matching `<option>` does not exist yet (for example when\n * the options themselves are rendered from a signal or other state, mounted\n * after this one) silently ends up with nothing selected: the DOM neither\n * errors nor retroactively applies `.value`/`.selected` once a matching\n * `<option>` is later added. The value subscription below only updates when\n * the bound signal itself changes, so it cannot see that the option list changed\n * out from under it. A MutationObserver on the select's subtree re-applies\n * the signal's current value whenever its `<option>` list changes, closing\n * that gap without requiring the signal to change too.\n */\nfunction bindSelectValue(select: HTMLSelectElement, source: ReadonlySignal<unknown>, apply: (value: unknown) => void): BindingSubscription {\n // Shared by both read sites below: a subscription-triggered failure and a\n // MutationObserver-triggered failure are the same underlying computed\n // erroring, so they report as one episode, not two.\n const episode: FailureEpisode = { hasReported: false };\n const subscription = createBindingSubscription(source, apply, episode);\n const observer = new MutationObserver(() => {\n applyBoundSignal(() => source.peek(), apply, episode);\n });\n observer.observe(select, { childList: true, subtree: true });\n return {\n dispose() {\n subscription.dispose();\n observer.disconnect();\n },\n refresh: subscription.refresh,\n };\n}\n\n/**\n * Forcing a `value` write while an IME composition is in progress can abort\n * the composition outright, independent of whether the string being written\n * happens to match what was typed — the write-skip guard in\n * `setControlledProp` only protects the same-value echo case, not this one.\n * `compositionstart`/`compositionend` listeners on the node itself track\n * composition state directly, regardless of whether the component declares\n * its own composition handlers, and a write requested while composing is\n * deferred until composition ends instead of applied immediately.\n */\nfunction bindTextValue(\n node: HTMLInputElement | HTMLTextAreaElement,\n source: ReadonlySignal<unknown>,\n write: (value: unknown) => void,\n): BindingSubscription {\n let composing = false;\n let hasPending = false;\n let pending: unknown;\n const episode: FailureEpisode = { hasReported: false };\n\n const onCompositionStart = () => {\n composing = true;\n };\n const onCompositionEnd = () => {\n composing = false;\n if (hasPending) {\n hasPending = false;\n write(pending);\n }\n };\n\n node.addEventListener(\"compositionstart\", onCompositionStart);\n node.addEventListener(\"compositionend\", onCompositionEnd);\n\n // A failed read must bail out before this touches `pending`/`hasPending` —\n // a stale or garbage value must never latch in. `createBindingSubscription`\n // already skips `apply` on a failed read, so that guard lives there once.\n const subscription = createBindingSubscription(source, (next) => {\n if (composing) {\n hasPending = true;\n pending = next;\n return;\n }\n write(next);\n }, episode);\n\n return {\n dispose() {\n subscription.dispose();\n node.removeEventListener(\"compositionstart\", onCompositionStart);\n node.removeEventListener(\"compositionend\", onCompositionEnd);\n },\n refresh: subscription.refresh,\n };\n}\n\nfunction clearStyleProperty(style: CSSStyleDeclaration, key: string): void {\n if (key.startsWith(\"--\")) style.removeProperty(key);\n else (style as unknown as Record<string, string>)[key] = \"\";\n}\n\nfunction setStyleProperty(style: CSSStyleDeclaration, key: string, value: unknown): void {\n if (value == null) {\n clearStyleProperty(style, key);\n return;\n }\n if (key.startsWith(\"--\")) {\n style.setProperty(key, String(value));\n return;\n }\n const cssValue = typeof value === \"number\" && !UNITLESS_CSS_PROPERTIES.has(key)\n ? `${value}px`\n : String(value);\n (style as unknown as Record<string, string>)[key] = cssValue;\n}\n\n/**\n * Applies a whole style object to an element, clearing keys that were present\n * in a previous call but are absent from this one. Only the coarse\n * `style={signal}` form is bound this way — an object whose individual entries\n * are themselves signals is out of scope (see development/design/direct-binding-value-checked-style.md).\n */\nfunction applyStyle(node: HTMLElement, value: unknown, previousKeys: readonly string[]): string[] {\n // A non-object value (an `any`-typed or otherwise unchecked caller passing\n // a string, for instance) would make `Object.keys` walk string indices\n // instead of CSS property names; treat anything that is not a plain object\n // as empty rather than writing garbage keys to the node's style.\n const nextStyle = (typeof value === \"object\" && value !== null && !Array.isArray(value) ? value : {}) as Record<string, unknown>;\n const nextKeys = Object.keys(nextStyle);\n const nextKeySet = new Set(nextKeys);\n\n for (const key of previousKeys) {\n if (!nextKeySet.has(key)) clearStyleProperty(node.style, key);\n }\n for (const key of nextKeys) {\n setStyleProperty(node.style, key, nextStyle[key]);\n }\n return nextKeys;\n}\n\ntype RefCleanup = void | (() => void);\ntype SupportedRef = React.Ref<Element> | undefined;\n\nfunction applyRef(ref: SupportedRef, node: Element | null): RefCleanup {\n if (typeof ref === \"function\") return ref(node);\n if (ref != null) ref.current = node;\n}\n\n/**\n * One live binding: the tuple it was mounted from, its teardown, and — for a\n * `\"style\"` binding only — a live accessor for the CSS property keys it has\n * actually applied to the node so far. `undefined` for every other kind.\n *\n * This is a getter, not a one-time snapshot, because a style binding's own\n * `previousKeys` keeps changing across its lifetime as its subscription updates; a\n * rebuild reads it just before disposing the binding, so it sees whatever the\n * binding last actually wrote, not what it started with. See `NodeBinder`.\n */\ntype MountedBinding = {\n readonly binding: Binding;\n readonly dispose: () => void;\n readonly refresh: (snapshot?: unknown) => void;\n readonly getStyleKeys: (() => readonly string[]) | undefined;\n readonly restore: ((snapshot: unknown) => void) | undefined;\n};\n\n/** A binding's identity for the re-render diff: same name, source, and kind. */\n// `b` is optional so callers can pass a positional lookup straight in: a\n// missing counterpart is simply not the same binding.\nfunction isSameBinding(a: Binding, b: Binding | undefined): b is Binding {\n return b !== undefined && a[0] === b[0] && a[1] === b[1] && a[2] === b[2];\n}\n\n/** Whether two style values set the same properties to the same values. */\nfunction isSameStyle(a: unknown, b: unknown): boolean {\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) return Object.is(a, b);\n const keys = Object.keys(a);\n return keys.length === Object.keys(b).length\n && keys.every((key) => Object.is((a as HostProps)[key], (b as HostProps)[key]));\n}\n\n/**\n * Whether React was handed the same value for this binding's prop. A two-way\n * binding hands React an uncontrolled default that it reads only at mount, so\n * only `\"prop\"` and `\"style\"` snapshots count; a style snapshot is a fresh copy\n * every render (see `readInitialValue`), so it is compared by content.\n */\nfunction hasSameSnapshot(a: Binding, b: Binding): boolean {\n return isTwoWayBindingKind(a[2]) || (a[2] === \"style\" ? isSameStyle(a[3], b[3]) : Object.is(a[3], b[3]));\n}\n\n/** What `subscribeBinding` hands back to `mountBinding`. See `MountedBinding`. */\ntype Subscription = BindingSubscription & {\n readonly getStyleKeys: (() => readonly string[]) | undefined;\n readonly restore: ((snapshot: unknown) => void) | undefined;\n};\n\n/**\n * Subscribes a single binding to `node` and returns its teardown. Split out of\n * the ref callback so `NodeBinder` can rebuild one binding on\n * its own, without disturbing the siblings that did not change.\n *\n * `initialStyleKeys` seeds a `\"style\"` binding's own `previousKeys` (see\n * `getInitialStyleKeys`), so the fresh binding starts already knowing which\n * CSS properties may be on the node, instead of starting from an empty set\n * and never clearing them. Ignored for every other kind.\n */\nfunction subscribeBinding(\n node: Element,\n name: string,\n source: ReadonlySignal<unknown>,\n kind: BindingKind,\n initialStyleKeys: readonly string[] | undefined,\n binder: NodeBinder,\n): Subscription {\n // Between a detach and its deferred teardown (see `NodeBinder`) the node is\n // no longer React's, so writes are held back; a re-attach refreshes instead.\n const whileAttached = <T,>(write: (value: T) => void) => (value: T) => {\n if (binder.attached) write(value);\n };\n switch (kind) {\n case \"style\": {\n let previousKeys: readonly string[] = initialStyleKeys ?? [];\n let applied: unknown;\n const write = (value: unknown) => {\n applied = value;\n previousKeys = applyStyle(node as HTMLElement, value, previousKeys);\n };\n const subscription = createBindingSubscription(source, whileAttached(write));\n return {\n ...subscription,\n // Kept across a re-attach for a newer render: React's diff has just\n // written that render's snapshot, whose keys the detach's `restore`\n // did not know about. The signal may already have dropped some of\n // them (a write while detached is held back), so the refresh must be\n // able to clear them.\n refresh: (snapshot) => {\n previousKeys = getInitialStyleKeys(previousKeys, snapshot);\n subscription.refresh();\n },\n getStyleKeys: () => previousKeys,\n restore: (snapshot) => { if (!isSameStyle(applied, snapshot)) write(snapshot); },\n };\n }\n case \"select-value\":\n return {\n ...bindSelectValue(node as HTMLSelectElement, source, whileAttached((value: unknown) => setControlledProp(node, \"value\", value))),\n getStyleKeys: undefined,\n restore: undefined,\n };\n case \"text-value\":\n return {\n ...bindTextValue(node as HTMLInputElement | HTMLTextAreaElement, source, whileAttached((value: unknown) => setControlledProp(node, \"value\", value))),\n getStyleKeys: undefined,\n restore: undefined,\n };\n case \"checked\":\n return {\n ...createBindingSubscription(source, whileAttached((value: unknown) => setControlledProp(node, name, value))),\n getStyleKeys: undefined,\n restore: undefined,\n };\n case \"prop\": {\n let applied: unknown;\n const write = (value: unknown) => {\n applied = value;\n setDomProp(node, name, value);\n };\n return {\n ...createBindingSubscription(source, whileAttached(write)),\n getStyleKeys: undefined,\n restore: (snapshot) => { if (!Object.is(applied, snapshot)) write(snapshot); },\n };\n }\n }\n}\n\n/**\n * The CSS properties a new `\"style\"` binding may find on the node: React wrote\n * this binding's render-time snapshot, and a replaced binding (`staleKeys`) may\n * have written keys React never saw. The signal can drop any of them before the\n * binding attaches (a write between render and commit, an Activity or Suspense\n * reveal), so the first write must be able to clear all of them. A kept\n * binding re-attached for a newer render widens its own keys the same way.\n */\nfunction getInitialStyleKeys(staleKeys: readonly string[] | undefined, snapshot: unknown): readonly string[] {\n const keys = typeof snapshot === \"object\" && snapshot !== null && !Array.isArray(snapshot) ? Object.keys(snapshot) : [];\n if (staleKeys === undefined) return keys;\n for (const key of staleKeys) if (!keys.includes(key)) keys.push(key);\n return keys;\n}\n\nfunction mountBinding(node: Element, binding: Binding, binder: NodeBinder, staleStyleKeys?: readonly string[]): MountedBinding {\n const initialStyleKeys = binding[2] === \"style\" ? getInitialStyleKeys(staleStyleKeys, binding[3]) : undefined;\n const { dispose, refresh, getStyleKeys, restore } = subscribeBinding(node, binding[0], binding[1], binding[2], initialStyleKeys, binder);\n return { binding, dispose, refresh, getStyleKeys, restore };\n}\n\n/**\n * Owns the direct bindings mounted on one DOM node.\n *\n * Bindings are attached through a callback ref on the host element itself\n * rather than through a wrapper component. A wrapper would change the element\n * type whenever a prop switched between a signal and a plain value, and React\n * remounts a subtree whose element type changes, losing descendant state and\n * focus. With the ref, the element stays the same host type in both cases.\n *\n * The binder is keyed by the node, not by the ref callback, because React\n * replaces a callback ref whose identity changed by detaching the old one and\n * attaching the new one to the same node within a single commit. Tearing the\n * bindings down on that detach would recreate every subscription — and reset\n * `bindTextValue`'s in-flight IME composition state — on unrelated re-renders.\n * So a detach only schedules the teardown, and a re-attach of the same node in\n * the same commit reconciles the bindings in place instead (`syncBindings`\n * diffs by `(name, source, kind)`). A detach that is not followed by an attach\n * (unmount, a hidden Activity or Suspense boundary) tears down in a microtask.\n *\n * The user's own ref is forwarded synchronously on every attach and detach,\n * which is exactly what React would do with it directly; `getBindingRef` keeps\n * the callback's identity stable whenever the inputs are, so a stable user ref\n * is not churned.\n */\nclass NodeBinder {\n #node: Element;\n #mounted: MountedBinding[] = [];\n #token = 0;\n #detached = false;\n\n constructor(node: Element) {\n this.#node = node;\n }\n\n /** Whether React currently has this node attached through a binding ref. */\n get attached(): boolean {\n return !this.#detached;\n }\n\n attach(bindings: readonly Binding[], userRef: SupportedRef): () => void {\n const token = ++this.#token;\n const wasDetached = this.#detached;\n this.#detached = false;\n // Kept bindings may have skipped a write while detached. Each is handed the\n // snapshot React just committed for its prop (matched by name, which is\n // unique per element), so a style binding can clear that snapshot's keys.\n // Only a binding the new render keeps as the same binding refreshes: one it\n // removed, turned plain, or replaced lost the prop to React's diff (or to\n // its replacement), and a refresh would write its stale source over that\n // just before `#sync` disposes it, with nothing left to correct it.\n if (wasDetached) {\n for (const entry of this.#mounted) {\n const next = bindings.find((binding) => binding[0] === entry.binding[0]);\n if (isSameBinding(entry.binding, next)) entry.refresh(next[3]);\n }\n }\n this.#sync(bindings);\n let userCleanup: RefCleanup;\n try {\n userCleanup = applyRef(userRef, this.#node);\n } catch (error) {\n // React gets no cleanup from a ref that threw, and later only calls it\n // with `null`, which carries no node. Detach now so the bindings just\n // subscribed do not outlive the element; the error is React's to handle.\n this.#detach(token, bindings);\n throw error;\n }\n return () => {\n // A throwing user cleanup is still reported by React, but must not keep\n // the bindings subscribed to an element React is letting go of.\n try {\n if (typeof userCleanup === \"function\") userCleanup();\n else applyRef(userRef, null);\n } finally {\n this.#detach(token, bindings);\n }\n };\n }\n\n /**\n * Hands the node back to React for the attach identified by `token`: writes\n * are held back from now on, and the bindings are disposed in a microtask\n * unless the same node is attached again first (see the class doc).\n */\n #detach(token: number, bindings: readonly Binding[]): void {\n // React detaches the old ref before attaching the new one, so a newer\n // attach can only exist here if this detach is stale.\n if (token !== this.#token) return;\n this.#detached = true;\n // React detaches a host's ref right before it diffs the host's props, and\n // that diff starts from the snapshot it was handed, not from what the\n // bindings wrote since. Hand the node back to that snapshot, or a plain\n // value equal to it is skipped and the signal's last value stays in the\n // DOM. `#mounted` lines up with `bindings` (see `#sync`), and a snapshot\n // change gives the element a new ref (`getBindingRef`), so this is the\n // committed one. A re-attach in the same commit refreshes right after.\n this.#mounted.forEach((entry, index) => entry.restore?.(bindings[index]![3]));\n queueMicrotask(() => {\n if (this.#detached && token === this.#token) this.#dispose();\n });\n }\n\n #dispose(): void {\n const mounted = this.#mounted;\n this.#mounted = [];\n for (const binding of mounted) binding.dispose();\n }\n\n #sync(bindings: readonly Binding[]): void {\n const mounted = this.#mounted;\n // The common re-attach — a re-render that changed nothing about the\n // bindings — costs one walk and allocates nothing.\n if (\n mounted.length === bindings.length\n && mounted.every((entry, index) => isSameBinding(entry.binding, bindings[index]))\n ) {\n return;\n }\n\n // Keyed by prop name, which is unique per element: a binding whose source\n // or kind changed under the same name is a rebuild, not a reuse.\n const reusable = new Map<string, MountedBinding>();\n for (const entry of mounted) reusable.set(entry.binding[0], entry);\n\n const reused = bindings.map((binding) => {\n const candidate = reusable.get(binding[0]);\n if (candidate === undefined || !isSameBinding(candidate.binding, binding)) return undefined;\n reusable.delete(binding[0]);\n return candidate;\n });\n\n // A `\"style\"` binding being replaced under the same name is the only record\n // of which CSS properties it actually wrote to the node (an off-render\n // write may have applied keys React never saw). Its replacement starts from\n // that set, plus its own snapshot's keys, so its first write can still\n // clear them.\n const staleStyleKeys = new Map<string, readonly string[]>();\n for (const stale of reusable.values()) {\n if (stale.getStyleKeys !== undefined) staleStyleKeys.set(stale.binding[0], stale.getStyleKeys());\n }\n\n // Everything stale is disposed before anything replacing it is mounted, so\n // a rebuilt binding never briefly holds two live subscriptions on one node.\n for (const stale of reusable.values()) stale.dispose();\n const node = this.#node;\n this.#mounted = bindings.map(\n (binding, index) => reused[index] ?? mountBinding(node, binding, this, staleStyleKeys.get(binding[0])),\n );\n }\n}\n\nconst nodeBinders = new WeakMap<Element, NodeBinder>();\n\nfunction createBindingRef(bindings: readonly Binding[], userRef: SupportedRef): (node: Element | null) => RefCleanup {\n return (node) => {\n // React 19 detaches through the returned cleanup; a `null` call only comes\n // from a host that ignores cleanups, where the next attach reconciles.\n if (node == null) return;\n let binder = nodeBinders.get(node);\n if (binder === undefined) {\n binder = new NodeBinder(node);\n nodeBinders.set(node, binder);\n }\n return binder.attach(bindings, userRef);\n };\n}\n\ntype BindingRefEntry = {\n readonly bindings: readonly Binding[];\n readonly userRef: SupportedRef;\n readonly ref: (node: Element | null) => RefCleanup;\n};\n\n// Recently created binding refs, so re-rendering an element with the same\n// signals and the same user ref hands React the same callback and React does\n// not detach and re-attach it at all. Keyed weakly by the user ref when there\n// is one (so the cache lives exactly as long as that ref) and otherwise by the\n// first bound signal, with a small bound per key so an element whose bindings\n// keep changing cannot grow it.\nconst bindingRefs = new WeakMap<object, BindingRefEntry[]>();\nconst BINDING_REF_CACHE_LIMIT = 8;\n\n// Also compares snapshots, so a ref is only ever attached for the exact values\n// React was handed: the detach in `NodeBinder` restores to those.\nfunction haveSameBindings(a: readonly Binding[], b: readonly Binding[]): boolean {\n return a.length === b.length\n && a.every((binding, index) => isSameBinding(binding, b[index]) && hasSameSnapshot(binding, b[index]!));\n}\n\nfunction getBindingRef(bindings: readonly Binding[], userRef: SupportedRef): (node: Element | null) => RefCleanup {\n // A user ref is an object or function, never one of the bound signals, so\n // the two kinds of key cannot collide in one map.\n const cacheKey: object = userRef ?? bindings[0]![1];\n const cache = bindingRefs;\n let entries = cache.get(cacheKey);\n if (entries !== undefined) {\n for (const entry of entries) {\n if (entry.userRef === userRef && haveSameBindings(entry.bindings, bindings)) return entry.ref;\n }\n } else {\n entries = [];\n cache.set(cacheKey, entries);\n }\n const ref = createBindingRef(bindings, userRef);\n if (entries.length >= BINDING_REF_CACHE_LIMIT) entries.shift();\n entries.push({ bindings, userRef, ref });\n return ref;\n}\n\ntype CreateElement = (type: React.ElementType, props: unknown, key?: React.Key) => React.ReactElement;\n\n/**\n * Scans a native host element's props for anything reactive (see\n * `isReactiveHostProp`). Kept separate from building the transformed props\n * copy in `transformHostProps` so that function can decide whether a copy is\n * needed at all before ever allocating one.\n */\nfunction findHostBindings(props: HostProps, tagName: string): Binding[] {\n const bindings: Binding[] = [];\n for (const [name, value] of Object.entries(props)) {\n if (isReactiveHostProp(name, value)) {\n const kind = resolveBindingKind(tagName, name);\n bindings.push([name, value, kind, readInitialValue(value, kind)]);\n }\n }\n return bindings;\n}\n\n/**\n * Transforms a native host element's (`<div>`, `<svg>`, ...) props: replaces\n * any directly-bound prop with its initial, non-reactive value (`bindings`\n * carries the reactive ones for the binding ref to mount later — see\n * `createJsxWrapper`) and normalizes a signal/array `children` the same way\n * `Fragment` does.\n *\n * The overwhelmingly common host element has neither. Scanning first and only\n * allocating a copy when something is actually found means a plain\n * `<div className=\"card\">…</div>` costs one prop walk and zero extra\n * allocations — the original props object is returned as-is (see the\n * `bindings.length === 0 && !childrenNeedNormalization` branch below), and\n * `createJsxWrapper` passes it straight to `factory` unchanged.\n */\nfunction transformHostProps(type: string, input: unknown): { props: HostProps; bindings: Binding[] } {\n const inputProps = (input ?? {}) as HostProps;\n const isHtmlHost = !NON_HTML_HOST_ELEMENTS.has(type);\n const bindings = isHtmlHost ? findHostBindings(inputProps, type) : [];\n\n const rawChildren = inputProps.children;\n const childrenNeedNormalization =\n \"children\" in inputProps && (isSignal(rawChildren) || Array.isArray(rawChildren));\n\n if (bindings.length === 0 && !childrenNeedNormalization) {\n return { props: inputProps, bindings };\n }\n\n // Something needs to change, so — and only so — a copy is made; the\n // original `inputProps` (and, transitively, whatever object the caller\n // passed as `input`) is never mutated.\n const props: HostProps = { ...inputProps };\n if (childrenNeedNormalization) {\n props.children = normalizeChild(rawChildren);\n }\n for (const [name, , kind, snapshot] of bindings) {\n // A two-way kind is only ever derived from a `value`/`checked` name (see\n // `resolveBindingKind`), so the lookup always hits; should it ever not, the\n // prop is written directly, which is the pre-substitution behaviour.\n const uncontrolledName = isTwoWayBindingKind(kind) ? UNCONTROLLED_PROP_NAMES[name] : undefined;\n if (uncontrolledName !== undefined) {\n // Leaving the controlled prop in place would keep the element\n // React-controlled, so an unrelated re-render of the owner would\n // re-diff and potentially re-write this prop — work relying on an\n // internal React guard (skipping a same-value write) rather than a\n // documented one. Substituting the uncontrolled prop instead means\n // React only ever reads it once, at mount, and never touches this\n // property again — see development/design/direct-binding-value-checked-style.md.\n delete props[name];\n props[uncontrolledName] = snapshot;\n } else {\n props[name] = snapshot;\n }\n }\n return { props, bindings };\n}\n\n/**\n * `Fragment`'s only prop worth transforming is `children`, and only when it\n * is itself a signal or array — `normalizeChild` is the identity for\n * anything else (see its definition) — so a plain `<>...</>` with ordinary\n * children is passed straight through, uncopied, the same way a custom\n * component is below.\n */\nfunction transformFragmentProps(input: unknown): unknown {\n const props = input as HostProps | null;\n if (\n props == null\n || !(\"children\" in props)\n || (!isSignal(props.children) && !Array.isArray(props.children))\n ) {\n return input;\n }\n return { ...props, children: normalizeChild(props.children) };\n}\n\n/**\n * A host element's final props: the transformed copy with the binding ref in\n * place of the user's own ref, which the binding ref forwards to. `props` is\n * always a fresh copy whenever there are bindings (see `transformHostProps`).\n */\nfunction withBindingRef(props: HostProps, bindings: readonly Binding[]): HostProps {\n if (bindings.length > 0) props.ref = getBindingRef(bindings, props.ref as SupportedRef);\n return props;\n}\n\n/** Creates a JSX wrapper while letting each module supply React's JSX factory. */\nexport function createJsxWrapper(factory: CreateElement): CreateElement {\n return (type, input, key) => {\n if (typeof type === \"string\") {\n // The element keeps its own host type whether or not any prop is a\n // signal, and its key is passed straight through, so React reconciles it\n // exactly as it would the plain element.\n const { props, bindings } = transformHostProps(type, input);\n return factory(type, withBindingRef(props, bindings), key);\n }\n\n if (type === Fragment) {\n return factory(type, transformFragmentProps(input), key);\n }\n\n // Every other type — function/class components, `memo`, `forwardRef`,\n // Context.Provider/Consumer, Suspense, lazy, ... — receives its props\n // exactly as its caller passed them. None of these were ever touched by\n // children normalization or the reactive-prop scan above, even before\n // this fast path existed, so skipping the copy here changes nothing\n // observable and removes an allocation nothing downstream ever read.\n return factory(type, input, key);\n };\n}\n\n/**\n * The classic-runtime `createElement` that the automatic runtime falls back to\n * for `<div {...props} key=\"k\" />` — TypeScript, Babel and Oxc all import it\n * from the package root of `jsxImportSource`. It applies the same host-prop\n * bindings and child normalization as `jsx`, and leaves `key` (and `ref`) in\n * the config for React's own `createElement` to extract.\n */\nexport function createSignalAwareElement(\n type: React.ElementType,\n config?: Record<string, unknown> | null,\n ...children: unknown[]\n): React.ReactElement {\n if (typeof type !== \"string\" && type !== Fragment) {\n return createElement(type, config, ...(children as React.ReactNode[]));\n }\n const normalizedChildren = children.map((child) => normalizeChild(child)) as React.ReactNode[];\n if (typeof type !== \"string\") {\n return createElement(type, config, ...normalizedChildren);\n }\n const { props, bindings } = transformHostProps(type, config ?? {});\n return createElement(type, withBindingRef(props, bindings), ...normalizedChildren);\n}\n\ntype Signalable<T> = T | (ReadonlySignal<T> & NotDeepSignal);\ntype DirectSignalPropName = \"title\" | \"id\" | \"className\" | \"hidden\" | \"disabled\" | \"style\" | \"value\" | \"checked\";\ntype AriaPropName = `aria-${string}`;\ntype AddSignalChildren<P> = Omit<P, \"children\"> & {\n children?: SignalChild;\n};\ntype SignalizeKnownHtmlProps<P> = {\n [Name in keyof P as Name extends DirectSignalPropName | AriaPropName ? Name : never]: Signalable<P[Name]>;\n};\ntype AddHtmlSignalProps<P> = Omit<P, DirectSignalPropName | AriaPropName | \"children\"> & {\n [Name in keyof SignalizeKnownHtmlProps<P>]: SignalizeKnownHtmlProps<P>[Name];\n} & {\n [name: `data-${string}`]: Signalable<string | number | boolean | undefined>;\n} & AddSignalChildren<{}>;\n\n/** Types exposed by `jsxImportSource: \"react-fine-grained-signals\"`. */\nexport namespace JSX {\n export type ElementType = React.JSX.ElementType;\n export interface Element extends React.JSX.Element {}\n export interface ElementClass extends React.JSX.ElementClass {}\n export interface ElementAttributesProperty extends React.JSX.ElementAttributesProperty {}\n export interface ElementChildrenAttribute extends React.JSX.ElementChildrenAttribute {}\n export type LibraryManagedAttributes<C, P> = React.JSX.LibraryManagedAttributes<C, P>;\n export interface IntrinsicAttributes extends React.JSX.IntrinsicAttributes {}\n export interface IntrinsicClassAttributes<T> extends React.JSX.IntrinsicClassAttributes<T> {}\n // An interface (rather than the mapped type itself) so consumers can merge\n // their own elements into it, as they can into React's. Elements added to\n // React's own `JSX.IntrinsicElements` flow through the mapped type as well.\n export interface IntrinsicElements extends SignalIntrinsicElements {}\n}\n\ntype SignalIntrinsicElements = {\n [Tag in keyof React.JSX.IntrinsicElements]: Tag extends NonHtmlHostElement\n ? AddSignalChildren<React.JSX.IntrinsicElements[Tag]>\n : AddHtmlSignalProps<React.JSX.IntrinsicElements[Tag]>;\n};\n"],"mappings":";;;;AAoDA,SAAS,aAAa,OAAiC;CACrD,OAAQ,OAAO,UAAU,YAAY,UAAU,QAAS,OAAO,UAAU;AAC3E;AAEA,SAAS,iBAAiB,OAAqB;CAC7C,IAAI,CAAC,OAAO,aAAa,KAAK,GAC5B,MAAM,IAAI,UAAU,4DAA4D;AAEpF;AAEA,SAAS,qBAAqB,OAAqB;CACjD,KAAK,MAAM,OAAO,QAAQ,QAAQ,KAAK,GAAG;EACxC,MAAM,aAAa,QAAQ,yBAAyB,OAAO,GAAG;EAC9D,IAAI,eAAe,KAAA,KAAa,EAAE,WAAW,aAC3C,MAAM,IAAI,UAAU,mDAAmD;CAE3E;AACF;AAEA,SAAS,mBAAmB,QAA2B;CACrD,MAAM,SAAoB,CAAC;CAC3B,OAAO,SAAS;CAChB,OAAO;AACT;AAEA,SAAS,aAAa,KAAiC;CACrD,IAAI,OAAO,QAAQ,YAAY,QAAQ,IAAI,OAAO;CAClD,MAAM,QAAQ,OAAO,GAAG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;EAC3B,IAAI,OAAO,SAAS,UAAU;GAI5B,MAAM,EAAE,OAAO,aAAa,mBAAmB,MAAM,KAAK;GAC1D,OAAO,QAAQ,MAAM,eAAe,OAAO,QAAQ,GAAG,GAAG;EAC3D;EAEA,IAAI,SAAS,UACX,OAAO,QAAQ,MAAM,uBAAuB,KAAK,GAAG,GAAG;EASzD,OAAO,QAAQ,MAAM,OAAO,GAAG;CACjC;AACF;;;;;;;;AASA,SAAgB,yBACd,MACA,QACA,GAAG,UACiB;CACpB,IAAI,OAAO,SAAS,YAAY,SAAS,UACvC,OAAO,cAAc,MAAM,QAAQ,GAAI,QAA8B;CAEvE,MAAM,qBAAqB,SAAS,KAAK,UAAU,eAAe,KAAK,CAAC;CACxE,IAAI,OAAO,SAAS,UAClB,OAAO,cAAc,MAAM,QAAQ,GAAG,kBAAkB;CAE1D,MAAM,EAAE,OAAO,aAAa,mBAAmB,MAAM,UAAU,CAAC,CAAC;CACjE,OAAO,cAAc,MAAM,eAAe,OAAO,QAAQ,GAAG,GAAG,kBAAkB;AACnF"}
@@ -1,7 +1,7 @@
1
- import { t as JSX } from "./jsx-Xp5q2y97.js";
1
+ import { t as JSX } from "./jsx-BQGrTir3.js";
2
2
  import { Fragment, jsxDEV as jsxDEV$1 } from "react/jsx-dev-runtime";
3
3
  //#region src/jsx-dev-runtime.d.ts
4
4
  /** Development JSX factory for `jsxImportSource: "react-fine-grained-signals"`. */
5
- declare function jsxDEV(type: Parameters<typeof jsxDEV$1>[0], props: Parameters<typeof jsxDEV$1>[1], key: Parameters<typeof jsxDEV$1>[2], isStaticChildren: Parameters<typeof jsxDEV$1>[3], source: Parameters<typeof jsxDEV$1>[4], self: Parameters<typeof jsxDEV$1>[5]): import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
5
+ export declare function jsxDEV(type: Parameters<typeof jsxDEV$1>[0], props: Parameters<typeof jsxDEV$1>[1], key: Parameters<typeof jsxDEV$1>[2], isStaticChildren: Parameters<typeof jsxDEV$1>[3], source: Parameters<typeof jsxDEV$1>[4], self: Parameters<typeof jsxDEV$1>[5]): import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
6
6
  //#endregion
7
- export { Fragment, type JSX, jsxDEV };
7
+ export { Fragment, type JSX };
@@ -1,4 +1,4 @@
1
- import { t as createJsxWrapper } from "./jsx-D9U6dSwL.js";
1
+ import { t as createJsxWrapper } from "./jsx-P6volZdr.js";
2
2
  import { Fragment, jsxDEV as jsxDEV$1 } from "react/jsx-dev-runtime";
3
3
  //#region src/jsx-dev-runtime.ts
4
4
  /** Development JSX factory for `jsxImportSource: "react-fine-grained-signals"`. */
@@ -1,9 +1,9 @@
1
- import { t as JSX } from "./jsx-Xp5q2y97.js";
1
+ import { t as JSX } from "./jsx-BQGrTir3.js";
2
2
  import { Fragment } from "react/jsx-runtime";
3
3
  //#region src/jsx-runtime.d.ts
4
4
  /** JSX factory for `jsxImportSource: "react-fine-grained-signals"`. */
5
- declare const jsx: (type: import("react").ElementType, props: unknown, key?: import("react").Key) => import("react").ReactElement;
5
+ export declare const jsx: (type: import("react").ElementType, props: unknown, key?: import("react").Key) => import("react").ReactElement;
6
6
  /** Static-children JSX factory for `jsxImportSource: "react-fine-grained-signals"`. */
7
- declare const jsxs: (type: import("react").ElementType, props: unknown, key?: import("react").Key) => import("react").ReactElement;
7
+ export declare const jsxs: (type: import("react").ElementType, props: unknown, key?: import("react").Key) => import("react").ReactElement;
8
8
  //#endregion
9
- export { Fragment, type JSX, jsx, jsxs };
9
+ export { Fragment, type JSX };
@@ -1,4 +1,4 @@
1
- import { t as createJsxWrapper } from "./jsx-D9U6dSwL.js";
1
+ import { t as createJsxWrapper } from "./jsx-P6volZdr.js";
2
2
  import { Fragment, jsx as jsx$1, jsxs as jsxs$1 } from "react/jsx-runtime";
3
3
  //#region src/jsx-runtime.ts
4
4
  /** JSX factory for `jsxImportSource: "react-fine-grained-signals"`. */
package/dist/runtime.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { n as useManagedSignals, t as ManagedSignalsStore } from "./use-signals-CBDbbAbV.js";
2
- export { type ManagedSignalsStore, useManagedSignals, useManagedSignals as useSignals };
1
+ import { n as useManagedSignals, t as ManagedSignalsStore } from "./use-signals-CJYcdFdL.js";
2
+ export { type ManagedSignalsStore, useManagedSignals };
package/dist/runtime.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as useManagedSignals } from "./use-signals-8i2B-94o.js";
2
- export { useManagedSignals, useManagedSignals as useSignals };
1
+ import { t as useManagedSignals } from "./use-signals-C1K8-vJX.js";
2
+ export { useManagedSignals };
@@ -0,0 +1,169 @@
1
+ import { t as coreRuntime } from "./core-runtime-2jSE9Tz5.js";
2
+ import { useEffect, useInsertionEffect, useLayoutEffect, useMemo, useSyncExternalStore } from "react";
3
+ //#region src/react/react-adapter.mts
4
+ function createAlienDerivedReactAdapter(_core, render) {
5
+ function isInteropProtocol(dependency) {
6
+ return Reflect.get(dependency, "version") === 1 && typeof Reflect.get(dependency, "getRevision") === "function" && typeof Reflect.get(dependency, "subscribe") === "function";
7
+ }
8
+ function dependencyVersion(dependency) {
9
+ return isInteropProtocol(dependency) ? dependency.getRevision() : render.getRenderVersion(dependency);
10
+ }
11
+ function subscribeDependency(dependency, notify) {
12
+ if (isInteropProtocol(dependency)) return dependency.subscribe(() => notify()).unsubscribe;
13
+ const subscribeRender = Reflect.get(dependency, "subscribeRender");
14
+ if (typeof subscribeRender === "function") return subscribeRender.call(dependency, notify);
15
+ return render.subscribeReadables([dependency], notify);
16
+ }
17
+ function snapshot(readable, cache) {
18
+ const captured = render.captureRenderSnapshot(readable);
19
+ const current = cache.current;
20
+ if (current !== void 0 && current.dependencies.size === captured.dependencies.size && [...captured.dependencies].every(([dependency, revision]) => current.dependencies.get(dependency) === revision && dependencyVersion(dependency) === revision)) return current.value;
21
+ cache.current = captured;
22
+ return captured.value;
23
+ }
24
+ class RenderStore {
25
+ #mode;
26
+ #subscriptions = /* @__PURE__ */ new Map();
27
+ #combinedDependencies = /* @__PURE__ */ new Set();
28
+ #listeners = /* @__PURE__ */ new Set();
29
+ #version = 0;
30
+ #lifecycle = 0;
31
+ constructor(mode) {
32
+ this.#mode = mode;
33
+ }
34
+ getSnapshot = () => this.#version;
35
+ subscribe = (listener) => {
36
+ this.#listeners.add(listener);
37
+ return () => this.#listeners.delete(listener);
38
+ };
39
+ begin(scopePolicy) {
40
+ const attempt = render.createRenderAttempt();
41
+ attempt.restoreScope = render.pushRenderScope(attempt, scopePolicy);
42
+ queueMicrotask(() => this.finish(attempt));
43
+ return attempt;
44
+ }
45
+ finish(attempt) {
46
+ attempt?.restoreScope?.();
47
+ attempt.restoreScope = void 0;
48
+ }
49
+ commit(attempt) {
50
+ this.#lifecycle += 1;
51
+ this.finish(attempt);
52
+ let changedDuringRender = !render.promoteRenderAttempt(attempt);
53
+ const desired = attempt.dependencies;
54
+ if (this.#mode === "combined") {
55
+ const local = new Set([...desired.keys()].filter((dependency) => !isInteropProtocol(dependency)));
56
+ if (!(local.size === this.#combinedDependencies.size && [...local].every((dependency) => this.#combinedDependencies.has(dependency)))) {
57
+ this.#subscriptions.get(this)?.();
58
+ this.#subscriptions.delete(this);
59
+ this.#combinedDependencies = local;
60
+ if (local.size > 0) this.#subscriptions.set(this, render.subscribeReadables([...local], this.#notify));
61
+ }
62
+ for (const [dependency, unsubscribe] of this.#subscriptions) if (dependency !== this && (!isInteropProtocol(dependency) || !desired.has(dependency))) {
63
+ unsubscribe();
64
+ this.#subscriptions.delete(dependency);
65
+ }
66
+ for (const dependency of desired.keys()) if (isInteropProtocol(dependency) && !this.#subscriptions.has(dependency)) this.#subscriptions.set(dependency, subscribeDependency(dependency, this.#notify));
67
+ } else {
68
+ for (const [dependency, unsubscribe] of this.#subscriptions) if (!desired.has(dependency)) {
69
+ unsubscribe();
70
+ this.#subscriptions.delete(dependency);
71
+ }
72
+ for (const dependency of desired.keys()) if (!this.#subscriptions.has(dependency)) this.#subscriptions.set(dependency, subscribeDependency(dependency, this.#notify));
73
+ }
74
+ if (!render.settleRenderAttempt(attempt)) changedDuringRender = true;
75
+ if (changedDuringRender) this.#notify();
76
+ }
77
+ #notify = () => {
78
+ this.#version = this.#version + 1 | 0;
79
+ for (const listener of this.#listeners) listener();
80
+ };
81
+ dispose() {
82
+ for (const unsubscribe of this.#subscriptions.values()) unsubscribe();
83
+ this.#subscriptions.clear();
84
+ this.#combinedDependencies.clear();
85
+ }
86
+ scheduleDispose() {
87
+ const lifecycle = ++this.#lifecycle;
88
+ queueMicrotask(() => {
89
+ if (this.#lifecycle === lifecycle) this.dispose();
90
+ });
91
+ }
92
+ activate() {
93
+ this.#lifecycle += 1;
94
+ }
95
+ }
96
+ function createReactAdapter(runtimeOrOptions = {}, maybeOptions = {}) {
97
+ const mode = maybeOptions.mode ?? runtimeOrOptions.mode ?? "combined";
98
+ if (mode !== "combined" && mode !== "per-readable") throw new Error(`Unknown render subscription mode: ${mode}`);
99
+ function useSignalValue(readable) {
100
+ const subscribe = useMemo(() => (notify) => subscribeDependency(readable, notify), [readable]);
101
+ const cache = useMemo(() => ({
102
+ readable,
103
+ current: void 0
104
+ }), [readable]);
105
+ const getSnapshot = useMemo(() => () => snapshot(readable, cache), [readable, cache]);
106
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
107
+ }
108
+ function useTrackingStore(scopePolicy) {
109
+ const store = useMemo(() => new RenderStore(mode), []);
110
+ useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
111
+ const attempt = store.begin(scopePolicy);
112
+ useInsertionEffect(() => {
113
+ store.finish(attempt);
114
+ }, [store, attempt]);
115
+ useLayoutEffect(() => {
116
+ store.commit(attempt);
117
+ }, [store, attempt]);
118
+ useEffect(() => {
119
+ store.activate();
120
+ return () => store.scheduleDispose();
121
+ }, [store]);
122
+ return {
123
+ store,
124
+ attempt
125
+ };
126
+ }
127
+ function useSignalTracking() {
128
+ useTrackingStore("bare");
129
+ }
130
+ function useManagedSignals() {
131
+ const { store, attempt } = useTrackingStore("managed");
132
+ return {
133
+ finish: () => store.finish(attempt),
134
+ getSnapshot: store.getSnapshot
135
+ };
136
+ }
137
+ return {
138
+ useSignalValue,
139
+ useSignalTracking,
140
+ useManagedSignals
141
+ };
142
+ }
143
+ function managed(scope, callback) {
144
+ try {
145
+ return callback();
146
+ } finally {
147
+ scope.finish();
148
+ }
149
+ }
150
+ return {
151
+ createReactAdapter,
152
+ managed
153
+ };
154
+ }
155
+ //#endregion
156
+ //#region src/react/use-signals.ts
157
+ const reactAdapter = createAlienDerivedReactAdapter(coreRuntime, coreRuntime.renderAdapter).createReactAdapter();
158
+ /** Best-effort render tracking for untransformed components. */
159
+ function useSignalTracking() {
160
+ reactAdapter.useSignalTracking();
161
+ }
162
+ /** Exact render scope used by the transform-managed boundary. */
163
+ function useManagedSignals() {
164
+ return reactAdapter.useManagedSignals();
165
+ }
166
+ //#endregion
167
+ export { useSignalTracking as n, useManagedSignals as t };
168
+
169
+ //# sourceMappingURL=use-signals-C1K8-vJX.js.map