All files / src/tracking tracking.js

91.35% Statements 95/104
100% Branches 39/39
100% Functions 20/20
91% Lines 91/100

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 235 236 237      6x 6x           123x 123x 123x 123x 123x 123x 123x 123x 123x 123x 123x 123x 123x 123x 123x   123x 93x         14x 14x 7x 7x 4x       3x       3x         20x 20x 20x 20x                                                       20x               11x 11x 6x 6x 5x 4x   11x               28x 28x 27x 27x                 5x   5x 5x 5x 5x 1x 1x                 7x 7x 7x               6x   6x 4x 4x 4x 4x 4x           3x 1x   2x 2x   2x 2x     4x     2x         1x 1x       1x 1x 1x   1x 1x 1x 1x   1x                 20x 20x       20x               20x 20x       20x               246x 246x 246x 246x 12x 12x 12x   246x              
import 'navigator.sendbeacon';
import * as cookie from  '../utils/cookies';
 
const VYBE_API_ROOT = "http://track.api.vybe.com/api";
const API = Object.freeze({
    TRACK:  `${VYBE_API_ROOT}/vybeevent`
});
 
class Tracking {
    constructor(options) {
        this._stack = [];
        this.pushMethod = "fetch";
        this.processingStack = false;
        this.polling = false;
        this.retryDelay = 5;
        this.retryAttempts = 0;
        this.internalDimensions = {};
        this.internalMetrics = {};
        this.customerDimensions = {};
        this.customerMetrics = {};
        this.apiTracking = {};
        this.start = this.start.bind(this);
        this.poller = requestAnimationFrame(this.start);
        this._sessionId = getTrackingCookie('session');
        this._customerId = getTrackingCookie('customer');
 
        if (options) {
            Object.assign(this, options);
        }
    }
 
    set(key, value, internal = false) {
        try {
            if (typeof key === "object") {
                this.apiTracking = Object.assign(this.apiTracking, key);
            } else if (typeof value === 'string' || typeof value === 'number') {
                typeof value === 'number' ? 
                    internal ? this.internalMetrics[key] = value : this.customerMetrics[key] = value : 
                    internal ? this.internalDimensions[key] = value : this.customerDimensions[key] = value;
            } else {
                throw Error('Custom dimensions or metrics must be a string or number value');
            }
        }
        catch (err) {
            this.sentry.captureException(err);
        }        
    }
 
    track(hitType, category, action, label, value) {
        try {
            let spread = typeof category === "object" ? category : '';
            category = typeof category === "object" ? undefined : category;
            let dataToTrack = {
                'hitType': hitType,
                'sessionId': this._sessionId,
                'customerId': this._customerId,
                'token': this.token,
                'timestamp': new Date().toISOString(),
                'customDimensions': {
                    ...this.internalDimensions,
                    ...this.apiTracking,
                    ...window.VybeExtraData,
                    'optional': {...this.customerDimensions},
                    'screenResolution': getScreenResolution(),
                    'windowSize': getWindowSize(),
                    'userLanguage': this.language,
                    'referrer': document.referrer
                },
                "customMetrics": {
                    'optional': {...this.customerMetrics},
                    ...this.internalMetrics,
                },
                "hitData": {
                    'category': category,
                    'action': action,
                    'label': label,
                    'value': value,
                    ...spread
                }
            };
            this._stack.push(dataToTrack);
        }
        catch (err) {
            this.sentry.captureException(err);
        }
    };
 
    poll() {
        try {
            if (this._stack.length > 0 && !this.processingStack) {
                this.processingStack = true;
                if (this.pushMethod === "img") this.pushStackImg();
                else if (this.pushMethod === "beacon") this.pushStackBeacon();
                else this.pushStackFetch();
            }        
            this.poller = requestAnimationFrame(() => this.poll());
        }
        catch (err) {
            this.sentry.captureException(err);
        }
    }
 
    start() {
        try {
            if (this.polling != true) {
                this.polling = true;
                this.poller = requestAnimationFrame(() => this.poll());
            }
        }
        catch (err) {
            this.sentry.captureException(err);
        }
    }
 
    restart() {
        try {
            let retryDelay;
            this.stop();
            this.retryAttempts++;
            retryDelay = this.retryDelay * this.retryAttempts;
            window.setTimeout(()=> {
                this.processingStack = false;
                this.start();
            }, retryDelay * 1000);
        }
        catch (err) {
            this.sentry.captureException(err);
        }
    }
 
    stop() {
        try {
            this.polling = false;
            cancelAnimationFrame(this.poller);
        }
        catch (err) {
            this.sentry.captureException(err);
        }
    }
 
    pushStackFetch() {
        try {
            let formData;
            let stack = this._stack;
            this._stack = [];
            stack.forEach((item) => {
                formData = new FormData();
                formData.append("json", JSON.stringify(item));
                fetch(API.TRACK, {
                    method: "POST",
                    credentials: "same-origin",
                    body: formData
                })
                .then((response) => {
                    if (!response.ok) {
                        throw Error();
                    }
                    this.processingStack = false;
                    return response;
                }).catch((err) => {
                    this._stack = stack;
                    this.sentry.captureException(err);
                });
            });
            this.restart();
        }
        catch (err) {
            this.sentry.captureException(err);
        }
    }
 
    pushStackImg() {
        this._stack = [];
        this.processingStack = false;        
    }
 
    pushStackBeacon() {
        try {
            let stack = this._stack;
            this._stack = [];
            let data;
            stack.forEach((item) => {
                data = new FormData();
                data.append("json", JSON.stringify(item));
                navigator.sendBeacon(API.TRACK, data);
            });
            this.processingStack = false;
        }
        catch (err) {
            this.sentry.captureException(err);
        }
    }
}
 
function getScreenResolution(obj = window) {
    try {
        let res = {
            width: obj.screen.width * obj.devicePixelRatio,
            height: obj.screen.height * obj.devicePixelRatio
        }
        return `${res.width}x${res.height}`;
    }
    catch (err) {
        this.sentry.captureException(err);
    }
}
 
function getWindowSize(obj = window) {
    try {
        let res = {
            width: obj.innerWidth * obj.devicePixelRatio,
            height: obj.innerHeight * obj.devicePixelRatio
        }
        return `${res.width}x${res.height}`;
    }
    catch (err) {
        this.sentry.captureException(err);
    }
}
 
function getTrackingCookie(type) {
    try {
        let cookieName = type == "customer" ? "_vc" : "_vs";
        let vybeCookie = cookie.get(cookieName);
        if (!vybeCookie) {
            vybeCookie = 'VT1.' + Math.random() + '.' + Date.now();
            let d = type == "customer" ? 730 : 0
            cookie.set(cookieName, vybeCookie, d);
        }
        return vybeCookie;
    }
    catch (err) {
        this.sentry.captureException(err);
    }
}
 
export default Tracking;