# State Utilities Audit **Date**: 2026-01-11 **Action**: 4.6.1.1 - List all state utility files **Status**: ✅ Complete ## Summary This document lists all state utility files found in `apps/web/src/utils/` and documents their purposes, usage, and status. ## State Utility Files Found ### 1. `stateMiddleware.ts` - **Purpose**: Zustand middleware for analytics tracking and error handling - **Exports**: - `setAnalyticsHandler()` - Set analytics handler - `setErrorHandler()` - Set error handler - `stateMiddleware()` - Middleware function - **Key Features**: - Tracks state changes for analytics - Handles errors in state updates - Provides context for debugging - **Used By**: Library Store (`stores/library.ts`) - **Status**: ⚠️ **Used by Library Store** (may be unnecessary complexity) - **Test File**: `stateMiddleware.test.ts` ✅ ### 2. `stateNormalization.ts` - **Purpose**: Utilities for normalized state management (entities by ID) - **Exports**: - `normalize()` - Convert array to normalized state - `denormalize()` - Convert normalized state to array - `addToNormalized()` - Add item to normalized state - `updateInNormalized()` - Update item in normalized state - `removeFromNormalized()` - Remove item from normalized state - `replaceNormalized()` - Replace normalized state - `mergeNormalized()` - Merge normalized states - `getById()` - Get item by ID - `getByIds()` - Get items by IDs - **Key Features**: - Normalized state structure: `{ byId: Record, allIds: string[] }` - Efficient lookups and updates - **Used By**: Library Store (`stores/library.ts`) - **Status**: ⚠️ **Used by Library Store** (will become obsolete when Library Store migrates to React Query) - **Test File**: None ❌ ### 3. `stateInvalidation.ts` - **Purpose**: Unified state invalidation for Zustand stores and React Query - **Exports**: - `invalidateState()` - Invalidate state by resource type - `invalidateStateAfterMutation()` - Invalidate after mutation - **Key Features**: - Invalidates both Zustand stores and React Query cache - Supports resource-based invalidation - Integrates with response cache - **Used By**: Various mutation handlers - **Status**: ✅ **Active** (useful for migration period) - **Test File**: None ❌ ### 4. `stateHydration.ts` - **Purpose**: Hydrate Zustand stores from API on app load - **Exports**: - `hydrateState()` - Hydrate stores from API - `useStateHydration()` - React hook for hydration - **Key Features**: - Loads initial state from API - Hydrates Auth, Library, and Chat stores - Handles errors and loading states - **Used By**: App initialization, store hydration - **Status**: ⚠️ **Used for Zustand stores** (will become obsolete when stores migrate to React Query) - **Test File**: None ❌ ### 5. `stateCleanup.ts` - **Purpose**: Cleanup utilities for Zustand stores (size/age-based) - **Exports**: - `applyCleanup()` - Apply cleanup strategy to store - **Key Features**: - Size-based cleanup (keep N items) - Age-based cleanup (remove old items) - Normalized state cleanup support - **Used By**: Potentially Library Store - **Status**: ⚠️ **May be unused** (needs verification) - **Test File**: `stateCleanup.test.ts` ✅ ### 6. `stateVersioning.ts` - **Purpose**: State versioning and migration utilities for Zustand stores - **Exports**: - `applyMigrations()` - Apply migrations to state - `versionState()` - Add version to state - `unversionState()` - Remove version from state - `createVersionedStorage()` - Create versioned storage adapter - **Key Features**: - Supports state schema migrations - Version tracking for persisted state - Migration functions for breaking changes - **Used By**: Potentially for store migrations - **Status**: ⚠️ **May be unused** (needs verification) - **Test Files**: `stateVersioning.test.ts` ✅, `stateVersioning.example.ts` ✅ ### 7. `statePersistence.ts` - **Purpose**: Persistence utilities for Zustand stores - **Exports**: (needs inspection) - **Key Features**: (needs inspection) - **Used By**: (needs inspection) - **Status**: ⚠️ **Needs inspection** - **Test File**: None ❌ ### 8. `broadcastSync.ts` - **Purpose**: Synchronize Zustand stores across browser tabs/windows - **Exports**: - `broadcastSync()` - Middleware for tab synchronization - `createSynchronizedStore()` - Create synchronized store - **Key Features**: - Uses BroadcastChannel API - Syncs state changes across tabs - Handles conflicts and race conditions - **Used By**: UI Store (`stores/ui.ts`), Auth Store (`features/auth/store/authStore.ts`) - **Status**: ✅ **Active** (useful for multi-tab sync) - **Test File**: None ❌ ### 9. `undoRedo.ts` - **Purpose**: Undo/redo functionality for Zustand stores - **Exports**: - `undoRedo()` - Middleware for undo/redo - `useUndoRedo()` - React hook for undo/redo - `UndoRedoManager` - Class for managing history - `undoRedoManager` - Singleton instance - **Key Features**: - History tracking for state changes - Undo/redo operations - Configurable history size - **Used By**: Library Store (`stores/library.ts`) - **Status**: ⚠️ **Used by Library Store** (will become obsolete when Library Store migrates to React Query) - **Test File**: None ❌ ### 10. `storeSelectors.ts` - **Purpose**: Optimized selectors for Zustand stores to prevent unnecessary re-renders - **Exports**: - `useAuthUser()` - Get user from auth store - `useAuthStatus()` - Get auth status - `useStoreSelector()` - Generic store selector - **Key Features**: - Uses `useShallow` for shallow comparison - Prevents unnecessary re-renders - Type-safe selectors - **Used By**: Various components - **Status**: ✅ **Active** (useful optimization) - **Test File**: None ❌ ## File Statistics - **Total State Utility Files**: 10 - **With Tests**: 3 (30%) - **Without Tests**: 7 (70%) - **Actively Used**: 6 - **Potentially Unused**: 2 (stateCleanup, stateVersioning - needs verification) - **Will Become Obsolete**: 4 (stateMiddleware, stateNormalization, stateHydration, undoRedo - when stores migrate) ## Usage Analysis ### Utilities Used by Stores - **Library Store**: `stateMiddleware`, `stateNormalization`, `undoRedo` - **UI Store**: `broadcastSync` - **Auth Store**: `broadcastSync` - **Chat Store**: None (uses Immer middleware) ### Utilities Used by Components - **storeSelectors**: Used by various components for optimized selectors - **stateInvalidation**: Used by mutation handlers - **stateHydration**: Used for app initialization ## Migration Impact ### Will Become Obsolete (After Store Migration) 1. **stateMiddleware** - Only used by Library Store 2. **stateNormalization** - Only used by Library Store 3. **stateHydration** - Only hydrates Zustand stores 4. **undoRedo** - Only used by Library Store ### Will Remain Useful 1. **broadcastSync** - Useful for UI state sync across tabs 2. **storeSelectors** - Useful for optimized Zustand selectors 3. **stateInvalidation** - Useful during migration period ### Needs Investigation 1. **stateCleanup** - Verify if actually used 2. **stateVersioning** - Verify if actually used 3. **statePersistence** - Inspect purpose and usage ## Recommendations ### High Priority 1. ✅ **Action 4.6.1.1**: Audit complete - 10 utilities documented 2. **Action 4.6.1.2**: Verify usage of `stateCleanup`, `stateVersioning`, `statePersistence` 3. **Action 4.6.1.3**: Add tests for utilities without tests (7 files) ### Medium Priority 1. Plan removal of obsolete utilities after store migration 2. Document migration path for utilities that will become obsolete ### Low Priority 1. Consider consolidating similar utilities 2. Review if `stateMiddleware` complexity is justified ## Next Steps 1. ✅ **Action 4.6.1.1**: List complete - 10 state utilities documented 2. **Action 4.6.1.2**: Verify usage of potentially unused utilities 3. **Action 4.6.1.3**: Add missing tests