source: trip-planner-front/node_modules/@angular/cli/models/analytics-collector.js@ 76712b2

Last change on this file since 76712b2 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 9.3 KB
Line 
1"use strict";
2/**
3 * @license
4 * Copyright Google LLC All Rights Reserved.
5 *
6 * Use of this source code is governed by an MIT-style license that can be
7 * found in the LICENSE file at https://angular.io/license
8 */
9var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10 if (k2 === undefined) k2 = k;
11 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
12}) : (function(o, m, k, k2) {
13 if (k2 === undefined) k2 = k;
14 o[k2] = m[k];
15}));
16var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17 Object.defineProperty(o, "default", { enumerable: true, value: v });
18}) : function(o, v) {
19 o["default"] = v;
20});
21var __importStar = (this && this.__importStar) || function (mod) {
22 if (mod && mod.__esModule) return mod;
23 var result = {};
24 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
25 __setModuleDefault(result, mod);
26 return result;
27};
28var __importDefault = (this && this.__importDefault) || function (mod) {
29 return (mod && mod.__esModule) ? mod : { "default": mod };
30};
31Object.defineProperty(exports, "__esModule", { value: true });
32exports.AnalyticsCollector = void 0;
33const core_1 = require("@angular-devkit/core");
34const child_process_1 = require("child_process");
35const debug_1 = __importDefault(require("debug"));
36const https = __importStar(require("https"));
37const os = __importStar(require("os"));
38const querystring = __importStar(require("querystring"));
39const version_1 = require("./version");
40/**
41 * See: https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
42 */
43class AnalyticsCollector {
44 constructor(trackingId, userId) {
45 this.trackingEventsQueue = [];
46 this.parameters = {};
47 this.analyticsLogDebug = debug_1.default('ng:analytics:log');
48 // API Version
49 this.parameters['v'] = '1';
50 // User ID
51 this.parameters['cid'] = userId;
52 // Tracking
53 this.parameters['tid'] = trackingId;
54 this.parameters['ds'] = 'cli';
55 this.parameters['ua'] = _buildUserAgentString();
56 this.parameters['ul'] = _getLanguage();
57 // @angular/cli with version.
58 this.parameters['an'] = '@angular/cli';
59 this.parameters['av'] = version_1.VERSION.full;
60 // We use the application ID for the Node version. This should be "node v12.10.0".
61 const nodeVersion = `node ${process.version}`;
62 this.parameters['aid'] = nodeVersion;
63 // Custom dimentions
64 // We set custom metrics for values we care about.
65 this.parameters['cd' + core_1.analytics.NgCliAnalyticsDimensions.CpuCount] = os.cpus().length;
66 // Get the first CPU's speed. It's very rare to have multiple CPUs of different speed (in most
67 // non-ARM configurations anyway), so that's all we care about.
68 this.parameters['cd' + core_1.analytics.NgCliAnalyticsDimensions.CpuSpeed] = Math.floor(os.cpus()[0].speed);
69 this.parameters['cd' + core_1.analytics.NgCliAnalyticsDimensions.RamInGigabytes] = Math.round(os.totalmem() / (1024 * 1024 * 1024));
70 this.parameters['cd' + core_1.analytics.NgCliAnalyticsDimensions.NodeVersion] = nodeVersion;
71 }
72 event(ec, ea, options = {}) {
73 const { label: el, value: ev, metrics, dimensions } = options;
74 this.addToQueue('event', { ec, ea, el, ev, metrics, dimensions });
75 }
76 pageview(dp, options = {}) {
77 const { hostname: dh, title: dt, metrics, dimensions } = options;
78 this.addToQueue('pageview', { dp, dh, dt, metrics, dimensions });
79 }
80 timing(utc, utv, utt, options = {}) {
81 const { label: utl, metrics, dimensions } = options;
82 this.addToQueue('timing', { utc, utv, utt, utl, metrics, dimensions });
83 }
84 screenview(cd, an, options = {}) {
85 const { appVersion: av, appId: aid, appInstallerId: aiid, metrics, dimensions } = options;
86 this.addToQueue('screenview', { cd, an, av, aid, aiid, metrics, dimensions });
87 }
88 async flush() {
89 const pending = this.trackingEventsQueue.length;
90 this.analyticsLogDebug(`flush queue size: ${pending}`);
91 if (!pending) {
92 return;
93 }
94 // The below is needed so that if flush is called multiple times,
95 // we don't report the same event multiple times.
96 const pendingTrackingEvents = this.trackingEventsQueue;
97 this.trackingEventsQueue = [];
98 try {
99 await this.send(pendingTrackingEvents);
100 }
101 catch (error) {
102 // Failure to report analytics shouldn't crash the CLI.
103 this.analyticsLogDebug('send error: %j', error);
104 }
105 }
106 addToQueue(eventType, parameters) {
107 const { metrics, dimensions, ...restParameters } = parameters;
108 const data = {
109 ...this.parameters,
110 ...restParameters,
111 ...this.customVariables({ metrics, dimensions }),
112 t: eventType,
113 };
114 this.analyticsLogDebug('add event to queue: %j', data);
115 this.trackingEventsQueue.push(data);
116 }
117 async send(data) {
118 this.analyticsLogDebug('send event: %j', data);
119 return new Promise((resolve, reject) => {
120 const request = https.request({
121 host: 'www.google-analytics.com',
122 method: 'POST',
123 path: data.length > 1 ? '/batch' : '/collect',
124 }, (response) => {
125 if (response.statusCode !== 200) {
126 reject(new Error(`Analytics reporting failed with status code: ${response.statusCode}.`));
127 return;
128 }
129 });
130 request.on('error', reject);
131 const queryParameters = data.map((p) => querystring.stringify(p)).join('\n');
132 request.write(queryParameters);
133 request.end(resolve);
134 });
135 }
136 /**
137 * Creates the dimension and metrics variables to add to the queue.
138 * @private
139 */
140 customVariables(options) {
141 const additionals = {};
142 const { dimensions, metrics } = options;
143 dimensions === null || dimensions === void 0 ? void 0 : dimensions.forEach((v, i) => (additionals[`cd${i}`] = v));
144 metrics === null || metrics === void 0 ? void 0 : metrics.forEach((v, i) => (additionals[`cm${i}`] = v));
145 return additionals;
146 }
147}
148exports.AnalyticsCollector = AnalyticsCollector;
149// These are just approximations of UA strings. We just try to fool Google Analytics to give us the
150// data we want.
151// See https://developers.whatismybrowser.com/useragents/
152const osVersionMap = {
153 darwin: {
154 '1.3.1': '10_0_4',
155 '1.4.1': '10_1_0',
156 '5.1': '10_1_1',
157 '5.2': '10_1_5',
158 '6.0.1': '10_2',
159 '6.8': '10_2_8',
160 '7.0': '10_3_0',
161 '7.9': '10_3_9',
162 '8.0': '10_4_0',
163 '8.11': '10_4_11',
164 '9.0': '10_5_0',
165 '9.8': '10_5_8',
166 '10.0': '10_6_0',
167 '10.8': '10_6_8',
168 // We stop here because we try to math out the version for anything greater than 10, and it
169 // works. Those versions are standardized using a calculation now.
170 },
171 win32: {
172 '6.3.9600': 'Windows 8.1',
173 '6.2.9200': 'Windows 8',
174 '6.1.7601': 'Windows 7 SP1',
175 '6.1.7600': 'Windows 7',
176 '6.0.6002': 'Windows Vista SP2',
177 '6.0.6000': 'Windows Vista',
178 '5.1.2600': 'Windows XP',
179 },
180};
181/**
182 * Build a fake User Agent string. This gets sent to Analytics so it shows the proper OS version.
183 * @private
184 */
185function _buildUserAgentString() {
186 switch (os.platform()) {
187 case 'darwin': {
188 let v = osVersionMap.darwin[os.release()];
189 if (!v) {
190 // Remove 4 to tie Darwin version to OSX version, add other info.
191 const x = parseFloat(os.release());
192 if (x > 10) {
193 v = `10_` + (x - 4).toString().replace('.', '_');
194 }
195 }
196 const cpuModel = os.cpus()[0].model.match(/^[a-z]+/i);
197 const cpu = cpuModel ? cpuModel[0] : os.cpus()[0].model;
198 return `(Macintosh; ${cpu} Mac OS X ${v || os.release()})`;
199 }
200 case 'win32':
201 return `(Windows NT ${os.release()})`;
202 case 'linux':
203 return `(X11; Linux i686; ${os.release()}; ${os.cpus()[0].model})`;
204 default:
205 return os.platform() + ' ' + os.release();
206 }
207}
208/**
209 * Get a language code.
210 * @private
211 */
212function _getLanguage() {
213 // Note: Windows does not expose the configured language by default.
214 return (process.env.LANG || // Default Unix env variable.
215 process.env.LC_CTYPE || // For C libraries. Sometimes the above isn't set.
216 process.env.LANGSPEC || // For Windows, sometimes this will be set (not always).
217 _getWindowsLanguageCode() ||
218 '??'); // ¯\_(ツ)_/¯
219}
220/**
221 * Attempt to get the Windows Language Code string.
222 * @private
223 */
224function _getWindowsLanguageCode() {
225 if (!os.platform().startsWith('win')) {
226 return undefined;
227 }
228 try {
229 // This is true on Windows XP, 7, 8 and 10 AFAIK. Would return empty string or fail if it
230 // doesn't work.
231 return child_process_1.execSync('wmic.exe os get locale').toString().trim();
232 }
233 catch { }
234 return undefined;
235}
Note: See TracBrowser for help on using the repository browser.