/* eslint-disable @typescript-eslint/no-unused-vars */ import type { StorageSettings, StorageMetadata, StorageStatistics, StorageVersion, QuotaStatus, SidePanelPreferences } from '@buzztrail/shared-types/extension-storage'; import type { ConversationMessage, DataSharingRecord } from '@buzztrail/shared-types/conversation'; import type { UserPreferences } from '@buzztrail/shared-types/user-preferences'; import type { Persona } from '@buzztrail/shared-types/persona'; import type { SiteConfiguration, PageContext } from '@buzztrail/shared-types/site-configuration'; /** * Storage error types */ export type StorageErrorType = | 'quota_exceeded' | 'write_failed' | 'read_failed' | 'delete_failed' | 'migration_failed' | 'cleanup_failed'; /** * Storage error information */ export interface StorageError { type: StorageErrorType; message: string; timestamp: string; key?: string; details?: Record; } /** * Quota information */ export interface QuotaInfo { bytesInUse: number; quotaBytes: number; availableBytes: number; usagePercentage: number; status: QuotaStatus; } /** * Cleanup strategy result */ export interface CleanupResult { itemsRemoved: number; bytesFreed: number; domainsCleaned: string[]; success: boolean; errors: StorageError[]; } /** * Storage Manager for Chrome Extension * Handles all persistent data storage with simplified user-controlled settings */ export class StorageManager { private static instance: StorageManager; private isInitialized = false; private currentVersion: StorageVersion = '1.2.0'; private errors: StorageError[] = []; /** * Internal stored conversations shape used by this manager */ /** * Get singleton instance */ public static getInstance(): StorageManager { if (!StorageManager.instance) { StorageManager.instance = new StorageManager(); } return StorageManager.instance; } /** * Initialize the storage manager */ public async initialize(): Promise { if (this.isInitialized) { return; } try { // Check if storage exists and migrate if needed await this.checkAndMigrateStorage(); this.isInitialized = true; } catch (error) { console.error('Failed to initialize StorageManager:', error); this.addError('migration_failed', 'Failed to initialize storage manager', { error: String(error) }); throw error; } } /** * Check if storage manager is initialized */ public getIsInitialized(): boolean { return this.isInitialized; } /** * Get current storage version */ public getVersion(): StorageVersion { return this.currentVersion; } /** * Get storage quota information */ public async getQuotaInfo(): Promise { try { const bytesInUse: number = await new Promise((resolve, reject) => { try { // Passing null requests total usage chrome.storage.local.getBytesInUse(null as unknown as string | string[], (n) => { const err = chrome.runtime.lastError; if (err) reject(err); else resolve(Number(n)) }); } catch { resolve(0); } }); // chrome.storage.local has effectively unbounded quota in MV3; provide 0 for unknown const quotaBytes = 0; const availableBytes = Math.max(0, quotaBytes - bytesInUse); const usagePercentage = quotaBytes > 0 ? (bytesInUse / quotaBytes) * 100 : 0; return { bytesInUse, quotaBytes, availableBytes, usagePercentage, status: usagePercentage > 90 ? 'critical' : usagePercentage > 75 ? 'warning' : 'normal' }; } catch (error) { console.error('Error getting quota info:', error); return { bytesInUse: 0, quotaBytes: 0, availableBytes: 0, usagePercentage: 0, status: 'normal' }; } } /** * Check if we have enough quota for a write operation */ private async checkQuotaForWrite(estimatedSize: number): Promise { const quotaInfo = await this.getQuotaInfo(); return quotaInfo.availableBytes >= estimatedSize; } /** * Perform storage cleanup based on user settings */ public async performCleanup(): Promise { const result: CleanupResult = { itemsRemoved: 0, bytesFreed: 0, domainsCleaned: [], success: false, errors: [] }; try { const settings = await this.getStorageSettings(); if (!settings.enableAutoCleanup) { result.success = true; return result; } const allData = await chrome.storage.local.get(null); const domainsToClean: string[] = []; // let totalBytesFreed = 0; // reserved for future cleanup metrics // Identify domains to clean based on settings for (const [key, value] of Object.entries(allData)) { if (key.startsWith('conversations_') && typeof value === 'object' && value !== null) { const domain = key.replace('conversations_', ''); const conversations = value as StoredDomainConversations; // Check age-based cleanup if (settings.retentionDays > 0) { const cutoffDate = new Date(); cutoffDate.setDate(cutoffDate.getDate() - settings.retentionDays); const oldConversations = conversations.conversations.filter( (conv: unknown) => new Date((conv as { timestamp: string }).timestamp) < cutoffDate ); if (oldConversations.length > 0) { conversations.conversations = conversations.conversations.filter( (conv: unknown) => new Date((conv as { timestamp: string }).timestamp) >= cutoffDate ); result.itemsRemoved += oldConversations.length; domainsToClean.push(domain); } } // Size-based cleanup removed (no setting for max conversations in current schema) // Save updated conversations if (domainsToClean.includes(domain)) { await chrome.storage.local.set({ [key]: conversations }); } } } result.domainsCleaned = domainsToClean; result.success = true; // Update statistics await this.updateStatistics(); } catch (error) { console.error('Error during cleanup:', error); this.addError('cleanup_failed', 'Failed to perform cleanup', { error: String(error) }); result.errors.push({ type: 'cleanup_failed', message: error instanceof Error ? error.message : 'Unknown cleanup error', timestamp: new Date().toISOString() }); } return result; } /** * Add an error to the error log */ private addError(type: StorageErrorType, message: string, details?: Record): void { const error: StorageError = { type, message, timestamp: new Date().toISOString(), details }; this.errors.push(error); console.error('Storage error:', error); } /** * Get all storage errors */ public getErrors(): StorageError[] { return [...this.errors]; } /** * Clear all storage errors */ public clearErrors(): void { this.errors = []; } /** * Save a conversation message */ public async saveConversation(domain: string, conversation: ConversationMessage): Promise { try { const key = `conversations_${domain}`; const existingData = await this.getStorageItem(key); const domainConversations: StoredDomainConversations = existingData || { domain, conversations: [], lastUpdated: new Date().toISOString() }; domainConversations.conversations.push(conversation); domainConversations.lastUpdated = new Date().toISOString(); await this.setStorageItem(key, domainConversations); } catch (error) { console.error('Error saving conversation:', error); this.addError('write_failed', 'Failed to save conversation', { domain, error: String(error) }); throw error; } } /** * Get conversations for a domain */ public async getConversations(domain: string, dateRange?: { start: string; end: string }): Promise { try { const key = `conversations_${domain}`; const domainConversations = await this.getStorageItem(key); if (!domainConversations) { return []; } // Filter by date range if provided if (dateRange) { const startDate = new Date(dateRange.start); const endDate = new Date(dateRange.end); domainConversations.conversations = domainConversations.conversations.filter((conv: unknown) => { const convDate = new Date((conv as { timestamp: string }).timestamp); return convDate >= startDate && convDate <= endDate; }); } return domainConversations.conversations as unknown as ConversationMessage[]; } catch (error) { console.error('Error getting conversations:', error); this.addError('read_failed', 'Failed to get conversations', { domain, error: String(error) }); return []; } } /** * Save user preferences */ public async saveUserPreferences(preferences: UserPreferences): Promise { try { await this.setStorageItem('user_preferences', preferences); } catch (error) { console.error('Error saving user preferences:', error); this.addError('write_failed', 'Failed to save user preferences', { error: String(error) }); throw error; } } /** * Get user preferences */ public async getUserPreferences(): Promise { try { return await this.getStorageItem('user_preferences'); } catch (error) { console.error('Error getting user preferences:', error); this.addError('read_failed', 'Failed to get user preferences', { error: String(error) }); return null; } } /** * Save site configuration */ public async saveSiteConfig(domain: string, config: SiteConfiguration): Promise { try { const key = `site_config_${domain}`; await this.setStorageItem(key, config); } catch (error) { console.error('Error saving site config:', error); this.addError('write_failed', 'Failed to save site config', { domain, error: String(error) }); throw error; } } /** * Get site configuration */ public async getSiteConfig(domain: string): Promise { try { const key = `site_config_${domain}`; return await this.getStorageItem(key); } catch (error) { console.error('Error getting site config:', error); this.addError('read_failed', 'Failed to get site config', { domain, error: String(error) }); return null; } } /** * Save data sharing record */ public async saveDataSharingRecord(record: DataSharingRecord): Promise { try { const key = `data_sharing_${record.domain}`; const existingRecords = await this.getStorageItem(key) || []; existingRecords.push(record); await this.setStorageItem(key, existingRecords); } catch (error) { console.error('Error saving data sharing record:', error); this.addError('write_failed', 'Failed to save data sharing record', { error: String(error) }); throw error; } } /** * Get data sharing records for a domain */ public async getDataSharingRecords(domain: string): Promise { try { const key = `data_sharing_${domain}`; return await this.getStorageItem(key) || []; } catch (error) { console.error('Error getting data sharing records:', error); this.addError('read_failed', 'Failed to get data sharing records', { domain, error: String(error) }); return []; } } /** * Save persona */ public async savePersona(persona: Persona): Promise { try { const key = `persona_${persona.metadata.id}`; await this.setStorageItem(key, persona); } catch (error) { console.error('Error saving persona:', error); this.addError('write_failed', 'Failed to save persona', { error: String(error) }); throw error; } } /** * Get persona by ID */ public async getPersona(personaId: string): Promise { try { const key = `persona_${personaId}`; return await this.getStorageItem(key); } catch (error) { console.error('Error getting persona:', error); this.addError('read_failed', 'Failed to get persona', { personaId, error: String(error) }); return null; } } /** * Get all personas */ public async getAllPersonas(): Promise> { try { const allData = await chrome.storage.local.get(null); const personas: Record = {}; for (const [key, value] of Object.entries(allData)) { if (key.startsWith('persona_') && typeof value === 'object' && value !== null) { const persona = value as Persona; personas[persona.metadata.id] = persona; } } return personas; } catch (error) { console.error('Error getting all personas:', error); this.addError('read_failed', 'Failed to get all personas', { error: String(error) }); return {}; } } /** * Save page context for a tab */ public async savePageContext(tabId: number, context: PageContext): Promise { try { const key = `page_context_${tabId}`; await this.setStorageItem(key, context); } catch (error) { console.error('Error saving page context:', error); this.addError('write_failed', 'Failed to save page context', { tabId, error: String(error) }); throw error; } } /** * Get page context for a tab */ public async getPageContext(tabId: number): Promise { try { const key = `page_context_${tabId}`; return await this.getStorageItem(key); } catch (error) { console.error('Error getting page context:', error); this.addError('read_failed', 'Failed to get page context', { tabId, error: String(error) }); return null; } } /** * Delete a specific conversation message */ public async deleteConversation(messageId: string): Promise { try { const allData = await chrome.storage.local.get(null); for (const [key, value] of Object.entries(allData)) { if (key.startsWith('conversations_') && typeof value === 'object' && value !== null) { const domainConversations = value as StoredDomainConversations; const originalLength = domainConversations.conversations.length; domainConversations.conversations = domainConversations.conversations.filter( (conv) => (conv as { id?: string }).id !== messageId ); if (domainConversations.conversations.length !== originalLength) { await chrome.storage.local.set({ [key]: domainConversations }); break; } } } } catch (error) { console.error('Error deleting conversation:', error); this.addError('delete_failed', 'Failed to delete conversation', { messageId, error: String(error) }); throw error; } } /** * Delete all conversations for a domain */ public async deleteDomainConversations(domain: string): Promise { try { const key = `conversations_${domain}`; await chrome.storage.local.remove(key); } catch (error) { console.error('Error deleting domain conversations:', error); this.addError('delete_failed', 'Failed to delete domain conversations', { domain, error: String(error) }); throw error; } } /** * Get storage settings */ public async getStorageSettings(): Promise { try { const settings = await this.getStorageItem('storage_settings'); return ( settings || { enableAutoCleanup: false, retentionDays: 30, enableCompression: false, enableEncryption: false, showStorageWarnings: false, warningThreshold: 80, autoDeleteOldData: false } ); } catch (error) { console.error('Error getting storage settings:', error); this.addError('read_failed', 'Failed to get storage settings', { error: String(error) }); return { enableAutoCleanup: false, retentionDays: 30, enableCompression: false, enableEncryption: false, showStorageWarnings: false, warningThreshold: 80, autoDeleteOldData: false }; } } /** * Save storage settings */ public async saveStorageSettings(settings: StorageSettings): Promise { try { await this.setStorageItem('storage_settings', settings); } catch (error) { console.error('Error saving storage settings:', error); this.addError('write_failed', 'Failed to save storage settings', { error: String(error) }); throw error; } } /** * Get storage metadata */ public async getStorageMetadata(): Promise { try { const metadata = await this.getStorageItem('storage_metadata'); return ( metadata || { version: this.currentVersion, lastUpdated: new Date().toISOString(), createdAt: new Date().toISOString(), totalSize: 0, availableSpace: 0, quotaStatus: 'normal', encryptionStatus: 'none', syncStatus: 'disabled', backupStatus: 'none', migrationStatus: 'completed', domainCount: 0, conversationCount: 0 } ); } catch (error) { console.error('Error getting storage metadata:', error); this.addError('read_failed', 'Failed to get storage metadata', { error: String(error) }); return { version: this.currentVersion, lastUpdated: new Date().toISOString(), createdAt: new Date().toISOString(), totalSize: 0, availableSpace: 0, quotaStatus: 'normal', encryptionStatus: 'none', syncStatus: 'disabled', backupStatus: 'none', migrationStatus: 'completed', domainCount: 0, conversationCount: 0 }; } } /** * Update storage metadata */ public async updateStorageMetadata(metadata: Partial): Promise { try { const currentMetadata = await this.getStorageMetadata(); const updatedMetadata = { ...currentMetadata, ...metadata, lastUpdated: new Date().toISOString() }; await this.setStorageItem('storage_metadata', updatedMetadata); } catch (error) { console.error('Error updating storage metadata:', error); this.addError('write_failed', 'Failed to update storage metadata', { error: String(error) }); throw error; } } /** * Get storage statistics */ public async getStorageStatistics(): Promise { try { const allData = await chrome.storage.local.get(null); let totalMessages = 0; const domainUsage: StorageStatistics['domainUsage'] = {}; for (const [key, value] of Object.entries(allData)) { if (key.startsWith('conversations_') && typeof value === 'object' && value !== null) { const domainConversations = value as StoredDomainConversations; totalMessages += domainConversations.conversations.length; domainUsage[domainConversations.domain] = { messageCount: domainConversations.conversations.length, lastActivity: domainConversations.lastUpdated }; } } // const quotaInfo = await this.getQuotaInfo(); return { totalMessages, averageResponseTime: 0, averageSatisfactionScore: 0, mostActiveDomain: Object.keys(domainUsage)[0] ?? '', mostUsedPersona: '', domainUsage, dateUsage: {}, personaUsage: {} }; } catch (error) { console.error('Error getting storage statistics:', error); this.addError('read_failed', 'Failed to get storage statistics', { error: String(error) }); return { totalMessages: 0, averageResponseTime: 0, averageSatisfactionScore: 0, mostActiveDomain: '', mostUsedPersona: '', domainUsage: {}, dateUsage: {}, personaUsage: {} }; } } /** * Update storage statistics */ public async updateStatistics(): Promise { try { const quotaInfo = await this.getQuotaInfo(); const stats = await this.getStorageStatistics(); await this.updateStorageMetadata({ conversationCount: Object.values(stats.domainUsage).reduce((sum, d) => sum + d.messageCount, 0), domainCount: Object.keys(stats.domainUsage).length, totalSize: quotaInfo.bytesInUse, availableSpace: quotaInfo.availableBytes, quotaStatus: quotaInfo.status, encryptionStatus: 'none', syncStatus: 'disabled', backupStatus: 'none', migrationStatus: 'completed' }); } catch (error) { console.error('Error updating statistics:', error); this.addError('write_failed', 'Failed to update statistics', { error: String(error) }); } } /** * Get domain conversations with error handling */ private async getDomainConversations(domain: string): Promise { try { const key = `conversations_${domain}`; const existingData = await this.getStorageItem(key); return existingData || { domain, conversations: [], lastUpdated: new Date().toISOString() }; } catch (error) { console.error('Error getting domain conversations:', error); this.addError('read_failed', 'Failed to get domain conversations', { domain, error: String(error) }); return { domain, conversations: [], lastUpdated: new Date().toISOString() }; } } /** * Check and migrate storage if needed */ private async checkAndMigrateStorage(): Promise { try { const metadata = await this.getStorageMetadata(); if (metadata.version !== this.currentVersion) { console.log(`Migrating storage from ${metadata.version} to ${this.currentVersion}`); await this.migrateStorage(metadata.version, this.currentVersion); await this.updateStorageMetadata({ version: this.currentVersion }); } } catch (error) { console.error('Error during storage migration check:', error); this.addError('migration_failed', 'Failed to check and migrate storage', { error: String(error) }); throw error; } } /** * Migrate storage from one version to another */ private async migrateStorage(fromVersion: StorageVersion, toVersion: StorageVersion): Promise { try { if (fromVersion === '1.0.0' && toVersion === '1.1.0') { await this.migrateFrom100To110(); } else if (fromVersion === '1.1.0' && toVersion === '1.2.0') { await this.migrateFrom110To120(); } } catch (error) { console.error('Error during storage migration:', error); this.addError('migration_failed', 'Failed to migrate storage', { fromVersion, toVersion, error: String(error) }); throw error; } } /** * Migrate from version 1.0.0 to 1.1.0 */ private async migrateFrom100To110(): Promise { // Add any migration logic for version 1.0.0 to 1.1.0 console.log('Migrating from version 1.0.0 to 1.1.0'); } /** * Migrate from version 1.1.0 to 1.2.0 */ private async migrateFrom110To120(): Promise { // Add any migration logic for version 1.1.0 to 1.2.0 console.log('Migrating from version 1.1.0 to 1.2.0'); } /** * Get a storage item with error handling */ private async getStorageItem(key: string): Promise { try { const result = await chrome.storage.local.get(key); return result[key] as T || null; } catch (error) { console.error(`Error getting storage item ${key}:`, error); this.addError('read_failed', `Failed to get storage item: ${key}`, { key, error: String(error) }); return null; } } // Deprecated: floating container state methods public async getFloatingContainerState(_domain: string): Promise { return null; } public async saveFloatingContainerPreferences(_domain: string, _preferences: unknown): Promise { // Intentionally empty - floating container functionality is deprecated } public async getFloatingContainerPreferences(_domain: string): Promise { // Intentionally empty - floating container functionality is deprecated return null; } public async deleteFloatingContainerData(_domain: string): Promise { // Intentionally empty - floating container functionality is deprecated } public async getAllFloatingContainerPreferences(): Promise> { return {}; } /** * Set a storage item with error handling */ private async setStorageItem(key: string, value: T): Promise { try { await chrome.storage.local.set({ [key]: value }); } catch (error) { console.error(`Error setting storage item ${key}:`, error); this.addError('write_failed', `Failed to set storage item: ${key}`, { key, error: String(error) }); throw error; } } /** * Get storage status */ public async getStatus(): Promise<{ isInitialized: boolean; version: StorageVersion; errors: StorageError[]; quotaInfo: QuotaInfo; statistics: StorageStatistics; }> { return { isInitialized: this.getIsInitialized(), version: this.currentVersion, errors: this.getErrors(), quotaInfo: await this.getQuotaInfo(), statistics: await this.getStorageStatistics() }; } /** * Save Side Panel preferences */ public async saveSidePanelPreferences(prefs: SidePanelPreferences): Promise { try { await this.setStorageItem('side_panel_prefs', prefs); } catch (error) { console.error('Error saving side panel preferences:', error); this.addError('write_failed', 'Failed to save side panel preferences', { error: String(error) }); throw error; } } /** * Get Side Panel preferences */ public async getSidePanelPreferences(): Promise { try { return await this.getStorageItem('side_panel_prefs'); } catch (error) { console.error('Error getting side panel preferences:', error); this.addError('read_failed', 'Failed to get side panel preferences', { error: String(error) }); return null; } } } /** * Minimal internal storage shape to hold conversations per domain in chrome.storage */ export interface StoredDomainConversations { domain: string; conversations: unknown[]; lastUpdated: string; }