Repository navigation
Expand file tree
/
Copy pathtelemetrydeck.js
More file actions
234 lines (195 loc) · 6.59 KB
/
Copy pathtelemetrydeck.js
File metadata and controls
234 lines (195 loc) · 6.59 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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import { randomString } from './utils/random-string.js';
import { sha256 } from './utils/sha256.js';
import { Store } from './utils/store.js';
import { version } from './utils/version.js';
const HEARTBEAT_INTERVALS = new Map([
['minute', 60_000],
['hour', 3_600_000],
['day', 86_400_000],
]);
/**
* @typedef {Object} TelemetryDeckOptions
*
* @property {string} appID the app ID to send telemetry data to
* @property {string} namespace the namespace of your organization, shown in the TelemetryDeck Dashboard
* @property {string} clientUser the clientUser ID to send telemetry data to
* @property {string} [target] the base URL to send telemetry data to. The namespace is appended to it.
* @property {string} [sessionID] An optional session ID to include in each event
* @property {string} [salt] A salt to use when hashing the clientUser ID
* @property {boolean} [testMode] If "true", events will be marked as test events and only show up in Test Mode in the Dashbaord
* @property {Store} [store] A store to use for queueing events
* @property {Function} [subtleCrypto] Used for providing an alternative implementation of SubtleCrypto where no browser is available. Expects a class providing a `.digest(method, value)` method.
*/
/**
* @typedef {Object.<string, any>} TelemetryDeckPayload
*/
export default class TelemetryDeck {
appID = '';
namespace = '';
clientUser = '';
salt = '';
target = 'https://nom.telemetrydeck.com/v3/';
testMode = false;
/**
*
* @param {TelemetryDeckOptions} options
*/
constructor(options = {}) {
const { target, appID, namespace, clientUser, sessionID, salt, testMode, store, subtleCrypto } =
options;
if (!appID) {
throw new Error('appID is required');
}
if (!namespace) {
throw new Error('namespace is required');
}
this.store = store ?? new Store();
this.target = target ?? this.target;
this.appID = appID;
this.namespace = namespace;
this.clientUser = clientUser;
this.sessionID = sessionID ?? randomString();
this.salt = salt ?? this.salt;
this.testMode = testMode ?? this.testMode;
this.subtleCrypto = subtleCrypto;
}
/**
* Send a TelemetryDeck event
*
* @param {string} type the type of telemetry data to send
* @param {TelemetryDeckPayload} [payload] custom payload to be stored with each event
* @param {TelemetryDeckOptions} [options]
* @returns <Promise<Response>> a promise with the response from the server. The body is the number of accepted events.
*/
async event(type, payload, options) {
const body = await this._build(type, payload, options);
return this._post([body]);
}
/**
* Enqueue an event to be sent to TelemetryDeck later.
*
* Use flush() to send all queued events.
*
* @param {string} type
* @param {TelemetryDeckPayload} [payload]
* @param {TelemetryDeckOptions} [options]
* @returns <Promise>
*/
async queue(type, payload, options) {
const bodyPromise = this._build(type, payload, options);
return this.store.push(bodyPromise);
}
/**
* Send all queued events to TelemetryDeck.
*
* Enqueue events with queue().
*
* @returns <Promise<Response>> a promise with the response from the server. The body is the number of accepted events.
*/
async flush() {
const flushPromise = this._post(this.store.values());
this.store.clear();
return flushPromise;
}
_heartbeats = new Map();
/**
* Start sending a heartbeat event now and then once per frequency.
*
* @param {'minute'|'hour'|'day'} frequency
* @param {string} [name]
*/
startHeartbeat(frequency, name = 'heartbeat') {
const interval = HEARTBEAT_INTERVALS.get(frequency);
if (!interval) {
throw new Error('TelemetryDeck: "frequency" must be "minute", "hour" or "day"');
}
this.stopHeartbeat(name);
const send = () =>
this.event('TelemetryDeck.Session.heartbeat', {
'TelemetryDeck.Session.Heartbeat.name': name,
'TelemetryDeck.Session.Heartbeat.frequency': frequency,
}).catch(() => {});
send();
this._heartbeats.set(name, setInterval(send, interval));
}
/**
* Stop sending the heartbeat with this name.
*
* @param {string} [name]
*/
stopHeartbeat(name = 'heartbeat') {
clearInterval(this._heartbeats.get(name));
this._heartbeats.delete(name);
}
_clientUserAndSalt = '';
_clientUserHashed = '';
async _hashedClientUser(clientUser, salt) {
if (clientUser + salt !== this._clientUserAndSalt) {
this._clientUserHashed = await sha256([clientUser, salt].join(''), this.subtleCrypto);
this._clientUserAndSalt = clientUser + salt;
}
return this._clientUserHashed;
}
async _build(type, payload, options) {
const receivedAt = new Date().toISOString();
const { appID, testMode } = this;
let { clientUser, salt, sessionID } = this;
options = options ?? {};
clientUser = options.clientUser ?? clientUser;
salt = options.salt ?? salt;
sessionID = options.sessionID ?? sessionID;
if (!type) {
throw new Error(`TelemetryDeck: "type" is not set`);
}
if (!appID) {
throw new Error(`TelemetryDeck: "appID" is not set`);
}
if (!clientUser) {
throw new Error(`TelemetryDeck: "clientUser" is not set`);
}
clientUser = await this._hashedClientUser(clientUser, salt);
return {
...this._flatPayload(payload),
clientUser,
sessionID,
appID,
type,
receivedAt,
isTestMode: testMode ? 'true' : 'false',
'TelemetryDeck.SDK.name': 'JavaScriptSDK',
'TelemetryDeck.SDK.version': version,
'TelemetryDeck.SDK.nameAndVersion': `JavaScriptSDK ${version}`,
};
}
_flatPayload(payload) {
const result = {};
if (!payload || typeof payload !== 'object') {
return result;
}
for (const [name, value] of Object.entries(payload)) {
// The server rejects the full batch if a key has other characters
const key = name.replaceAll(/[^\w.-]/g, '_');
if (key === 'floatValue') {
result[key] = Number.parseFloat(value);
} else if (value instanceof Date) {
result[key] = value.toISOString();
} else if (value !== null && typeof value === 'object') {
result[key] = JSON.stringify(value);
} else {
result[key] = value;
}
}
return result;
}
_post(body) {
const { target, namespace } = this;
return fetch(`${target.replace(/\/+$/, '')}/${namespace}/`, {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: JSON.stringify(body),
});
}
}