|
1 |
| -import { isLocalStorageAvailable } from './utils' |
2 |
| - |
3 |
| -// todo: Remove check for `next-usequerystate` in v2 |
4 |
| -let enabled = false |
5 |
| - |
6 |
| -try { |
7 |
| - enabled = |
8 |
| - (isLocalStorageAvailable() && |
9 |
| - (localStorage.getItem('debug')?.includes('next-usequerystate') || |
10 |
| - localStorage.getItem('debug')?.includes('nuqs'))) || |
11 |
| - false |
12 |
| -} catch (error) { |
13 |
| - console.error( |
14 |
| - '[nuqs]: debug mode is disabled (localStorage unavailable).', |
15 |
| - error |
16 |
| - ) |
17 |
| -} |
| 1 | +const enabled = isDebugEnabled() |
18 | 2 |
|
19 | 3 | export function debug(message: string, ...args: any[]) {
|
20 | 4 | if (!enabled) {
|
@@ -42,3 +26,31 @@ export function sprintf(base: string, ...args: any[]) {
|
42 | 26 | }
|
43 | 27 | })
|
44 | 28 | }
|
| 29 | + |
| 30 | +function isDebugEnabled() { |
| 31 | + // Check if localStorage is available. |
| 32 | + // It may be unavailable in some environments, |
| 33 | + // like Safari in private browsing mode. |
| 34 | + // See https://github.com/47ng/nuqs/pull/588 |
| 35 | + try { |
| 36 | + if (typeof localStorage === 'undefined') { |
| 37 | + return false |
| 38 | + } |
| 39 | + const test = 'nuqs-localStorage-test' |
| 40 | + localStorage.setItem(test, test) |
| 41 | + const isStorageAvailable = localStorage.getItem(test) === test |
| 42 | + localStorage.removeItem(test) |
| 43 | + if (!isStorageAvailable) { |
| 44 | + return false |
| 45 | + } |
| 46 | + } catch (error) { |
| 47 | + console.error( |
| 48 | + '[nuqs]: debug mode is disabled (localStorage unavailable).', |
| 49 | + error |
| 50 | + ) |
| 51 | + return false |
| 52 | + } |
| 53 | + const debug = localStorage.getItem('debug') ?? '' |
| 54 | + // todo: Remove check for `next-usequerystate` in v2 |
| 55 | + return debug.includes('nuqs') || debug.includes('next-usequerystate') |
| 56 | +} |
0 commit comments