{"version":3,"file":"state-coordinator.mjs","sources":["../../../src/lib/coordination/state-coordinator.ts"],"sourcesContent":["/**\n * @file State Coordinator\n * @module coordination/state-coordinator\n * @description PhD-level cross-library state synchronization system.\n *\n * Implements sophisticated state coordination with:\n * - Cross-library state slice registration\n * - Reactive subscription model\n * - Batched updates for performance\n * - Two-way synchronization rules\n * - Conflict resolution strategies\n * - State persistence integration\n * - Debug/replay capabilities\n *\n * @author Agent 5 - PhD TypeScript Architect\n * @version 1.0.0\n */\n\nimport {\n  type StateSliceId,\n  type StateChange,\n  type StateSubscriber,\n  type StateSliceRegistration,\n  type StateSyncRule,\n  type StateCoordinator,\n  type StateCoordinatorConfig,\n  DEFAULT_STATE_COORDINATOR_CONFIG,\n  createStateSliceId,\n} from './types';\nimport { publishEvent } from './event-bus';\n\n// ============================================================================\n// Internal Types\n// ============================================================================\n\n/**\n * Internal slice entry with metadata.\n */\ninterface SliceEntry<T = unknown> {\n  /** Slice registration */\n  registration: StateSliceRegistration<T>;\n  /** Change subscribers */\n  subscribers: Set<StateSubscriber<T>>;\n  /** Last known value (for change detection) */\n  lastValue: T;\n  /** Unsubscribe from source changes */\n  sourceUnsubscribe?: () => void;\n}\n\n/**\n * Pending batch update.\n */\ninterface PendingUpdate {\n  /** Slice ID */\n  sliceId: StateSliceId;\n  /** Change details */\n  change: StateChange;\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Deep equality check for state values.\n */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n  if (a === b) return true;\n  if (a === null || b === null) return false;\n  if (typeof a !== typeof b) return false;\n  if (typeof a !== 'object') return false;\n\n  if (Array.isArray(a) && Array.isArray(b)) {\n    if (a.length !== b.length) return false;\n    return a.every((val, idx) => deepEqual(val, b[idx]));\n  }\n\n  if (Array.isArray(a) || Array.isArray(b)) return false;\n\n  const aKeys = Object.keys(a);\n  const bKeys = Object.keys(b as object);\n  if (aKeys.length !== bKeys.length) return false;\n\n  return aKeys.every((key) =>\n    deepEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])\n  );\n}\n\n/**\n * Gets a value at a path in an object.\n */\nfunction getAtPath(obj: unknown, path: string[]): unknown {\n  let current = obj;\n  for (const key of path) {\n    if (current === null || current === undefined) return undefined;\n    current = (current as Record<string, unknown>)[key];\n  }\n  return current;\n}\n\n/**\n * Sets a value at a path in an object (immutably).\n */\nfunction setAtPath<T>(obj: T, path: string[], value: unknown): T {\n  if (path.length === 0) return value as T;\n\n  const [head, ...tail] = path;\n  const current = obj as Record<string, unknown>;\n\n  if (head === undefined) return value as T;\n\n  return {\n    ...current,\n    [head]: tail.length === 0 ? value : setAtPath(current[head] ?? {}, tail, value),\n  } as T;\n}\n\n// ============================================================================\n// StateCoordinatorImpl Class\n// ============================================================================\n\n/**\n * Implementation of the state coordinator.\n *\n * @example\n * ```typescript\n * const coordinator = new StateCoordinatorImpl();\n *\n * // Register a state slice\n * coordinator.registerSlice({\n *   id: createStateSliceId('settings'),\n *   library: createLibraryId('state'),\n *   initialValue: { theme: 'light' },\n *   getState: () => store.getState().settings,\n *   setState: (value) => store.setState({ settings: value }),\n *   subscribe: (callback) => store.subscribe(\n *     (state) => state.settings,\n *     callback\n *   ),\n * });\n *\n * // Add a sync rule\n * coordinator.addSyncRule({\n *   id: 'theme-sync',\n *   sourceSlice: createStateSliceId('settings'),\n *   sourcePath: ['theme'],\n *   targetSlice: createStateSliceId('ui-prefs'),\n *   targetPath: ['colorMode'],\n *   direction: 'one-way',\n * });\n * ```\n */\nexport class StateCoordinatorImpl implements StateCoordinator {\n  /** Configuration */\n  private readonly config: StateCoordinatorConfig;\n\n  /** Registered slices */\n  private readonly slices: Map<StateSliceId, SliceEntry> = new Map();\n\n  /** Sync rules */\n  private readonly syncRules: Map<string, StateSyncRule> = new Map();\n\n  /** Global subscribers (receive all changes) */\n  private readonly globalSubscribers: Set<StateSubscriber> = new Set();\n\n  /** Pending batched updates */\n  private pendingUpdates: PendingUpdate[] = [];\n\n  /** Batch timer */\n  private batchTimer: ReturnType<typeof setTimeout> | null = null;\n\n  /** Whether currently syncing (to prevent loops) */\n  private isSyncing = false;\n\n  /**\n   * Creates a new state coordinator.\n   * @param config - Configuration options\n   */\n  constructor(config: Partial<StateCoordinatorConfig> = {}) {\n    this.config = { ...DEFAULT_STATE_COORDINATOR_CONFIG, ...config };\n  }\n\n  // ==========================================================================\n  // Public API\n  // ==========================================================================\n\n  /**\n   * Registers a state slice.\n   * @template T - State type\n   * @param registration - Slice registration\n   */\n  registerSlice<T>(registration: StateSliceRegistration<T>): void {\n    // Check for existing registration\n    if (this.slices.has(registration.id)) {\n      console.warn(`[StateCoordinator] Slice already registered: ${registration.id}`);\n      return;\n    }\n\n    const entry: SliceEntry<T> = {\n      registration,\n      subscribers: new Set(),\n      lastValue: registration.getState(),\n    };\n\n    // Subscribe to source changes\n    entry.sourceUnsubscribe = registration.subscribe((change) => {\n      this.handleSliceChange(registration.id, change);\n    });\n\n    this.slices.set(registration.id, entry as SliceEntry);\n\n    if (this.config.debug) {\n      console.info(`[StateCoordinator] Registered slice: ${registration.id}`);\n    }\n  }\n\n  /**\n   * Unregisters a state slice.\n   * @param id - Slice ID\n   */\n  unregisterSlice(id: StateSliceId): void {\n    const entry = this.slices.get(id);\n    if (entry) {\n      entry.sourceUnsubscribe?.();\n      entry.subscribers.clear();\n      this.slices.delete(id);\n\n      // Remove any sync rules involving this slice\n      for (const [ruleId, rule] of this.syncRules) {\n        if (rule.sourceSlice === id || rule.targetSlice === id) {\n          this.syncRules.delete(ruleId);\n        }\n      }\n    }\n  }\n\n  /**\n   * Adds a synchronization rule.\n   * @template TSource - Source state type\n   * @template TTarget - Target state type\n   * @param rule - Sync rule\n   */\n  addSyncRule<TSource, TTarget>(rule: StateSyncRule<TSource, TTarget>): void {\n    if (this.syncRules.has(rule.id)) {\n      console.warn(`[StateCoordinator] Sync rule already exists: ${rule.id}`);\n      return;\n    }\n\n    // Validate slices exist\n    if (!this.slices.has(rule.sourceSlice)) {\n      console.warn(`[StateCoordinator] Source slice not found: ${rule.sourceSlice}`);\n    }\n    if (!this.slices.has(rule.targetSlice)) {\n      console.warn(`[StateCoordinator] Target slice not found: ${rule.targetSlice}`);\n    }\n\n    this.syncRules.set(rule.id, rule as StateSyncRule);\n\n    if (this.config.debug) {\n      console.info(`[StateCoordinator] Added sync rule: ${rule.id}`);\n    }\n  }\n\n  /**\n   * Removes a synchronization rule.\n   * @param id - Rule ID\n   */\n  removeSyncRule(id: string): void {\n    this.syncRules.delete(id);\n  }\n\n  /**\n   * Gets state from a slice.\n   * @template T - State type\n   * @param sliceId - Slice ID\n   * @returns State value or undefined\n   */\n  getState<T>(sliceId: StateSliceId): T | undefined {\n    const entry = this.slices.get(sliceId);\n    if (!entry) return undefined;\n    return entry.registration.getState() as T;\n  }\n\n  /**\n   * Sets state in a slice.\n   * @template T - State type\n   * @param sliceId - Slice ID\n   * @param value - New value or updater function\n   */\n  setState<T>(sliceId: StateSliceId, value: T | ((prev: T) => T)): void {\n    const entry = this.slices.get(sliceId) as SliceEntry<T> | undefined;\n    if (!entry) {\n      console.warn(`[StateCoordinator] Slice not found: ${sliceId}`);\n      return;\n    }\n\n    const currentValue = entry.registration.getState();\n    const newValue = typeof value === 'function' ? (value as (prev: T) => T)(currentValue) : value;\n\n    entry.registration.setState(newValue);\n  }\n\n  /**\n   * Subscribes to state changes for a slice.\n   * @template T - State type\n   * @param sliceId - Slice ID\n   * @param subscriber - Change callback\n   * @returns Unsubscribe function\n   */\n  subscribe<T>(sliceId: StateSliceId, subscriber: StateSubscriber<T>): () => void {\n    const entry = this.slices.get(sliceId);\n    if (!entry) {\n      console.warn(`[StateCoordinator] Slice not found: ${sliceId}`);\n      return () => {};\n    }\n\n    entry.subscribers.add(subscriber as StateSubscriber);\n\n    return () => {\n      entry.subscribers.delete(subscriber as StateSubscriber);\n    };\n  }\n\n  /**\n   * Subscribes to all state changes.\n   * @param subscriber - Change callback\n   * @returns Unsubscribe function\n   */\n  subscribeAll(subscriber: StateSubscriber): () => void {\n    this.globalSubscribers.add(subscriber);\n    return () => {\n      this.globalSubscribers.delete(subscriber);\n    };\n  }\n\n  /**\n   * Forces synchronization of all rules.\n   */\n  forceSync(): void {\n    for (const rule of this.syncRules.values()) {\n      this.executeSyncRule(rule);\n    }\n  }\n\n  /**\n   * Gets all registered slice IDs.\n   * @returns Array of slice IDs\n   */\n  getSliceIds(): StateSliceId[] {\n    return Array.from(this.slices.keys());\n  }\n\n  /**\n   * Gets all sync rule IDs.\n   * @returns Array of rule IDs\n   */\n  getSyncRuleIds(): string[] {\n    return Array.from(this.syncRules.keys());\n  }\n\n  /**\n   * Disposes the coordinator.\n   */\n  dispose(): void {\n    // Cancel pending batch\n    if (this.batchTimer) {\n      clearTimeout(this.batchTimer);\n      this.batchTimer = null;\n    }\n\n    // Unsubscribe from all sources\n    for (const entry of this.slices.values()) {\n      entry.sourceUnsubscribe?.();\n      entry.subscribers.clear();\n    }\n\n    this.slices.clear();\n    this.syncRules.clear();\n    this.globalSubscribers.clear();\n    this.pendingUpdates = [];\n  }\n\n  // ==========================================================================\n  // Private Methods\n  // ==========================================================================\n\n  /**\n   * Handles a slice change.\n   */\n  private handleSliceChange<T>(sliceId: StateSliceId, change: StateChange<T>): void {\n    const entry = this.slices.get(sliceId);\n    if (!entry) return;\n\n    // Check if value actually changed\n    const currentValue = entry.registration.getState();\n    if (deepEqual(currentValue, entry.lastValue)) {\n      return;\n    }\n\n    entry.lastValue = currentValue;\n\n    // Emit event\n    publishEvent('state:changed', {\n      sliceId,\n      path: change.path,\n      previousValue: change.previousValue,\n      newValue: change.newValue,\n    });\n\n    if (this.config.enableBatching) {\n      // Queue update for batching\n      this.pendingUpdates.push({ sliceId, change: change as StateChange });\n      this.scheduleBatch();\n    } else {\n      // Process immediately\n      this.processChange(sliceId, change as StateChange);\n    }\n  }\n\n  /**\n   * Schedules batch processing.\n   */\n  private scheduleBatch(): void {\n    if (this.batchTimer) return;\n\n    this.batchTimer = setTimeout(() => {\n      this.batchTimer = null;\n      this.processBatch();\n    }, this.config.batchWindow);\n  }\n\n  /**\n   * Processes batched updates.\n   */\n  private processBatch(): void {\n    const updates = this.pendingUpdates;\n    this.pendingUpdates = [];\n\n    // Deduplicate by slice ID (keep last change per slice)\n    const latestBySlice = new Map<StateSliceId, StateChange>();\n    for (const update of updates) {\n      latestBySlice.set(update.sliceId, update.change);\n    }\n\n    // Process each change\n    for (const [sliceId, change] of latestBySlice) {\n      this.processChange(sliceId, change);\n    }\n  }\n\n  /**\n   * Processes a single change.\n   */\n  private processChange(sliceId: StateSliceId, change: StateChange): void {\n    const entry = this.slices.get(sliceId);\n    if (!entry) return;\n\n    // Notify slice subscribers\n    for (const subscriber of entry.subscribers) {\n      try {\n        subscriber(change);\n      } catch (error) {\n        console.error(`[StateCoordinator] Subscriber error:`, error);\n      }\n    }\n\n    // Notify global subscribers\n    for (const subscriber of this.globalSubscribers) {\n      try {\n        subscriber(change);\n      } catch (error) {\n        console.error(`[StateCoordinator] Global subscriber error:`, error);\n      }\n    }\n\n    // Execute sync rules\n    if (!this.isSyncing) {\n      this.executeSyncRulesForSlice(sliceId);\n    }\n\n    if (this.config.debug) {\n      console.info(`[StateCoordinator] Processed change:`, { sliceId, change });\n    }\n  }\n\n  /**\n   * Executes sync rules for a slice.\n   */\n  private executeSyncRulesForSlice(sliceId: StateSliceId): void {\n    for (const rule of this.syncRules.values()) {\n      if (rule.sourceSlice === sliceId) {\n        this.executeSyncRule(rule);\n      }\n      // Handle two-way sync\n      if (rule.direction === 'two-way' && rule.targetSlice === sliceId) {\n        this.executeSyncRule(rule, true);\n      }\n    }\n  }\n\n  /**\n   * Executes a single sync rule.\n   */\n  private executeSyncRule(rule: StateSyncRule, reverse = false): void {\n    this.isSyncing = true;\n\n    try {\n      const sourceSliceId = reverse ? rule.targetSlice : rule.sourceSlice;\n      const targetSliceId = reverse ? rule.sourceSlice : rule.targetSlice;\n      const sourcePath = reverse ? rule.targetPath : rule.sourcePath;\n      const targetPath = reverse ? rule.sourcePath : rule.targetPath;\n\n      const sourceEntry = this.slices.get(sourceSliceId);\n      const targetEntry = this.slices.get(targetSliceId);\n\n      if (!sourceEntry || !targetEntry) return;\n\n      const sourceState = sourceEntry.registration.getState();\n      const sourceValue = getAtPath(sourceState, sourcePath);\n\n      // Check condition\n      if (rule.condition && !rule.condition(sourceValue)) {\n        return;\n      }\n\n      // Transform value\n      const transformedValue = rule.transform ? rule.transform(sourceValue) : sourceValue;\n\n      // Get current target state\n      const targetState = targetEntry.registration.getState();\n      const currentTargetValue = getAtPath(targetState, targetPath);\n\n      // Skip if values are equal\n      if (deepEqual(transformedValue, currentTargetValue)) {\n        return;\n      }\n\n      // Update target\n      const newTargetState = setAtPath(targetState, targetPath, transformedValue);\n      targetEntry.registration.setState(newTargetState);\n\n      if (this.config.debug) {\n        console.info(`[StateCoordinator] Synced ${rule.id}:`, {\n          from: sourceSliceId,\n          to: targetSliceId,\n          value: transformedValue,\n        });\n      }\n    } finally {\n      this.isSyncing = false;\n    }\n  }\n}\n\n// ============================================================================\n// Singleton Instance\n// ============================================================================\n\n/**\n * Global state coordinator instance.\n */\nlet globalCoordinator: StateCoordinatorImpl | null = null;\n\n/**\n * Gets the global state coordinator.\n * @param config - Optional configuration\n * @returns Global state coordinator instance\n */\nexport function getStateCoordinator(\n  config?: Partial<StateCoordinatorConfig>\n): StateCoordinatorImpl {\n  globalCoordinator ??= new StateCoordinatorImpl(config);\n  return globalCoordinator;\n}\n\n/**\n * Sets the global state coordinator.\n * @param coordinator - State coordinator instance\n */\nexport function setStateCoordinator(coordinator: StateCoordinatorImpl): void {\n  if (globalCoordinator) {\n    globalCoordinator.dispose();\n  }\n  globalCoordinator = coordinator;\n}\n\n/**\n * Resets the global state coordinator.\n */\nexport function resetStateCoordinator(): void {\n  if (globalCoordinator) {\n    globalCoordinator.dispose();\n    globalCoordinator = null;\n  }\n}\n\n// ============================================================================\n// Convenience Functions\n// ============================================================================\n\n/**\n * Registers a state slice with the global coordinator.\n */\nexport function registerStateSlice<T>(registration: StateSliceRegistration<T>): void {\n  getStateCoordinator().registerSlice(registration);\n}\n\n/**\n * Creates a state slice ID.\n */\nexport { createStateSliceId };\n\n// ============================================================================\n// Pre-defined Slice IDs\n// ============================================================================\n\nexport const SLICE_IDS = {\n  session: createStateSliceId('session'),\n  settings: createStateSliceId('settings'),\n  ui: createStateSliceId('ui'),\n  auth: createStateSliceId('auth'),\n  theme: createStateSliceId('theme'),\n  featureFlags: createStateSliceId('feature-flags'),\n  network: createStateSliceId('network'),\n  hydration: createStateSliceId('hydration'),\n} as const;\n"],"names":["deepEqual","a","b","val","idx","aKeys","bKeys","key","getAtPath","obj","path","current","setAtPath","value","head","tail","StateCoordinatorImpl","config","DEFAULT_STATE_COORDINATOR_CONFIG","registration","entry","change","id","ruleId","rule","sliceId","currentValue","newValue","subscriber","publishEvent","updates","latestBySlice","update","error","reverse","sourceSliceId","targetSliceId","sourcePath","targetPath","sourceEntry","targetEntry","sourceState","sourceValue","transformedValue","targetState","currentTargetValue","newTargetState","globalCoordinator","getStateCoordinator","setStateCoordinator","coordinator","resetStateCoordinator","registerStateSlice","SLICE_IDS","createStateSliceId"],"mappings":";;AAkEA,SAASA,EAAUC,GAAYC,GAAqB;AAClD,MAAID,MAAMC,EAAG,QAAO;AAGpB,MAFID,MAAM,QAAQC,MAAM,QACpB,OAAOD,KAAM,OAAOC,KACpB,OAAOD,KAAM,SAAU,QAAO;AAElC,MAAI,MAAM,QAAQA,CAAC,KAAK,MAAM,QAAQC,CAAC;AACrC,WAAID,EAAE,WAAWC,EAAE,SAAe,KAC3BD,EAAE,MAAM,CAACE,GAAKC,MAAQJ,EAAUG,GAAKD,EAAEE,CAAG,CAAC,CAAC;AAGrD,MAAI,MAAM,QAAQH,CAAC,KAAK,MAAM,QAAQC,CAAC,EAAG,QAAO;AAEjD,QAAMG,IAAQ,OAAO,KAAKJ,CAAC,GACrBK,IAAQ,OAAO,KAAKJ,CAAW;AACrC,SAAIG,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