forked from Echo-Mirror-Butler/echomirror-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.ts
More file actions
89 lines (76 loc) · 2.23 KB
/
Copy pathstorage.ts
File metadata and controls
89 lines (76 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import type { AnalyticsEvent, AnalyticsStorage } from './types.js'
export const DEFAULT_STORAGE_KEY = 'echomirror.analytics.v1'
export interface PersistedAnalyticsState {
version: 1
anonymousId: string
sessionId: string
userId?: string
queue: AnalyticsEvent[]
}
export class MemoryStorage implements AnalyticsStorage {
private readonly values = new Map<string, string>()
getItem(key: string): string | null {
return this.values.get(key) ?? null
}
setItem(key: string, value: string): void {
this.values.set(key, value)
}
removeItem(key: string): void {
this.values.delete(key)
}
}
const fallbackStorage = new MemoryStorage()
export function defaultStorage(): AnalyticsStorage {
try {
if (typeof globalThis.localStorage !== 'undefined') return globalThis.localStorage
} catch {
// Access can throw when browser storage is disabled.
}
return fallbackStorage
}
function isEvent(value: unknown): value is AnalyticsEvent {
if (!value || typeof value !== 'object') return false
const event = value as Partial<AnalyticsEvent>
return (
typeof event.id === 'string' &&
typeof event.name === 'string' &&
typeof event.timestamp === 'string' &&
typeof event.anonymousId === 'string' &&
typeof event.sessionId === 'string' &&
!!event.properties &&
typeof event.properties === 'object'
)
}
export function readState(
storage: AnalyticsStorage,
key: string,
): PersistedAnalyticsState | undefined {
const value = storage.getItem(key)
if (!value) return undefined
try {
const parsed = JSON.parse(value) as Partial<PersistedAnalyticsState>
if (
parsed.version !== 1 ||
typeof parsed.anonymousId !== 'string' ||
typeof parsed.sessionId !== 'string' ||
!Array.isArray(parsed.queue)
) {
return undefined
}
const seen = new Set<string>()
const queue = parsed.queue.filter((event) => {
if (!isEvent(event) || seen.has(event.id)) return false
seen.add(event.id)
return true
})
return {
version: 1,
anonymousId: parsed.anonymousId,
sessionId: parsed.sessionId,
...(typeof parsed.userId === 'string' ? { userId: parsed.userId } : {}),
queue,
}
} catch {
return undefined
}
}