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 { yellow } = require('colors');
|
12 | const osName = require('os-name');
|
13 | const getProfileFromFile = require('../lib/profile').getProfileFromFile;
|
14 |
|
15 | const detectMocha = require('detect-mocha');
|
16 |
|
17 | const os = osName();
|
18 | const packageName = pkg.name;
|
19 | const nodeVersion = process.version;
|
20 | const appVersion = pkg.version;
|
21 |
|
22 | const conf = new Conf({
|
23 | configName: `ga-${packageName}`,
|
24 | projectName: packageName,
|
25 | defaults: {
|
26 | cid: uuid.v4()
|
27 | }
|
28 | });
|
29 |
|
30 | process.on('unhandledRejection', error => {
|
31 | require('../lib/exception-handler')(error);
|
32 | });
|
33 |
|
34 | var fake = {
|
35 | pageview: () => {
|
36 | return {
|
37 | send: () => { return 'fake'; }
|
38 | };
|
39 | },
|
40 | event: () => {
|
41 | return {
|
42 | send: () => { return 'fake'; }
|
43 | };
|
44 | }
|
45 | };
|
46 |
|
47 | var fakeMocha = {
|
48 | pageview: () => {
|
49 | return {
|
50 | send: () => { return 'fakeMocha'; }
|
51 | };
|
52 | },
|
53 | event: () => {
|
54 | return {
|
55 | send: () => { return 'fakeMocha'; }
|
56 | };
|
57 | }
|
58 | };
|
59 |
|
60 | var real = ua('UA-139874201-1', conf.get('cid'));
|
61 |
|
62 | real.set('cd1', os);
|
63 | real.set('cd2', nodeVersion);
|
64 | real.set('cd3', appVersion);
|
65 |
|
66 | var visitor;
|
67 |
|
68 | async function getVisitor(returnFakeIfMissingConfig = false) {
|
69 |
|
70 | if (!visitor) {
|
71 | const profile = await getProfileFromFile();
|
72 |
|
73 |
|
74 | if (_.isEmpty(profile)) {
|
75 |
|
76 | if (detectMocha()) {
|
77 | return fakeMocha;
|
78 | }
|
79 |
|
80 | if (ci.isCI) {
|
81 | real.pageview(`/downloaded/ci/${ci.name}`).send();
|
82 | }
|
83 |
|
84 | return fake;
|
85 | }
|
86 |
|
87 | if (profile.report === undefined) {
|
88 | if (returnFakeIfMissingConfig) { return fake; }
|
89 |
|
90 | if (detectMocha()) {
|
91 | return fakeMocha;
|
92 | }
|
93 |
|
94 | real.pageview('/downloaded').send();
|
95 | throw new Error(`Please re-execute ${yellow('fun config')} command`);
|
96 | }
|
97 |
|
98 | if (profile.report === true) {
|
99 | visitor = real;
|
100 | } else {
|
101 | visitor = fake;
|
102 | }
|
103 | }
|
104 |
|
105 | return visitor;
|
106 | }
|
107 |
|
108 | module.exports = { getVisitor };
|