UNPKG

1.99 kBJavaScriptView Raw
1'use strict';
2
3const pkg = require('../package.json');
4
5const uuid = require('uuid');
6
7const ua = require('universal-analytics');
8const _ = require('lodash');
9const ci = require('ci-info');
10const Conf = require('conf');
11const osName = require('os-name');
12const getProfileFromFile = require('../lib/profile').getProfileFromFile;
13
14const detectMocha = require('detect-mocha');
15
16const os = osName();
17const packageName = pkg.name;
18const nodeVersion = process.version;
19const appVersion = pkg.version;
20
21const conf = new Conf({
22 configName: `ga-${packageName}`,
23 projectName: packageName,
24 defaults: {
25 cid: uuid.v4()
26 }
27});
28
29process.on('unhandledRejection', error => {
30 require('../lib/exception-handler')(error);
31});
32
33var fake = {
34 pageview: () => {
35 return {
36 send: () => { return 'fake'; }
37 };
38 },
39 event: () => {
40 return {
41 send: () => { return 'fake'; }
42 };
43 }
44};
45
46var fakeMocha = {
47 pageview: () => {
48 return {
49 send: () => { return 'fakeMocha'; }
50 };
51 },
52 event: () => {
53 return {
54 send: () => { return 'fakeMocha'; }
55 };
56 }
57};
58
59var real = ua('UA-139874201-1', conf.get('cid'));
60
61real.set('cd1', os);
62real.set('cd2', nodeVersion);
63real.set('cd3', appVersion);
64
65var visitor;
66
67async function getVisitor(returnFakeIfMissingConfig = false) {
68
69 if (!visitor) {
70 const profile = await getProfileFromFile();
71
72 // use fake if it is in a ci environment or has never been configured
73 if (_.isEmpty(profile)) {
74
75 if (detectMocha()) {
76 return fakeMocha;
77 }
78
79 if (ci.isCI) {
80 real.pageview(`/downloaded/ci/${ci.name}`).send();
81 }
82
83 return fake;
84 }
85
86 if (profile.report === undefined) {
87 if (returnFakeIfMissingConfig) { return fake; }
88
89 if (detectMocha()) {
90 return fakeMocha;
91 }
92
93 visitor = real;
94 }
95
96 if (profile.report === true) {
97 visitor = real;
98 } else {
99 visitor = fake;
100 }
101 }
102
103 return visitor;
104}
105
106module.exports = { getVisitor };