()
| 36 | } |
| 37 | |
| 38 | async loadApiKey() { |
| 39 | try { |
| 40 | if (typeof chatDB !== 'undefined') { |
| 41 | if (!chatDB.db && typeof chatDB.init === 'function') { |
| 42 | await chatDB.init(); |
| 43 | } |
| 44 | const stored = await chatDB.getSetting(ACCESS_DB_KEY); |
| 45 | if (stored) { |
| 46 | this.state = { |
| 47 | apiKey: stored.key, |
| 48 | apiKeyInfo: stored, |
| 49 | expiresAt: stored.expiresAt || stored.expires_at, // Support both formats |
| 50 | ticketUsed: stored.ticketUsed || stored.ticket_used |
| 51 | }; |
| 52 | console.log('📥 Loaded API key from IndexedDB'); |
| 53 | this.notify(); |
| 54 | return; |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | const legacyStored = localStorage.getItem(ACCESS_STORAGE_KEY); |
| 59 | if (legacyStored) { |
| 60 | const data = JSON.parse(legacyStored); |
| 61 | this.state = { |
| 62 | apiKey: data.key, |
| 63 | apiKeyInfo: data, |
| 64 | expiresAt: data.expiresAt || data.expires_at, |
| 65 | ticketUsed: data.ticketUsed || data.ticket_used |
| 66 | }; |
| 67 | let persisted = false; |
| 68 | if (typeof chatDB !== 'undefined' && chatDB.db) { |
| 69 | try { |
| 70 | await chatDB.saveSetting(ACCESS_DB_KEY, data); |
| 71 | persisted = true; |
| 72 | } catch (error) { |
| 73 | console.warn('Failed to persist API key during migration:', error); |
| 74 | } |
| 75 | } |
| 76 | if (persisted) { |
| 77 | localStorage.removeItem(ACCESS_STORAGE_KEY); |
| 78 | console.log('📥 Migrated API key from localStorage'); |
| 79 | } else { |
| 80 | console.warn('📥 Loaded API key from localStorage (IndexedDB unavailable)'); |
| 81 | } |
| 82 | this.notify(); |
| 83 | } |
| 84 | } catch (error) { |
| 85 | console.error('❌ Error loading API key:', error); |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | async setApiKey(apiKeyData) { |
| 90 | try { |
no test coverage detected