1 | 'use strict';
|
2 |
|
3 | const pkg = require('../package.json');
|
4 |
|
5 | const uuid = require('uuid');
|
6 |
|
7 | const ua = require('universal-analytics');
|
8 | const _ = require('lodash');
|
9 | const ci = require('ci-info');
|
10 | const Conf = require('conf');
|
11 | const osName = require('os-name');
|
12 | const getProfileFromFile = require('../lib/profile').getProfileFromFile;
|
13 |
|
14 | const detectMocha = require('detect-mocha');
|
15 |
|
16 | const os = osName();
|
17 | const packageName = pkg.name;
|
18 | const nodeVersion = process.version;
|
19 | const appVersion = pkg.version;
|
20 |
|
21 | const conf = new Conf({
|
22 | configName: `ga-${packageName}`,
|
23 | projectName: packageName,
|
24 | defaults: {
|
25 | cid: uuid.v4()
|
26 | }
|
27 | });
|
28 |
|
29 | process.on('unhandledRejection', error => {
|
30 | require('../lib/exception-handler')(error);
|
31 | });
|
32 |
|
33 | var fake = {
|
34 | pageview: () => {
|
35 | return {
|
36 | send: () => { return 'fake'; }
|
37 | };
|
38 | },
|
39 | event: () => {
|
40 | return {
|
41 | send: () => { return 'fake'; }
|
42 | };
|
43 | }
|
44 | };
|
45 |
|
46 | var fakeMocha = {
|
47 | pageview: () => {
|
48 | return {
|
49 | send: () => { return 'fakeMocha'; }
|
50 | };
|
51 | },
|
52 | event: () => {
|
53 | return {
|
54 | send: () => { return 'fakeMocha'; }
|
55 | };
|
56 | }
|
57 | };
|
58 |
|
59 | var real = ua('UA-139874201-1', conf.get('cid'));
|
60 |
|
61 | real.set('cd1', os);
|
62 | real.set('cd2', nodeVersion);
|
63 | real.set('cd3', appVersion);
|
64 |
|
65 | var visitor;
|
66 |
|
67 | async function getVisitor(returnFakeIfMissingConfig = false) {
|
68 |
|
69 | if (!visitor) {
|
70 | const profile = await getProfileFromFile();
|
71 |
|
72 |
|
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 |
|
106 | module.exports = { getVisitor };
|