generated from ipfs/ipfs-repository-template
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMetricsProvider.ts
216 lines (193 loc) · 6.71 KB
/
MetricsProvider.ts
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import type {
CountlyEvent,
CountlyWebSdk,
IgnoreList,
Segments,
metricFeatures
} from 'countly-sdk-web'
import type { consentTypes, consentTypesExceptAll } from './typings/countly.js'
import { COUNTLY_SETUP_DEFAULTS } from './config.js'
import type { CountlyNodeSdk } from 'countly-sdk-nodejs'
import { EventAccumulator } from './EventAccumulator.js'
import type { StorageProviderInterface } from './StorageProvider.js'
export interface MetricsProviderConstructorOptions<T> {
appKey: string
autoTrack?: boolean
interval?: number
max_events?: number
metricsService: T
queue_size?: number
session_update?: number
// one of these are required for storing metric related info.
// eslint-disable-next-line no-warning-comments
// TODO(whizzzkid): default to none storage on countly and instead use our own storage provider.
storage?: 'none' | 'localStorage' | 'sessionStorage' | 'cookie'
storageProvider?: StorageProviderInterface | null
url?: string
}
export default class MetricsProvider<T extends CountlyWebSdk | CountlyNodeSdk> {
public readonly accumulate: EventAccumulator<T>
private readonly groupedFeatures: Record<consentTypes, metricFeatures[]> = this.mapAllEvents({
minimal: ['sessions', 'views', 'events'],
performance: ['crashes', 'apm'],
ux: ['scrolls', 'clicks', 'forms'],
feedback: ['star-rating', 'feedback'],
location: ['location']
})
private sessionStarted: boolean = false
private readonly _consentGranted: Set<consentTypes> = new Set()
private readonly metricsService: T
private readonly storageProvider: StorageProviderInterface | null
public initDone: Promise<void>
constructor (config: MetricsProviderConstructorOptions<T>) {
const { appKey, ...remainderConfig } = config
const serviceConfig = {
...COUNTLY_SETUP_DEFAULTS,
...remainderConfig,
app_key: appKey
}
const { autoTrack, metricsService, storageProvider } = serviceConfig
this.metricsService = metricsService
this.storageProvider = storageProvider ?? null
this.metricsService.init(serviceConfig)
this.accumulate = new EventAccumulator(metricsService)
this.metricsService.group_features(this.groupedFeatures)
if (autoTrack) {
this.setupAutoTrack()
}
this.initDone = this.initExistingConsent()
}
private async initExistingConsent (): Promise<void> {
const existingConsent = await this.getConsentStore()
if (existingConsent.length > 0) {
await this.addConsent(existingConsent)
}
}
mapAllEvents (eventMap: Record<consentTypesExceptAll, metricFeatures[]>): Record<consentTypes, metricFeatures[]> {
return {
...eventMap,
all: Object.values(eventMap).flat()
}
}
get consentGranted (): consentTypes[] {
return [...this._consentGranted]
}
setupAutoTrack (): void {
const webSdk = this.metricsService as CountlyWebSdk
webSdk.track_clicks?.()
webSdk.track_forms?.()
webSdk.track_links?.()
webSdk.track_scrolls?.()
webSdk.track_sessions?.()
this.metricsService.track_errors()
this.metricsService.track_pageview()
this.metricsService.track_view()
}
async addConsent (consent: consentTypes | consentTypes[]): Promise<void> {
if (!Array.isArray(consent)) {
consent = [consent]
}
consent.forEach(c => this._consentGranted.add(c))
this.metricsService.add_consent(consent)
await this.setConsentStore()
}
async removeConsent (consent: consentTypes | consentTypes[]): Promise<void> {
if (!Array.isArray(consent)) {
consent = [consent]
}
consent.forEach(c => this._consentGranted.delete(c))
this.metricsService.remove_consent(consent, true)
await this.setConsentStore()
}
private async setConsentStore (): Promise<void> {
/**
* Only set the consent store if
* 1. we have a storage provider
* 2. we're out of the initialization phase.
*/
if (this.storageProvider != null) {
await this.storageProvider.setStore(Array.from(this._consentGranted))
}
}
private async getConsentStore (): Promise<consentTypes[]> {
return await this.storageProvider?.getStore() ?? []
}
checkConsent (consent: consentTypes | metricFeatures): boolean {
if (consent in this.groupedFeatures) {
return this.groupedFeatures[consent as consentTypes].every(this.metricsService.check_consent)
}
return this.metricsService.check_consent(consent)
}
/**
* Update consent.
*
* @param {string[]} consent
*/
async updateConsent (consent: string[]): Promise<void> {
const approvedConsent = new Set(consent)
await Promise.all(Object.keys(this.groupedFeatures).map(async (groupName): Promise<void> => {
if (approvedConsent.has(groupName)) {
await this.addConsent(groupName as consentTypes)
} else {
await this.removeConsent(groupName as consentTypes)
}
}))
}
/**
* Track a page view
*
* Leave arguments empty to have countly automatically track the events for you.
*
* @param page - The page name to track
* @param ignoreList - A list of urls to ignore
* @param viewSegments - A list of segments to add to the view event
*/
trackView (page?: string, ignoreList?: IgnoreList, viewSegments?: Segments): void {
this.metricsService.track_view(page, ignoreList, viewSegments)
}
/**
* Track a custom event
*
* @param event - The event to add to the queue
*/
trackEvent (event: CountlyEvent): void {
this.metricsService.add_event(event)
}
/**
* Track an Error
*
* @param error - The Error instance
* @param nonFatal - Whether the error is fatal or not
* @param segments - A list of segments to add to the error event
*/
trackError (error: Error, nonFatal = true, segments: Segments = {}): void {
this.metricsService.recordError(error, nonFatal, segments)
}
/**
*
* @param {boolean} noHeartBeat - By defaulting to false, we allow countly to calculate session lengths. Countly will send session_duration events every ~60 seconds.
* @param {boolean} force
*/
startSession (noHeartBeat = false, force = false): void {
/**
* Don't call start_session if there is already a session.
*/
if (!this.sessionStarted) {
this.sessionStarted = true
this.metricsService.begin_session(noHeartBeat, force)
}
}
endSession (force = false): void {
/**
* Don't call end_session if there is no session.
*/
if (this.sessionStarted) {
/**
* Don't pass seconds to Countly, it will calculate session duration for us.
* When ending a session, countly will set session_duration to the length of time between now and the last session_duration event.
*/
this.metricsService.end_session(undefined, force)
this.sessionStarted = false
}
}
}