Jotley / website · jotley.ai / src / instrumentation.ts
| 1 | type StorageLike = Pick<Storage, 'getItem' | 'setItem' | 'removeItem' | 'clear' | 'key'> & { |
| 2 | length: number |
| 3 | } |
| 4 | |
| 5 | function createNoopStorage(): StorageLike { |
| 6 | return { |
| 7 | getItem: () => null, |
| 8 | setItem: () => {}, |
| 9 | removeItem: () => {}, |
| 10 | clear: () => {}, |
| 11 | key: () => null, |
| 12 | length: 0 |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | function ensureStorage(name: 'localStorage' | 'sessionStorage') { |
| 17 | const globalObj = globalThis as Record<string, unknown> |
| 18 | const storage = globalObj[name] as Partial<Storage> | undefined |
| 19 | const isUsable = |
| 20 | storage && |
| 21 | typeof storage.getItem === 'function' && |
| 22 | typeof storage.setItem === 'function' && |
| 23 | typeof storage.removeItem === 'function' |
| 24 | |
| 25 | if (!isUsable) { |
| 26 | globalObj[name] = createNoopStorage() |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | export async function register() { |
| 31 | if (typeof window !== 'undefined') return |
| 32 | |
| 33 | ensureStorage('localStorage') |
| 34 | ensureStorage('sessionStorage') |
| 35 | } |