{"version":3,"file":"animate-jcotZdO1.cjs","sources":["../src/scheduler/driver.ts","../src/scheduler/scheduler.ts","../src/scheduler/shared.ts","../src/physics/easings.ts","../src/value/warn.ts","../src/physics/easing-registry.ts","../src/a11y/config.ts","../src/a11y/reduced-motion.ts","../src/physics/decay.ts","../src/physics/motion.ts","../src/physics/spring.ts","../src/physics/tween.ts","../src/value/lifecycle.ts","../src/value/thenable.ts","../src/value/animatable.ts","../src/dom/transform.ts","../src/dom/bind-style.ts","../src/value/value-type.ts","../src/dom/read-style.ts","../src/dom/bind-property.ts","../src/value/channel-group.ts","../src/value/types/color.ts","../src/value/types/complex.ts","../src/value/types/length.ts","../src/value/types/number.ts","../src/value/registry.ts","../src/compose/wait.ts","../src/dom/keyframes.ts","../src/dom/resolve-target.ts","../src/dom/resolve-value.ts","../src/dom/units.ts","../src/dom/animate.ts"],"sourcesContent":["/** Cancels a frame scheduled via FrameDriver.schedule. */\nexport type CancelFrame = () => void\n\n/**\n * Source of display frames. The production driver wraps requestAnimationFrame;\n * tests inject a manual driver to control timestamps deterministically.\n * The scheduler is the only consumer - no other module may schedule frames.\n */\nexport interface FrameDriver {\n  schedule(callback: (timestampMs: number) => void): CancelFrame\n}\n\n// Browser globals are only touched when schedule() is called, never at module\n// evaluation - importing the core must stay safe under SSR.\nexport const rafDriver: FrameDriver = {\n  schedule(callback) {\n    const id = requestAnimationFrame(callback)\n    return () => cancelAnimationFrame(id)\n  },\n}\n","import type { CancelFrame, FrameDriver } from './driver'\n\nexport interface FrameInfo {\n  /** Time since the previous frame, in ms. 0 on the first frame after a wake. */\n  deltaMs: number\n  /** Driver timestamp of this frame, in ms. */\n  timestampMs: number\n}\n\nexport type FrameCallback = (frame: FrameInfo) => void\n\n/**\n * 'update' (default) runs simulations; 'render' runs DOM writes, after every\n * update of the same tick. A render subscription made during the update phase\n * still runs this tick - that is what lets bindings batch all style writes\n * produced by a frame into a single flush.\n */\nexport type FramePhase = 'update' | 'render'\n\nexport interface Scheduler {\n  /** Register a per-frame callback. Starts the loop if it was sleeping. */\n  subscribe(callback: FrameCallback, phase?: FramePhase): () => void\n  isRunning(): boolean\n}\n\n/**\n * Upper bound on the delta fed to subscribers. After a freeze (inactive tab,\n * GC pause, breakpoint) the lost time is dropped, never replayed: physics\n * must not teleport.\n */\nexport const MAX_FRAME_DELTA_MS = 64\n\nexport function createScheduler(driver: FrameDriver): Scheduler {\n  const updateSubscribers = new Set<FrameCallback>()\n  const renderSubscribers = new Set<FrameCallback>()\n  let cancelFrame: CancelFrame | null = null\n  let lastTimestampMs: number | null = null\n  let running = false\n  let inTick = false\n\n  const count = () => updateSubscribers.size + renderSubscribers.size\n\n  const stop = () => {\n    cancelFrame?.()\n    cancelFrame = null\n    lastTimestampMs = null\n    running = false\n  }\n\n  // Snapshot: subscriptions made during a phase start at that phase's next\n  // run. The membership check skips callbacks removed earlier in the tick.\n  const runPhase = (subscribers: Set<FrameCallback>, frame: FrameInfo) => {\n    for (const callback of [...subscribers]) {\n      if (subscribers.has(callback)) callback(frame)\n    }\n  }\n\n  const tick = (timestampMs: number) => {\n    const deltaMs =\n      lastTimestampMs === null\n        ? 0\n        : Math.min(timestampMs - lastTimestampMs, MAX_FRAME_DELTA_MS)\n    lastTimestampMs = timestampMs\n    const frame: FrameInfo = { deltaMs, timestampMs }\n\n    inTick = true\n    runPhase(updateSubscribers, frame)\n    runPhase(renderSubscribers, frame) // snapshot after updates: same-tick flushes\n    inTick = false\n\n    if (count() > 0) {\n      cancelFrame = driver.schedule(tick)\n    } else {\n      cancelFrame = null\n      stop()\n    }\n  }\n\n  return {\n    subscribe(callback, phase = 'update') {\n      const subscribers = phase === 'render' ? renderSubscribers : updateSubscribers\n      subscribers.add(callback)\n      if (!running) {\n        running = true\n        cancelFrame = driver.schedule(tick)\n      }\n      return () => {\n        subscribers.delete(callback)\n        // Mid-tick, the loop decides for itself at the end of the tick.\n        if (count() === 0 && running && !inTick) stop()\n      }\n    },\n    isRunning: () => running,\n  }\n}\n","import { rafDriver } from './driver'\nimport { createScheduler, type Scheduler } from './scheduler'\n\n// All animatables and bindings batch into the same rAF loop. Created lazily\n// so that merely importing the core never touches browser globals (SSR-safe).\nlet shared: Scheduler | null = null\n\nexport const getSharedScheduler = (): Scheduler => (shared ??= createScheduler(rafDriver))\n","/** Easing over normalized progress [0, 1] -> [0, 1]. */\nexport type Easing = (progress: number) => number\n\nexport const linear: Easing = (p) => p\nexport const easeInCubic: Easing = (p) => p * p * p\nexport const easeOutCubic: Easing = (p) => 1 - (1 - p) ** 3\nexport const easeInOutCubic: Easing = (p) => (p < 0.5 ? 4 * p ** 3 : 1 - (-2 * p + 2) ** 3 / 2)\n","// Deduplicated, prefixed console.warn for design-boundary conditions:\n// unconvertible units, snap fallbacks, shorthand traps. One message per key\n// for the lifetime of the process - never a per-frame log. Ships always-on\n// (no __DEV__ dual build: it would complicate the exports map and the size\n// gate); the message text is centralized and budgeted instead.\nconst seen = new Set<string>()\n\nexport function warnOnce(key: string, message: string): void {\n  if (seen.has(key)) return\n  seen.add(key)\n  console.warn(`[underlying] ${message}`)\n}\n\n/** Test-only: clears the dedup set so a fresh key warns again. Not exported from the entry. */\nexport function __resetWarnings(): void {\n  seen.clear()\n}\n","import { warnOnce } from '../value/warn'\nimport { easeInOutCubic, type Easing } from './easings'\n\n/** A passed easing: a function, or a named ease by string ('power2.out', 'elastic.out(1, 0.3)'). */\nexport type EasingInput = Easing | string\n\nexport type EasingVariant = 'in' | 'out' | 'inOut'\n\n/** Builds the actual easing for a named family, given the variant and any numeric params. */\nexport type EasingFactory = (variant: EasingVariant, params: ReadonlyArray<number>) => Easing\n\n// Named ease families live here. Nothing is registered at module scope - a\n// top-level set() would pin this into the primitives tree-shake graph;\n// @underlying/utils registers the families on import instead.\nconst registry = new Map<string, EasingFactory>()\n\n/** Register a named ease family ('power2', 'elastic', 'steps', ...) so strings resolve. */\nexport function registerEasing(name: string, factory: EasingFactory): void {\n  registry.set(name.toLowerCase(), factory)\n}\n\nconst SPEC = /^([a-z]+\\d*)(?:\\.(inout|in|out))?(?:\\(([^)]*)\\))?$/i\n\nconst parseSpec = (spec: string): { name: string; variant: EasingVariant; params: number[] } | null => {\n  const match = SPEC.exec(spec.trim())\n  if (match === null) return null\n  const variantRaw = match[2]?.toLowerCase()\n  const variant: EasingVariant = variantRaw === 'in' ? 'in' : variantRaw === 'inout' ? 'inOut' : 'out'\n  const params =\n    match[3] !== undefined && match[3].trim() !== '' ? match[3].split(',').map((part) => Number(part.trim())) : []\n  return { name: match[1]!.toLowerCase(), variant, params }\n}\n\n/**\n * Resolve a function-or-name into an Easing. Functions pass through untouched;\n * an unknown name warns once and falls back to easeInOutCubic.\n */\nexport function resolveEasing(input: EasingInput): Easing {\n  if (typeof input !== 'string') return input\n  const parsed = parseSpec(input)\n  if (parsed !== null) {\n    const factory = registry.get(parsed.name)\n    if (factory !== undefined) return factory(parsed.variant, parsed.params)\n  }\n  warnOnce(\n    `easing:${input}`,\n    `unknown easing \"${input}\" - import @underlying/utils to register named eases. Using easeInOutCubic.`,\n  )\n  return easeInOutCubic\n}\n","/**\n * What happens when the user prefers reduced motion:\n * - 'skip'  (default): animations land instantly on their rest state\n * - 'fade'  : movement snaps, element-level opacity still animates (animate())\n * - 'allow' : motion plays normally (only for essential, e.g. gesture-driven, motion)\n */\nexport type ReducedMotionBehavior = 'skip' | 'fade' | 'allow'\n\n/** Per-animation override on a raw value - fade only makes sense element-side. */\nexport type ReducedMotionOverride = 'skip' | 'allow'\n\nlet behavior: ReducedMotionBehavior = 'skip'\n\nexport const setReducedMotionBehavior = (next: ReducedMotionBehavior): void => {\n  behavior = next\n}\n\nexport const getReducedMotionBehavior = (): ReducedMotionBehavior => behavior\n","type ReducedMotionListener = (reduced: boolean) => void\n\n// Lazy: browser globals are only touched on first use, never at import\n// (SSR-safe). The media query is watched so mid-session OS toggles are\n// reflected in every subsequent animation start. An app-level override\n// (in-app accessibility toggle, demos, tests) takes precedence over the OS.\nlet initialized = false\nlet current = false\nlet override: boolean | null = null\nconst listeners = new Set<ReducedMotionListener>()\n\nconst effective = (): boolean => override ?? current\n\nconst notifyIfChanged = (before: boolean) => {\n  const after = effective()\n  if (after === before) return\n  for (const listener of [...listeners]) listener(after)\n}\n\nconst init = () => {\n  if (initialized) return\n  initialized = true\n  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return\n  const query = window.matchMedia('(prefers-reduced-motion: reduce)')\n  current = query.matches\n  query.addEventListener('change', (event) => {\n    const before = effective()\n    current = event.matches\n    notifyIfChanged(before)\n  })\n}\n\n/** Current effective preference (override, else OS). False when no DOM. */\nexport function prefersReducedMotion(): boolean {\n  init()\n  return effective()\n}\n\n/**\n * App-level override of the OS preference - in-app accessibility toggles.\n * `null` returns control to the OS media query.\n */\nexport function setReducedMotionOverride(value: boolean | null): void {\n  init()\n  const before = effective()\n  override = value\n  notifyIfChanged(before)\n}\n\n/** Notifies on effective preference changes. Returns an unsubscribe. */\nexport function onReducedMotionChange(listener: ReducedMotionListener): () => void {\n  init()\n  listeners.add(listener)\n  return () => {\n    listeners.delete(listener)\n  }\n}\n\n/** Test-only: clears the cached media query state. Not part of the public API. */\nexport function __resetReducedMotion(): void {\n  initialized = false\n  current = false\n  override = null\n  listeners.clear()\n}\n","import type { ReducedMotionOverride } from '../a11y/config'\nimport type { Simulation } from './simulation'\n\nexport interface DecayOptions {\n  /** Per-animation override of the reduced-motion behavior. */\n  reducedMotion?: ReducedMotionOverride\n  /** Initial velocity in units/s; defaults to the value's current velocity. */\n  velocity?: number\n  /** Exponential time constant, in ms. Higher = longer glide. Total distance ~ v0 * tau. */\n  timeConstant?: number\n  /** Rest when |velocity| < restSpeed (units/s). */\n  restSpeed?: number\n  /** Optional clamp boundary: crossing it turns the glide into a spring toward the edge. */\n  min?: number\n  max?: number\n  bounceStiffness?: number\n  bounceDamping?: number\n  restDelta?: number\n}\n\nexport function decaySimulation(options: DecayOptions = {}): Simulation {\n  const {\n    timeConstant = 325,\n    restSpeed = 0.1,\n    min,\n    max,\n    bounceStiffness = 500,\n    bounceDamping = 40,\n    restDelta = 0.01,\n  } = options\n  const tauS = timeConstant / 1000\n\n  // Latched: once a boundary is crossed the spring stays in charge, even back\n  // inside the range - otherwise inward velocity would decay-glide away from\n  // the edge instead of settling on it. One simulation instance per animation.\n  let edge: number | null = null\n  const checkEdge = (position: number): number | null => {\n    if (edge === null) {\n      if (min !== undefined && position < min) edge = min\n      else if (max !== undefined && position > max) edge = max\n    }\n    return edge\n  }\n\n  return {\n    acceleration(position, velocity) {\n      const boundary = checkEdge(position)\n      if (boundary !== null) return -bounceStiffness * (position - boundary) - bounceDamping * velocity\n      return -velocity / tauS\n    },\n    rest(position, velocity) {\n      const boundary = checkEdge(position)\n      if (boundary !== null) {\n        return Math.abs(velocity) < restSpeed && Math.abs(position - boundary) < restDelta\n          ? boundary\n          : null\n      }\n      return Math.abs(velocity) < restSpeed ? position : null\n    },\n  }\n}\n","import { stepSimulation, type Simulation, type SimulationState } from './simulation'\n\n/**\n * What the Animatable actually drives: anything that advances a\n * (position, velocity) state by fixed timesteps and knows when it is done.\n * Physics modes wrap a Simulation; the duration/easing escape hatch samples\n * a curve instead - same state shape, so handoff between modes is free.\n */\nexport interface Motion {\n  step(state: SimulationState, timestepS: number): SimulationState\n  /** Settled position when the state qualifies as rest, null while moving. */\n  rest(state: SimulationState): number | null\n}\n\n/**\n * A Motion whose elapsed clock can be repositioned: the seek seam for duration\n * tweens and baked-spring tables. A live spring/decay is NOT seekable - it has\n * no fixed durationS - so simulationMotion stays a plain Motion.\n */\nexport interface SeekableMotion extends Motion {\n  /** Reposition to an absolute elapsed time (seconds); returns the sample there. Next step() continues from it. */\n  seek(elapsedS: number): SimulationState\n  /** Total elapsed at rest (seconds). Tweens: the duration. Sampled tables: the last entry. */\n  readonly durationS: number\n}\n\nexport function simulationMotion(simulation: Simulation): Motion {\n  return {\n    step: (state, timestepS) => stepSimulation(simulation, state, timestepS),\n    rest: (state) => simulation.rest(state.position, state.velocity),\n  }\n}\n","import type { ReducedMotionOverride } from '../a11y/config'\nimport type { Simulation } from './simulation'\n\nexport interface SpringOptions {\n  /** Per-animation override of the reduced-motion behavior. */\n  reducedMotion?: ReducedMotionOverride\n  stiffness?: number\n  damping?: number\n  mass?: number\n  /** Initial velocity in units/s - handoff from a gesture (drag -> release). */\n  velocity?: number\n  /** Rest requires |position - target| < restDelta... */\n  restDelta?: number\n  /** ...AND |velocity| < restSpeed (units/s). */\n  restSpeed?: number\n}\n\n/** A spring whose target can be re-aimed in place: no Motion rebuild on a moving target (follow). */\nexport interface RetargetableSpring extends Simulation {\n  retarget(target: number): void\n}\n\nexport function springSimulation(target: number, options: SpringOptions = {}): RetargetableSpring {\n  const { stiffness = 100, damping = 10, mass = 1, restDelta = 0.01, restSpeed = 0.1 } = options\n  let aim = target\n  return {\n    acceleration: (position, velocity) => (-stiffness * (position - aim) - damping * velocity) / mass,\n    rest: (position, velocity) =>\n      Math.abs(velocity) < restSpeed && Math.abs(position - aim) < restDelta ? aim : null,\n    retarget: (next) => {\n      aim = next\n    },\n  }\n}\n","import type { ReducedMotionOverride } from '../a11y/config'\nimport { resolveEasing, type EasingInput } from './easing-registry'\nimport { easeInOutCubic } from './easings'\nimport type { SeekableMotion } from './motion'\nimport { SIMULATION_TIMESTEP_S, type SimulationState } from './simulation'\n\nexport interface ToOptions {\n  /** ms */\n  duration?: number\n  /** A function, or a named ease by string once @underlying/utils is imported ('power2.out'). */\n  easing?: EasingInput\n  /** Per-animation override of the reduced-motion behavior. */\n  reducedMotion?: ReducedMotionOverride\n}\n\n/**\n * Duration/easing escape hatch. Sampled on the same fixed-step clock as the\n * physics, with a finite-difference velocity - so even a tween can hand off\n * to a spring mid-flight. Incoming velocity is ignored: a tween is positional\n * control. Seekable: it owns its elapsed clock, so the playback layer can jump\n * the playhead. One instance per animation.\n */\nexport function tweenMotion(from: number, to: number, options: ToOptions = {}): SeekableMotion {\n  const durationS = (options.duration ?? 300) / 1000\n  const easing = resolveEasing(options.easing ?? easeInOutCubic)\n  let elapsedS = 0\n\n  const positionAt = (t: number): number => {\n    const progress = durationS <= 0 ? 1 : Math.min(Math.max(t, 0) / durationS, 1)\n    return progress >= 1 ? to : from + (to - from) * easing(progress)\n  }\n\n  return {\n    step(state, timestepS) {\n      elapsedS += timestepS\n      const position = positionAt(elapsedS)\n      return { position, velocity: (position - state.position) / timestepS }\n    },\n    rest: () => (elapsedS >= durationS ? to : null),\n    durationS,\n    seek(target): SimulationState {\n      elapsedS = durationS <= 0 ? durationS : Math.min(Math.max(target, 0), durationS)\n      const position = positionAt(elapsedS)\n      // Curve derivative via a central finite difference clamped to [0, durationS].\n      const hi = Math.min(elapsedS + SIMULATION_TIMESTEP_S, durationS)\n      const lo = Math.max(elapsedS - SIMULATION_TIMESTEP_S, 0)\n      const span = hi - lo\n      const velocity = span > 0 ? (positionAt(hi) - positionAt(lo)) / span : 0\n      return { position, velocity }\n    },\n  }\n}\n","// The animation lifecycle surface, shared by animatable, the playback handles, and\n// animate(). Callbacks ride the existing options object; physics builders never see\n// them (their option types stay lifecycle-blind), and a small per-run registry fans\n// the events. A handle also exposes eventCallback() to attach/replace them post-hoc.\n\n/** The lifecycle moments a run can emit. `repeat`/`reverseComplete` are playback-only. */\nexport type LifecycleEvent = 'start' | 'update' | 'complete' | 'interrupt' | 'repeat' | 'reverseComplete'\n\nexport interface LifecycleCallbacks<H = unknown> {\n  /** Fired once when the run begins (after any delay). Also fires on the reduced/instant path. */\n  onStart?(this: object, handle: H): void\n  /** Per frame with the live value. A number on animatable/playable; the values object on animate(). */\n  onUpdate?(this: object, value: number, handle: H): void\n  /** Natural settle to rest. Never fires for an Infinity-repeat run. Fires on the reduced/instant path. */\n  onComplete?(this: object, handle: H): void\n  /** Replaced, stopped, teleported, or disposed mid-flight. Never fires on the reduced/instant path. */\n  onInterrupt?(this: object, handle: H): void\n  /** Playable only: an iteration boundary (the iteration index is the run's repeat count so far). */\n  onRepeat?(this: object, handle: H): void\n  /** Playable only: a reversed leg reached its start. */\n  onReverseComplete?(this: object, handle: H): void\n  /** The `this` receiver for every callback. Defaults to the handle. */\n  scope?: object\n}\n\nconst EVENT_TO_KEY: Record<LifecycleEvent, keyof LifecycleCallbacks> = {\n  start: 'onStart',\n  update: 'onUpdate',\n  complete: 'onComplete',\n  interrupt: 'onInterrupt',\n  repeat: 'onRepeat',\n  reverseComplete: 'onReverseComplete',\n}\n\nexport interface LifecycleRegistry<H> {\n  /** Load the callbacks (and scope) from an options bag. Ignores a missing/empty bag. */\n  seed(callbacks: LifecycleCallbacks<H> | undefined): void\n  /** Attach or (with null) clear one event's callback - the post-hoc eventCallback path. Last writer wins. */\n  set(event: LifecycleEvent, fn: ((handle: H) => void) | null): void\n  /** True if anyone is listening for this event (lets callers skip work, e.g. force the JS path for `update`). */\n  has(event: LifecycleEvent): boolean\n  /** Invoke the event's callback with the configured scope (`update` also passes the value). */\n  fire(event: LifecycleEvent, handle: H, value?: number): void\n}\n\n// deno-lint-ignore no-explicit-any\ntype AnyFn = (...args: any[]) => void\n\nexport function lifecycleRegistry<H>(): LifecycleRegistry<H> {\n  const fns: Partial<Record<LifecycleEvent, AnyFn>> = {}\n  let scope: object | undefined\n\n  return {\n    seed(callbacks) {\n      if (callbacks === undefined) return\n      if (callbacks.scope !== undefined) scope = callbacks.scope\n      for (const event of Object.keys(EVENT_TO_KEY) as LifecycleEvent[]) {\n        const fn = callbacks[EVENT_TO_KEY[event]]\n        if (typeof fn === 'function') fns[event] = fn as AnyFn\n      }\n    },\n    set(event, fn) {\n      if (fn === null) delete fns[event]\n      else fns[event] = fn as AnyFn\n    },\n    has(event) {\n      return fns[event] !== undefined\n    },\n    fire(event, handle, value) {\n      const fn = fns[event]\n      if (fn === undefined) return\n      const receiver = scope ?? (handle as object)\n      if (event === 'update') fn.call(receiver, value, handle)\n      else fn.call(receiver, handle)\n    },\n  }\n}\n","// Handles are PromiseLike<void>: `await animate(...)` / `await handle` resolves\n// when the animation settles or is interrupted (never rejects, mirroring\n// `finished`). The `then` on every handle delegates to its `finished` promise.\n\n/** A PromiseLike `then` that resolves with void when the handle's `finished` does. */\nexport type ThenFn = <TResult1 = void, TResult2 = never>(\n  onfulfilled?: ((value: void) => TResult1 | PromiseLike<TResult1>) | null,\n  onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n) => Promise<TResult1 | TResult2>\n\n/** Build a handle's `then` from its `finished` promise (handles never reject). */\nexport const thenFinished =\n  (finished: Promise<void>): ThenFn =>\n  (onfulfilled, onrejected) =>\n    finished.then(onfulfilled ?? undefined, onrejected ?? undefined)\n","import { getReducedMotionBehavior, type ReducedMotionOverride } from '../a11y/config'\nimport { prefersReducedMotion } from '../a11y/reduced-motion'\nimport { decaySimulation, type DecayOptions } from '../physics/decay'\nimport { simulationMotion, type Motion } from '../physics/motion'\nimport { SIMULATION_TIMESTEP_S, type Simulation, type SimulationState } from '../physics/simulation'\nimport { springSimulation, type SpringOptions } from '../physics/spring'\nimport { tweenMotion, type ToOptions } from '../physics/tween'\nimport type { FrameInfo, Scheduler } from '../scheduler/scheduler'\nimport { getSharedScheduler } from '../scheduler/shared'\nimport { lifecycleRegistry, type LifecycleCallbacks, type LifecycleEvent, type LifecycleRegistry } from './lifecycle'\nimport { thenFinished, type ThenFn } from './thenable'\n\nexport interface AnimationHandle {\n  /** Resolves when the animation settles OR is interrupted. Never rejects. */\n  readonly finished: Promise<void>\n  /**\n   * Handles are awaitable: `await animate(...)` / `await handle` resolves when the\n   * animation settles or is interrupted (delegates to `finished`; never rejects).\n   */\n  then: ThenFn\n  /** Freezes the value in place - only if this animation is still the active one. */\n  stop(): void\n  /**\n   * Attach or (with `null`) replace a lifecycle callback after creation; last writer wins per event.\n   * Present on the handles that carry a lifecycle (spring/to/decay/simulate, playable, animate); use\n   * `?.` on a handle whose source may not (a composed/keyframe aggregate). Callbacks passed in the\n   * call always fire regardless.\n   */\n  eventCallback?(event: LifecycleEvent, fn: ((handle: AnimationHandle) => void) | null): AnimationHandle\n}\n\nexport interface AnimatableOptions {\n  /** Injection point for tests; defaults to the shared rAF scheduler. */\n  scheduler?: Scheduler\n}\n\nexport interface SetOptions {\n  /** Seed a velocity (units/s) along with the value - external handoffs (WAAPI reclaim, gestures). */\n  velocity?: number\n}\n\nexport interface SimulateOptions {\n  /** Initial velocity (units/s); defaults to the value's current velocity. */\n  velocity?: number\n  /** Per-animation override of the reduced-motion behavior. */\n  reducedMotion?: ReducedMotionOverride\n}\n\nexport interface Animatable {\n  get(): number\n  /** units/s */\n  velocity(): number\n  isAnimating(): boolean\n  /** Teleport: cancels any animation; velocity resets to 0 unless seeded. */\n  set(value: number, options?: SetOptions): void\n  /**\n   * Passive write of position+velocity: emits `change`, but does NOT freeze an\n   * active animation, fire `rest`, or zero velocity. The playback layer drives\n   * a value through this; the value stays a state holder.\n   */\n  drive(state: SimulationState): void\n  /** Freeze in place: position AND velocity stay readable. */\n  stop(): void\n  /** Retargets from the current position and velocity - interruptible at any time. */\n  spring(target: number, options?: SpringOptions & LifecycleCallbacks<AnimationHandle>): AnimationHandle\n  /** Glide on inertia from the current (or imposed) velocity; optional clamp boundaries. */\n  decay(options?: DecayOptions & LifecycleCallbacks<AnimationHandle>): AnimationHandle\n  /** Duration/easing escape hatch - still interruptible, with a readable derived velocity. */\n  to(target: number, options?: ToOptions & LifecycleCallbacks<AnimationHandle>): AnimationHandle\n  /**\n   * Drive the value with a custom Simulation - the general physics mode that\n   * spring/decay/to specialize. Runs from the current position and velocity on\n   * the same fixed-timestep clock, fully interruptible. Bring your own\n   * acceleration (gravity, a force field, a bounce) and rest condition.\n   */\n  simulate(simulation: Simulation, options?: SimulateOptions & LifecycleCallbacks<AnimationHandle>): AnimationHandle\n  on(event: 'change', listener: (value: number) => void): () => void\n  on(event: 'rest', listener: () => void): () => void\n  dispose(): void\n}\n\ninterface ActiveAnimation {\n  motion: Motion\n  prev: SimulationState\n  curr: SimulationState\n  accumulatorS: number\n  registry: LifecycleRegistry<AnimationHandle>\n  handle: AnimationHandle\n  /** True once onStart has fired - so a run replaced before it ever started emits nothing (re-entrancy safety). */\n  started: boolean\n  /** Resolve `finished`; on an interrupt also fire onInterrupt (onComplete is fired at the rest site). */\n  finish(reason: 'complete' | 'interrupt'): void\n}\n\nconst shouldSkip = (override?: ReducedMotionOverride): boolean => {\n  if (override === 'allow') return false\n  if (override === undefined && getReducedMotionBehavior() === 'allow') return false\n  return prefersReducedMotion()\n}\n\n// Backstop for motions that never rest (e.g. an undamped spring): give up\n// fast-forwarding and settle wherever the simulation stands.\nconst MAX_SKIP_STEPS = 100_000\n\nexport function animatable(initial: number, options: AnimatableOptions = {}): Animatable {\n  const scheduler = options.scheduler ?? getSharedScheduler()\n  const changeListeners = new Set<(value: number) => void>()\n  const restListeners = new Set<() => void>()\n\n  let position = initial\n  let velocity = 0\n  let active: ActiveAnimation | null = null\n  let unsubscribeFrames: (() => void) | null = null\n\n  const emitChange = () => {\n    for (const listener of [...changeListeners]) listener(position)\n  }\n\n  /** Detach the active animation, resolving its `finished`. State is left as-is. */\n  const freeze = (reason: 'complete' | 'interrupt') => {\n    const animation = active\n    if (animation === null) return\n    active = null\n    unsubscribeFrames?.()\n    unsubscribeFrames = null\n    animation.finish(reason)\n  }\n\n  const onFrame = ({ deltaMs }: FrameInfo) => {\n    const animation = active\n    if (animation === null) return\n    animation.accumulatorS += deltaMs / 1000\n\n    while (animation.accumulatorS >= SIMULATION_TIMESTEP_S) {\n      animation.accumulatorS -= SIMULATION_TIMESTEP_S\n      animation.prev = animation.curr\n      animation.curr = animation.motion.step(animation.curr, SIMULATION_TIMESTEP_S)\n\n      const rested = animation.motion.rest(animation.curr)\n      if (rested !== null) {\n        const before = position\n        position = rested // exact snap on the settle position\n        velocity = 0\n        freeze('complete')\n        emitChange()\n        if (position !== before) animation.registry.fire('update', animation.handle, position) // update only on a real change\n        for (const listener of [...restListeners]) listener()\n        animation.registry.fire('complete', animation.handle, position)\n        return\n      }\n    }\n\n    // The exposed state is interpolated between the two latest simulated\n    // steps: jitter-free rendering, and retargets inherit exactly what is\n    // visible on screen.\n    const alpha = animation.accumulatorS / SIMULATION_TIMESTEP_S\n    const previous = position\n    position = animation.prev.position + (animation.curr.position - animation.prev.position) * alpha\n    velocity = animation.prev.velocity + (animation.curr.velocity - animation.prev.velocity) * alpha\n    if (position !== previous) {\n      emitChange()\n      animation.registry.fire('update', animation.handle, position)\n    }\n  }\n\n  // Reduced motion (default 'skip'): the animation \"runs\" instantly - the\n  // simulation is fast-forwarded to its rest state in one synchronous pass,\n  // so even a decay with boundaries lands exactly where the full glide would.\n  const settleInstantly = (\n    motion: Motion,\n    state: SimulationState,\n    lifecycle?: LifecycleCallbacks<AnimationHandle>,\n  ): AnimationHandle => {\n    const registry = lifecycleRegistry<AnimationHandle>()\n    registry.seed(lifecycle)\n    const finished = Promise.resolve()\n    const handle: AnimationHandle = {\n      finished,\n      then: thenFinished(finished),\n      stop: () => {},\n      eventCallback(event, fn) {\n        registry.set(event, fn)\n        return handle\n      },\n    }\n    freeze('interrupt') // any in-flight animation is replaced by this instant settle\n    registry.fire('start', handle, position)\n    let current = state\n    let settled: number | null = null\n    for (let i = 0; i < MAX_SKIP_STEPS && settled === null; i++) {\n      current = motion.step(current, SIMULATION_TIMESTEP_S)\n      settled = motion.rest(current)\n    }\n    const previous = position\n    position = settled ?? current.position\n    velocity = 0\n    if (position !== previous) {\n      emitChange()\n      registry.fire('update', handle, position)\n    }\n    for (const listener of [...restListeners]) listener()\n    registry.fire('complete', handle, position)\n    return handle\n  }\n\n  const startAnimation = (\n    motion: Motion,\n    state: SimulationState,\n    lifecycle?: LifecycleCallbacks<AnimationHandle>,\n  ): AnimationHandle => {\n    const previous = active\n    let resolveFinished = () => {}\n    const finished = new Promise<void>((resolve) => {\n      resolveFinished = resolve\n    })\n    const registry = lifecycleRegistry<AnimationHandle>()\n    registry.seed(lifecycle)\n    const animation: ActiveAnimation = {\n      motion,\n      prev: state,\n      curr: state,\n      accumulatorS: 0,\n      registry,\n      handle: null as unknown as AnimationHandle, // assigned just below\n      started: false,\n      finish(reason) {\n        resolveFinished()\n        // Only a run that actually started can be interrupted (skips a run replaced re-entrantly before its start).\n        if (reason === 'interrupt' && this.started) registry.fire('interrupt', this.handle)\n      },\n    }\n    const handle: AnimationHandle = {\n      finished,\n      then: thenFinished(finished),\n      stop: () => {\n        if (active === animation) freeze('interrupt')\n      },\n      eventCallback(event, fn) {\n        registry.set(event, fn)\n        return handle\n      },\n    }\n    animation.handle = handle\n    active = animation\n    velocity = state.velocity\n    previous?.finish('interrupt') // replaced -> resolve + fire the prior run's onInterrupt\n    unsubscribeFrames ??= scheduler.subscribe(onFrame)\n    // Only fire start if still active - an onInterrupt above may have re-entrantly replaced us.\n    if (active === animation) {\n      animation.started = true\n      registry.fire('start', handle, position)\n    }\n    return handle\n  }\n\n  return {\n    get: () => position,\n    velocity: () => velocity,\n    isAnimating: () => active !== null,\n    set(value, setOptions = {}) {\n      freeze('interrupt')\n      velocity = setOptions.velocity ?? 0\n      if (position !== value) {\n        position = value\n        emitChange()\n      }\n    },\n    drive(state) {\n      velocity = state.velocity\n      if (position !== state.position) {\n        position = state.position\n        emitChange()\n      }\n    },\n    stop: () => freeze('interrupt'),\n    spring(target, springOptions = {}) {\n      const motion = simulationMotion(springSimulation(target, springOptions))\n      const state = { position, velocity: springOptions.velocity ?? velocity }\n      if (shouldSkip(springOptions.reducedMotion)) return settleInstantly(motion, state, springOptions)\n      return startAnimation(motion, state, springOptions)\n    },\n    decay(decayOptions = {}) {\n      const motion = simulationMotion(decaySimulation(decayOptions))\n      const state = { position, velocity: decayOptions.velocity ?? velocity }\n      if (shouldSkip(decayOptions.reducedMotion)) return settleInstantly(motion, state, decayOptions)\n      return startAnimation(motion, state, decayOptions)\n    },\n    to(target, toOptions = {}) {\n      const motion = tweenMotion(position, target, toOptions)\n      const state = { position, velocity }\n      if (shouldSkip(toOptions.reducedMotion)) return settleInstantly(motion, state, toOptions)\n      return startAnimation(motion, state, toOptions)\n    },\n    simulate(simulation, simulateOptions = {}) {\n      const motion = simulationMotion(simulation)\n      const state = { position, velocity: simulateOptions.velocity ?? velocity }\n      if (shouldSkip(simulateOptions.reducedMotion)) return settleInstantly(motion, state, simulateOptions)\n      return startAnimation(motion, state, simulateOptions)\n    },\n    on(event: 'change' | 'rest', listener: (value: number) => void) {\n      const listeners: Set<(value: number) => void> = event === 'change' ? changeListeners : restListeners\n      listeners.add(listener)\n      return () => {\n        listeners.delete(listener)\n      }\n    },\n    dispose() {\n      freeze('interrupt')\n      changeListeners.clear()\n      restListeners.clear()\n    },\n  }\n}\n","export type TransformChannel =\n  | 'perspective'\n  | 'x'\n  | 'y'\n  | 'rotateX'\n  | 'rotateY'\n  | 'rotateZ'\n  | 'rotate'\n  | 'skewX'\n  | 'skewY'\n  | 'scale'\n  | 'scaleX'\n  | 'scaleY'\n\nexport type TransformChannels = Partial<Record<TransformChannel, number>>\n\n/** Every key that resolves into the transform string (i.e. all but opacity). */\nexport const TRANSFORM_KEYS = [\n  'perspective',\n  'x',\n  'y',\n  'rotateX',\n  'rotateY',\n  'rotateZ',\n  'rotate',\n  'skewX',\n  'skewY',\n  'scale',\n  'scaleX',\n  'scaleY',\n] as const satisfies readonly TransformChannel[]\n\n// transform-origin is a separate CSS property, not a transform function, so it\n// is its own little channel group: two percentages forming `X% Y%`.\nexport type OriginChannel = 'originX' | 'originY'\nexport type OriginChannels = Partial<Record<OriginChannel, number>>\nexport const ORIGIN_KEYS = ['originX', 'originY'] as const satisfies readonly OriginChannel[]\n\n/** transform-origin from originX/originY percentages; an unset axis is center. */\nexport function formatOrigin(c: OriginChannels): string {\n  return `${c.originX ?? 50}% ${c.originY ?? 50}%`\n}\n\n/**\n * Single source of the transform string format. The WAAPI delegation builds\n * its keyframes with it and the binding writes frames with it - both MUST\n * produce byte-identical strings for the same values, or handoffs would\n * visually jump.\n *\n * Canonical order: perspective first (so the 3D rotations have depth), then\n * translate, rotations, skews, scales. The functions do not all commute, so a\n * fixed order is what keeps every code path identical.\n */\nexport function formatTransform(c: TransformChannels): string {\n  const parts: string[] = []\n  // perspective(0) collapses the element to a point, so only emit it when positive.\n  if (c.perspective !== undefined && c.perspective > 0) parts.push(`perspective(${c.perspective}px)`)\n  if (c.x !== undefined || c.y !== undefined) parts.push(`translate3d(${c.x ?? 0}px, ${c.y ?? 0}px, 0)`)\n  if (c.rotateX !== undefined) parts.push(`rotateX(${c.rotateX}deg)`)\n  if (c.rotateY !== undefined) parts.push(`rotateY(${c.rotateY}deg)`)\n  if (c.rotateZ !== undefined) parts.push(`rotateZ(${c.rotateZ}deg)`)\n  if (c.rotate !== undefined) parts.push(`rotate(${c.rotate}deg)`)\n  if (c.skewX !== undefined) parts.push(`skewX(${c.skewX}deg)`)\n  if (c.skewY !== undefined) parts.push(`skewY(${c.skewY}deg)`)\n  if (c.scale !== undefined) parts.push(`scale(${c.scale})`)\n  if (c.scaleX !== undefined) parts.push(`scaleX(${c.scaleX})`)\n  if (c.scaleY !== undefined) parts.push(`scaleY(${c.scaleY})`)\n  return parts.join(' ')\n}\n","import { getSharedScheduler } from '../scheduler/shared'\nimport type { Scheduler } from '../scheduler/scheduler'\nimport type { Animatable } from '../value/animatable'\nimport type { AnimatableElement } from './resolve-target'\nimport {\n  formatOrigin,\n  formatTransform,\n  ORIGIN_KEYS,\n  TRANSFORM_KEYS,\n  type OriginChannel,\n  type OriginChannels,\n  type TransformChannel,\n  type TransformChannels,\n} from './transform'\n\n/** Each channel is an Animatable bound to one transform function, transform-origin axis, or opacity. */\nexport type StyleBindings = Partial<Record<TransformChannel | OriginChannel, Animatable>> & {\n  opacity?: Animatable\n}\n\nexport interface BindStyleOptions {\n  /** Must be the scheduler driving the bound animatables. Defaults to the shared one. */\n  scheduler?: Scheduler\n  /**\n   * When set, the opacity write also toggles `visibility` - `hidden` at 0, cleared\n   * otherwise - so a fully transparent element stops capturing pointer events (the\n   * autoAlpha behavior). No effect without an opacity binding.\n   */\n  autoAlpha?: boolean\n}\n\n/**\n * Writes animatable values straight to element.style from the scheduler's\n * render phase - outside any framework reactivity. All channels that moved\n * during a frame are flushed in a single write per property, per element.\n * Returns a dispose function.\n */\nexport function bindStyle(\n  element: AnimatableElement,\n  bindings: StyleBindings,\n  options: BindStyleOptions = {},\n): () => void {\n  const scheduler = options.scheduler ?? getSharedScheduler()\n  const autoAlpha = options.autoAlpha === true\n  const { opacity } = bindings\n  const transformBindings = TRANSFORM_KEYS.map((key) => [key, bindings[key]] as const).filter(\n    (entry): entry is readonly [TransformChannel, Animatable] => entry[1] !== undefined,\n  )\n  const originBindings = ORIGIN_KEYS.map((key) => [key, bindings[key]] as const).filter(\n    (entry): entry is readonly [OriginChannel, Animatable] => entry[1] !== undefined,\n  )\n\n  let transformDirty = false\n  let originDirty = false\n  let opacityDirty = false\n  let cancelFlush: (() => void) | null = null\n  const unsubscribers: Array<() => void> = []\n\n  const writeTransform = () => {\n    const channels: TransformChannels = {}\n    for (const [key, value] of transformBindings) channels[key] = value.get()\n    element.style.transform = formatTransform(channels)\n  }\n\n  const writeOrigin = () => {\n    const channels: OriginChannels = {}\n    for (const [key, value] of originBindings) channels[key] = value.get()\n    element.style.transformOrigin = formatOrigin(channels)\n  }\n\n  const writeOpacity = () => {\n    if (opacity === undefined) return\n    const value = opacity.get()\n    element.style.opacity = String(value)\n    // autoAlpha: a fully transparent element also goes visibility:hidden so it\n    // drops out of hit-testing; any non-zero opacity clears it back to visible.\n    if (autoAlpha) element.style.visibility = value <= 0.0001 ? 'hidden' : ''\n  }\n\n  const flush = () => {\n    if (transformDirty) {\n      transformDirty = false\n      writeTransform()\n    }\n    if (originDirty) {\n      originDirty = false\n      writeOrigin()\n    }\n    if (opacityDirty) {\n      opacityDirty = false\n      writeOpacity()\n    }\n  }\n\n  // One-shot render subscription: the flush runs after every simulation of\n  // the same tick (or on the next frame for changes made outside a tick),\n  // then lets the loop go back to sleep.\n  const scheduleFlush = () => {\n    if (cancelFlush !== null) return\n    cancelFlush = scheduler.subscribe(() => {\n      cancelFlush?.()\n      cancelFlush = null\n      flush()\n    }, 'render')\n  }\n\n  const track = (value: Animatable | undefined, markDirty: () => void) => {\n    if (value === undefined) return\n    unsubscribers.push(\n      value.on('change', () => {\n        markDirty()\n        scheduleFlush()\n      }),\n    )\n  }\n\n  const markTransformDirty = () => {\n    transformDirty = true\n  }\n  const markOriginDirty = () => {\n    originDirty = true\n  }\n  for (const [, value] of transformBindings) track(value, markTransformDirty)\n  for (const [, value] of originBindings) track(value, markOriginDirty)\n  track(opacity, () => {\n    opacityDirty = true\n  })\n\n  // The element reflects the current values from bind time, synchronously.\n  if (transformBindings.length > 0) writeTransform()\n  if (originBindings.length > 0) writeOrigin()\n  writeOpacity()\n\n  return () => {\n    for (const unsubscribe of unsubscribers) unsubscribe()\n    cancelFlush?.()\n    cancelFlush = null\n  }\n}\n","/**\n * The value-type contract: how a CSS property name maps to the scalar channels\n * the physics drives. A `ValueType` decomposes a raw value into channels\n * (`parse`), names their magnitude/precision (`channels`), and is the SOLE\n * producer of that property's CSS strings (`format`) - the analogue of\n * `formatTransform` for the transform property. Equal shapes are\n * channel-for-channel interpolable AND share a format template.\n */\nexport interface ParsedValue {\n  /** Scalar channels the physics drives, in template order. */\n  channels: number[]\n  /**\n   * Shape identity: equal shapes are channel-for-channel interpolable AND share\n   * a format template. For the complex type the shape IS the compiled template -\n   * same token kinds with different literals are different shapes.\n   */\n  shape: string\n}\n\n/** Per-channel metadata: format precision, clamp bounds, and rest tolerances scaled to the channel's magnitude. */\nexport interface ChannelMeta {\n  /** Decimals kept at format time. The simulation always runs full precision. */\n  precision: number\n  /** Format-time clamp - spring overshoot on bounded channels (rgb, alpha). */\n  min?: number\n  max?: number\n  /** Rest tolerance scaled to the channel's magnitude. An explicit per-call restDelta wins. */\n  restDelta?: number\n  /** Rest speed scaled to the channel's magnitude (channel-units/s). Per-call restSpeed wins. */\n  restSpeed?: number\n}\n\n/** px per 1 unit in this element+property context; null = not measurable. */\nexport type MeasureUnit = (unit: string) => number | null\n\nexport interface ValueType {\n  /** Decompose an author/computed value. null = not animatable - the caller snaps. */\n  parse(raw: string | number): ParsedValue | null\n  /** Pure, deterministic, byte-identical for identical input. The ONLY producer of this property's CSS strings. */\n  format(channels: readonly number[], shape: string): string\n  /** Per-channel metadata for a shape; length matches parse().channels. */\n  channels(shape: string): readonly ChannelMeta[]\n  /** Linear multiplier mapping channel values AND velocities between shapes; null = not convertible (caller snaps). */\n  convert?(fromShape: string, toShape: string, measure: MeasureUnit): number | null\n  /** Re-read a raw value through a target shape: kind-stable realign, 'none' synthesis. null = incompatible. */\n  reconcile?(raw: string, targetShape: string): ParsedValue | null\n  /** false for non-spatial types (colors): they stay animated under reduced-motion 'fade'. Default true. */\n  spatial?: boolean\n}\n\n/**\n * The one formatter primitive every value type shares: clamp to the channel's\n * bounds, round to its precision, and emit a byte-stable decimal string - no\n * scientific notation, no negative zero, no sub-precision churn. Rounding makes\n * equal floats produce byte-equal strings across runs and frame rates.\n */\nexport function formatChannelNumber(value: number, meta: ChannelMeta): string {\n  let v = value\n  // Never emit 'NaN'/'Infinity' into a CSS string (a non-finite source value, a\n  // bad target). Fall back to the channel's floor, or 0.\n  if (!Number.isFinite(v)) v = meta.min ?? 0\n  if (meta.min !== undefined && v < meta.min) v = meta.min\n  if (meta.max !== undefined && v > meta.max) v = meta.max\n  const factor = 10 ** meta.precision\n  v = Math.round(v * factor) / factor\n  return v === 0 ? '0' : String(v)\n}\n","/** camelCase or custom property -> the kebab name getComputedStyle/setProperty expect. */\nexport function toKebab(property: string): string {\n  if (property.startsWith('--')) return property\n  return property.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)\n}\n\nexport interface StyleReader {\n  /** Computed value of a property (kebab-converted), trimmed. '' when unset. */\n  get(property: string): string\n}\n\n/**\n * An attribute reader with the same shape as `readStyle` - `get(name)` returns\n * the element's current attribute value (`getAttribute`), '' when unset. The seam\n * for animating SVG/element attributes (viewBox, r, points) through the same group\n * machinery as style properties.\n */\nexport function readAttribute(element: Element): StyleReader {\n  return {\n    get(name) {\n      return (element.getAttribute(name) ?? '').trim()\n    },\n  }\n}\n\n/**\n * One getComputedStyle(element) per animate()/setStyle() call, evaluated lazily\n * and shared by every property read of that call - getComputedStyle forces a\n * style/layout flush, so it must happen at most once and before any write.\n * Lazy so a call that never reads (pure numeric fast path) touches no DOM.\n */\nexport function readStyle(element: Element): StyleReader {\n  let computed: CSSStyleDeclaration | null = null\n  return {\n    get(property) {\n      computed ??= getComputedStyle(element)\n      return computed.getPropertyValue(toKebab(property)).trim()\n    },\n  }\n}\n","import { getSharedScheduler } from '../scheduler/shared'\nimport type { Scheduler } from '../scheduler/scheduler'\nimport { toKebab } from './read-style'\nimport type { AnimatableElement } from './resolve-target'\n\nexport interface BindPropertyOptions {\n  scheduler?: Scheduler\n  /**\n   * Where the formatted value is written. 'style' (default) sets the inline style\n   * property (kebab-cased); 'attr' calls setAttribute with the bare `property`\n   * name - the seam for SVG/element attribute animation (viewBox, r, points).\n   */\n  target?: 'style' | 'attr'\n}\n\n/**\n * The structural source bindProperty writes: anything that can produce a CSS\n * string and notify when it changes. A ChannelGroup satisfies it (the animate()\n * path), and so does a composed template (bindTemplate) - one render-phase binder\n * serves both.\n */\nexport interface FormatSource {\n  format(): string\n  onChange(listener: () => void): () => void\n}\n\nexport interface PropertyBinding {\n  dispose(): void\n  /** Write the current value synchronously now, cancelling any pending flush (setStyle path). */\n  flushNow(): void\n}\n\n/**\n * Writes a channel group's formatted value to one element property from the\n * scheduler's render phase - bind-style's pattern, one property at a time: a\n * group change marks dirty and arms a one-shot render subscription that flushes\n * once, then lets the loop sleep. The formatted string is deduplicated, so a\n * channel that jitters below its format precision produces no DOM write at all.\n */\nexport function bindProperty(\n  element: AnimatableElement,\n  property: string,\n  source: FormatSource,\n  options: BindPropertyOptions = {},\n): PropertyBinding {\n  const scheduler = options.scheduler ?? getSharedScheduler()\n  const attr = options.target === 'attr'\n  // Attributes take the bare name verbatim (viewBox, stroke-width); style takes kebab.\n  const name = attr ? property : toKebab(property)\n  let dirty = false\n  let lastWritten: string | null = null\n  let cancelFlush: (() => void) | null = null\n\n  const write = (): void => {\n    const value = source.format()\n    if (value === lastWritten) return // byte-identical: no DOM write\n    lastWritten = value\n    if (attr) element.setAttribute(name, value)\n    else element.style.setProperty(name, value)\n  }\n\n  const scheduleFlush = (): void => {\n    if (cancelFlush !== null) return\n    cancelFlush = scheduler.subscribe(() => {\n      cancelFlush?.()\n      cancelFlush = null\n      if (dirty) {\n        dirty = false\n        write()\n      }\n    }, 'render')\n  }\n\n  const unsubscribe = source.onChange(() => {\n    dirty = true\n    scheduleFlush()\n  })\n\n  // The element reflects the current value synchronously at bind time.\n  write()\n\n  return {\n    dispose() {\n      unsubscribe()\n      cancelFlush?.()\n      cancelFlush = null\n    },\n    flushNow() {\n      dirty = false\n      cancelFlush?.()\n      cancelFlush = null\n      write()\n    },\n  }\n}\n","import type { SpringOptions } from '../physics/spring'\nimport type { ToOptions } from '../physics/tween'\nimport type { Scheduler } from '../scheduler/scheduler'\nimport { animatable, type Animatable, type AnimationHandle } from './animatable'\nimport { thenFinished } from './thenable'\nimport type { ChannelMeta, ParsedValue, ValueType } from './value-type'\n\n/**\n * The bridge between one CSS value and the scalar physics: a value's channels\n * each become a plain Animatable, so springs, decay-grade velocity\n * conservation, interpolated exposure, exact rest snap, and reduced-motion\n * fast-forward are all INHERITED, not re-implemented. The group owns the shared\n * shape, the cached format string, and a generation counter (keyframe chains\n * read it to detect staleness). Aggregate handles fan out: `finished` resolves\n * when the last channel rests, `stop()` freezes them all.\n */\nexport interface ChannelGroup {\n  readonly type: ValueType\n  shape: string\n  readonly channels: ReadonlyArray<Animatable>\n  generation: number\n  format(): string\n  isAnimating(): boolean\n  set(parsed: ParsedValue, options?: { velocity?: number }): void\n  /** Same rendered pixels, new coordinate system: every channel set(pos*m, { velocity: vel*m }). */\n  rebase(multiplier: number, shape: string): void\n  spring(target: ParsedValue, options?: SpringOptions): AnimationHandle\n  to(target: ParsedValue, options?: ToOptions): AnimationHandle\n  onChange(listener: () => void): () => void\n  stop(): void\n  dispose(): void\n}\n\nexport interface ChannelGroupOptions {\n  scheduler?: Scheduler\n}\n\n// The aggregate forwards its channels' interrupt up as ONE interrupt: a registry\n// property's channels are plain Animatables, so superseding the group (a later\n// animate() retargets a channel) interrupts them - and a lifecycle owner above\n// (animate()'s withLifecycle) hooks THIS handle to tell a supersede from a settle.\nconst aggregate = (handles: AnimationHandle[]): AnimationHandle => {\n  let onInterrupt: ((h: AnimationHandle) => void) | null = null\n  let fired = false\n  const fireInterrupt = (): void => {\n    if (fired) return\n    fired = true\n    onInterrupt?.(handle)\n  }\n  for (const child of handles) child.eventCallback?.('interrupt', fireInterrupt)\n  const finished = Promise.all(handles.map((child) => child.finished)).then(() => undefined)\n  const handle: AnimationHandle = {\n    finished,\n    then: thenFinished(finished),\n    stop: () => {\n      for (const child of handles) child.stop()\n    },\n    eventCallback(event, fn) {\n      if (event === 'interrupt') onInterrupt = fn ?? null\n      return handle\n    },\n  }\n  return handle\n}\n\nexport function channelGroup(\n  type: ValueType,\n  parsed: ParsedValue,\n  options: ChannelGroupOptions = {},\n): ChannelGroup {\n  const scheduler = options.scheduler\n  let shape = parsed.shape\n  let metas = type.channels(shape)\n  let generation = 0\n  let cachedFormat: string | null = null\n  const changeListeners = new Set<() => void>()\n\n  const notify = (): void => {\n    cachedFormat = null\n    for (const listener of [...changeListeners]) listener()\n  }\n\n  const channels = parsed.channels.map((value) =>\n    animatable(value, scheduler !== undefined ? { scheduler } : {}),\n  )\n  const unsubscribers = channels.map((channel) => channel.on('change', notify))\n  // Reused scratch: one allocation for the channel count, refilled per format.\n  const scratch: number[] = new Array<number>(channels.length)\n\n  // Per-call options win; channel meta fills only the keys the call left absent;\n  // anything still absent falls through to the animatable's own defaults. Never\n  // assigns undefined to an optional key (exactOptionalPropertyTypes).\n  const channelOptions = (base: SpringOptions, index: number): SpringOptions => {\n    const meta: ChannelMeta | undefined = metas[index]\n    const opts: SpringOptions = { ...base }\n    if (meta !== undefined) {\n      if (opts.restDelta === undefined && meta.restDelta !== undefined) opts.restDelta = meta.restDelta\n      if (opts.restSpeed === undefined && meta.restSpeed !== undefined) opts.restSpeed = meta.restSpeed\n    }\n    return opts\n  }\n\n  return {\n    type,\n    get shape() {\n      return shape\n    },\n    set shape(next: string) {\n      shape = next\n    },\n    channels,\n    get generation() {\n      return generation\n    },\n    set generation(next: number) {\n      generation = next\n    },\n    format() {\n      if (cachedFormat !== null) return cachedFormat\n      for (let i = 0; i < channels.length; i++) scratch[i] = channels[i]!.get()\n      cachedFormat = type.format(scratch, shape)\n      return cachedFormat\n    },\n    isAnimating() {\n      return channels.some((channel) => channel.isAnimating())\n    },\n    set(next, setOptions = {}) {\n      generation += 1\n      shape = next.shape\n      metas = type.channels(shape)\n      cachedFormat = null\n      const velocity = setOptions.velocity\n      for (let i = 0; i < channels.length; i++) {\n        // Broadcast a scalar velocity to every channel: exact for single-channel\n        // values (the gesture case), the documented approximation otherwise.\n        channels[i]!.set(next.channels[i] ?? 0, velocity !== undefined ? { velocity } : undefined)\n      }\n    },\n    rebase(multiplier, nextShape) {\n      generation += 1\n      shape = nextShape\n      metas = type.channels(shape)\n      cachedFormat = null\n      for (const channel of channels) {\n        channel.set(channel.get() * multiplier, { velocity: channel.velocity() * multiplier })\n      }\n    },\n    spring(target, springOptions = {}) {\n      generation += 1\n      return aggregate(\n        channels.map((channel, i) => channel.spring(target.channels[i] ?? 0, channelOptions(springOptions, i))),\n      )\n    },\n    to(target, toOptions = {}) {\n      generation += 1\n      return aggregate(channels.map((channel, i) => channel.to(target.channels[i] ?? 0, toOptions)))\n    },\n    onChange(listener) {\n      changeListeners.add(listener)\n      return () => {\n        changeListeners.delete(listener)\n      }\n    },\n    stop() {\n      generation += 1\n      for (const channel of channels) channel.stop()\n    },\n    dispose() {\n      for (const unsubscribe of unsubscribers) unsubscribe()\n      for (const channel of channels) channel.dispose()\n      changeListeners.clear()\n    },\n  }\n}\n","import { formatChannelNumber, type ChannelMeta, type ValueType } from '../value-type'\n\n// Colors decompose into [r^2, g^2, b^2, a]: storing the channels squared means a\n// per-channel linear spring runs in gamma-2.0 (approximate linear-light) space,\n// which IS the mix - no dark sRGB midpoint, no separate color-mixing pass.\n// `sqrt` + clamp + integer round happen only at format. Oklab/OKLCH ship later as\n// @underlying/color via registerValueType.\n//\n// Rest tolerances are scaled to the squared magnitude (0..65025): 40 / 400 is\n// roughly 0.16 sRGB steps at midrange, so the loop sleeps at visual rest rather\n// than chasing px-tuned defaults for seconds.\nconst RGB_META: ChannelMeta = { precision: 0, min: 0, max: 65025, restDelta: 40, restSpeed: 400 }\nconst ALPHA_META: ChannelMeta = { precision: 4, min: 0, max: 1, restDelta: 0.005, restSpeed: 0.05 }\nexport const COLOR_METAS: readonly ChannelMeta[] = [RGB_META, RGB_META, RGB_META, ALPHA_META]\n\n/** The single color shape: 4 channels, one canonical rgba layout. */\nexport const COLOR_SHAPE = 'rgba'\n\nconst sqrtByte = (squared: number): number => {\n  const clamped = squared < 0 ? 0 : squared > 65025 ? 65025 : squared\n  return Math.round(Math.sqrt(clamped))\n}\n\n/** Channels [r^2, g^2, b^2, a] -> canonical, byte-stable `rgba(R, G, B, A)`. */\nexport function formatColor(channels: readonly number[]): string {\n  const r = sqrtByte(channels[0] ?? 0)\n  const g = sqrtByte(channels[1] ?? 0)\n  const b = sqrtByte(channels[2] ?? 0)\n  const a = formatChannelNumber(channels[3] ?? 1, ALPHA_META)\n  return `rgba(${r}, ${g}, ${b}, ${a})`\n}\n\nconst hexComponent = (hex: string): [number, number, number, number] | null => {\n  if (!/^[0-9a-f]+$/.test(hex)) return null\n  // Expand the 3/4-digit short form: 'f04' -> 'ff0044'.\n  const full = hex.length === 3 || hex.length === 4 ? hex.replace(/./g, (c) => c + c) : hex\n  if (full.length !== 6 && full.length !== 8) return null\n  const r = parseInt(full.slice(0, 2), 16)\n  const g = parseInt(full.slice(2, 4), 16)\n  const b = parseInt(full.slice(4, 6), 16)\n  const a = full.length === 8 ? parseInt(full.slice(6, 8), 16) / 255 : 1\n  return Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b) || Number.isNaN(a) ? null : [r, g, b, a]\n}\n\nconst functionalArgs = (s: string): string[] | null => {\n  const open = s.indexOf('(')\n  const close = s.lastIndexOf(')')\n  if (open < 0 || close < open) return null\n  return s\n    .slice(open + 1, close)\n    .split(/[\\s,/]+/)\n    .filter((part) => part !== '')\n}\n\nconst component = (raw: string, scale: number): number =>\n  raw.endsWith('%') ? (parseFloat(raw) / 100) * scale : parseFloat(raw)\n\nconst rgbComponent = (s: string): [number, number, number, number] | null => {\n  const parts = functionalArgs(s)\n  if (parts === null || parts.length < 3 || parts.length > 4) return null\n  const [p0, p1, p2, p3] = parts\n  if (p0 === undefined || p1 === undefined || p2 === undefined) return null\n  const r = component(p0, 255)\n  const g = component(p1, 255)\n  const b = component(p2, 255)\n  const a = p3 === undefined ? 1 : component(p3, 1)\n  return Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b) || Number.isNaN(a) ? null : [r, g, b, a]\n}\n\nconst hslToRgb = (h: number, s: number, l: number): [number, number, number] => {\n  const c = (1 - Math.abs(2 * l - 1)) * s\n  const hp = ((((h % 360) + 360) % 360) / 60)\n  const x = c * (1 - Math.abs((hp % 2) - 1))\n  const [r1, g1, b1] =\n    hp < 1 ? [c, x, 0] : hp < 2 ? [x, c, 0] : hp < 3 ? [0, c, x] : hp < 4 ? [0, x, c] : hp < 5 ? [x, 0, c] : [c, 0, x]\n  const m = l - c / 2\n  return [(r1 + m) * 255, (g1 + m) * 255, (b1 + m) * 255]\n}\n\nconst hslComponent = (s: string): [number, number, number, number] | null => {\n  const parts = functionalArgs(s)\n  if (parts === null || parts.length < 3 || parts.length > 4) return null\n  const [p0, p1, p2, p3] = parts\n  if (p0 === undefined || p1 === undefined || p2 === undefined) return null\n  const h = parseFloat(p0)\n  const sat = parseFloat(p1) / 100\n  const light = parseFloat(p2) / 100\n  const a = p3 === undefined ? 1 : component(p3, 1)\n  if (Number.isNaN(h) || Number.isNaN(sat) || Number.isNaN(light) || Number.isNaN(a)) return null\n  const [r, g, b] = hslToRgb(h, sat, light)\n  return [r, g, b, a]\n}\n\n// Reused, in-document probe: detached elements have no computed style, so the\n// element must live in the tree. display:none is fine - `color` is not\n// layout-dependent. Created lazily on the first named candidate (SSR-safe).\nlet probe: HTMLElement | null = null\nconst NON_COLOR_KEYWORDS = new Set([\n  'none', 'auto', 'inherit', 'initial', 'unset', 'revert', 'currentcolor', 'transparent',\n])\n\nconst namedComponent = (name: string): [number, number, number, number] | null => {\n  if (NON_COLOR_KEYWORDS.has(name)) return null\n  if (typeof document === 'undefined') return null\n  if (probe === null) {\n    probe = document.createElement('div')\n    probe.style.display = 'none'\n    document.documentElement.appendChild(probe)\n  }\n  probe.style.color = ''\n  probe.style.color = name\n  // An invalid keyword is rejected by the CSSOM: the assignment leaves it empty.\n  if (probe.style.color === '') return null\n  return rgbComponent(getComputedStyle(probe).color)\n}\n\n/** Decompose a color into squared-sRGB channels [r^2, g^2, b^2, a]. null = not a parseable color. */\nexport function parseColor(raw: string | number): [number, number, number, number] | null {\n  if (typeof raw === 'number') return null\n  const s = raw.trim().toLowerCase()\n  if (s === '') return null\n  if (s === 'transparent') return [0, 0, 0, 0]\n  const rgba =\n    s[0] === '#'\n      ? hexComponent(s.slice(1))\n      : s.startsWith('rgb')\n        ? rgbComponent(s)\n        : s.startsWith('hsl')\n          ? hslComponent(s)\n          : /^[a-z]+$/.test(s)\n            ? namedComponent(s)\n            : null\n  if (rgba === null) return null\n  const [r, g, b, a] = rgba\n  return [r * r, g * g, b * b, a]\n}\n\nexport const colorValueType: ValueType = {\n  spatial: false,\n  parse(raw) {\n    const channels = parseColor(raw)\n    return channels === null ? null : { channels, shape: COLOR_SHAPE }\n  },\n  format(channels) {\n    return formatColor(channels)\n  },\n  channels() {\n    return COLOR_METAS\n  },\n}\n\n/** Test-only: drops the cached probe element so a fresh document can be used. */\nexport function __resetColorProbe(): void {\n  probe?.remove()\n  probe = null\n}\n","import { formatChannelNumber, type ChannelMeta, type ValueType } from '../value-type'\nimport { COLOR_METAS, formatColor, parseColor } from './color'\n\n// The generic value type: any CSS value that is a mix of literal text, numbers\n// (with units), and embedded colors - box-shadow, filter, the fallback for\n// unknown and custom properties. One tokenizer pass turns a value into scalar\n// channels plus a SHAPE that IS the compiled template: same token kinds with\n// the same literals and units share a shape and are channel-for-channel\n// interpolable; anything else is a different shape (snap, not a silent\n// mis-mix). The hot path (format) never tokenizes - it reuses the template.\n\ntype Token = { kind: 'number'; unit: string } | { kind: 'color' }\n\ninterface Template {\n  literals: string[] // length = tokens.length + 1\n  tokens: Token[]\n}\n\nconst NUMBER_TOKEN_META: ChannelMeta = { precision: 4, restDelta: 0.01, restSpeed: 0.1 }\n\n// Token-slot delimiter inside a shape string. NUL never appears in a CSS value,\n// so literal chunks (which freely contain spaces, parens, commas) never collide\n// with the slot markers `<NUL>c<NUL>` (color) and `<NUL>n:<unit><NUL>` (number).\nconst SEP = '\\u0000'\nconst colorSlot = `${SEP}c${SEP}`\nconst numberSlot = (unit: string): string => `${SEP}n:${unit}${SEP}`\nconst SINGLE_NUMBER_SHAPE = numberSlot('')\n\n// Colors are matched before numbers so the numbers inside rgb()/hsl() are not\n// mistaken for standalone tokens. The unit group (index 1) is populated only\n// for the number alternative.\nconst tokenPattern =\n  /rgba?\\([^)]*\\)|hsla?\\([^)]*\\)|#[0-9a-fA-F]+|[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(px|%|em|rem|vw|vh|vmin|vmax|deg|rad|turn|s|ms)?/gi\n\nconst isColorText = (text: string): boolean => text[0] === '#' || /^(?:rgb|hsl)/i.test(text)\n\ninterface Decomposed {\n  channels: number[]\n  shape: string\n  template: Template\n}\n\n// Test seam: the hot path (format) must never reach this.\nlet tokenizeCount = 0\n\nconst decompose = (raw: string): Decomposed | null => {\n  tokenizeCount += 1\n  const channels: number[] = []\n  const tokens: Token[] = []\n  const literals: string[] = []\n  let shape = ''\n  let cursor = 0\n  for (const match of raw.matchAll(tokenPattern)) {\n    const text = match[0]\n    const index = match.index\n    const literal = raw.slice(cursor, index)\n    literals.push(literal)\n    shape += literal\n    cursor = index + text.length\n    if (isColorText(text)) {\n      const color = parseColor(text)\n      if (color === null) return null\n      channels.push(color[0], color[1], color[2], color[3])\n      tokens.push({ kind: 'color' })\n      shape += colorSlot\n    } else {\n      const unit = match[1] ?? ''\n      const num = parseFloat(text)\n      if (Number.isNaN(num)) return null\n      channels.push(num)\n      tokens.push({ kind: 'number', unit })\n      shape += numberSlot(unit)\n    }\n  }\n  if (tokens.length === 0) return null\n  const tail = raw.slice(cursor)\n  literals.push(tail)\n  shape += tail\n  return { channels, shape, template: { literals, tokens } }\n}\n\n// Templates are decoded from their shape string once and cached: the shape was\n// produced by decompose, so it always round-trips. split on SEP yields\n// alternating [literal, descriptor, literal, descriptor, ..., literal].\nconst templateCache = new Map<string, Template>()\n\nconst compileShape = (shape: string): Template => {\n  const cached = templateCache.get(shape)\n  if (cached !== undefined) return cached\n  const parts = shape.split(SEP)\n  const literals: string[] = []\n  const tokens: Token[] = []\n  for (let i = 0; i < parts.length; i++) {\n    const part = parts[i] ?? ''\n    if (i % 2 === 0) literals.push(part)\n    else if (part === 'c') tokens.push({ kind: 'color' })\n    else tokens.push({ kind: 'number', unit: part.slice(2) })\n  }\n  const template: Template = { literals, tokens }\n  templateCache.set(shape, template)\n  return template\n}\n\nconst channelMetas = (shape: string): ChannelMeta[] => {\n  const { tokens } = compileShape(shape)\n  const metas: ChannelMeta[] = []\n  for (const token of tokens) {\n    if (token.kind === 'color') metas.push(...COLOR_METAS)\n    else metas.push(NUMBER_TOKEN_META)\n  }\n  return metas\n}\n\n/** Source channels grouped by kind, preserving order - the basis for kind-stable realignment. */\nconst groupByKind = (source: Decomposed): { numbers: number[]; colors: number[][] } => {\n  const numbers: number[] = []\n  const colors: number[][] = []\n  let offset = 0\n  for (const token of source.template.tokens) {\n    if (token.kind === 'color') {\n      colors.push(source.channels.slice(offset, offset + 4))\n      offset += 4\n    } else {\n      numbers.push(source.channels[offset] ?? 0)\n      offset += 1\n    }\n  }\n  return { numbers, colors }\n}\n\nexport const complexValueType: ValueType = {\n  parse(raw) {\n    if (typeof raw === 'number') {\n      return Number.isFinite(raw) ? { channels: [raw], shape: SINGLE_NUMBER_SHAPE } : null\n    }\n    const decomposed = decompose(raw)\n    return decomposed === null ? null : { channels: decomposed.channels, shape: decomposed.shape }\n  },\n  format(channels, shape) {\n    const { literals, tokens } = compileShape(shape)\n    let out = literals[0] ?? ''\n    let offset = 0\n    for (let i = 0; i < tokens.length; i++) {\n      const token = tokens[i]\n      if (token === undefined) break\n      if (token.kind === 'color') {\n        out += formatColor(channels.slice(offset, offset + 4))\n        offset += 4\n      } else {\n        out += formatChannelNumber(channels[offset] ?? 0, NUMBER_TOKEN_META) + token.unit\n        offset += 1\n      }\n      out += literals[i + 1] ?? ''\n    }\n    return out\n  },\n  channels(shape) {\n    return channelMetas(shape)\n  },\n  reconcile(raw, targetShape) {\n    const { tokens } = compileShape(targetShape)\n    const trimmed = raw.trim().toLowerCase()\n    // 'none' and an empty computed value (the unset initial: browsers serialize\n    // box-shadow/filter as 'none', jsdom as '') both mean \"no value yet\".\n    if (trimmed === 'none' || trimmed === '') {\n      // Zero-equivalent of the target template: numbers collapse to 0, colors\n      // to transparent (correct for the dominant black-shadow case).\n      const channels: number[] = []\n      for (const token of tokens) {\n        if (token.kind === 'color') channels.push(0, 0, 0, 0)\n        else channels.push(0)\n      }\n      return { channels, shape: targetShape }\n    }\n    const source = decompose(raw)\n    if (source === null) return null\n    const { numbers, colors } = groupByKind(source)\n    let ni = 0\n    let ci = 0\n    const channels: number[] = []\n    for (const token of tokens) {\n      if (token.kind === 'color') {\n        const color = colors[ci]\n        if (color === undefined) return null\n        channels.push(...color)\n        ci += 1\n      } else {\n        const num = numbers[ni]\n        if (num === undefined) return null\n        channels.push(num)\n        ni += 1\n      }\n    }\n    // Exact count: leftover source tokens of either kind means the shapes are\n    // structurally different (e.g. 1 shadow vs 2) - snap, do not pad.\n    if (ni !== numbers.length || ci !== colors.length) return null\n    return { channels, shape: targetShape }\n  },\n}\n\n/** Test-only: number of full tokenizer passes (the hot path must add none). */\nexport function __tokenizeCount(): number {\n  return tokenizeCount\n}\n\n/** Test-only: clears the template cache and the tokenizer counter. */\nexport function __resetComplexCaches(): void {\n  templateCache.clear()\n  tokenizeCount = 0\n}\n","import { formatChannelNumber, type ChannelMeta, type ValueType } from '../value-type'\n\n// One channel; the shape IS the unit. Cross-unit interpolation is forbidden -\n// a '50%' target and a '240px' current are different shapes, reconciled by a\n// measure-once multiplier (see convert) rather than mixed numerically.\nconst LENGTH_META: ChannelMeta = { precision: 4, restDelta: 0.01, restSpeed: 0.1 }\nconst LENGTH_METAS: readonly ChannelMeta[] = [LENGTH_META]\n\nconst LENGTH_RE = /^([+-]?(?:\\d+\\.?\\d*|\\.\\d+))(px|%|em|rem|vw|vh|vmin|vmax|deg|rad|turn)$/\n\n// Angle units convert arithmetically (no layout measurement). Reference: degrees.\nconst ANGLE_TO_DEG: Record<string, number | undefined> = { deg: 1, rad: 180 / Math.PI, turn: 360 }\n\nexport const lengthValueType: ValueType = {\n  parse(raw) {\n    // Bare numbers default to px (the registry seeds length properties).\n    if (typeof raw === 'number') {\n      return Number.isFinite(raw) ? { channels: [raw], shape: 'px' } : null\n    }\n    const s = raw.trim()\n    if (s === '') return null\n    // Unitless zero is valid CSS for lengths; it carries no unit of its own.\n    if (s === '0' || s === '+0' || s === '-0') return { channels: [0], shape: 'px' }\n    const match = LENGTH_RE.exec(s)\n    if (match === null) return null\n    return { channels: [Number(match[1])], shape: match[2] as string }\n  },\n  format(channels, shape) {\n    return formatChannelNumber(channels[0] ?? 0, LENGTH_META) + shape\n  },\n  channels() {\n    return LENGTH_METAS\n  },\n  convert(fromShape, toShape, measure) {\n    const fromAngle = ANGLE_TO_DEG[fromShape]\n    const toAngle = ANGLE_TO_DEG[toShape]\n    if (fromAngle !== undefined || toAngle !== undefined) {\n      // Angle <-> angle only; a cross-kind conversion (deg <-> px) is undefined.\n      if (fromAngle === undefined || toAngle === undefined) return null\n      return fromAngle / toAngle\n    }\n    const from = measure(fromShape)\n    const to = measure(toShape)\n    if (from === null || to === null || to === 0) return null\n    return from / to\n  },\n}\n","import { formatChannelNumber, type ChannelMeta, type ValueType } from '../value-type'\n\n// Unitless scalar - flexGrow, fontWeight, custom properties registered by the\n// app. Shape is the empty string: one canonical shape, always interpolable.\nconst NUMBER_META: ChannelMeta = { precision: 4, restDelta: 0.01, restSpeed: 0.1 }\nconst NUMBER_METAS: readonly ChannelMeta[] = [NUMBER_META]\n\nexport const numberValueType: ValueType = {\n  parse(raw) {\n    if (typeof raw === 'string' && raw.trim() === '') return null\n    const n = Number(raw)\n    return Number.isFinite(n) ? { channels: [n], shape: '' } : null\n  },\n  format(channels) {\n    return formatChannelNumber(channels[0] ?? 0, NUMBER_META)\n  },\n  channels() {\n    return NUMBER_METAS\n  },\n}\n","import { colorValueType } from './types/color'\nimport { complexValueType } from './types/complex'\nimport { lengthValueType } from './types/length'\nimport { numberValueType } from './types/number'\nimport type { ValueType } from './value-type'\nimport { warnOnce } from './warn'\n\n// Property -> value-type map. Built-in seeds are installed LAZILY on first\n// resolution, never at module scope: a top-level Map.set() would be retained by\n// flat-bundle tree-shakers (esbuild/Vite) even for a transforms-only user. The\n// CI tree-shake probe enforces that this module stays out of the primitives\n// graph entirely.\nconst registry = new Map<string, ValueType>()\nconst shorthands = new Set<string>()\nlet seeded = false\n\n// camelCase property names, space-packed to keep the seed table small.\nconst LENGTH_PROPERTIES =\n  'width height minWidth minHeight maxWidth maxHeight top right bottom left ' +\n  'marginTop marginRight marginBottom marginLeft paddingTop paddingRight paddingBottom paddingLeft ' +\n  'fontSize letterSpacing wordSpacing textIndent gap rowGap columnGap outlineWidth outlineOffset ' +\n  'borderTopWidth borderRightWidth borderBottomWidth borderLeftWidth ' +\n  'borderTopLeftRadius borderTopRightRadius borderBottomLeftRadius borderBottomRightRadius'\n\nconst COLOR_PROPERTIES =\n  'color backgroundColor borderTopColor borderRightColor borderBottomColor borderLeftColor ' +\n  'outlineColor textDecorationColor caretColor accentColor fill stroke'\n\nconst NUMBER_PROPERTIES = 'flexGrow flexShrink fontWeight'\n\n// Shorthands expand to longhands the browser reorders and pads unpredictably:\n// resolve them to the complex fallback but warn first, pointing at the longhand.\nconst SHORTHAND_PROPERTIES = 'margin padding border background font borderRadius borderColor borderWidth'\n\nconst seed = (): void => {\n  if (seeded) return\n  seeded = true\n  for (const property of LENGTH_PROPERTIES.split(' ')) registry.set(property, lengthValueType)\n  for (const property of COLOR_PROPERTIES.split(' ')) registry.set(property, colorValueType)\n  for (const property of NUMBER_PROPERTIES.split(' ')) registry.set(property, numberValueType)\n  for (const property of SHORTHAND_PROPERTIES.split(' ')) shorthands.add(property)\n}\n\n/**\n * Claim properties for a descriptor - the extension point for @underlying/color,\n * @underlying/scroll, and app code. Call it from explicit user code only, never\n * from a module's import side effects (a sideEffects:false bundler would drop\n * the registration). Later registrations win for groups created afterwards;\n * a live group keeps the descriptor it was created with.\n */\nexport function registerValueType(properties: readonly string[], type: ValueType): void {\n  seed()\n  for (const property of properties) {\n    if (registry.get(property) !== undefined) {\n      warnOnce(\n        `reregister:${property}`,\n        `value type for \"${property}\" re-registered; existing groups keep their current descriptor`,\n      )\n    }\n    registry.set(property, type)\n  }\n}\n\n/** Resolve a property to its value type. Unknown and custom (--*) properties fall back to complex. */\nexport function resolveValueType(property: string): ValueType {\n  seed()\n  const existing = registry.get(property)\n  if (existing !== undefined) return existing\n  if (shorthands.has(property)) {\n    warnOnce(\n      `shorthand:${property}`,\n      `\"${property}\" is a shorthand; animate its longhands (e.g. ${property}Top) for predictable results`,\n    )\n    return complexValueType\n  }\n  return complexValueType\n}\n\n/** Test-only: whether the built-in seeds have been installed yet. */\nexport function __isSeeded(): boolean {\n  return seeded\n}\n\n/** Test-only: clears all registrations and the seed flag. */\nexport function __resetRegistry(): void {\n  registry.clear()\n  shorthands.clear()\n  seeded = false\n}\n","import type { Scheduler } from '../scheduler/scheduler'\n\n/**\n * A delay on the frame clock (clamped, batched into the single loop), never on\n * setTimeout: a background tab pauses the delay like everything else. Returns an\n * unsubscribe that cancels a still-pending wait. Shared by stagger() and the\n * animate() delay wave so there is ONE frame-clock delay implementation.\n */\nexport const waitFrames = (ms: number, scheduler: Scheduler, onDone: () => void): (() => void) => {\n  let elapsedMs = 0\n  const unsubscribe = scheduler.subscribe(({ deltaMs }) => {\n    elapsedMs += deltaMs\n    if (elapsedMs >= ms) {\n      unsubscribe()\n      onDone()\n    }\n  })\n  return unsubscribe\n}\n","import type { EasingInput } from '../physics/easing-registry'\nimport type { Easing } from '../physics/easings'\nimport type { AnimationHandle } from '../value/animatable'\nimport { thenFinished } from '../value/thenable'\n\n/**\n * One expressive keyframe stop: a value plus an optional position and the easing\n * of the segment REACHING it. `at` is a 0..1 fraction of the total duration\n * (tween mode); `ease` overrides the animation easing for that one segment. A\n * bare value is shorthand for `{ value }`. `null` at index 0 means \"from the\n * current value\"; a `null` later HOLDS the previous value (a dwell).\n *\n * `at` positions a waypoint in time (WAAPI-consistent): an `at` on the LAST\n * waypoint means the final value is reached at that fraction and then held to the\n * end of the duration - a settle-and-dwell, not the full-duration default.\n */\nexport interface KeyframeStop<V> {\n  value: V | null\n  /** 0..1 position along the total duration where this stop is reached (tween mode). Non-decreasing. */\n  at?: number\n  /** Easing of the segment reaching this stop (tween mode); defaults to the animation easing. */\n  ease?: EasingInput\n}\n\n/** A keyframe entry: a bare value, `null` (from-current / hold), or an expressive stop. */\nexport type KeyframeInput<V> = V | null | KeyframeStop<V>\n\n/**\n * Keyframe semantics, shared by numeric channels and registry property groups.\n * Without a duration the waypoints are CHAINED SPRINGS: spring to waypoint k,\n * and only once it has rested (exact snap) spring to k+1 - the honest physics\n * of \"spring through a list of targets\" (positions/per-segment easing are\n * tween-only and ignored here). With a duration they become a piecewise tween;\n * the duration is split by the stops' positions (evenly when unset) and each\n * segment eases with its own easing (the animation easing when unset). A new\n * animate() interrupts the chain (velocity conserved into the replacement);\n * stop() freezes the running segment and drops the rest. Never rejects.\n */\nexport interface ChainOps<T> {\n  /** Teleport to a value (explicit keyframe-0 start), velocity 0. */\n  teleport(target: T): void\n  spring(target: T): AnimationHandle\n  tween(target: T, durationMs: number, easing: Easing): AnimationHandle\n  /** Reduced-motion: settle directly onto the final waypoint. */\n  settle(target: T): void\n}\n\nexport interface ChainConfig {\n  duration?: number\n  easing: Easing\n  reduced: boolean\n  /** Per-waypoint segment duration in ms (tween mode); overrides the even split where present. */\n  segmentDurations?: number[]\n  /** Per-waypoint easing (tween mode); overrides `easing` for that segment where defined. */\n  segmentEasings?: ReadonlyArray<Easing | undefined>\n}\n\nexport interface KeyframeChain {\n  handle: AnimationHandle\n  /** A new animate() took over this channel: stop advancing and resolve (do not freeze - the replacement owns it now). */\n  interrupt(): void\n}\n\nexport interface NormalizedKeyframes<V> {\n  /** undefined = start from the current value+velocity; otherwise a teleport start. */\n  teleport: V | undefined\n  waypoints: V[]\n  /** Per-waypoint 0..1 arrival position; undefined = auto (even split). Aligned to `waypoints`. */\n  offsets: ReadonlyArray<number | undefined>\n  /** Per-waypoint easing input reaching it; undefined = the animation easing. Aligned to `waypoints`. */\n  eases: ReadonlyArray<EasingInput | undefined>\n}\n\nconst isStop = <V>(entry: KeyframeInput<V>): entry is KeyframeStop<V> =>\n  entry !== null && typeof entry === 'object' && !Array.isArray(entry)\n\n/**\n * Normalize a keyframe array. `[]` -> null (ignored). `[a]` -> from current to a.\n * `[a, b, ...]` -> teleport to a (null a = from current), then chain b, ... . A\n * `null` past index 0 HOLDS the previous value (a dwell); a leading run of nulls\n * with no prior value is dropped. Bare values and `{ value, at, ease }` stops mix\n * freely; the per-waypoint `at`/`ease` are collected into parallel arrays.\n */\nexport function normalizeKeyframes<V>(frames: ReadonlyArray<KeyframeInput<V>>): NormalizedKeyframes<V> | null {\n  if (frames.length === 0) return null\n\n  // Flatten each entry to (value|null, at?, ease?), resolving a mid-chain null to\n  // a hold of the last concrete value.\n  const values: (V | null)[] = []\n  const offsets: (number | undefined)[] = []\n  const eases: (EasingInput | undefined)[] = []\n  let lastConcrete: V | undefined\n  for (const entry of frames) {\n    const stop = isStop(entry) ? entry : { value: entry as V | null }\n    let value = stop.value\n    if (value === null && values.length > 0) {\n      // A hold: repeat the previous concrete value. With nothing concrete yet, drop it.\n      if (lastConcrete === undefined) continue\n      value = lastConcrete\n    }\n    if (value !== null) lastConcrete = value\n    values.push(value)\n    offsets.push(stop.at)\n    eases.push(stop.ease)\n  }\n  if (values.length === 0) return null\n\n  const head = values[0] ?? null\n  const tailValues: V[] = []\n  const tailOffsets: (number | undefined)[] = []\n  const tailEases: (EasingInput | undefined)[] = []\n  for (let i = 1; i < values.length; i++) {\n    const value = values[i]\n    if (value === null || value === undefined) continue // an unresolved head-hold; skip\n    tailValues.push(value)\n    tailOffsets.push(offsets[i])\n    tailEases.push(eases[i])\n  }\n\n  if (tailValues.length === 0) {\n    // Single meaningful value: animate from the current state to it.\n    if (head === null) return null\n    return { teleport: undefined, waypoints: [head], offsets: [offsets[0]], eases: [eases[0]] }\n  }\n  return { teleport: head === null ? undefined : head, waypoints: tailValues, offsets: tailOffsets, eases: tailEases }\n}\n\nexport function runKeyframeChain<T>(\n  normalized: { teleport: T | undefined; waypoints: T[] },\n  ops: ChainOps<T>,\n  config: ChainConfig,\n): KeyframeChain {\n  const { waypoints } = normalized\n  let cancelled = false\n  let current: AnimationHandle | null = null\n  let onInterrupt: ((h: AnimationHandle) => void) | null = null\n  let resolveFinished = (): void => {}\n  const finished = new Promise<void>((resolve) => {\n    resolveFinished = resolve\n  })\n\n  if (waypoints.length === 0) {\n    resolveFinished()\n    return { handle: { finished, then: thenFinished(finished), stop: () => {} }, interrupt: () => {} }\n  }\n\n  if (config.reduced) {\n    // Springs converge, so fast-forwarding every segment equals settling on the\n    // last target: collapse straight to the final waypoint.\n    ops.settle(waypoints[waypoints.length - 1]!)\n    resolveFinished()\n    return { handle: { finished, then: thenFinished(finished), stop: () => {} }, interrupt: () => {} }\n  }\n\n  if (normalized.teleport !== undefined) ops.teleport(normalized.teleport)\n\n  const evenMs = config.duration !== undefined ? config.duration / waypoints.length : 0\n\n  void (async () => {\n    for (let i = 0; i < waypoints.length; i++) {\n      if (cancelled) return\n      const waypoint = waypoints[i]!\n      if (config.duration !== undefined) {\n        const ms = config.segmentDurations?.[i] ?? evenMs\n        const easing = config.segmentEasings?.[i] ?? config.easing\n        current = ops.tween(waypoint, ms, easing)\n      } else {\n        current = ops.spring(waypoint)\n      }\n      await current.finished\n      if (cancelled) return\n    }\n    resolveFinished()\n  })()\n\n  // stop() and interrupt() both end the chain mid-flight (a freeze vs. a handoff),\n  // so both fire 'interrupt' - the lifecycle owner above hooks it to report\n  // onInterrupt instead of onComplete. Natural completion never sets `cancelled`,\n  // so it never fires interrupt.\n  const handle: AnimationHandle = {\n    finished,\n    then: thenFinished(finished),\n    stop: () => {\n      if (cancelled) return\n      cancelled = true\n      current?.stop()\n      resolveFinished()\n      onInterrupt?.(handle)\n    },\n    eventCallback(event, fn) {\n      if (event === 'interrupt') onInterrupt = fn ?? null\n      return handle\n    },\n  }\n  return {\n    handle,\n    interrupt: () => {\n      if (cancelled) return\n      cancelled = true\n      resolveFinished()\n      onInterrupt?.(handle)\n    },\n  }\n}\n\n/**\n * Fill per-waypoint arrival positions to a non-decreasing 0..1 array. Explicit\n * `at` values anchor; gaps interpolate linearly between the nearest anchors (a\n * virtual 0 before the first, 1 at the last when unset) - the times[] contract.\n */\nexport function fillOffsets(count: number, explicit: ReadonlyArray<number | undefined>): number[] {\n  const out: (number | undefined)[] = []\n  for (let i = 0; i < count; i++) {\n    const at = explicit[i]\n    out.push(at === undefined ? undefined : Math.min(1, Math.max(0, at)))\n  }\n  if (out[count - 1] === undefined) out[count - 1] = 1\n\n  let lastIdx = -1\n  let lastVal = 0\n  for (let i = 0; i < count; i++) {\n    const at = out[i]\n    if (at === undefined) continue\n    const span = i - lastIdx\n    for (let j = lastIdx + 1; j < i; j++) out[j] = lastVal + ((at - lastVal) * (j - lastIdx)) / span\n    lastIdx = i\n    lastVal = at\n  }\n\n  // Clamp to non-decreasing so a mis-ordered `at` can never make a negative segment.\n  let prev = 0\n  const result: number[] = []\n  for (let i = 0; i < count; i++) {\n    const at = Math.min(1, Math.max(prev, out[i] ?? prev))\n    result.push(at)\n    prev = at\n  }\n  return result\n}\n","import { warnOnce } from '../value/warn'\n\n/**\n * An element animate() can drive: an HTML or SVG element. Both carry `.style`,\n * `getAttribute`/`setAttribute`, and resolve under getComputedStyle, so the same\n * style + attribute machinery serves both (SVG unlocks viewBox/r/points via `attr:`).\n */\nexport type AnimatableElement = HTMLElement | SVGElement\n\n/** What animate() accepts as its target: one element, a selector, a NodeList, or any element iterable. */\nexport type AnimationTarget = AnimatableElement | string | NodeList | Iterable<Element>\n\n/**\n * SSR-safe HTMLElement check. `typeof` guard first: HTMLElement is not a global\n * server-side, where a bare `instanceof HTMLElement` would throw ReferenceError.\n * Exported so animate()'s fast-path guard reuses it instead of a bare instanceof.\n */\nexport const isHTMLElement = (value: unknown): value is HTMLElement =>\n  typeof HTMLElement !== 'undefined' && value instanceof HTMLElement\n\n/** SSR-safe check for an animatable (HTML or SVG) element. */\nexport const isAnimatableElement = (value: unknown): value is AnimatableElement =>\n  (typeof HTMLElement !== 'undefined' && value instanceof HTMLElement) ||\n  (typeof SVGElement !== 'undefined' && value instanceof SVGElement)\n\n/**\n * Resolve an animate() target to a concrete element list. A selector is queried\n * against `root` (or the document) at call time - a static snapshot, so nodes\n * added later are not animated (re-resolve to pick them up). Non-element matches\n * (text nodes) are filtered out. SSR-safe: a selector with no document resolves to\n * [] (no throw), and an empty selector match warns once.\n */\nexport function resolveTargets(input: AnimationTarget, root?: ParentNode): AnimatableElement[] {\n  if (isAnimatableElement(input)) return [input]\n  if (typeof input === 'string') {\n    if (typeof document === 'undefined') {\n      warnOnce('targets:ssr', 'animate(selector) needs a document; no targets resolved server-side')\n      return []\n    }\n    const found = Array.from((root ?? document).querySelectorAll(input)).filter(isAnimatableElement)\n    if (found.length === 0) warnOnce(`targets:empty:${input}`, `selector \"${input}\" matched no elements`)\n    return found\n  }\n  // NodeList or any Element iterable: keep only HTML/SVG elements.\n  return Array.from(input as Iterable<Node>).filter(isAnimatableElement)\n}\n","import { warnOnce } from '../value/warn'\nimport type { AnimateKeyframes, AnimateValue } from './animate'\nimport type { AnimatableElement } from './resolve-target'\n\n/**\n * A target resolved against the current value. The numeric channels accept the\n * precise literal form (unitless); a registry property accepts the same plus a\n * unit (e.g. '+=40px'), which type-checks as a plain string and is detected at\n * runtime. '*=' scales.\n */\nexport type RelativeValue = `+=${number}` | `-=${number}` | `*=${number}`\n\n/** A per-target value: receives the item's index, its element, and the set count. */\nexport type ValueFn<V> = (index: number, element: AnimatableElement, total: number) => V\n\n/** A single magnitude read from a registry property, plus how to re-emit it preserving the unit/template. */\nexport interface Magnitude {\n  readonly value: number\n  reformat(next: number): string\n}\n\nexport interface ResolveContext {\n  readonly index: number\n  readonly element: AnimatableElement\n  readonly total: number\n  /** Current value of a numeric channel (caller bakes in the INITIAL fallback); undefined if `key` is not a numeric channel. */\n  readNumeric(key: string): number | undefined\n  /** Current single magnitude of a registry property + a re-emitter; undefined if not resolvable or multi-channel. */\n  readMagnitude(key: string): Magnitude | undefined\n}\n\n// A relative operand may carry a unit on a registry property (width:'+=40px');\n// the unit is informational - the result is re-emitted in the property's CURRENT\n// unit/template. Numeric channels are unitless.\nconst RELATIVE = /^([+\\-*])=(-?\\d*\\.?\\d+)[a-z%]*$/i\n\nconst parseRelative = (s: string): { op: '+' | '-' | '*'; operand: number } | null => {\n  const match = RELATIVE.exec(s)\n  if (match === null) return null\n  return { op: match[1] as '+' | '-' | '*', operand: Number(match[2]) }\n}\n\nconst applyRelative = (cur: number, op: '+' | '-' | '*', operand: number): number =>\n  op === '+' ? cur + operand : op === '-' ? cur - operand : cur * operand\n\n/** A keyframe stop object `{ value, at?, ease? }` - distinguished from a bare value/null. */\nconst isStop = (w: unknown): w is { value: AnimateValue | null } =>\n  w !== null && typeof w === 'object' && !Array.isArray(w)\n\n/** The value a waypoint carries (a bare value, a hold null, or a stop's `.value`). */\nconst waypointValue = (w: unknown): AnimateValue | null => (isStop(w) ? w.value : (w as AnimateValue | null))\n\n/** True if a raw value needs per-element resolution (a function, or a relative string incl. inside keyframes). */\nexport const needsResolve = (raw: unknown): boolean => {\n  if (typeof raw === 'function') return true\n  if (typeof raw === 'string') return RELATIVE.test(raw)\n  if (Array.isArray(raw)) {\n    return raw.some((waypoint) => {\n      const value = waypointValue(waypoint)\n      return typeof value === 'string' && RELATIVE.test(value)\n    })\n  }\n  return false\n}\n\nconst resolveScalar = (key: string, value: AnimateValue, ctx: ResolveContext): AnimateValue => {\n  if (typeof value !== 'string') return value\n  const rel = parseRelative(value)\n  if (rel === null) return value\n  const num = ctx.readNumeric(key)\n  if (num !== undefined) return applyRelative(num, rel.op, rel.operand)\n  const mag = ctx.readMagnitude(key)\n  if (mag !== undefined) return mag.reformat(applyRelative(mag.value, rel.op, rel.operand))\n  warnOnce(`relative:${key}`, `relative \"${value}\" on \"${key}\" is not decomposable; used ${rel.operand}`)\n  return rel.operand\n}\n\nconst resolveKeyframes = (key: string, frames: AnimateKeyframes, ctx: ResolveContext): AnimateKeyframes => {\n  // Relatives chain against the prior resolved waypoint (index 0 against the current value).\n  // One running magnitude serves both numeric channels and single-magnitude registry\n  // properties; the magnitude reader is fetched only when a relative is present (it reads\n  // computed style). An absolute waypoint re-seeds the chain so a following relative is correct.\n  const numeric = ctx.readNumeric(key)\n  const mag =\n    numeric === undefined &&\n    frames.some((waypoint) => {\n      const value = waypointValue(waypoint)\n      return typeof value === 'string' && parseRelative(value) !== null\n    })\n      ? ctx.readMagnitude(key)\n      : undefined\n  let running: number | undefined = numeric ?? mag?.value\n\n  // Resolve one waypoint's value against the running magnitude, advancing it.\n  const resolveOne = (value: AnimateValue | null): AnimateValue | null => {\n    if (value === null) return null\n    if (typeof value === 'number') {\n      running = value\n      return value\n    }\n    const rel = parseRelative(value)\n    if (rel === null) {\n      const seed = Number.parseFloat(value)\n      running = Number.isFinite(seed) ? seed : undefined\n      return value\n    }\n    if (running === undefined) {\n      warnOnce(`relative:${key}`, `relative \"${value}\" on \"${key}\" keyframe is not decomposable; used ${rel.operand}`)\n      return rel.operand\n    }\n    running = applyRelative(running, rel.op, rel.operand)\n    return mag !== undefined ? mag.reformat(running) : running\n  }\n\n  return frames.map((waypoint) =>\n    // A stop keeps its position/easing metadata; only its value resolves.\n    isStop(waypoint) ? { ...waypoint, value: resolveOne(waypoint.value) } : resolveOne(waypoint as AnimateValue | null),\n  )\n}\n\n/** A value before per-target resolution: an absolute value/keyframes, a relative string, or a function returning any of those. */\nexport type ResolvableValue =\n  | AnimateValue\n  | AnimateKeyframes\n  | RelativeValue\n  | ValueFn<AnimateValue | AnimateKeyframes | RelativeValue>\n\n/**\n * Resolve a possibly function/relative/keyframe value to an absolute value or\n * keyframe array for one element. A function is evaluated first (it may return a\n * relative string or a keyframe array, which re-enter resolution); relatives read\n * the LIVE cached value through `ctx`, so a re-fire retargets from the in-flight\n * position. Pure; never throws.\n */\nexport function resolveValue(key: string, raw: ResolvableValue, ctx: ResolveContext): AnimateValue | AnimateKeyframes {\n  const value = typeof raw === 'function' ? raw(ctx.index, ctx.element, ctx.total) : raw\n  if (Array.isArray(value)) return resolveKeyframes(key, value, ctx)\n  return resolveScalar(key, value as AnimateValue, ctx)\n}\n","import type { MeasureUnit } from '../value/value-type'\nimport type { StyleReader } from './read-style'\n\n// Percentages resolve against the containing block: the block axis for these\n// properties, the inline axis (parent width) for everything else - including all\n// margins and paddings, per CSS.\nconst BLOCK_AXIS = new Set(['height', 'minHeight', 'maxHeight', 'top', 'bottom', 'rowGap'])\n\nconst positive = (value: number): number | null =>\n  Number.isFinite(value) && value > 0 ? value : null\n\n/**\n * Builds the \"px per 1 unit\" function for one element+property context, used by\n * a value type's `convert` to rebase across units. Reads happen at most once per\n * unit (memoized) and only when that unit is actually requested; an unmeasurable\n * unit (no parent, zero/auto computed basis, unknown unit) returns null, which\n * makes the caller snap rather than mix incompatible units.\n */\nexport function createMeasure(\n  element: Element,\n  property: string,\n  read: StyleReader,\n): MeasureUnit {\n  const cache = new Map<string, number | null>()\n\n  const viewport = (pick: (w: number, h: number) => number): number | null => {\n    const doc = element.ownerDocument.documentElement\n    return positive(pick(doc.clientWidth, doc.clientHeight) / 100)\n  }\n\n  const compute = (unit: string): number | null => {\n    switch (unit) {\n      case 'px':\n        return 1\n      case 'em':\n        return positive(parseFloat(read.get('fontSize')))\n      case 'rem':\n        return positive(parseFloat(getComputedStyle(element.ownerDocument.documentElement).fontSize))\n      case '%': {\n        const parent = element.parentElement\n        if (parent === null) return null\n        const parentStyle = getComputedStyle(parent)\n        const basis = BLOCK_AXIS.has(property) ? parentStyle.height : parentStyle.width\n        return positive(parseFloat(basis) / 100)\n      }\n      case 'vw':\n        return viewport((w) => w)\n      case 'vh':\n        return viewport((_w, h) => h)\n      case 'vmin':\n        return viewport((w, h) => Math.min(w, h))\n      case 'vmax':\n        return viewport((w, h) => Math.max(w, h))\n      default:\n        return null\n    }\n  }\n\n  return (unit) => {\n    const cached = cache.get(unit)\n    if (cached !== undefined) return cached\n    const value = compute(unit)\n    cache.set(unit, value)\n    return value\n  }\n}\n","import { getReducedMotionBehavior, type ReducedMotionBehavior } from '../a11y/config'\nimport { prefersReducedMotion } from '../a11y/reduced-motion'\nimport { resolveEasing, type EasingInput } from '../physics/easing-registry'\nimport { easeInOutCubic, type Easing } from '../physics/easings'\nimport type { SpringOptions } from '../physics/spring'\nimport type { ToOptions } from '../physics/tween'\nimport type { Scheduler } from '../scheduler/scheduler'\nimport { getSharedScheduler } from '../scheduler/shared'\nimport { channelGroup, type ChannelGroup } from '../value/channel-group'\nimport { resolveValueType } from '../value/registry'\nimport type { ParsedValue, ValueType } from '../value/value-type'\nimport { warnOnce } from '../value/warn'\nimport { animatable, type Animatable, type AnimationHandle } from '../value/animatable'\nimport { thenFinished } from '../value/thenable'\nimport { waitFrames } from '../compose/wait'\nimport type { DelayFn } from '../compose/stagger-delay'\nimport { bindProperty, type PropertyBinding } from './bind-property'\nimport { bindStyle } from './bind-style'\nimport {\n  fillOffsets,\n  normalizeKeyframes,\n  runKeyframeChain,\n  type ChainConfig,\n  type ChainOps,\n  type KeyframeChain,\n  type KeyframeInput,\n  type NormalizedKeyframes,\n} from './keyframes'\nimport { readAttribute, readStyle, toKebab, type StyleReader } from './read-style'\nimport { isHTMLElement, resolveTargets, type AnimatableElement, type AnimationTarget } from './resolve-target'\nimport {\n  needsResolve,\n  resolveValue,\n  type Magnitude,\n  type RelativeValue,\n  type ResolvableValue,\n  type ResolveContext,\n  type ValueFn,\n} from './resolve-value'\nimport {\n  formatOrigin,\n  formatTransform,\n  ORIGIN_KEYS,\n  TRANSFORM_KEYS,\n  type OriginChannel,\n  type OriginChannels,\n  type TransformChannel,\n  type TransformChannels,\n} from './transform'\nimport { createMeasure } from './units'\n\ntype Channel = TransformChannel | OriginChannel | 'opacity'\n\n/** A CSS value the registry path animates: a number or a CSS string. */\nexport type AnimateValue = number | string\n\n/**\n * Keyframe waypoints. Each entry is a bare value, `null` (from-current at index 0,\n * a hold later), or an expressive `{ value, at, ease }` stop for per-segment\n * position and easing.\n */\nexport type AnimateKeyframes = ReadonlyArray<KeyframeInput<AnimateValue>>\nexport type NumericKeyframes = ReadonlyArray<KeyframeInput<number>>\n\n/**\n * Any property key that is NOT one of the five numeric channels: a\n * CSSStyleDeclaration property (camelCase), a custom property, or an `attr:name`\n * key routed to setAttribute (SVG/element attributes - viewBox, r, points). A typo\n * like `{ opactiy: 1 }` does not compile. (CSSStyleDeclaration method names\n * type-check as keys - accepted noise.)\n */\nexport type AnimateProperty = Exclude<Extract<keyof CSSStyleDeclaration, string>, Channel> | `--${string}` | `attr:${string}`\n\n/** A numeric-channel key: a transform/origin channel, opacity, or the autoAlpha alias (opacity + visibility). */\ntype NumericKey = Channel | 'autoAlpha'\n\nexport type { AnimationTarget } from './resolve-target'\nexport type { RelativeValue, ValueFn } from './resolve-value'\n\n/** A numeric-channel target: absolute, keyframes, a relative string, or a per-target function. */\ntype ResolvableNumeric = number | NumericKeyframes | RelativeValue | ValueFn<number | NumericKeyframes | RelativeValue>\n/** A registry-property target: absolute, keyframes, a relative string, or a per-target function. */\ntype ResolvableProperty =\n  | AnimateValue\n  | AnimateKeyframes\n  | RelativeValue\n  | ValueFn<AnimateValue | AnimateKeyframes | RelativeValue>\n\n/**\n * The five channels stay numeric; everything else routes through the value-type\n * registry. Each value may also be a relative string (`'+=100'`) resolved against\n * the current value, or a per-target function `(index, element, count) => value`.\n * The keys are unchanged, so a typo like `{ opactiy: 1 }` still does not compile.\n */\nexport type AnimateTargets = Partial<Record<NumericKey, ResolvableNumeric>> &\n  Partial<Record<AnimateProperty, ResolvableProperty>>\n\n/** The absolute targets animateOne() consumes after the per-element pre-pass (no functions/relatives). */\ntype ResolvedTargets = Partial<Record<Channel, number | NumericKeyframes>> &\n  Partial<Record<AnimateProperty, AnimateValue | AnimateKeyframes>>\n\n/** A from-state numeric value: absolute, a relative string, or a per-target function (no keyframes - a from-state is one value). */\ntype FromNumeric = number | RelativeValue | ValueFn<number | RelativeValue>\n/** A from-state registry value: absolute, a relative string, or a per-target function (no keyframes). */\ntype FromProperty = AnimateValue | RelativeValue | ValueFn<AnimateValue | RelativeValue>\n\n/**\n * An entrance from-state: the same keys and value forms as a target (channels\n * plus arbitrary CSS properties; absolute, relative `'+='`, or a per-target\n * function), but a single value per key - a from-state is one point, not a\n * keyframe path. Resolved per element against the live value at the call.\n */\nexport type FromTargets = Partial<Record<NumericKey, FromNumeric>> & Partial<Record<AnimateProperty, FromProperty>>\n\n/** The absolute from-state setStyle() teleports to, after per-element resolution. */\ntype ResolvedFrom = Partial<Record<NumericKey, number>> & Partial<Record<AnimateProperty, AnimateValue>>\n\nexport interface AnimateOptions extends Omit<SpringOptions, 'reducedMotion'> {\n  /** ms - providing a duration switches to the tween escape hatch. */\n  duration?: number\n  easing?: EasingInput\n  scheduler?: Scheduler\n  /**\n   * Per-target start delay. A number staggers each target by index*delay; a\n   * `DelayFn` from `staggerDelay()` is an expressive wave (origin, grid, axis,\n   * easing). On a single element it is just a flat lead-in.\n   */\n  delay?: number | DelayFn\n  /** Element-level reduced-motion strategy - 'fade' keeps opacity AND colors animated. */\n  reducedMotion?: ReducedMotionBehavior\n  /**\n   * Entrance from-state. Each key is set to its from-value SYNCHRONOUSLY at the\n   * call (no flash, no manual setStyle), then animated to `targets`. With a\n   * stagger `delay`, every element is parked at its from-state immediately and\n   * holds it through its own delay, like a real entrance. Same value forms as a\n   * target (absolute, relative `'+='`, per-target function), resolved per element\n   * against the live value. Under reduced motion the from-set is skipped: the\n   * element ends at `targets`, never stranded at the from-state. The `from()` and\n   * `fromTo()` helpers are thin sugar over this option.\n   */\n  from?: FromTargets\n  /** Fired once when the animation begins. */\n  onStart?(this: object, handle: AnimationHandle): void\n  /**\n   * Per frame with the live numeric channel values (`{ x, y, scale, ... }`). Requesting it\n   * runs the JS path (a per-frame tick), so it skips the WAAPI compositor fast path. Unlike a\n   * single value's `onUpdate`, this is NOT change-guarded - it ticks every frame of the run\n   * (a multi-channel object has no single \"changed\"); guard in the callback if you need to.\n   */\n  onUpdate?(this: object, values: Record<string, number>, handle: AnimationHandle): void\n  /** Fired once when every channel settles (no channel was interrupted). */\n  onComplete?(this: object, handle: AnimationHandle): void\n  /** Fired once when a channel is superseded by a later animate(), or the handle is stopped. */\n  onInterrupt?(this: object, handle: AnimationHandle): void\n  /** The `this` receiver for the callbacks. Defaults to the handle. */\n  scope?: object\n}\n\n/**\n * True if any lifecycle callback was requested - then the numeric path stays on the JS loop.\n * Even onStart/onComplete/scope opt out of WAAPI: the compositor reclaim path resolves\n * `finished` on a supersede the same as on a settle, so it cannot tell onComplete (settle)\n * from onInterrupt (supersede). The JS path can - each child handle reports its own interrupt -\n * so honoring the onComplete contract (never fires on a supersede) means owning every frame.\n */\nconst hasLifecycle = (o: AnimateOptions): boolean =>\n  o.onStart !== undefined ||\n  o.onUpdate !== undefined ||\n  o.onComplete !== undefined ||\n  o.onInterrupt !== undefined ||\n  o.scope !== undefined\n\n// First touch of a channel starts from its CSS-neutral value; afterwards the\n// cached animatable carries the real state across calls - that is what makes\n// a second animate() an interruption instead of a parallel animation.\nconst INITIAL: Record<Channel, number> = {\n  perspective: 0,\n  x: 0,\n  y: 0,\n  rotateX: 0,\n  rotateY: 0,\n  rotateZ: 0,\n  rotate: 0,\n  skewX: 0,\n  skewY: 0,\n  scale: 1,\n  scaleX: 1,\n  scaleY: 1,\n  originX: 50,\n  originY: 50,\n  opacity: 1,\n}\n\nconst TRANSFORM_CHANNELS: ReadonlyArray<Channel> = TRANSFORM_KEYS\nconst NUMERIC_CHANNELS = new Set<string>([...TRANSFORM_KEYS, ...ORIGIN_KEYS, 'opacity'])\n\n/** The slice of a WAAPI Animation the delegation relies on (testable shape). */\nexport interface DelegatedAnimation {\n  currentTime: CSSNumberish | null\n  onfinish: (() => void) | null\n  cancel(): void\n  // Optional members the playback layer drives; the two-field call sites here are unaffected.\n  playbackRate?: number\n  pause?(): void\n  play?(): void\n}\n\n/** Internal handle the playback layer maps controls onto. Not re-exported from the package entry. */\nexport interface DelegatedControls {\n  readonly animation: DelegatedAnimation\n  readonly durationMs: number\n}\n\ninterface DelegatedTween {\n  animation: DelegatedAnimation\n  /** Per-channel frame arrays, all of length n (the keyframe count). */\n  channels: Map<Channel, number[]>\n  n: number\n  durationMs: number\n  easing: Easing\n  finish: () => void\n}\n\ninterface GroupEntry {\n  group: ChannelGroup\n  binding: PropertyBinding\n  /** 'attr' groups clean up via removeAttribute; 'style' via style.removeProperty. */\n  target: PropTarget\n  /** The bare DOM name written (an attribute name, or the style property). */\n  name: string\n}\n\n/** Where a registry-property group writes: an inline style property or an element attribute. */\ntype PropTarget = 'style' | 'attr'\nconst ATTR_PREFIX = 'attr:'\nconst isAttrKey = (key: string): boolean => key.startsWith(ATTR_PREFIX)\n/** The bare DOM name behind a target key ('attr:r' -> 'r'; a style key is itself). */\nconst bareName = (key: string): string => (key.startsWith(ATTR_PREFIX) ? key.slice(ATTR_PREFIX.length) : key)\n\ninterface ElementEntry {\n  values: Partial<Record<Channel, Animatable>>\n  disposeBinding: () => void\n  scheduler: Scheduler\n  delegated: DelegatedTween | null\n  groups: Map<string, GroupEntry>\n  /** Per-key running keyframe chains, so a new animate() on that key can interrupt them. */\n  chains: Map<string, () => void>\n  /** Bumped on every animation intent on this element, so a pending staggered start can tell it was superseded. */\n  generation: number\n  /** Once autoAlpha touched this element, its opacity write also toggles visibility. */\n  autoAlpha: boolean\n}\n\n/** Mark a new animation intent on the element and return the fresh generation token. */\nconst markIntent = (entry: ElementEntry): number => (entry.generation += 1)\n\nconst registry = new WeakMap<AnimatableElement, ElementEntry>()\n\nconst supportsWaapi = (element: AnimatableElement): boolean =>\n  typeof element.animate === 'function' &&\n  typeof CSS !== 'undefined' &&\n  typeof CSS.supports === 'function' &&\n  CSS.supports('animation-timing-function', 'linear(0, 1)')\n\n// Arbitrary easing functions ride to the compositor as a sampled linear().\nconst EASING_SAMPLES = 16\nconst toLinearEasing = (easing: Easing): string => {\n  const stops: string[] = []\n  for (let i = 0; i <= EASING_SAMPLES; i++) stops.push(String(easing(i / EASING_SAMPLES)))\n  return `linear(${stops.join(', ')})`\n}\n\n/**\n * Take control back from the compositor: evaluate the curve at currentTime -\n * position AND derivative, per segment - seed the animatables with both, cancel\n * WAAPI. No DOM readback, no precision loss: the math was ours all along. With\n * n keyframes the progress maps onto an even segment grid; n = 2 degenerates to\n * a single segment (the original two-keyframe reclaim).\n */\nconst reclaim = (entry: ElementEntry): void => {\n  const delegated = entry.delegated\n  if (delegated === null) return\n  entry.delegated = null\n\n  const elapsedMs = Math.min(\n    Number(delegated.animation.currentTime ?? delegated.durationMs),\n    delegated.durationMs,\n  )\n  const progress = delegated.durationMs <= 0 ? 1 : elapsedMs / delegated.durationMs\n  const segments = delegated.n - 1\n  const s = progress * segments\n  const index = Math.min(Math.floor(s), segments - 1)\n  const t = s - index\n  const window = 0.01\n  const t1 = Math.min(1, t + window)\n  const t0 = Math.max(0, t - window)\n  const slope = (delegated.easing(t1) - delegated.easing(t0)) / (t1 - t0)\n  const segmentDurationS = delegated.durationMs / 1000 / segments\n  // A reversed delegated tween (playbackRate < 0) hands back a negated velocity;\n  // the forward path defaults to 1, so existing reclaims are byte-identical.\n  const rateSign = Math.sign(delegated.animation.playbackRate ?? 1) || 1\n\n  for (const [channel, frames] of delegated.channels) {\n    const value = entry.values[channel]\n    if (value === undefined) continue\n    const from = frames[index] ?? 0\n    const to = frames[index + 1] ?? from\n    const span = to - from\n    value.set(from + span * delegated.easing(t), { velocity: ((span * slope) / segmentDurationS) * rateSign })\n  }\n  delegated.animation.cancel()\n  delegated.finish()\n}\n\nconst ensureChannel = (entry: ElementEntry, channel: Channel): { value: Animatable; created: boolean } => {\n  const existing = entry.values[channel]\n  if (existing !== undefined) return { value: existing, created: false }\n  const value = animatable(INITIAL[channel], { scheduler: entry.scheduler })\n  entry.values[channel] = value\n  return { value, created: true }\n}\n\nconst rebind = (entry: ElementEntry, element: AnimatableElement): void => {\n  entry.disposeBinding()\n  entry.disposeBinding = bindStyle(element, entry.values, { scheduler: entry.scheduler, autoAlpha: entry.autoAlpha })\n}\n\ntype NumericNorm = { teleport: number | undefined; waypoints: number[] }\n\nconst delegateMultiKeyframe = (\n  entry: ElementEntry,\n  element: AnimatableElement,\n  scalars: Array<[Channel, number]>,\n  keyframeNorms: Array<[Channel, NumericNorm]>,\n  durationMs: number,\n  easing: Easing,\n): AnimationHandle => {\n  const channels = new Map<Channel, number[]>()\n  let newChannel = false\n  for (const [channel, target] of scalars) {\n    const { value, created } = ensureChannel(entry, channel)\n    newChannel ||= created\n    channels.set(channel, [value.get(), target])\n  }\n  for (const [channel, norm] of keyframeNorms) {\n    const { value, created } = ensureChannel(entry, channel)\n    newChannel ||= created\n    channels.set(channel, norm.teleport !== undefined ? [norm.teleport, ...norm.waypoints] : [value.get(), ...norm.waypoints])\n  }\n  if (newChannel) rebind(entry, element)\n\n  const n = [...channels.values()][0]?.length ?? 2\n\n  // A transform / transform-origin keyframe overrides the whole property, so\n  // carry the untouched channels of that group along as constants every frame.\n  const animatedKeys = [...channels.keys()]\n  const carry = (group: ReadonlyArray<Channel>): void => {\n    for (const channel of group) {\n      const value = entry.values[channel]\n      if (value !== undefined && !channels.has(channel)) {\n        channels.set(channel, new Array<number>(n).fill(value.get()))\n      }\n    }\n  }\n  if (animatedKeys.some((c) => c !== 'opacity' && c !== 'originX' && c !== 'originY')) carry(TRANSFORM_CHANNELS)\n  if (animatedKeys.some((c) => c === 'originX' || c === 'originY')) carry(ORIGIN_KEYS)\n\n  const linearEasing = toLinearEasing(easing)\n  const keyframes: Record<string, string>[] = []\n  for (let i = 0; i < n; i++) {\n    const frame: Record<string, string> = {}\n    const transform: TransformChannels = {}\n    const origin: OriginChannels = {}\n    for (const [channel, frames] of channels) {\n      const value = frames[i] ?? 0\n      if (channel === 'opacity') frame['opacity'] = String(value)\n      else if (channel === 'originX' || channel === 'originY') origin[channel] = value\n      else transform[channel] = value\n    }\n    if (Object.keys(transform).length > 0) frame['transform'] = formatTransform(transform)\n    if (Object.keys(origin).length > 0) frame['transformOrigin'] = formatOrigin(origin)\n    // Multi-keyframe: the easing rides each keyframe but the last - WAAPI applies\n    // a keyframe's easing across the interval to the next one (so the JS reclaim\n    // and the compositor agree on per-segment timing).\n    if (n > 2 && i < n - 1) frame['easing'] = linearEasing\n    keyframes.push(frame)\n  }\n\n  let resolveFinished = () => {}\n  const finished = new Promise<void>((resolve) => {\n    resolveFinished = resolve\n  })\n\n  // Two keyframes: a single segment, easing at the animation level - the\n  // original delegation shape.\n  const options: Record<string, unknown> = { duration: durationMs, fill: 'forwards' }\n  if (n === 2) options['easing'] = linearEasing\n  const animation = element.animate(keyframes, options) as unknown as DelegatedAnimation\n  const tween: DelegatedTween = { animation, channels, n, durationMs, easing, finish: resolveFinished }\n  entry.delegated = tween\n\n  animation.onfinish = () => {\n    if (entry.delegated !== tween) return\n    entry.delegated = null\n    for (const [channel, frames] of channels) entry.values[channel]?.set(frames[frames.length - 1] ?? 0)\n    // Cancel only after the next render flush wrote the committed values -\n    // cancelling first would flash the pre-animation inline style.\n    const unsubscribe = entry.scheduler.subscribe(() => {\n      unsubscribe()\n      animation.cancel()\n    }, 'render')\n    resolveFinished()\n  }\n\n  return {\n    finished,\n    then: thenFinished(finished),\n    stop: () => {\n      if (entry.delegated === tween) reclaim(entry)\n    },\n  }\n}\n\nconst RESOLVED_PROMISE = Promise.resolve()\nconst RESOLVED: AnimationHandle = {\n  finished: RESOLVED_PROMISE,\n  then: thenFinished(RESOLVED_PROMISE),\n  stop: () => {},\n}\n\n// Forwards its children's interrupt up as ONE interrupt, so an outer lifecycle\n// owner (multi-target withLifecycle, where each child IS an aggregate) can tell a\n// supersede from a settle. The single-channel case returns the bare handle, which\n// already carries eventCallback.\nconst aggregate = (handles: AnimationHandle[]): AnimationHandle => {\n  if (handles.length === 0) return RESOLVED\n  if (handles.length === 1) return handles[0]!\n  let onInterrupt: ((h: AnimationHandle) => void) | null = null\n  let fired = false\n  const fireInterrupt = (): void => {\n    if (fired) return\n    fired = true\n    onInterrupt?.(handle)\n  }\n  for (const child of handles) child.eventCallback?.('interrupt', fireInterrupt)\n  const finished = Promise.all(handles.map((child) => child.finished)).then(() => undefined)\n  const handle: AnimationHandle = {\n    finished,\n    then: thenFinished(finished),\n    stop: () => {\n      for (const child of handles) child.stop()\n    },\n    eventCallback(event, fn) {\n      if (event === 'interrupt') onInterrupt = fn ?? null\n      return handle\n    },\n  }\n  return handle\n}\n\n/**\n * Wrap the aggregate with lifecycle callbacks. onStart fires synchronously; onUpdate\n * ticks the live numeric values each frame (not change-guarded - see AnimateOptions);\n * the FIRST child interrupted fires onInterrupt, else onComplete fires at settle. Every\n * child reports its own interrupt: a numeric channel IS an animatable, and the keyframe\n * chain and registry-property group each forward their interrupt through eventCallback,\n * so a superseded color or keyframe channel reads as onInterrupt, never a false onComplete.\n * post-hoc eventCallback handles start/complete/interrupt; onUpdate must be passed at the\n * call (it decides the JS path up front), and repeat/reverseComplete are playback-only.\n */\nconst withLifecycle = (\n  base: AnimationHandle,\n  children: AnimationHandle[],\n  options: AnimateOptions,\n  readValues: () => Record<string, number>,\n  scheduler: Scheduler,\n): AnimationHandle => {\n  const scope = options.scope\n  let onStart = options.onStart\n  let onUpdate = options.onUpdate\n  let onComplete = options.onComplete\n  let onInterrupt = options.onInterrupt\n  let ended = false\n  let unsubUpdate: (() => void) | null = null\n  let handle: AnimationHandle\n  const finishUpdate = (): void => {\n    unsubUpdate?.()\n    unsubUpdate = null\n  }\n  const end = (cb: ((this: object, handle: AnimationHandle) => void) | undefined): void => {\n    if (ended) return\n    ended = true\n    finishUpdate()\n    cb?.call(scope ?? handle, handle)\n  }\n\n  for (const child of children) child.eventCallback?.('interrupt', () => end(onInterrupt))\n  void base.finished.then(() => end(onComplete))\n\n  handle = {\n    finished: base.finished,\n    then: thenFinished(base.finished),\n    stop: () => base.stop(), // interrupts the children -> their interrupt fires onInterrupt above\n    eventCallback(event, fn) {\n      const cb = fn ?? undefined\n      if (event === 'start') onStart = cb as AnimateOptions['onStart']\n      else if (event === 'complete') onComplete = cb as AnimateOptions['onComplete']\n      else if (event === 'interrupt') onInterrupt = cb as AnimateOptions['onInterrupt']\n      return handle\n    },\n  }\n\n  if (onUpdate !== undefined) {\n    unsubUpdate = scheduler.subscribe(() => {\n      if (ended) {\n        finishUpdate()\n        return\n      }\n      onUpdate?.call(scope ?? handle, readValues(), handle)\n    })\n  }\n  onStart?.call(scope ?? handle, handle)\n  return handle\n}\n\nconst springOptionsFrom = (options: AnimateOptions): SpringOptions => {\n  const spring: SpringOptions = { reducedMotion: 'allow' }\n  if (options.stiffness !== undefined) spring.stiffness = options.stiffness\n  if (options.damping !== undefined) spring.damping = options.damping\n  if (options.mass !== undefined) spring.mass = options.mass\n  if (options.velocity !== undefined) spring.velocity = options.velocity\n  if (options.restDelta !== undefined) spring.restDelta = options.restDelta\n  if (options.restSpeed !== undefined) spring.restSpeed = options.restSpeed\n  return spring\n}\n\n/** Stop a running keyframe chain on this key (a new motion is taking over). */\nconst interruptKey = (entry: ElementEntry, key: string): void => {\n  const interrupt = entry.chains.get(key)\n  if (interrupt !== undefined) {\n    entry.chains.delete(key)\n    interrupt()\n  }\n}\n\n/** Register a chain so the next animate() on its key can interrupt it, and self-clean on completion. */\nconst startChain = (entry: ElementEntry, key: string, chain: KeyframeChain): AnimationHandle => {\n  entry.chains.set(key, chain.interrupt)\n  void chain.handle.finished.then(() => {\n    if (entry.chains.get(key) === chain.interrupt) entry.chains.delete(key)\n  })\n  return chain.handle\n}\n\n/** The motion for one scalar numeric target - the original per-channel decision. */\nconst startNumericScalar = (\n  value: Animatable,\n  target: number,\n  channel: Channel,\n  options: AnimateOptions,\n  behavior: ReducedMotionBehavior,\n  reduced: boolean,\n): AnimationHandle => {\n  if (reduced) {\n    if (behavior === 'fade' && channel === 'opacity') {\n      return value.to(target, { duration: 250, reducedMotion: 'allow' })\n    }\n    return value.spring(target, { reducedMotion: 'skip' })\n  }\n  if (options.duration !== undefined) {\n    const toOptions: ToOptions =\n      options.easing === undefined\n        ? { duration: options.duration, reducedMotion: 'allow' }\n        : { duration: options.duration, easing: options.easing, reducedMotion: 'allow' }\n    return value.to(target, toOptions)\n  }\n  return value.spring(target, springOptionsFrom(options))\n}\n\n/** Start the right motion on a group given the element-side reduced-motion decision. */\nconst startGroupMotion = (\n  group: ChannelGroup,\n  target: ParsedValue,\n  type: ValueType,\n  options: AnimateOptions,\n  behavior: ReducedMotionBehavior,\n  reduced: boolean,\n): AnimationHandle => {\n  if (reduced) {\n    // Colors (non-spatial) keep crossfading under 'fade'; everything spatial snaps.\n    if (behavior === 'fade' && type.spatial === false) {\n      return group.to(target, { duration: 250, reducedMotion: 'allow' })\n    }\n    return group.spring(target, { reducedMotion: 'skip' })\n  }\n  if (options.duration !== undefined) {\n    const toOptions: ToOptions =\n      options.easing === undefined\n        ? { duration: options.duration, reducedMotion: 'allow' }\n        : { duration: options.duration, easing: options.easing, reducedMotion: 'allow' }\n    return group.to(target, toOptions)\n  }\n  return group.spring(target, springOptionsFrom(options))\n}\n\n/** Create a cold group, start its motion BEFORE binding (so a skip settle rides the synchronous bind write), then store it. */\nconst installGroup = (\n  entry: ElementEntry,\n  element: AnimatableElement,\n  property: string,\n  type: ValueType,\n  start: ParsedValue,\n  startMotion: (group: ChannelGroup) => AnimationHandle,\n  target: PropTarget = 'style',\n): AnimationHandle => {\n  const name = target === 'attr' ? bareName(property) : property\n  const group = channelGroup(type, start, { scheduler: entry.scheduler })\n  const handle = startMotion(group)\n  const binding = bindProperty(element, name, group, { scheduler: entry.scheduler, target })\n  entry.groups.set(property, { group, binding, target, name })\n  return handle\n}\n\n/** Write a literal value, dropping any group on the property. Resolves immediately, no warning. */\nconst writeLiteral = (\n  entry: ElementEntry,\n  element: AnimatableElement,\n  property: string,\n  value: AnimateValue,\n  target: PropTarget = 'style',\n): AnimationHandle => {\n  const existing = entry.groups.get(property)\n  if (existing !== undefined) {\n    existing.binding.dispose()\n    existing.group.dispose()\n    entry.groups.delete(property)\n  }\n  if (target === 'attr') element.setAttribute(bareName(property), String(value))\n  else element.style.setProperty(toKebab(property), String(value))\n  return RESOLVED\n}\n\n/** Drop a property's group: cannot decompose the target, write it literally and warn. */\nconst snapLiteral = (\n  entry: ElementEntry,\n  element: AnimatableElement,\n  property: string,\n  value: AnimateValue,\n  target: PropTarget = 'style',\n): AnimationHandle => {\n  warnOnce(`snap:${property}`, `cannot animate \"${property}\" to \"${String(value)}\"; snapped`)\n  return writeLiteral(entry, element, property, value, target)\n}\n\nconst animateProperty = (\n  entry: ElementEntry,\n  element: AnimatableElement,\n  property: string,\n  value: AnimateValue,\n  read: StyleReader,\n  options: AnimateOptions,\n  behavior: ReducedMotionBehavior,\n  reduced: boolean,\n  channel: PropTarget = 'style',\n): AnimationHandle => {\n  const name = bareName(property)\n  const type = resolveValueType(name)\n  const begin = (group: ChannelGroup, target: ParsedValue): AnimationHandle =>\n    startGroupMotion(group, target, type, options, behavior, reduced)\n  const existing = entry.groups.get(property)\n\n  if (existing !== undefined) {\n    const group = existing.group\n    // A keyword target (e.g. 'none') resolves against the live shape.\n    const target = type.parse(value) ?? type.reconcile?.(String(value), group.shape) ?? null\n    if (target === null) return snapLiteral(entry, element, property, value, channel)\n    if (target.shape === group.shape) return begin(group, target)\n    const multiplier = type.convert?.(group.shape, target.shape, createMeasure(element, name, read)) ?? null\n    if (multiplier !== null) {\n      group.rebase(multiplier, target.shape)\n      return begin(group, target)\n    }\n    // Shape mismatch with no conversion (e.g. 1 shadow -> 2): snap, recreate at target.\n    existing.binding.dispose()\n    existing.group.dispose()\n    entry.groups.delete(property)\n    warnOnce(`snap:${property}`, `\"${name}\" changed shape (${group.shape} -> ${target.shape}); snapped`)\n    return installGroup(entry, element, property, type, target, () => RESOLVED, channel)\n  }\n\n  // Cold start.\n  const raw = read.get(name)\n  const parsedTarget = type.parse(value)\n  if (parsedTarget === null) {\n    // Keyword target: synthesize against the current computed shape.\n    const current = type.parse(raw)\n    if (current !== null && type.reconcile !== undefined) {\n      const recon = type.reconcile(String(value), current.shape)\n      if (recon !== null)\n        return installGroup(entry, element, property, type, current, (group) => begin(group, recon), channel)\n    }\n    return snapLiteral(entry, element, property, value, channel)\n  }\n  const target = parsedTarget\n\n  const current = type.reconcile?.(raw, target.shape) ?? type.parse(raw)\n  if (current !== null && current.shape === target.shape) {\n    return installGroup(entry, element, property, type, current, (group) => begin(group, target), channel)\n  }\n  if (current !== null) {\n    const multiplier = type.convert?.(current.shape, target.shape, createMeasure(element, name, read)) ?? null\n    if (multiplier !== null) {\n      return installGroup(\n        entry,\n        element,\n        property,\n        type,\n        current,\n        (group) => {\n          group.rebase(multiplier, target.shape)\n          return begin(group, target)\n        },\n        channel,\n      )\n    }\n  }\n  // No resolvable start value (computed 'auto', detached parent, ...): snap to target.\n  warnOnce(`snap:${property}`, `cannot resolve a start for \"${name}\" (computed \"${raw}\"); snapped to target`)\n  return installGroup(entry, element, property, type, target, () => RESOLVED, channel)\n}\n\n/**\n * Per-segment tween timings from a normalized keyframe result: variable segment\n * durations from explicit `at` positions and per-segment easings from explicit\n * `ease`. Both are tween-only - positions need a duration; per-segment easing is\n * carried regardless (the chain applies it only on the tween branch).\n */\nconst segmentTimings = (\n  normalized: NormalizedKeyframes<unknown>,\n  duration: number | undefined,\n): Pick<ChainConfig, 'segmentDurations' | 'segmentEasings'> => {\n  const { waypoints, offsets, eases } = normalized\n  const out: Pick<ChainConfig, 'segmentDurations' | 'segmentEasings'> = {}\n  if (eases.some((e) => e !== undefined)) {\n    out.segmentEasings = eases.map((e) => (e !== undefined ? resolveEasing(e) : undefined))\n  }\n  if (duration !== undefined && offsets.some((o) => o !== undefined)) {\n    const arrivals = fillOffsets(waypoints.length, offsets)\n    const durations: number[] = []\n    let prev = 0\n    for (const arrival of arrivals) {\n      durations.push(Math.max(0, arrival - prev) * duration)\n      prev = arrival\n    }\n    out.segmentDurations = durations\n  }\n  return out\n}\n\n/** True if any waypoint carries an explicit position or per-segment easing (the expressive form). */\nconst hasKeyframeMeta = (normalized: NormalizedKeyframes<unknown>): boolean =>\n  normalized.offsets.some((o) => o !== undefined) || normalized.eases.some((e) => e !== undefined)\n\nconst animatePropertyKeyframes = (\n  entry: ElementEntry,\n  element: AnimatableElement,\n  property: string,\n  frames: AnimateKeyframes,\n  read: StyleReader,\n  options: AnimateOptions,\n  reduced: boolean,\n  channel: PropTarget = 'style',\n): AnimationHandle => {\n  const name = bareName(property)\n  const type = resolveValueType(name)\n  const normalized = normalizeKeyframes<AnimateValue>(frames)\n  if (normalized === null) return RESOLVED\n  const last = normalized.waypoints[normalized.waypoints.length - 1] ?? ''\n\n  // Every non-null entry - the explicit keyframe-0 lead AND every waypoint -\n  // must parse to one common shape (same unit, same template).\n  const rawEntries: AnimateValue[] =\n    normalized.teleport !== undefined ? [normalized.teleport, ...normalized.waypoints] : [...normalized.waypoints]\n  const parsedEntries: ParsedValue[] = []\n  for (const raw of rawEntries) {\n    const parsed = type.parse(raw)\n    if (parsed === null) return snapLiteral(entry, element, property, last, channel)\n    parsedEntries.push(parsed)\n  }\n  const first = parsedEntries[0]\n  if (first === undefined) return RESOLVED\n  const shape = first.shape\n  if (parsedEntries.some((parsed) => parsed.shape !== shape)) {\n    warnOnce(`keyframe-shape:${property}`, `\"${name}\" keyframes mix units/shapes; snapped to the last`)\n    return writeLiteral(entry, element, property, last, channel)\n  }\n\n  const teleport = normalized.teleport !== undefined ? parsedEntries[0] : undefined\n  const waypoints = normalized.teleport !== undefined ? parsedEntries.slice(1) : parsedEntries\n\n  const buildChain = (group: ChannelGroup): AnimationHandle => {\n    const ops: ChainOps<ParsedValue> = {\n      teleport: (target) => group.set(target),\n      spring: (target) => group.spring(target, springOptionsFrom(options)),\n      tween: (target, ms, easing) => group.to(target, { duration: ms, easing, reducedMotion: 'allow' }),\n      settle: (target) => group.spring(target, { reducedMotion: 'skip' }),\n    }\n    const chain = runKeyframeChain({ teleport, waypoints }, ops, {\n      ...(options.duration !== undefined ? { duration: options.duration } : {}),\n      easing: resolveEasing(options.easing ?? easeInOutCubic),\n      reduced,\n      ...segmentTimings(normalized, options.duration),\n    })\n    return startChain(entry, property, chain)\n  }\n\n  // Reuse a warm group of the matching shape; otherwise (re)create at a start.\n  const existing = entry.groups.get(property)\n  if (existing !== undefined && existing.group.shape === shape) {\n    return buildChain(existing.group)\n  }\n  if (existing !== undefined) {\n    existing.binding.dispose()\n    existing.group.dispose()\n    entry.groups.delete(property)\n  }\n  let start = teleport\n  if (start === undefined) {\n    const raw = read.get(name)\n    const current = type.reconcile?.(raw, shape) ?? type.parse(raw)\n    start = current !== null && current.shape === shape ? current : first\n  }\n  return installGroup(entry, element, property, type, start, buildChain, channel)\n}\n\n/**\n * Internal seam for @underlying/core/playback: the live WAAPI animation an\n * element's delegated tween rides, so playback can map pause/seek/timeScale/\n * reverse onto native compositor controls. Returns null on the JS path. NOT\n * exported from the package entry (index.ts).\n */\nexport function __getDelegated(element: AnimatableElement): DelegatedControls | null {\n  const delegated = registry.get(element)?.delegated\n  if (delegated === null || delegated === undefined) return null\n  return { animation: delegated.animation, durationMs: delegated.durationMs }\n}\n\nconst ensureEntry = (element: AnimatableElement, scheduler: Scheduler | undefined): ElementEntry => {\n  let entry = registry.get(element)\n  if (entry === undefined) {\n    entry = {\n      values: {},\n      disposeBinding: () => {},\n      scheduler: scheduler ?? getSharedScheduler(),\n      delegated: null,\n      groups: new Map(),\n      chains: new Map(),\n      generation: 0,\n      autoAlpha: false,\n    }\n    registry.set(element, entry)\n  }\n  return entry\n}\n\n/**\n * The numeric channels: delegate an eligible duration tween (scalar or uniform\n * multi-keyframe) to the compositor, else run on the rAF loop. Delegation needs\n * a duration, WAAPI with linear() support, no other numeric channel mid-physics\n * (a transform-ownership conflict), and a single frame count across channels.\n */\nconst handleNumeric = (\n  entry: ElementEntry,\n  element: AnimatableElement,\n  scalars: Array<[Channel, number]>,\n  keyframes: Array<[Channel, NumericKeyframes]>,\n  options: AnimateOptions,\n  behavior: ReducedMotionBehavior,\n  reduced: boolean,\n): AnimationHandle[] => {\n  // Any lifecycle callback opts out of WAAPI delegation onto the per-channel JS handles:\n  // onUpdate ticks them each frame, onInterrupt reads a child's interrupt, and even\n  // onStart/onComplete need it - the compositor reclaim cannot tell a settle from a\n  // supersede, so onComplete would fire on both (see hasLifecycle).\n  // autoAlpha opts out too: its visibility toggle rides the JS opacity write, which\n  // the compositor path skips.\n  if (!reduced && options.duration !== undefined && supportsWaapi(element) && !hasLifecycle(options) && !entry.autoAlpha) {\n    const midPhysics = Object.values(entry.values).some((value) => value !== undefined && value.isAnimating())\n    if (!midPhysics) {\n      // Frame counts WITHOUT side effects: scalar = 2, keyframe = 1 + waypoints.\n      const lengths = new Set<number>()\n      for (const _ of scalars) lengths.add(2)\n      const norms: Array<[Channel, NumericNorm]> = []\n      let expressive = false\n      for (const [channel, frames] of keyframes) {\n        const norm = normalizeKeyframes<number>(frames)\n        if (norm === null) continue\n        // Per-segment positions/easings vary per channel; WAAPI shares one offset/\n        // easing per keyframe row across all properties, so route the whole set to\n        // the JS path (which applies them per channel) rather than delegate.\n        if (hasKeyframeMeta(norm)) expressive = true\n        norms.push([channel, norm])\n        lengths.add(1 + norm.waypoints.length)\n      }\n      if (!expressive && lengths.size === 1 && scalars.length + norms.length > 0) {\n        return [delegateMultiKeyframe(entry, element, scalars, norms, options.duration, resolveEasing(options.easing ?? easeInOutCubic))]\n      }\n    }\n  }\n  return animateNumericJs(entry, element, scalars, keyframes, options, behavior, reduced)\n}\n\n/**\n * The numeric path on the rAF loop: scalar channels spring or tween; keyframe\n * channels run a chained-spring / piecewise-tween sequence. Used whenever\n * delegation is ineligible (springs, reduced motion, mixed frame counts, a\n * channel mid-physics, or no WAAPI).\n */\nconst animateNumericJs = (\n  entry: ElementEntry,\n  element: AnimatableElement,\n  scalars: Array<[Channel, number]>,\n  keyframes: Array<[Channel, NumericKeyframes]>,\n  options: AnimateOptions,\n  behavior: ReducedMotionBehavior,\n  reduced: boolean,\n): AnimationHandle[] => {\n  let newChannel = false\n  const prepared: Array<{ value: Animatable; channel: Channel; frames: NumericKeyframes }> = []\n  const handles: AnimationHandle[] = []\n\n  for (const [channel, target] of scalars) {\n    const { value, created } = ensureChannel(entry, channel)\n    newChannel ||= created\n    handles.push(startNumericScalar(value, target, channel, options, behavior, reduced))\n  }\n  for (const [channel, frames] of keyframes) {\n    const { value, created } = ensureChannel(entry, channel)\n    newChannel ||= created\n    prepared.push({ value, channel, frames })\n  }\n\n  // Rebind once before starting chains so a reduced-motion settle on a freshly\n  // created channel rides the first flush.\n  if (newChannel) rebind(entry, element)\n\n  for (const { value, channel, frames } of prepared) {\n    const normalized = normalizeKeyframes(frames)\n    if (normalized === null) continue\n    const ops: ChainOps<number> = {\n      teleport: (v) => value.set(v),\n      spring: (v) => value.spring(v, springOptionsFrom(options)),\n      tween: (v, ms, easing) => value.to(v, { duration: ms, easing, reducedMotion: 'allow' }),\n      settle: (v) => value.spring(v, { reducedMotion: 'skip' }),\n    }\n    const chain = runKeyframeChain(normalized, ops, {\n      ...(options.duration !== undefined ? { duration: options.duration } : {}),\n      easing: resolveEasing(options.easing ?? easeInOutCubic),\n      reduced,\n      ...segmentTimings(normalized, options.duration),\n    })\n    handles.push(startChain(entry, channel, chain))\n  }\n  return handles\n}\n\n/**\n * Spring (default) or tween the style channels of ONE element with ALREADY\n * RESOLVED targets (no functions/relatives - the public animate() does the\n * per-element pre-pass). The five numeric channels keep their compositor fast\n * path; any other CSS property routes through the value-type registry. Repeated\n * calls retarget the same underlying values - never a jump.\n */\nfunction animateOne(element: AnimatableElement, targets: AnimateTargets, options: AnimateOptions): AnimationHandle {\n  const entry = ensureEntry(element, options.scheduler)\n  markIntent(entry) // a fresh intent supersedes any still-waiting staggered start on this element\n  // Any new call on the element interrupts a delegated tween first.\n  reclaim(entry)\n\n  const behavior = options.reducedMotion ?? getReducedMotionBehavior()\n  const reduced = behavior !== 'allow' && prefersReducedMotion()\n\n  const numericScalars: Array<[Channel, number]> = []\n  const numericKeyframes: Array<[Channel, NumericKeyframes]> = []\n  const scalarProperties: Array<[string, AnimateValue]> = []\n  const keyframeProperties: Array<[string, AnimateKeyframes]> = []\n  const attrScalars: Array<[string, AnimateValue]> = []\n  const attrKeyframes: Array<[string, AnimateKeyframes]> = []\n  let autoAlpha = false\n  let plainOpacity = false\n  for (const key of Object.keys(targets)) {\n    const value = (targets as Record<string, AnimateValue | AnimateKeyframes | undefined>)[key]\n    if (value === undefined) continue\n    // A new motion on a key takes over any keyframe chain still running there.\n    interruptKey(entry, key)\n    if (key === 'autoAlpha') {\n      // An alias of the opacity channel that also toggles visibility (handled at the bind).\n      autoAlpha = true\n      interruptKey(entry, 'opacity')\n      if (Array.isArray(value)) numericKeyframes.push(['opacity', value as NumericKeyframes])\n      else numericScalars.push(['opacity', value as number])\n    } else if (NUMERIC_CHANNELS.has(key)) {\n      if (key === 'opacity') plainOpacity = true\n      if (Array.isArray(value)) numericKeyframes.push([key as Channel, value as NumericKeyframes])\n      else numericScalars.push([key as Channel, value as number])\n    } else if (key === 'transform') {\n      warnOnce('transform', 'animate x/y/scale/rotate instead of the transform shorthand')\n    } else if (isAttrKey(key)) {\n      if (Array.isArray(value)) attrKeyframes.push([key, value as AnimateKeyframes])\n      else attrScalars.push([key, value as AnimateValue])\n    } else if (Array.isArray(value)) {\n      keyframeProperties.push([key, value as AnimateKeyframes])\n    } else {\n      scalarProperties.push([key, value as AnimateValue])\n    }\n  }\n  // The visibility link follows the latest opacity intent: autoAlpha turns it on,\n  // a plain opacity animation turns it off (and reveals) so it never leaks onto\n  // an unrelated later opacity tween. Latched BEFORE the numeric path so the flag\n  // is right when a fresh opacity channel binds (and gates WAAPI delegation).\n  const opacityExisted = entry.values.opacity !== undefined\n  const unlinkAutoAlpha = plainOpacity && !autoAlpha && entry.autoAlpha\n  if (autoAlpha) entry.autoAlpha = true\n  else if (plainOpacity) entry.autoAlpha = false\n\n  const handles: AnimationHandle[] = []\n  if (numericScalars.length > 0 || numericKeyframes.length > 0) {\n    handles.push(...handleNumeric(entry, element, numericScalars, numericKeyframes, options, behavior, reduced))\n    if (unlinkAutoAlpha) element.style.visibility = '' // drop the hidden state we may have set\n    // Refresh the binding to apply/remove the visibility toggle - but only when\n    // handleNumeric did not already rebind a freshly created opacity channel.\n    if ((autoAlpha || unlinkAutoAlpha) && opacityExisted) rebind(entry, element)\n  }\n  if (scalarProperties.length > 0 || keyframeProperties.length > 0) {\n    const read = readStyle(element)\n    for (const [property, value] of scalarProperties) {\n      handles.push(animateProperty(entry, element, property, value, read, options, behavior, reduced))\n    }\n    for (const [property, frames] of keyframeProperties) {\n      handles.push(animatePropertyKeyframes(entry, element, property, frames, read, options, reduced))\n    }\n  }\n  if (attrScalars.length > 0 || attrKeyframes.length > 0) {\n    const read = readAttribute(element)\n    for (const [property, value] of attrScalars) {\n      handles.push(animateProperty(entry, element, property, value, read, options, behavior, reduced, 'attr'))\n    }\n    for (const [property, frames] of attrKeyframes) {\n      handles.push(animatePropertyKeyframes(entry, element, property, frames, read, options, reduced, 'attr'))\n    }\n  }\n  const base = aggregate(handles)\n  if (!hasLifecycle(options)) return base\n  const readValues = (): Record<string, number> => {\n    const out: Record<string, number> = {}\n    for (const [key, value] of Object.entries(entry.values)) if (value !== undefined) out[key] = value.get()\n    return out\n  }\n  return withLifecycle(base, handles, options, readValues, entry.scheduler)\n}\n\n// A registry property's current value as ONE magnitude plus a re-emitter that\n// preserves its unit/template - only for single-channel value types (length,\n// number). Multi-channel (color, shadow) returns undefined; a relative there\n// degrades to the operand (resolveValue warns).\nconst readMagnitude = (element: AnimatableElement, entry: ElementEntry | undefined, key: string): Magnitude | undefined => {\n  const warm = entry?.groups.get(key)\n  if (warm !== undefined) {\n    if (warm.group.channels.length !== 1) return undefined\n    const channel = warm.group.channels[0]!\n    const { type, shape } = warm.group\n    return { value: channel.get(), reformat: (next) => type.format([next], shape) }\n  }\n  const name = bareName(key)\n  const type = resolveValueType(name)\n  // Attributes read via getAttribute; style properties via computed style.\n  const raw = isAttrKey(key) ? (element.getAttribute(name) ?? '').trim() : readStyle(element).get(name)\n  const parsed = type.parse(raw)\n  if (parsed === null || parsed.channels.length !== 1) return undefined\n  return { value: parsed.channels[0]!, reformat: (next) => type.format([next], parsed.shape) }\n}\n\n/** The per-element resolution context: live channel reads plus the single-magnitude registry reader. */\nconst resolveContextFor = (element: AnimatableElement, index: number, total: number): ResolveContext => {\n  const entry = registry.get(element)\n  return {\n    index,\n    element,\n    total,\n    readNumeric: (key) => {\n      const channel = key === 'autoAlpha' ? 'opacity' : key\n      if (!NUMERIC_CHANNELS.has(channel)) return undefined\n      const value = entry?.values[channel as Channel]\n      return value !== undefined ? value.get() : INITIAL[channel as Channel]\n    },\n    readMagnitude: (key) => readMagnitude(element, entry, key),\n  }\n}\n\n/** Resolve every target value for one element (functions, relatives, keyframe chaining) to absolutes. */\nconst resolveTargetsFor = (\n  element: AnimatableElement,\n  targets: AnimateTargets,\n  index: number,\n  total: number,\n): ResolvedTargets => {\n  const ctx = resolveContextFor(element, index, total)\n  const out: Record<string, AnimateValue | AnimateKeyframes> = {}\n  for (const key of Object.keys(targets)) {\n    const raw = (targets as Record<string, ResolvableValue | undefined>)[key]\n    if (raw === undefined) continue\n    out[key] = resolveValue(key, raw, ctx)\n  }\n  return out as ResolvedTargets\n}\n\n/** Resolve a from-state for one element to absolute teleport values (functions/relatives against the live value). */\nconst resolveFromFor = (element: AnimatableElement, from: FromTargets, index: number, total: number): ResolvedFrom =>\n  // A from-state is scalar-only, so the resolved shape never carries keyframe arrays.\n  resolveTargetsFor(element, from as AnimateTargets, index, total) as ResolvedFrom\n\n/**\n * Capture one element's NATURAL (current) value for each given key, synchronously\n * - the to-state `from()` animates back to. A numeric channel reads its live\n * animatable value (mid-flight if interrupted) or the CSS-neutral INITIAL when\n * untouched; any other property reads computed/inline style. Must run BEFORE the\n * from-set moves the element, so the captured value is the real resting state.\n */\nconst captureNatural = (element: AnimatableElement, keys: string[]): ResolvedTargets => {\n  const entry = registry.get(element)\n  const read = readStyle(element)\n  const out: Record<string, AnimateValue> = {}\n  for (const key of keys) {\n    const channel = key === 'autoAlpha' ? 'opacity' : key\n    if (NUMERIC_CHANNELS.has(channel)) {\n      const value = entry?.values[channel as Channel]\n      out[key] = value !== undefined ? value.get() : INITIAL[channel as Channel]\n    } else if (isAttrKey(key)) {\n      out[key] = element.getAttribute(bareName(key)) ?? ''\n    } else {\n      out[key] = read.get(key)\n    }\n  }\n  return out as ResolvedTargets\n}\n\n/** True if any target value needs per-element resolution (a function, or a relative string incl. inside keyframes). */\nconst hasResolvable = (targets: AnimateTargets): boolean => {\n  for (const key of Object.keys(targets)) {\n    if (needsResolve((targets as Record<string, unknown>)[key])) return true\n  }\n  return false\n}\n\n// Reclaim any delegated WAAPI tween FIRST (so a relative/function reads the true\n// mid-flight position, not a stale pre-tween value), then resolve this element's\n// targets and start them. Resolution happens at the element's START time.\nconst startResolved = (\n  element: AnimatableElement,\n  targets: AnimateTargets,\n  index: number,\n  total: number,\n  options: AnimateOptions,\n): AnimationHandle => {\n  const existing = registry.get(element)\n  if (existing != null && existing.delegated !== null) reclaim(existing)\n  const resolved = resolveTargetsFor(element, targets, index, total)\n  return animateOne(element, resolved, options)\n}\n\n// Start one element's motion after a frame-clock delay, as ONE handle: finished\n// resolves when the post-delay inner settles or the wait is cancelled; stop cancels\n// a pending wait then freezes a started run; interrupt is forwarded so a superseded\n// or stopped deferred element reads as onInterrupt. The targets are resolved at\n// START time (after the wait), off the live value. A later animate() on this element\n// (a supersede during the wait) bumps the generation, so the stale start is dropped.\nconst deferredStart = (\n  element: AnimatableElement,\n  targets: AnimateTargets,\n  options: AnimateOptions,\n  index: number,\n  total: number,\n  delayMs: number,\n  scheduler: Scheduler,\n): AnimationHandle => {\n  const entry = ensureEntry(element, options.scheduler)\n  const scheduledGen = markIntent(entry) // claim the element; a later intent bumps past this token\n  let inner: AnimationHandle | null = null\n  let cancelled = false\n  let onInterrupt: ((h: AnimationHandle) => void) | null = null\n  let resolveFinished = (): void => {}\n  const finished = new Promise<void>((resolve) => {\n    resolveFinished = resolve\n  })\n  const cancelWait = waitFrames(delayMs, scheduler, () => {\n    if (cancelled) return\n    // Superseded during the wait: do NOT clobber the newer animation - report the\n    // interrupt and settle, so the set reads onInterrupt instead of a false complete.\n    if (entry.generation !== scheduledGen) {\n      cancelled = true\n      onInterrupt?.(handle)\n      resolveFinished()\n      return\n    }\n    inner = startResolved(element, targets, index, total, options)\n    inner.eventCallback?.('interrupt', () => onInterrupt?.(handle))\n    void inner.finished.then(resolveFinished)\n  })\n  const handle: AnimationHandle = {\n    finished,\n    then: thenFinished(finished),\n    stop: () => {\n      if (cancelled) return\n      cancelled = true\n      cancelWait()\n      if (inner !== null) inner.stop()\n      else onInterrupt?.(handle)\n      resolveFinished()\n    },\n    eventCallback(event, fn) {\n      if (event === 'interrupt') onInterrupt = fn ?? null\n      return handle\n    },\n  }\n  return handle\n}\n\n/** Strip the set-level options (delay, lifecycle) so each animateOne() sees only its own element's motion options. */\nconst perElementOptions = (options: AnimateOptions): AnimateOptions => {\n  const out: AnimateOptions = { ...options }\n  delete out.delay\n  delete out.from\n  delete out.onStart\n  delete out.onUpdate\n  delete out.onComplete\n  delete out.onInterrupt\n  delete out.scope\n  return out\n}\n\n/**\n * Imperative escape hatch: spring (default) or tween style channels. The target\n * is one element, an array, a NodeList, or a CSS selector - one handle drives the\n * whole set. Each value may be a relative string (`'+=100'`, resolved against the\n * live value) or a per-target function `(index, element, count)`. `delay` staggers\n * the starts (a number, or a `staggerDelay()` wave). The five numeric channels\n * keep their compositor fast path; everything else routes through the value\n * registry. Repeated calls retarget the same underlying values - never a jump.\n *\n * Multi-target lifecycle is set-level: `onComplete` fires when the WHOLE set has\n * settled, `onInterrupt` when the first element is interrupted, `onUpdate` reports\n * the first element's channels.\n */\nexport function animate(target: AnimatableElement, targets: AnimateTargets, options?: AnimateOptions): AnimationHandle\nexport function animate(target: AnimationTarget, targets: AnimateTargets, options?: AnimateOptions): AnimationHandle\nexport function animate(target: AnimationTarget, targets: AnimateTargets, options: AnimateOptions = {}): AnimationHandle {\n  // Fast path: one element, no delay, no function/relative - today's exact behavior\n  // (lifecycle included), with no per-element pre-pass allocation. isHTMLElement is\n  // SSR-safe (a bare `instanceof HTMLElement` throws server-side).\n  if (isHTMLElement(target) && options.delay === undefined && options.from === undefined && !hasResolvable(targets)) {\n    return animateOne(target, targets, options)\n  }\n\n  const elements = resolveTargets(target)\n  if (elements.length === 0) return RESOLVED\n  const total = elements.length\n  const scheduler = options.scheduler ?? getSharedScheduler()\n  const behavior = options.reducedMotion ?? getReducedMotionBehavior()\n  const reduced = behavior !== 'allow' && prefersReducedMotion()\n  const fromValues = options.from\n  const delayOf: DelayFn | null =\n    options.delay === undefined\n      ? null\n      : typeof options.delay === 'function'\n        ? options.delay\n        : (index) => (options.delay as number) * index\n  const optionsForOne = perElementOptions(options)\n\n  const children = elements.map((element, index) => {\n    // Immediate-render the from-state synchronously, here in the call frame, for\n    // EVERY element - so a staggered element is parked at its from-state and holds\n    // it through its own delay before deferredStart runs. Skipped under reduced\n    // motion, where the run settles straight to the to-state (no stranded from).\n    if (fromValues !== undefined && !reduced) {\n      // Pass the resolved scheduler so the from-set binds the element to the SAME\n      // clock the animation runs on - else setStyle defaults to the shared\n      // scheduler and the spring, on the injected one, never drives the channel.\n      setStyle(element, resolveFromFor(element, fromValues, index, total), { scheduler })\n    }\n    const d = delayOf !== null ? delayOf(index, total) : 0\n    if (d <= 0) return startResolved(element, targets, index, total, optionsForOne)\n    return deferredStart(element, targets, optionsForOne, index, total, d, scheduler)\n  })\n\n  const base = aggregate(children)\n  if (!hasLifecycle(options)) return base\n  const first = registry.get(elements[0]!)\n  const readValues = (): Record<string, number> => {\n    const out: Record<string, number> = {}\n    if (first !== undefined) {\n      for (const [key, value] of Object.entries(first.values)) if (value !== undefined) out[key] = value.get()\n    }\n    return out\n  }\n  return withLifecycle(base, children, options, readValues, scheduler)\n}\n\n/**\n * Entrance: animate each target element FROM `fromValues` INTO its natural\n * (current) state, with no manual setStyle first. Each element's current value is\n * captured per key as its own to-state (so a set animates to PER-element naturals),\n * the from-state is set synchronously (no flash, held through any stagger delay),\n * then the element springs/tweens back. One aggregate handle drives the whole set.\n *\n * Same options as `animate()` - `delay`/`staggerDelay()`, lifecycle, spring config,\n * reduced motion (under which each element ends at its natural state, not the\n * from-state). If an element is mid-animation, the captured to is its live value,\n * so the hand-off has no jump. From-values take the same forms as a target\n * (absolute, relative `'+='`, per-target function), resolved against the live value.\n */\nexport function from(target: AnimationTarget, fromValues: FromTargets, options: AnimateOptions = {}): AnimationHandle {\n  const elements = resolveTargets(target)\n  if (elements.length === 0) return RESOLVED\n  const keys = Object.keys(fromValues)\n  // Capture the natural to-state NOW, per element, before animate() sets the\n  // from-state. The to is handed to animate() as a per-target function that just\n  // returns the pre-captured constant, so its start-time resolution is exact.\n  const captured = elements.map((element) => captureNatural(element, keys))\n  const to: AnimateTargets = {}\n  for (const key of keys) {\n    ;(to as Record<string, ValueFn<AnimateValue | AnimateKeyframes>>)[key] = (index) =>\n      (captured[index] as Record<string, AnimateValue | AnimateKeyframes>)[key]!\n  }\n  // Pass the resolved element array (a stable snapshot) so animate() does not\n  // re-query a selector and capture/animate a different set.\n  return animate(elements, to, { ...options, from: fromValues })\n}\n\n/**\n * Animate each target element FROM an explicit `fromValues` TO an explicit\n * `toValues`. The from-state is set synchronously (no flash, held through any\n * stagger delay), then the element animates to the to-state. Thin sugar over\n * `animate(target, toValues, { ...options, from: fromValues })`: `toValues` keep\n * full target parity (keyframes, relatives, per-target functions); `fromValues`\n * are a single per-key state. Shares every `animate()` option (stagger, lifecycle,\n * spring config, reduced motion - under which it settles straight to `toValues`).\n */\nexport function fromTo(\n  target: AnimationTarget,\n  fromValues: FromTargets,\n  toValues: AnimateTargets,\n  options: AnimateOptions = {},\n): AnimationHandle {\n  return animate(target, toValues, { ...options, from: fromValues })\n}\n\nexport interface SetStyleOptions {\n  /**\n   * Seed a velocity (channel-unit/s) along with the values - gesture handoffs.\n   * Broadcast to every channel of every touched property; exact for\n   * single-channel values, which is the gesture case.\n   */\n  velocity?: number\n  scheduler?: Scheduler\n}\n\n/** Teleport a registry property, coherently with the channel state, writing synchronously. */\nconst setStyleProperty = (\n  entry: ElementEntry,\n  element: AnimatableElement,\n  property: string,\n  value: AnimateValue,\n  velocity: number | undefined,\n  target: PropTarget = 'style',\n): void => {\n  const name = bareName(property)\n  const type = resolveValueType(name)\n  const existing = entry.groups.get(property)\n  if (existing !== undefined) {\n    // Fast path: the incoming value parses into the live shape - update channel\n    // values against the compiled template, no rebuild (the pointermove case).\n    const parsed = type.parse(value) ?? type.reconcile?.(String(value), existing.group.shape) ?? null\n    if (parsed !== null && parsed.shape === existing.group.shape) {\n      existing.group.set(parsed, velocity !== undefined ? { velocity } : {})\n      existing.binding.flushNow()\n      return\n    }\n    // Shape change: teleport by recreating at the new value.\n    existing.binding.dispose()\n    existing.group.dispose()\n    entry.groups.delete(property)\n  }\n  const parsed = type.parse(value)\n  if (parsed === null) {\n    writeLiteral(entry, element, property, value, target)\n    return\n  }\n  const group = channelGroup(type, parsed, { scheduler: entry.scheduler })\n  if (velocity !== undefined) group.set(parsed, { velocity })\n  const binding = bindProperty(element, name, group, { scheduler: entry.scheduler, target })\n  entry.groups.set(property, { group, binding, target, name })\n  binding.flushNow()\n}\n\n/**\n * Teleport: cancel animations on the touched properties only, write the style,\n * and keep the registry channel state coherent - unlike a raw element.style\n * write, which desyncs the cache. Seed a velocity for a following spring/decay\n * to inherit (the drag-release handoff). Registry properties write synchronously\n * (zero-latency scrubbing); numeric channels reflect on the next frame.\n */\nexport function setStyle(\n  element: AnimatableElement,\n  targets: Partial<Record<NumericKey, number>> & Partial<Record<AnimateProperty, AnimateValue>>,\n  options: SetStyleOptions = {},\n): void {\n  const entry = ensureEntry(element, options.scheduler)\n  // Reclaim only if a delegated tween owns a touched numeric channel.\n  if (entry.delegated !== null) {\n    const owned = Object.keys(targets).some(\n      (key) => NUMERIC_CHANNELS.has(key) && entry.delegated?.channels.has(key as Channel) === true,\n    )\n    if (owned) reclaim(entry)\n  }\n  const velocity = options.velocity\n  let newChannel = false\n  let autoAlpha = false\n  let plainOpacity = false\n  for (const key of Object.keys(targets)) {\n    const value = (targets as Record<string, AnimateValue | undefined>)[key]\n    if (value === undefined) continue\n    interruptKey(entry, key)\n    if (key === 'autoAlpha') {\n      autoAlpha = true\n      interruptKey(entry, 'opacity')\n      const { value: channel, created } = ensureChannel(entry, 'opacity')\n      newChannel ||= created\n      channel.set(value as number, velocity !== undefined ? { velocity } : undefined)\n    } else if (NUMERIC_CHANNELS.has(key)) {\n      if (key === 'opacity') plainOpacity = true\n      const { value: channel, created } = ensureChannel(entry, key as Channel)\n      newChannel ||= created\n      channel.set(value as number, velocity !== undefined ? { velocity } : undefined)\n    } else if (isAttrKey(key)) {\n      setStyleProperty(entry, element, key, value, velocity, 'attr')\n    } else if (key !== 'transform') {\n      setStyleProperty(entry, element, key, value, velocity)\n    }\n  }\n  const unlinkAutoAlpha = plainOpacity && !autoAlpha && entry.autoAlpha\n  if (autoAlpha) entry.autoAlpha = true\n  else if (plainOpacity) entry.autoAlpha = false\n  if (unlinkAutoAlpha) element.style.visibility = ''\n  if (newChannel || autoAlpha || unlinkAutoAlpha) rebind(entry, element)\n}\n\n/**\n * Forget the element: reclaim any delegated tween, dispose every channel, group,\n * and binding, remove the inline styles we wrote. The next animate() starts cold\n * (re-reads computed style). The sanctioned uncache hatch after an external\n * style write. Idempotent; an unknown element is a no-op.\n */\nexport function releaseStyle(element: AnimatableElement): void {\n  const entry = registry.get(element)\n  if (entry === undefined) return\n  reclaim(entry)\n  for (const interrupt of [...entry.chains.values()]) interrupt()\n  entry.chains.clear()\n\n  for (const value of Object.values(entry.values)) value?.dispose()\n  entry.disposeBinding()\n  if (Object.keys(entry.values).length > 0) {\n    element.style.removeProperty('transform')\n    element.style.removeProperty('opacity')\n    if (entry.autoAlpha) element.style.removeProperty('visibility')\n  }\n\n  for (const { group, binding, target, name } of entry.groups.values()) {\n    binding.dispose()\n    group.dispose()\n    if (target === 'attr') element.removeAttribute(name)\n    else element.style.removeProperty(toKebab(name))\n  }\n  entry.groups.clear()\n  registry.delete(element)\n}\n"],"names":["rafDriver","callback","id","MAX_FRAME_DELTA_MS","createScheduler","driver","updateSubscribers","renderSubscribers","cancelFrame","lastTimestampMs","running","inTick","count","stop","runPhase","subscribers","frame","tick","timestampMs","deltaMs","phase","shared","getSharedScheduler","linear","p","easeInCubic","easeOutCubic","easeInOutCubic","seen","warnOnce","key","message","registry","registerEasing","name","factory","SPEC","parseSpec","spec","match","variantRaw","_a","variant","params","part","resolveEasing","input","parsed","behavior","setReducedMotionBehavior","next","getReducedMotionBehavior","initialized","current","override","listeners","effective","notifyIfChanged","before","after","listener","init","query","event","prefersReducedMotion","setReducedMotionOverride","value","onReducedMotionChange","decaySimulation","options","timeConstant","restSpeed","min","max","bounceStiffness","bounceDamping","restDelta","tauS","edge","checkEdge","position","velocity","boundary","simulationMotion","simulation","state","timestepS","stepSimulation","springSimulation","target","stiffness","damping","mass","aim","tweenMotion","from","to","durationS","easing","elapsedS","positionAt","t","progress","hi","SIMULATION_TIMESTEP_S","lo","span","EVENT_TO_KEY","lifecycleRegistry","fns","scope","callbacks","fn","handle","receiver","thenFinished","finished","onfulfilled","onrejected","shouldSkip","MAX_SKIP_STEPS","animatable","initial","scheduler","changeListeners","restListeners","active","unsubscribeFrames","emitChange","freeze","reason","animation","onFrame","rested","alpha","previous","settleInstantly","motion","lifecycle","settled","i","startAnimation","resolveFinished","resolve","setOptions","springOptions","decayOptions","toOptions","simulateOptions","TRANSFORM_KEYS","ORIGIN_KEYS","formatOrigin","c","formatTransform","parts","bindStyle","element","bindings","autoAlpha","opacity","transformBindings","entry","originBindings","transformDirty","originDirty","opacityDirty","cancelFlush","unsubscribers","writeTransform","channels","writeOrigin","writeOpacity","flush","scheduleFlush","track","markDirty","markTransformDirty","markOriginDirty","unsubscribe","formatChannelNumber","meta","v","factor","toKebab","property","readAttribute","readStyle","computed","bindProperty","source","attr","dirty","lastWritten","write","aggregate","handles","onInterrupt","fired","fireInterrupt","child","channelGroup","type","shape","metas","generation","cachedFormat","notify","channel","scratch","channelOptions","base","index","opts","multiplier","nextShape","RGB_META","ALPHA_META","COLOR_METAS","COLOR_SHAPE","sqrtByte","squared","clamped","formatColor","r","g","b","a","hexComponent","hex","full","functionalArgs","s","open","close","component","raw","scale","rgbComponent","p0","p1","p2","p3","hslToRgb","h","l","hp","x","r1","g1","b1","m","hslComponent","sat","light","probe","NON_COLOR_KEYWORDS","namedComponent","parseColor","rgba","colorValueType","NUMBER_TOKEN_META","SEP","colorSlot","numberSlot","unit","SINGLE_NUMBER_SHAPE","tokenPattern","isColorText","text","decompose","tokens","literals","cursor","literal","color","num","tail","templateCache","compileShape","cached","template","channelMetas","token","groupByKind","numbers","colors","offset","complexValueType","decomposed","out","targetShape","trimmed","ni","ci","LENGTH_META","LENGTH_METAS","LENGTH_RE","ANGLE_TO_DEG","lengthValueType","fromShape","toShape","measure","fromAngle","toAngle","NUMBER_META","NUMBER_METAS","numberValueType","n","shorthands","seeded","LENGTH_PROPERTIES","COLOR_PROPERTIES","NUMBER_PROPERTIES","SHORTHAND_PROPERTIES","seed","registerValueType","properties","resolveValueType","existing","waitFrames","ms","onDone","elapsedMs","isStop","normalizeKeyframes","frames","values","offsets","eases","lastConcrete","head","tailValues","tailOffsets","tailEases","runKeyframeChain","normalized","ops","config","waypoints","cancelled","evenMs","waypoint","_b","fillOffsets","explicit","at","lastIdx","lastVal","j","prev","result","isHTMLElement","isAnimatableElement","resolveTargets","root","found","RELATIVE","parseRelative","applyRelative","cur","op","operand","w","waypointValue","needsResolve","resolveScalar","ctx","rel","mag","resolveKeyframes","numeric","resolveOne","resolveValue","BLOCK_AXIS","positive","createMeasure","read","cache","viewport","pick","doc","compute","parent","parentStyle","basis","_w","hasLifecycle","o","INITIAL","TRANSFORM_CHANNELS","NUMERIC_CHANNELS","ATTR_PREFIX","isAttrKey","bareName","markIntent","supportsWaapi","EASING_SAMPLES","toLinearEasing","stops","reclaim","delegated","segments","window","t1","t0","slope","segmentDurationS","rateSign","ensureChannel","rebind","delegateMultiKeyframe","scalars","keyframeNorms","durationMs","newChannel","created","norm","animatedKeys","carry","group","linearEasing","keyframes","transform","origin","tween","RESOLVED_PROMISE","RESOLVED","withLifecycle","children","readValues","onStart","onUpdate","onComplete","ended","unsubUpdate","finishUpdate","end","cb","springOptionsFrom","spring","interruptKey","interrupt","startChain","chain","startNumericScalar","reduced","startGroupMotion","installGroup","start","startMotion","binding","writeLiteral","snapLiteral","animateProperty","begin","parsedTarget","recon","_c","_d","segmentTimings","duration","e","arrivals","durations","arrival","hasKeyframeMeta","animatePropertyKeyframes","last","rawEntries","parsedEntries","first","teleport","buildChain","__getDelegated","ensureEntry","handleNumeric","lengths","_","norms","expressive","animateNumericJs","prepared","animateOne","targets","numericScalars","numericKeyframes","scalarProperties","keyframeProperties","attrScalars","attrKeyframes","plainOpacity","opacityExisted","unlinkAutoAlpha","readMagnitude","warm","resolveContextFor","total","resolveTargetsFor","resolveFromFor","captureNatural","keys","hasResolvable","startResolved","resolved","deferredStart","delayMs","scheduledGen","inner","cancelWait","perElementOptions","animate","elements","fromValues","delayOf","optionsForOne","setStyle","d","captured","fromTo","toValues","setStyleProperty","releaseStyle"],"mappings":"oDAcaA,GAAyB,CACpC,SAASC,EAAU,CACjB,MAAMC,EAAK,sBAAsBD,CAAQ,EACzC,MAAO,IAAM,qBAAqBC,CAAE,CACtC,CACF,ECWaC,GAAqB,GAE3B,SAASC,GAAgBC,EAAgC,CAC9D,MAAMC,MAAwB,IACxBC,MAAwB,IAC9B,IAAIC,EAAkC,KAClCC,EAAiC,KACjCC,EAAU,GACVC,EAAS,GAEb,MAAMC,EAAQ,IAAMN,EAAkB,KAAOC,EAAkB,KAEzDM,EAAO,IAAM,CACjBL,GAAA,MAAAA,IACAA,EAAc,KACdC,EAAkB,KAClBC,EAAU,EACZ,EAIMI,EAAW,CAACC,EAAiCC,IAAqB,CACtE,UAAWf,IAAY,CAAC,GAAGc,CAAW,EAChCA,EAAY,IAAId,CAAQ,KAAYe,CAAK,CAEjD,EAEMC,EAAQC,GAAwB,CACpC,MAAMC,EACJV,IAAoB,KAChB,EACA,KAAK,IAAIS,EAAcT,EAAiBN,EAAkB,EAChEM,EAAkBS,EAClB,MAAMF,EAAmB,CAAE,QAAAG,EAAS,YAAAD,CAAA,EAEpCP,EAAS,GACTG,EAASR,EAAmBU,CAAK,EACjCF,EAASP,EAAmBS,CAAK,EACjCL,EAAS,GAELC,EAAA,EAAU,EACZJ,EAAcH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