@temps-sdk/analytics-core 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Analytics.d.ts +7 -0
- package/dist/Analytics.d.ts.map +1 -0
- package/dist/Analytics.js +218 -0
- package/dist/EngagementTracker.d.ts +56 -0
- package/dist/EngagementTracker.d.ts.map +1 -0
- package/dist/EngagementTracker.js +211 -0
- package/dist/SessionRecorder.d.ts +69 -0
- package/dist/SessionRecorder.d.ts.map +1 -0
- package/dist/SessionRecorder.js +407 -0
- package/dist/SpeedTracker.d.ts +18 -0
- package/dist/SpeedTracker.d.ts.map +1 -0
- package/dist/SpeedTracker.js +61 -0
- package/dist/constants.d.ts +13 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +30 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/types.d.ts +108 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/dist/utils.d.ts +7 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +96 -0
- package/package.json +44 -0
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
import { record } from "rrweb";
|
|
2
|
+
import { pack } from "@rrweb/packer";
|
|
3
|
+
import { SESSION_RECORDER_ENDPOINT, DEFAULT_BASE_PATH, DEFAULT_EXCLUDED_PATHS } from "./constants";
|
|
4
|
+
function generateSessionId() {
|
|
5
|
+
if (typeof crypto !== "undefined" && crypto.randomUUID) {
|
|
6
|
+
return crypto.randomUUID();
|
|
7
|
+
}
|
|
8
|
+
return `session_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
|
|
9
|
+
}
|
|
10
|
+
function generateVisitorId() {
|
|
11
|
+
if (typeof localStorage !== "undefined") {
|
|
12
|
+
let visitorId = localStorage.getItem("temps_visitor_id");
|
|
13
|
+
if (!visitorId) {
|
|
14
|
+
visitorId = `visitor_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
|
|
15
|
+
localStorage.setItem("temps_visitor_id", visitorId);
|
|
16
|
+
}
|
|
17
|
+
return visitorId;
|
|
18
|
+
}
|
|
19
|
+
return `visitor_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
|
|
20
|
+
}
|
|
21
|
+
function matchesAnyPath(currentPath, paths) {
|
|
22
|
+
return paths.some((path) => {
|
|
23
|
+
const regex = new RegExp(`^${path.replace(/\*/g, ".*")}$`);
|
|
24
|
+
return regex.test(currentPath);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
function getSessionMetadata() {
|
|
28
|
+
if (typeof window === "undefined")
|
|
29
|
+
return {};
|
|
30
|
+
const screen = window.screen || {};
|
|
31
|
+
const nav = window.navigator || {};
|
|
32
|
+
return {
|
|
33
|
+
visitorId: generateVisitorId(),
|
|
34
|
+
userAgent: nav.userAgent,
|
|
35
|
+
language: nav.language,
|
|
36
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
37
|
+
screenWidth: screen.width,
|
|
38
|
+
screenHeight: screen.height,
|
|
39
|
+
colorDepth: screen.colorDepth || 24,
|
|
40
|
+
viewportWidth: window.innerWidth,
|
|
41
|
+
viewportHeight: window.innerHeight,
|
|
42
|
+
url: window.location.href,
|
|
43
|
+
timestamp: new Date().toISOString(),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Framework-agnostic rrweb wrapper. Call `start()` to begin recording and
|
|
48
|
+
* `stop()` to end. `destroy()` removes all listeners and flushes pending events.
|
|
49
|
+
*/
|
|
50
|
+
export class SessionRecorder {
|
|
51
|
+
constructor(options = {}) {
|
|
52
|
+
this.stopFn = null;
|
|
53
|
+
this.takeSnapshot = null;
|
|
54
|
+
this.events = [];
|
|
55
|
+
this.sessionId = "";
|
|
56
|
+
this.sessionInitialized = false;
|
|
57
|
+
this.flushTimer = null;
|
|
58
|
+
this.initRetryCount = 0;
|
|
59
|
+
this.initFailed = false;
|
|
60
|
+
this.maxInitRetries = 3;
|
|
61
|
+
this.sendRetryCount = 0;
|
|
62
|
+
this.maxSendRetries = 5;
|
|
63
|
+
this.lastSendAttempt = 0;
|
|
64
|
+
this.isSending = false;
|
|
65
|
+
this.originalPushState = null;
|
|
66
|
+
this.originalReplaceState = null;
|
|
67
|
+
this.handleUnload = () => {
|
|
68
|
+
if (this.sessionInitialized && this.events.length > 0) {
|
|
69
|
+
void this.sendEvents(true);
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
this.handlePopState = () => {
|
|
73
|
+
if (this.stopFn && this.events.length > 0)
|
|
74
|
+
void this.sendEvents(false);
|
|
75
|
+
setTimeout(() => {
|
|
76
|
+
this.checkPath();
|
|
77
|
+
if (this.takeSnapshot)
|
|
78
|
+
this.takeSnapshot();
|
|
79
|
+
}, 100);
|
|
80
|
+
};
|
|
81
|
+
this.basePath = options.basePath || DEFAULT_BASE_PATH;
|
|
82
|
+
this.excludedPaths =
|
|
83
|
+
options.useDefaultExcludedPaths === false
|
|
84
|
+
? options.excludedPaths || []
|
|
85
|
+
: [...DEFAULT_EXCLUDED_PATHS, ...(options.excludedPaths || [])];
|
|
86
|
+
this.sessionSampleRate = options.sessionSampleRate ?? 1.0;
|
|
87
|
+
this.maskAllInputs = options.maskAllInputs ?? true;
|
|
88
|
+
this.maskTextSelector = options.maskTextSelector || "[data-mask]";
|
|
89
|
+
this.blockClass = options.blockClass || "rr-block";
|
|
90
|
+
this.ignoreClass = options.ignoreClass || "rr-ignore";
|
|
91
|
+
this.maskTextClass = options.maskTextClass || "rr-mask";
|
|
92
|
+
this.ignoreSelector = options.ignoreSelector || "[data-ignore]";
|
|
93
|
+
this.blockSelector = options.blockSelector || "[data-private]";
|
|
94
|
+
this.recordCanvas = options.recordCanvas ?? false;
|
|
95
|
+
this.collectFonts = options.collectFonts ?? true;
|
|
96
|
+
this.batchSize = options.batchSize ?? 100;
|
|
97
|
+
this.flushInterval = options.flushInterval ?? 10000;
|
|
98
|
+
this.slimDOMOptions = options.slimDOMOptions || {
|
|
99
|
+
script: false,
|
|
100
|
+
comment: true,
|
|
101
|
+
headFavicon: true,
|
|
102
|
+
headWhitespace: true,
|
|
103
|
+
headMetaDescKeywords: true,
|
|
104
|
+
headMetaSocial: true,
|
|
105
|
+
headMetaRobots: true,
|
|
106
|
+
headMetaHttpEquiv: true,
|
|
107
|
+
headMetaAuthorship: true,
|
|
108
|
+
headMetaVerification: true,
|
|
109
|
+
};
|
|
110
|
+
this.maskInputOptions = options.maskInputOptions || { password: true, email: true };
|
|
111
|
+
this.samplingConfig = {
|
|
112
|
+
scroll: 500,
|
|
113
|
+
media: 800,
|
|
114
|
+
mouseInteraction: {
|
|
115
|
+
MouseUp: false,
|
|
116
|
+
MouseDown: false,
|
|
117
|
+
Click: true,
|
|
118
|
+
ContextMenu: false,
|
|
119
|
+
DblClick: true,
|
|
120
|
+
Focus: true,
|
|
121
|
+
Blur: true,
|
|
122
|
+
TouchStart: false,
|
|
123
|
+
TouchEnd: false,
|
|
124
|
+
},
|
|
125
|
+
mousemove: false,
|
|
126
|
+
input: "last",
|
|
127
|
+
...(options.sampling || {}),
|
|
128
|
+
};
|
|
129
|
+
this.enabled = options.enabled ?? false;
|
|
130
|
+
if (this.enabled && typeof window !== "undefined") {
|
|
131
|
+
this.start();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
shouldRecord() {
|
|
135
|
+
if (!this.enabled || typeof window === "undefined")
|
|
136
|
+
return false;
|
|
137
|
+
const currentPath = window.location.pathname;
|
|
138
|
+
const isExcluded = matchesAnyPath(currentPath, this.excludedPaths);
|
|
139
|
+
if (isExcluded)
|
|
140
|
+
return false;
|
|
141
|
+
if (this.sessionSampleRate < 1.0 && Math.random() > this.sessionSampleRate)
|
|
142
|
+
return false;
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
async initializeSession() {
|
|
146
|
+
if (this.sessionInitialized)
|
|
147
|
+
return true;
|
|
148
|
+
if (this.initFailed)
|
|
149
|
+
return false;
|
|
150
|
+
if (this.initRetryCount >= this.maxInitRetries) {
|
|
151
|
+
this.initFailed = true;
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
this.initRetryCount++;
|
|
155
|
+
const sessionId = generateSessionId();
|
|
156
|
+
this.sessionId = sessionId;
|
|
157
|
+
try {
|
|
158
|
+
const metadata = { sessionId, ...getSessionMetadata() };
|
|
159
|
+
const response = await fetch(`${this.basePath}/${SESSION_RECORDER_ENDPOINT}/init`, {
|
|
160
|
+
method: "POST",
|
|
161
|
+
headers: { "Content-Type": "application/json" },
|
|
162
|
+
body: JSON.stringify(metadata),
|
|
163
|
+
});
|
|
164
|
+
if (response.status === 201) {
|
|
165
|
+
this.sessionInitialized = true;
|
|
166
|
+
this.initRetryCount = 0;
|
|
167
|
+
this.initFailed = false;
|
|
168
|
+
if (typeof localStorage !== "undefined") {
|
|
169
|
+
localStorage.setItem("currentRecordingSessionId", sessionId);
|
|
170
|
+
}
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
this.sessionId = "";
|
|
174
|
+
if (this.initRetryCount >= this.maxInitRetries)
|
|
175
|
+
this.initFailed = true;
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
// eslint-disable-next-line no-console
|
|
180
|
+
console.error("[SessionRecorder] init failed:", error);
|
|
181
|
+
this.sessionId = "";
|
|
182
|
+
if (this.initRetryCount >= this.maxInitRetries)
|
|
183
|
+
this.initFailed = true;
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
async sendEvents(isReliable = false) {
|
|
188
|
+
if (!this.sessionInitialized || this.events.length === 0)
|
|
189
|
+
return;
|
|
190
|
+
if (this.isSending && !isReliable)
|
|
191
|
+
return;
|
|
192
|
+
const now = Date.now();
|
|
193
|
+
if (this.sendRetryCount > 0 && !isReliable) {
|
|
194
|
+
const backoff = Math.min(1000 * Math.pow(2, this.sendRetryCount), 30000);
|
|
195
|
+
if (now - this.lastSendAttempt < backoff)
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
this.isSending = true;
|
|
199
|
+
this.lastSendAttempt = now;
|
|
200
|
+
const eventsToSend = [...this.events];
|
|
201
|
+
try {
|
|
202
|
+
const packed = pack(eventsToSend);
|
|
203
|
+
const encodedEvents = btoa(packed);
|
|
204
|
+
const payload = { sessionId: this.sessionId, events: encodedEvents };
|
|
205
|
+
const url = `${this.basePath}/${SESSION_RECORDER_ENDPOINT}/events`;
|
|
206
|
+
if (isReliable) {
|
|
207
|
+
if (navigator.sendBeacon) {
|
|
208
|
+
const blob = new Blob([JSON.stringify(payload)], { type: "application/json" });
|
|
209
|
+
if (!navigator.sendBeacon(url, blob)) {
|
|
210
|
+
await fetch(url, {
|
|
211
|
+
method: "POST",
|
|
212
|
+
headers: { "Content-Type": "application/json" },
|
|
213
|
+
body: JSON.stringify(payload),
|
|
214
|
+
keepalive: true,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
await fetch(url, {
|
|
220
|
+
method: "POST",
|
|
221
|
+
headers: { "Content-Type": "application/json" },
|
|
222
|
+
body: JSON.stringify(payload),
|
|
223
|
+
keepalive: true,
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
this.events = [];
|
|
227
|
+
this.sendRetryCount = 0;
|
|
228
|
+
}
|
|
229
|
+
else {
|
|
230
|
+
const response = await fetch(url, {
|
|
231
|
+
method: "POST",
|
|
232
|
+
headers: { "Content-Type": "application/json" },
|
|
233
|
+
body: JSON.stringify(payload),
|
|
234
|
+
});
|
|
235
|
+
if (response.status === 404) {
|
|
236
|
+
this.sessionInitialized = false;
|
|
237
|
+
this.sessionId = "";
|
|
238
|
+
if (typeof localStorage !== "undefined") {
|
|
239
|
+
localStorage.removeItem("currentRecordingSessionId");
|
|
240
|
+
}
|
|
241
|
+
this.stopRecording();
|
|
242
|
+
this.events = [];
|
|
243
|
+
this.sendRetryCount = 0;
|
|
244
|
+
}
|
|
245
|
+
else if (!response.ok) {
|
|
246
|
+
this.sendRetryCount++;
|
|
247
|
+
if (this.sendRetryCount >= this.maxSendRetries) {
|
|
248
|
+
this.events = [];
|
|
249
|
+
this.sendRetryCount = 0;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
else {
|
|
253
|
+
this.events = [];
|
|
254
|
+
this.sendRetryCount = 0;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
// eslint-disable-next-line no-console
|
|
260
|
+
console.error("[SessionRecorder] send failed:", error);
|
|
261
|
+
this.sendRetryCount++;
|
|
262
|
+
if (this.sendRetryCount >= this.maxSendRetries) {
|
|
263
|
+
this.events = [];
|
|
264
|
+
this.sendRetryCount = 0;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
finally {
|
|
268
|
+
this.isSending = false;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
scheduleFlush() {
|
|
272
|
+
if (this.flushTimer)
|
|
273
|
+
clearTimeout(this.flushTimer);
|
|
274
|
+
this.flushTimer = setTimeout(() => {
|
|
275
|
+
if (this.events.length > 0)
|
|
276
|
+
void this.sendEvents(false);
|
|
277
|
+
this.scheduleFlush();
|
|
278
|
+
}, this.flushInterval);
|
|
279
|
+
}
|
|
280
|
+
async startRecording() {
|
|
281
|
+
if (this.stopFn || this.initFailed)
|
|
282
|
+
return;
|
|
283
|
+
if (!this.shouldRecord())
|
|
284
|
+
return;
|
|
285
|
+
const ok = await this.initializeSession();
|
|
286
|
+
if (!ok)
|
|
287
|
+
return;
|
|
288
|
+
const stopFn = record({
|
|
289
|
+
emit: (event) => {
|
|
290
|
+
this.events.push(event);
|
|
291
|
+
if (this.events.length >= this.batchSize) {
|
|
292
|
+
void this.sendEvents(false);
|
|
293
|
+
this.scheduleFlush();
|
|
294
|
+
}
|
|
295
|
+
},
|
|
296
|
+
sampling: this.samplingConfig,
|
|
297
|
+
blockSelector: this.blockSelector,
|
|
298
|
+
ignoreSelector: this.ignoreSelector,
|
|
299
|
+
recordCanvas: this.recordCanvas,
|
|
300
|
+
collectFonts: this.collectFonts,
|
|
301
|
+
maskAllInputs: this.maskAllInputs,
|
|
302
|
+
maskInputOptions: this.maskInputOptions,
|
|
303
|
+
maskTextSelector: this.maskTextSelector,
|
|
304
|
+
blockClass: this.blockClass,
|
|
305
|
+
ignoreClass: this.ignoreClass,
|
|
306
|
+
maskTextClass: this.maskTextClass,
|
|
307
|
+
slimDOMOptions: this.slimDOMOptions,
|
|
308
|
+
checkoutEveryNms: 30000,
|
|
309
|
+
checkoutEveryNth: 200,
|
|
310
|
+
});
|
|
311
|
+
if (stopFn) {
|
|
312
|
+
this.stopFn = stopFn;
|
|
313
|
+
const exposed = stopFn;
|
|
314
|
+
this.takeSnapshot = exposed.takeFullSnapshot || null;
|
|
315
|
+
}
|
|
316
|
+
this.scheduleFlush();
|
|
317
|
+
}
|
|
318
|
+
stopRecording() {
|
|
319
|
+
if (!this.stopFn)
|
|
320
|
+
return;
|
|
321
|
+
this.stopFn();
|
|
322
|
+
this.stopFn = null;
|
|
323
|
+
if (this.flushTimer) {
|
|
324
|
+
clearTimeout(this.flushTimer);
|
|
325
|
+
this.flushTimer = null;
|
|
326
|
+
}
|
|
327
|
+
void this.sendEvents(true);
|
|
328
|
+
this.sessionInitialized = false;
|
|
329
|
+
this.sessionId = "";
|
|
330
|
+
if (typeof localStorage !== "undefined") {
|
|
331
|
+
localStorage.removeItem("currentRecordingSessionId");
|
|
332
|
+
}
|
|
333
|
+
this.initRetryCount = 0;
|
|
334
|
+
this.initFailed = false;
|
|
335
|
+
}
|
|
336
|
+
wrapHistory() {
|
|
337
|
+
this.originalPushState = window.history.pushState;
|
|
338
|
+
this.originalReplaceState = window.history.replaceState;
|
|
339
|
+
const flushAndCheck = () => {
|
|
340
|
+
if (this.stopFn && this.events.length > 0)
|
|
341
|
+
void this.sendEvents(false);
|
|
342
|
+
setTimeout(() => {
|
|
343
|
+
this.checkPath();
|
|
344
|
+
if (this.takeSnapshot)
|
|
345
|
+
this.takeSnapshot();
|
|
346
|
+
}, 100);
|
|
347
|
+
};
|
|
348
|
+
window.history.pushState = ((...args) => {
|
|
349
|
+
this.originalPushState?.apply(window.history, args);
|
|
350
|
+
flushAndCheck();
|
|
351
|
+
});
|
|
352
|
+
window.history.replaceState = ((...args) => {
|
|
353
|
+
this.originalReplaceState?.apply(window.history, args);
|
|
354
|
+
flushAndCheck();
|
|
355
|
+
});
|
|
356
|
+
window.addEventListener("popstate", this.handlePopState);
|
|
357
|
+
window.addEventListener("beforeunload", this.handleUnload);
|
|
358
|
+
window.addEventListener("pagehide", this.handleUnload);
|
|
359
|
+
}
|
|
360
|
+
checkPath() {
|
|
361
|
+
if (!this.enabled || this.initFailed) {
|
|
362
|
+
if (!this.enabled)
|
|
363
|
+
this.stopRecording();
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
const currentPath = window.location.pathname;
|
|
367
|
+
const isExcluded = matchesAnyPath(currentPath, this.excludedPaths);
|
|
368
|
+
const isRecording = this.stopFn !== null;
|
|
369
|
+
if (isExcluded && isRecording) {
|
|
370
|
+
this.stopRecording();
|
|
371
|
+
}
|
|
372
|
+
else if (!isExcluded && !isRecording && !this.initFailed) {
|
|
373
|
+
void this.startRecording();
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
start() {
|
|
377
|
+
if (this.enabled && this.stopFn)
|
|
378
|
+
return;
|
|
379
|
+
this.enabled = true;
|
|
380
|
+
if (typeof window === "undefined")
|
|
381
|
+
return;
|
|
382
|
+
if (!this.originalPushState)
|
|
383
|
+
this.wrapHistory();
|
|
384
|
+
void this.startRecording();
|
|
385
|
+
}
|
|
386
|
+
stop() {
|
|
387
|
+
this.enabled = false;
|
|
388
|
+
this.stopRecording();
|
|
389
|
+
}
|
|
390
|
+
destroy() {
|
|
391
|
+
this.stop();
|
|
392
|
+
if (this.originalPushState) {
|
|
393
|
+
window.history.pushState = this.originalPushState;
|
|
394
|
+
this.originalPushState = null;
|
|
395
|
+
}
|
|
396
|
+
if (this.originalReplaceState) {
|
|
397
|
+
window.history.replaceState = this.originalReplaceState;
|
|
398
|
+
this.originalReplaceState = null;
|
|
399
|
+
}
|
|
400
|
+
window.removeEventListener("popstate", this.handlePopState);
|
|
401
|
+
window.removeEventListener("beforeunload", this.handleUnload);
|
|
402
|
+
window.removeEventListener("pagehide", this.handleUnload);
|
|
403
|
+
}
|
|
404
|
+
getSessionId() {
|
|
405
|
+
return this.sessionId || null;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface SpeedTrackerOptions {
|
|
2
|
+
basePath: string;
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* Subscribes to Web Vitals and forwards metrics to the Temps analytics endpoint.
|
|
6
|
+
* Initial metrics (TTFB, FCP, LCP, FID) are batched into a single "speed" request.
|
|
7
|
+
* Late metrics (CLS, INP) are sent individually as they stabilize.
|
|
8
|
+
*/
|
|
9
|
+
export declare class SpeedTracker {
|
|
10
|
+
private readonly basePath;
|
|
11
|
+
private initialMetrics;
|
|
12
|
+
constructor(options: SpeedTrackerOptions);
|
|
13
|
+
private start;
|
|
14
|
+
private sendInitial;
|
|
15
|
+
private sendLate;
|
|
16
|
+
destroy(): void;
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=SpeedTracker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SpeedTracker.d.ts","sourceRoot":"","sources":["../src/SpeedTracker.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,mBAAmB;IAClC,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;;GAIG;AACH,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,cAAc,CAAsC;gBAEhD,OAAO,EAAE,mBAAmB;IAMxC,OAAO,CAAC,KAAK;IAsBb,OAAO,CAAC,WAAW;IAanB,OAAO,CAAC,QAAQ;IAUT,OAAO,IAAI,IAAI;CAGvB"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { onCLS, onFID, onLCP, onTTFB, onFCP, onINP } from "web-vitals";
|
|
2
|
+
import { sendAnalytics } from "./utils";
|
|
3
|
+
/**
|
|
4
|
+
* Subscribes to Web Vitals and forwards metrics to the Temps analytics endpoint.
|
|
5
|
+
* Initial metrics (TTFB, FCP, LCP, FID) are batched into a single "speed" request.
|
|
6
|
+
* Late metrics (CLS, INP) are sent individually as they stabilize.
|
|
7
|
+
*/
|
|
8
|
+
export class SpeedTracker {
|
|
9
|
+
constructor(options) {
|
|
10
|
+
this.initialMetrics = {};
|
|
11
|
+
this.basePath = options.basePath;
|
|
12
|
+
if (typeof window === "undefined")
|
|
13
|
+
return;
|
|
14
|
+
this.start();
|
|
15
|
+
}
|
|
16
|
+
start() {
|
|
17
|
+
onTTFB((m) => {
|
|
18
|
+
this.initialMetrics.TTFB = { value: m.value, rating: m.rating };
|
|
19
|
+
this.sendInitial();
|
|
20
|
+
});
|
|
21
|
+
onLCP((m) => {
|
|
22
|
+
this.initialMetrics.LCP = { value: m.value, rating: m.rating };
|
|
23
|
+
this.sendInitial();
|
|
24
|
+
});
|
|
25
|
+
onFID((m) => {
|
|
26
|
+
this.initialMetrics.FID = { value: m.value, rating: m.rating };
|
|
27
|
+
this.sendInitial();
|
|
28
|
+
});
|
|
29
|
+
onFCP((m) => {
|
|
30
|
+
this.initialMetrics.FCP = { value: m.value, rating: m.rating };
|
|
31
|
+
this.sendInitial();
|
|
32
|
+
});
|
|
33
|
+
onCLS((m) => this.sendLate("cls", m.value));
|
|
34
|
+
onINP((m) => this.sendLate("inp", m.value));
|
|
35
|
+
}
|
|
36
|
+
sendInitial() {
|
|
37
|
+
if (Object.keys(this.initialMetrics).length !== 4)
|
|
38
|
+
return;
|
|
39
|
+
const payload = {
|
|
40
|
+
ttfb: this.initialMetrics.TTFB?.value ?? null,
|
|
41
|
+
lcp: this.initialMetrics.LCP?.value ?? null,
|
|
42
|
+
fid: this.initialMetrics.FID?.value ?? null,
|
|
43
|
+
fcp: this.initialMetrics.FCP?.value ?? null,
|
|
44
|
+
path: window.location.pathname,
|
|
45
|
+
query: window.location.search,
|
|
46
|
+
};
|
|
47
|
+
void sendAnalytics("speed", payload, "POST", this.basePath);
|
|
48
|
+
}
|
|
49
|
+
sendLate(name, value) {
|
|
50
|
+
const payload = {
|
|
51
|
+
[name]: value,
|
|
52
|
+
path: window.location.pathname,
|
|
53
|
+
query: window.location.search,
|
|
54
|
+
};
|
|
55
|
+
void sendAnalytics("speed", payload, "POST", this.basePath);
|
|
56
|
+
}
|
|
57
|
+
// Web-vitals subscriptions are fire-and-forget; there's nothing to tear down.
|
|
58
|
+
destroy() {
|
|
59
|
+
this.initialMetrics = {};
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare const DEFAULT_BASE_PATH = "/api/_temps";
|
|
2
|
+
export declare const SESSION_RECORDER_ENDPOINT = "session-replay";
|
|
3
|
+
/**
|
|
4
|
+
* Built-in paths excluded from session replay by default, covering common
|
|
5
|
+
* authentication and payment flows so integrators don't accidentally record
|
|
6
|
+
* sensitive pages. Supports `*` wildcards, matched against
|
|
7
|
+
* `window.location.pathname` only (case-sensitive, anchored at both ends).
|
|
8
|
+
*
|
|
9
|
+
* Merged with any user-supplied `excludedPaths` unless
|
|
10
|
+
* `useDefaultExcludedPaths: false` is passed to `SessionRecorder`.
|
|
11
|
+
*/
|
|
12
|
+
export declare const DEFAULT_EXCLUDED_PATHS: string[];
|
|
13
|
+
//# sourceMappingURL=constants.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAC/C,eAAO,MAAM,yBAAyB,mBAAmB,CAAC;AAE1D;;;;;;;;GAQG;AACH,eAAO,MAAM,sBAAsB,EAAE,MAAM,EAkB1C,CAAC"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export const DEFAULT_BASE_PATH = "/api/_temps";
|
|
2
|
+
export const SESSION_RECORDER_ENDPOINT = "session-replay";
|
|
3
|
+
/**
|
|
4
|
+
* Built-in paths excluded from session replay by default, covering common
|
|
5
|
+
* authentication and payment flows so integrators don't accidentally record
|
|
6
|
+
* sensitive pages. Supports `*` wildcards, matched against
|
|
7
|
+
* `window.location.pathname` only (case-sensitive, anchored at both ends).
|
|
8
|
+
*
|
|
9
|
+
* Merged with any user-supplied `excludedPaths` unless
|
|
10
|
+
* `useDefaultExcludedPaths: false` is passed to `SessionRecorder`.
|
|
11
|
+
*/
|
|
12
|
+
export const DEFAULT_EXCLUDED_PATHS = [
|
|
13
|
+
"/login",
|
|
14
|
+
"/log-in",
|
|
15
|
+
"/signin",
|
|
16
|
+
"/sign-in",
|
|
17
|
+
"/logout",
|
|
18
|
+
"/log-out",
|
|
19
|
+
"/signup",
|
|
20
|
+
"/sign-up",
|
|
21
|
+
"/register",
|
|
22
|
+
"/checkout*",
|
|
23
|
+
"/payment*",
|
|
24
|
+
"/billing*",
|
|
25
|
+
"/reset-password*",
|
|
26
|
+
"/forgot-password*",
|
|
27
|
+
"/mfa*",
|
|
28
|
+
"/2fa*",
|
|
29
|
+
"/verify*",
|
|
30
|
+
];
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from "./types";
|
|
2
|
+
export * from "./constants";
|
|
3
|
+
export * from "./utils";
|
|
4
|
+
export { EngagementTracker, type EngagementTrackerOptions, type EngagementData } from "./EngagementTracker";
|
|
5
|
+
export { SpeedTracker, type SpeedTrackerOptions } from "./SpeedTracker";
|
|
6
|
+
export { SessionRecorder, type SessionRecorderOptions } from "./SessionRecorder";
|
|
7
|
+
export { createAnalytics } from "./Analytics";
|
|
8
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC;AAC5B,cAAc,SAAS,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,KAAK,wBAAwB,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC5G,OAAO,EAAE,YAAY,EAAE,KAAK,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,KAAK,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AACjF,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export * from "./types";
|
|
2
|
+
export * from "./constants";
|
|
3
|
+
export * from "./utils";
|
|
4
|
+
export { EngagementTracker } from "./EngagementTracker";
|
|
5
|
+
export { SpeedTracker } from "./SpeedTracker";
|
|
6
|
+
export { SessionRecorder } from "./SessionRecorder";
|
|
7
|
+
export { createAnalytics } from "./Analytics";
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
export type JsonPrimitive = string | number | boolean | null;
|
|
2
|
+
export type JsonValue = JsonPrimitive | JsonValue[] | {
|
|
3
|
+
[key: string]: JsonValue;
|
|
4
|
+
};
|
|
5
|
+
export interface AnalyticsEventBase {
|
|
6
|
+
event_name: string;
|
|
7
|
+
request_query?: string;
|
|
8
|
+
request_path?: string;
|
|
9
|
+
event_data?: Record<string, JsonValue>;
|
|
10
|
+
}
|
|
11
|
+
export interface SessionRecordingConfig {
|
|
12
|
+
/**
|
|
13
|
+
* Paths to exclude from recording. Supports `*` wildcards. Merged with the
|
|
14
|
+
* built-in `DEFAULT_EXCLUDED_PATHS` (login, checkout, payment, etc.) unless
|
|
15
|
+
* `useDefaultExcludedPaths` is set to `false`.
|
|
16
|
+
*/
|
|
17
|
+
excludedPaths?: string[];
|
|
18
|
+
/**
|
|
19
|
+
* Whether to merge the built-in default excluded paths (see
|
|
20
|
+
* `DEFAULT_EXCLUDED_PATHS`) with `excludedPaths`. Defaults to `true`. Set to
|
|
21
|
+
* `false` to record every path except the ones you explicitly list in
|
|
22
|
+
* `excludedPaths`.
|
|
23
|
+
*/
|
|
24
|
+
useDefaultExcludedPaths?: boolean;
|
|
25
|
+
/** Sample rate for recording sessions (0.0 to 1.0). Defaults to 1.0. */
|
|
26
|
+
sessionSampleRate?: number;
|
|
27
|
+
/** Mask all inputs. Defaults to true. */
|
|
28
|
+
maskAllInputs?: boolean;
|
|
29
|
+
/** CSS selector for masking text. Defaults to "[data-mask]". */
|
|
30
|
+
maskTextSelector?: string;
|
|
31
|
+
/** CSS class to block from recording. Defaults to "rr-block". */
|
|
32
|
+
blockClass?: string;
|
|
33
|
+
/** CSS class to ignore from recording. Defaults to "rr-ignore". */
|
|
34
|
+
ignoreClass?: string;
|
|
35
|
+
/** CSS class to mask text. Defaults to "rr-mask". */
|
|
36
|
+
maskTextClass?: string;
|
|
37
|
+
/** Record canvas elements. Defaults to false. */
|
|
38
|
+
recordCanvas?: boolean;
|
|
39
|
+
/** Collect fonts. Defaults to false. */
|
|
40
|
+
collectFonts?: boolean;
|
|
41
|
+
/** Number of events to batch before sending. Defaults to 100. */
|
|
42
|
+
batchSize?: number;
|
|
43
|
+
/** Interval in ms to flush events. Defaults to 5000. */
|
|
44
|
+
flushInterval?: number;
|
|
45
|
+
}
|
|
46
|
+
export interface AnalyticsClientOptions {
|
|
47
|
+
/** Base endpoint path. Defaults to `/api/_temps`. */
|
|
48
|
+
basePath?: string;
|
|
49
|
+
/** Set to true to disable analytics (e.g., for tests). */
|
|
50
|
+
disabled?: boolean;
|
|
51
|
+
/** Ignore localhost/test env automatically. Defaults to true. */
|
|
52
|
+
ignoreLocalhost?: boolean;
|
|
53
|
+
/** Custom domain to use for analytics. Defaults to window.location.hostname. */
|
|
54
|
+
domain?: string;
|
|
55
|
+
}
|
|
56
|
+
export interface AnalyticsOptions extends AnalyticsClientOptions {
|
|
57
|
+
/** Auto track pageviews on route changes. Defaults to true. */
|
|
58
|
+
autoTrackPageviews?: boolean;
|
|
59
|
+
/** Auto track page leave events. Defaults to true. */
|
|
60
|
+
autoTrackPageLeave?: boolean;
|
|
61
|
+
/** Custom event name for page leave events. Defaults to "page_leave". */
|
|
62
|
+
pageLeaveEventName?: string;
|
|
63
|
+
/** Auto track speed analytics (Web Vitals). Defaults to true. */
|
|
64
|
+
autoTrackSpeedAnalytics?: boolean;
|
|
65
|
+
/** Auto track engagement with heartbeats. Defaults to true. */
|
|
66
|
+
autoTrackEngagement?: boolean;
|
|
67
|
+
/** Heartbeat interval in milliseconds. Defaults to 30000 (30 seconds). */
|
|
68
|
+
heartbeatInterval?: number;
|
|
69
|
+
/** Inactivity timeout in milliseconds. Defaults to 30000 (30 seconds). */
|
|
70
|
+
inactivityTimeout?: number;
|
|
71
|
+
/** Engagement threshold in milliseconds to consider session engaged. Defaults to 10000 (10 seconds). */
|
|
72
|
+
engagementThreshold?: number;
|
|
73
|
+
/** Enable session recording. Defaults to false. */
|
|
74
|
+
enableSessionRecording?: boolean;
|
|
75
|
+
/** Session recording configuration. */
|
|
76
|
+
sessionRecordingConfig?: SessionRecordingConfig;
|
|
77
|
+
}
|
|
78
|
+
export interface AnalyticsApi {
|
|
79
|
+
/** Whether analytics are currently enabled. */
|
|
80
|
+
readonly enabled: boolean;
|
|
81
|
+
/** Send a custom event. */
|
|
82
|
+
trackEvent(eventName: string, data?: Record<string, JsonValue>): Promise<void>;
|
|
83
|
+
/** Manually trigger a pageview. */
|
|
84
|
+
trackPageview(): void;
|
|
85
|
+
/** Identify a user. No-op placeholder for now. */
|
|
86
|
+
identify(userId: string, traits?: Record<string, JsonValue>): Promise<void> | void;
|
|
87
|
+
/** Enable session recording at runtime. */
|
|
88
|
+
enableSessionRecording(): void;
|
|
89
|
+
/** Disable session recording at runtime. */
|
|
90
|
+
disableSessionRecording(): void;
|
|
91
|
+
/** Tear down all listeners, timers, and recorders. */
|
|
92
|
+
destroy(): void;
|
|
93
|
+
}
|
|
94
|
+
export interface WebVitalMetric {
|
|
95
|
+
value: number;
|
|
96
|
+
rating: "good" | "needs-improvement" | "poor";
|
|
97
|
+
}
|
|
98
|
+
export interface SpeedMetric {
|
|
99
|
+
ttfb?: number | null;
|
|
100
|
+
lcp?: number | null;
|
|
101
|
+
fid?: number | null;
|
|
102
|
+
fcp?: number | null;
|
|
103
|
+
cls?: number | null;
|
|
104
|
+
inp?: number | null;
|
|
105
|
+
path?: string | null;
|
|
106
|
+
query?: string | null;
|
|
107
|
+
}
|
|
108
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC;AAC7D,MAAM,MAAM,SAAS,GAAG,aAAa,GAAG,SAAS,EAAE,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AAEnF,MAAM,WAAW,kBAAkB;IACjC,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;CACxC;AAED,MAAM,WAAW,sBAAsB;IACrC;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB;;;;;OAKG;IACH,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,wEAAwE;IACxE,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3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