| 375 | } |
| 376 | |
| 377 | export function safeLocalStorage(): { |
| 378 | getItem: (key: string) => string | null; |
| 379 | setItem: (key: string, value: string) => void; |
| 380 | removeItem: (key: string) => void; |
| 381 | clear: () => void; |
| 382 | } { |
| 383 | let storage: Storage | null; |
| 384 | |
| 385 | try { |
| 386 | if (typeof window !== "undefined" && window.localStorage) { |
| 387 | storage = window.localStorage; |
| 388 | } else { |
| 389 | storage = null; |
| 390 | } |
| 391 | } catch (e) { |
| 392 | console.error("localStorage is not available:", e); |
| 393 | storage = null; |
| 394 | } |
| 395 | |
| 396 | return { |
| 397 | getItem(key: string): string | null { |
| 398 | if (storage) { |
| 399 | return storage.getItem(key); |
| 400 | } else { |
| 401 | console.warn( |
| 402 | `Attempted to get item "${key}" from localStorage, but localStorage is not available.`, |
| 403 | ); |
| 404 | return null; |
| 405 | } |
| 406 | }, |
| 407 | setItem(key: string, value: string): void { |
| 408 | if (storage) { |
| 409 | storage.setItem(key, value); |
| 410 | } else { |
| 411 | console.warn( |
| 412 | `Attempted to set item "${key}" in localStorage, but localStorage is not available.`, |
| 413 | ); |
| 414 | } |
| 415 | }, |
| 416 | removeItem(key: string): void { |
| 417 | if (storage) { |
| 418 | storage.removeItem(key); |
| 419 | } else { |
| 420 | console.warn( |
| 421 | `Attempted to remove item "${key}" from localStorage, but localStorage is not available.`, |
| 422 | ); |
| 423 | } |
| 424 | }, |
| 425 | clear(): void { |
| 426 | if (storage) { |
| 427 | storage.clear(); |
| 428 | } else { |
| 429 | console.warn( |
| 430 | "Attempted to clear localStorage, but localStorage is not available.", |
| 431 | ); |
| 432 | } |
| 433 | }, |
| 434 | }; |