@grafana/faro-web-sdk
Version:
Faro instrumentations, metas, transports for web.
57 lines • 2.52 kB
JavaScript
import { faro, stringifyExternalJson } from '@grafana/faro-core';
import { throttle } from '../../../utils';
import { getItem, removeItem, setItem, webStorageType } from '../../../utils/webStorage';
import { STORAGE_KEY, STORAGE_UPDATE_DELAY } from './sessionConstants';
import { getSessionMetaUpdateHandler, getUserSessionUpdater } from './sessionManagerUtils';
export class PersistentSessionsManager {
constructor() {
// Set only for the synchronous span of an adopting setSession(); the session
// instrumentation reads isAdopting() to suppress its lifecycle event.
this.adopting = false;
this.isAdopting = () => this.adopting;
this.adoptSession = (sessionMeta) => {
var _a;
this.adopting = true;
try {
(_a = faro.api) === null || _a === void 0 ? void 0 : _a.setSession(sessionMeta);
}
finally {
this.adopting = false;
}
};
this.updateSession = throttle(() => this.updateUserSession(), STORAGE_UPDATE_DELAY);
this.updateUserSession = getUserSessionUpdater({
fetchUserSession: PersistentSessionsManager.fetchUserSession,
storeUserSession: PersistentSessionsManager.storeUserSession,
adoptSession: this.adoptSession,
});
this.init();
}
static removeUserSession() {
removeItem(STORAGE_KEY, PersistentSessionsManager.storageTypeLocal);
}
static storeUserSession(session) {
setItem(STORAGE_KEY, stringifyExternalJson(session), PersistentSessionsManager.storageTypeLocal);
}
static fetchUserSession() {
const storedSession = getItem(STORAGE_KEY, PersistentSessionsManager.storageTypeLocal);
if (storedSession) {
return JSON.parse(storedSession);
}
return null;
}
init() {
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
this.updateSession();
}
});
// Users can call the setSession() method, so we need to sync this with the local storage session
faro.metas.addListener(getSessionMetaUpdateHandler({
fetchUserSession: PersistentSessionsManager.fetchUserSession,
storeUserSession: PersistentSessionsManager.storeUserSession,
}));
}
}
PersistentSessionsManager.storageTypeLocal = webStorageType.local;
//# sourceMappingURL=PersistentSessionsManager.js.map