@react-native-windows/telemetry 0.0.0-canary.22 → 0.0.0-canary.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/lib-commonjs/index.d.ts +4 -2
  2. package/lib-commonjs/index.js +12 -5
  3. package/lib-commonjs/index.js.map +1 -1
  4. package/lib-commonjs/telemetry.d.ts +71 -20
  5. package/lib-commonjs/telemetry.js +267 -171
  6. package/lib-commonjs/telemetry.js.map +1 -1
  7. package/lib-commonjs/test/{sanitize.test.d.ts → basePropUtils.test.d.ts} +0 -0
  8. package/lib-commonjs/test/basePropUtils.test.js +116 -0
  9. package/lib-commonjs/test/basePropUtils.test.js.map +1 -0
  10. package/lib-commonjs/test/errorUtils.test.d.ts +7 -0
  11. package/lib-commonjs/test/errorUtils.test.js +161 -0
  12. package/lib-commonjs/test/errorUtils.test.js.map +1 -0
  13. package/lib-commonjs/test/projectUtils.test.d.ts +7 -0
  14. package/lib-commonjs/test/projectUtils.test.js +84 -0
  15. package/lib-commonjs/test/projectUtils.test.js.map +1 -0
  16. package/lib-commonjs/test/sanitizeUtils.test.d.ts +7 -0
  17. package/lib-commonjs/test/sanitizeUtils.test.js +88 -0
  18. package/lib-commonjs/test/sanitizeUtils.test.js.map +1 -0
  19. package/lib-commonjs/test/telemetry.test.d.ts +26 -0
  20. package/lib-commonjs/test/telemetry.test.js +469 -0
  21. package/lib-commonjs/test/telemetry.test.js.map +1 -0
  22. package/lib-commonjs/test/versionUtils.test.d.ts +7 -0
  23. package/lib-commonjs/test/versionUtils.test.js +122 -0
  24. package/lib-commonjs/test/versionUtils.test.js.map +1 -0
  25. package/lib-commonjs/utils/basePropUtils.d.ts +66 -0
  26. package/lib-commonjs/utils/basePropUtils.js +133 -0
  27. package/lib-commonjs/utils/basePropUtils.js.map +1 -0
  28. package/lib-commonjs/{CodedError.d.ts → utils/errorUtils.d.ts} +27 -8
  29. package/lib-commonjs/utils/errorUtils.js +164 -0
  30. package/lib-commonjs/utils/errorUtils.js.map +1 -0
  31. package/lib-commonjs/utils/optionUtils.d.ts +45 -0
  32. package/lib-commonjs/utils/optionUtils.js +96 -0
  33. package/lib-commonjs/utils/optionUtils.js.map +1 -0
  34. package/lib-commonjs/utils/projectUtils.d.ts +50 -0
  35. package/lib-commonjs/utils/projectUtils.js +187 -0
  36. package/lib-commonjs/utils/projectUtils.js.map +1 -0
  37. package/lib-commonjs/utils/sanitizeUtils.d.ts +12 -0
  38. package/lib-commonjs/utils/sanitizeUtils.js +80 -0
  39. package/lib-commonjs/utils/sanitizeUtils.js.map +1 -0
  40. package/lib-commonjs/utils/versionUtils.d.ts +38 -0
  41. package/lib-commonjs/utils/versionUtils.js +159 -0
  42. package/lib-commonjs/utils/versionUtils.js.map +1 -0
  43. package/package.json +22 -8
  44. package/CHANGELOG.json +0 -457
  45. package/CHANGELOG.md +0 -197
  46. package/lib-commonjs/CodedError.js +0 -77
  47. package/lib-commonjs/CodedError.js.map +0 -1
  48. package/lib-commonjs/test/sanitize.test.js +0 -258
  49. package/lib-commonjs/test/sanitize.test.js.map +0 -1
@@ -3,5 +3,7 @@
3
3
  * Licensed under the MIT License.
4
4
  * @format
5
5
  */
6
- export { Telemetry, isMSFTInternal, getDiskFreeSpace } from './telemetry';
7
- export { CodedError, CodedErrorType, CodedErrors } from './CodedError';
6
+ export { Telemetry, TelemetryOptions, CommandStartInfo, CommandEndInfo, } from './telemetry';
7
+ export { CodedError, CodedErrorType, CodedErrors } from './utils/errorUtils';
8
+ export { yargsOptionsToOptions, commanderNameToOptionName, commanderOptionsToOptions, optionsToArgs, OptionSanitizer, YargsOptionsType, CommanderOptionsType, } from './utils/optionUtils';
9
+ export { configToProjectInfo, getProjectFileFromConfig, AppProjectInfo, DependencyProjectInfo, } from './utils/projectUtils';
@@ -5,11 +5,18 @@
5
5
  * @format
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.getProjectFileFromConfig = exports.configToProjectInfo = exports.optionsToArgs = exports.commanderOptionsToOptions = exports.commanderNameToOptionName = exports.yargsOptionsToOptions = exports.CodedErrors = exports.CodedError = exports.Telemetry = void 0;
8
9
  var telemetry_1 = require("./telemetry");
9
10
  Object.defineProperty(exports, "Telemetry", { enumerable: true, get: function () { return telemetry_1.Telemetry; } });
10
- Object.defineProperty(exports, "isMSFTInternal", { enumerable: true, get: function () { return telemetry_1.isMSFTInternal; } });
11
- Object.defineProperty(exports, "getDiskFreeSpace", { enumerable: true, get: function () { return telemetry_1.getDiskFreeSpace; } });
12
- var CodedError_1 = require("./CodedError");
13
- Object.defineProperty(exports, "CodedError", { enumerable: true, get: function () { return CodedError_1.CodedError; } });
14
- Object.defineProperty(exports, "CodedErrors", { enumerable: true, get: function () { return CodedError_1.CodedErrors; } });
11
+ var errorUtils_1 = require("./utils/errorUtils");
12
+ Object.defineProperty(exports, "CodedError", { enumerable: true, get: function () { return errorUtils_1.CodedError; } });
13
+ Object.defineProperty(exports, "CodedErrors", { enumerable: true, get: function () { return errorUtils_1.CodedErrors; } });
14
+ var optionUtils_1 = require("./utils/optionUtils");
15
+ Object.defineProperty(exports, "yargsOptionsToOptions", { enumerable: true, get: function () { return optionUtils_1.yargsOptionsToOptions; } });
16
+ Object.defineProperty(exports, "commanderNameToOptionName", { enumerable: true, get: function () { return optionUtils_1.commanderNameToOptionName; } });
17
+ Object.defineProperty(exports, "commanderOptionsToOptions", { enumerable: true, get: function () { return optionUtils_1.commanderOptionsToOptions; } });
18
+ Object.defineProperty(exports, "optionsToArgs", { enumerable: true, get: function () { return optionUtils_1.optionsToArgs; } });
19
+ var projectUtils_1 = require("./utils/projectUtils");
20
+ Object.defineProperty(exports, "configToProjectInfo", { enumerable: true, get: function () { return projectUtils_1.configToProjectInfo; } });
21
+ Object.defineProperty(exports, "getProjectFileFromConfig", { enumerable: true, get: function () { return projectUtils_1.getProjectFileFromConfig; } });
15
22
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,yCAAwE;AAAhE,sGAAA,SAAS,OAAA;AAAE,2GAAA,cAAc,OAAA;AAAE,6GAAA,gBAAgB,OAAA;AACnD,2CAAqE;AAA7D,wGAAA,UAAU,OAAA;AAAkB,yGAAA,WAAW,OAAA","sourcesContent":["/**\n * Copyright (c) Microsoft Corporation.\n * Licensed under the MIT License.\n * @format\n */\n\nexport {Telemetry, isMSFTInternal, getDiskFreeSpace} from './telemetry';\nexport {CodedError, CodedErrorType, CodedErrors} from './CodedError';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAEH,yCAKqB;AAJnB,sGAAA,SAAS,OAAA;AAMX,iDAA2E;AAAnE,wGAAA,UAAU,OAAA;AAAkB,yGAAA,WAAW,OAAA;AAE/C,mDAQ6B;AAP3B,oHAAA,qBAAqB,OAAA;AACrB,wHAAA,yBAAyB,OAAA;AACzB,wHAAA,yBAAyB,OAAA;AACzB,4GAAA,aAAa,OAAA;AAMf,qDAK8B;AAJ5B,mHAAA,mBAAmB,OAAA;AACnB,wHAAA,wBAAwB,OAAA","sourcesContent":["/**\n * Copyright (c) Microsoft Corporation.\n * Licensed under the MIT License.\n * @format\n */\n\nexport {\n Telemetry,\n TelemetryOptions,\n CommandStartInfo,\n CommandEndInfo,\n} from './telemetry';\n\nexport {CodedError, CodedErrorType, CodedErrors} from './utils/errorUtils';\n\nexport {\n yargsOptionsToOptions,\n commanderNameToOptionName,\n commanderOptionsToOptions,\n optionsToArgs,\n OptionSanitizer,\n YargsOptionsType,\n CommanderOptionsType,\n} from './utils/optionUtils';\n\nexport {\n configToProjectInfo,\n getProjectFileFromConfig,\n AppProjectInfo,\n DependencyProjectInfo,\n} from './utils/projectUtils';\n"]}
@@ -4,26 +4,77 @@
4
4
  * @format
5
5
  */
6
6
  import * as appInsights from 'applicationinsights';
7
- export declare class Telemetry {
8
- static client?: appInsights.TelemetryClient | undefined;
9
- static disable(): void;
10
- static setup(preserveMessages?: boolean): void;
11
- static isCI(): boolean;
12
- static trackException(e: Error, properties?: Record<string, any>): void;
13
- static shouldDisable: boolean;
14
- static preserveMessages: boolean;
7
+ import * as errorUtils from './utils/errorUtils';
8
+ import * as projectUtils from './utils/projectUtils';
9
+ export interface TelemetryOptions {
10
+ setupString: string;
11
+ preserveErrorMessages: boolean;
15
12
  }
13
+ export interface CommandStartInfo {
14
+ commandName: string;
15
+ args: Record<string, any>;
16
+ options: Record<string, any>;
17
+ defaultOptions: Record<string, any>;
18
+ }
19
+ export interface CommandEndInfo {
20
+ resultCode: errorUtils.CodedErrorType;
21
+ }
22
+ interface CommandInfo {
23
+ startTime?: number;
24
+ endTime?: number;
25
+ startInfo?: CommandStartInfo;
26
+ endInfo?: CommandEndInfo;
27
+ }
28
+ export declare const NpmPackagesWeTrack: string[];
29
+ export declare const NuGetPackagesWeTrack: string[];
16
30
  /**
17
- * Sanitize any paths that appear between quotes (''), brackets ([]), or double quotes ("").
18
- * @param msg the string to sanitize
19
- */
20
- export declare function sanitizeMessage(msg: string): string;
21
- export declare function sanitizeFrame(frame: any): void;
22
- export declare function tryGetErrorCode(msg: string): string | undefined;
23
- /**
24
- * Remove PII from exceptions' stack traces and messages
25
- * @param envelope the telemetry envelope. Provided by AppInsights.
31
+ * The Telemetry class is responsible for reporting telemetry for RNW CLI.
26
32
  */
27
- export declare function sanitizeEnvelope(envelope: any): boolean;
28
- export declare function isMSFTInternal(): boolean;
29
- export declare function getDiskFreeSpace(drivePath: string | null): number;
33
+ export declare class Telemetry {
34
+ protected static client?: appInsights.TelemetryClient;
35
+ protected static options: TelemetryOptions;
36
+ protected static isTest: boolean;
37
+ protected static commandInfo: CommandInfo;
38
+ protected static versionsProp: Record<string, string>;
39
+ protected static projectProp?: projectUtils.AppProjectInfo | projectUtils.DependencyProjectInfo;
40
+ protected static getDefaultSetupString(): string;
41
+ protected static reset(): void;
42
+ static isEnabled(): boolean;
43
+ static getSessionId(): string;
44
+ /** Sets up the Telemetry static to be used elsewhere. */
45
+ static setup(options?: Partial<TelemetryOptions>): Promise<void>;
46
+ /** Sets up Telemetry.client. */
47
+ private static setupClient;
48
+ /** Sets up any base properties that all telemetry events require. */
49
+ private static setupBaseProperties;
50
+ /** Sets up any telemetry processors. */
51
+ private static setupTelemetryProcessors;
52
+ /**
53
+ * Performs the processing necessary (mostly PII sanitization) for all events.
54
+ * @param envelope The ApplicationInsights event envelope.
55
+ * @param _contextObjects An optional context object.
56
+ * @returns Whether to kee
57
+ */
58
+ private static basicTelemetryProcessor;
59
+ /**
60
+ * Performs the processing necessary (mostly PII sanitization) for error events.
61
+ * @param envelope
62
+ * @param _contextObjects
63
+ * @returns
64
+ */
65
+ private static errorTelemetryProcessor;
66
+ /** Tries to update the version of the named package/tool by calling getValue(). */
67
+ static tryUpdateVersionsProp(name: string, getValue: () => Promise<string | null>, forceRefresh?: boolean): Promise<boolean>;
68
+ /** Populates the versions property of tools we care to track. */
69
+ static populateToolsVersions(refresh?: boolean): Promise<void>;
70
+ /** Populates the versions property of npm packages we care to track. */
71
+ static populateNpmPackageVersions(refresh?: boolean): Promise<void>;
72
+ /** Populates the versions property of nuget packages we care to track. */
73
+ static populateNuGetPackageVersions(projectFile: string, refresh?: boolean): Promise<void>;
74
+ static setProjectInfo(info: projectUtils.AppProjectInfo | projectUtils.DependencyProjectInfo): void;
75
+ static startCommand(info: CommandStartInfo): void;
76
+ static endCommand(info: CommandEndInfo, extraProps?: Record<string, any>): void;
77
+ private static trackCommandEvent;
78
+ static trackException(error: Error, extraProps?: Record<string, any>): void;
79
+ }
80
+ export {};
@@ -19,206 +19,302 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
19
19
  var __importStar = (this && this.__importStar) || function (mod) {
20
20
  if (mod && mod.__esModule) return mod;
21
21
  var result = {};
22
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
23
  __setModuleDefault(result, mod);
24
24
  return result;
25
25
  };
26
- var __importDefault = (this && this.__importDefault) || function (mod) {
27
- return (mod && mod.__esModule) ? mod : { "default": mod };
28
- };
29
26
  Object.defineProperty(exports, "__esModule", { value: true });
30
- exports.getDiskFreeSpace = exports.isMSFTInternal = exports.sanitizeEnvelope = exports.tryGetErrorCode = exports.sanitizeFrame = exports.sanitizeMessage = exports.Telemetry = void 0;
31
- const path_1 = __importDefault(require("path"));
32
- const crypto_1 = require("crypto");
27
+ exports.Telemetry = exports.NuGetPackagesWeTrack = exports.NpmPackagesWeTrack = void 0;
33
28
  const appInsights = __importStar(require("applicationinsights"));
34
- const child_process_1 = require("child_process");
35
- const CodedError_1 = require("./CodedError");
29
+ const basePropUtils = __importStar(require("./utils/basePropUtils"));
30
+ const versionUtils = __importStar(require("./utils/versionUtils"));
31
+ const errorUtils = __importStar(require("./utils/errorUtils"));
32
+ // This is our key with the AI backend
33
+ const RNWSetupString = '795006ca-cf54-40ee-8bc6-03deb91401c3';
34
+ // Environment variable to override the default setup string
35
+ const ENV_SETUP_OVERRIDE = 'RNW_TELEMETRY_SETUP';
36
+ // Environment variable to override the http proxy (such as http://localhost:8888 for Fiddler debugging)
37
+ const ENV_PROXY_OVERRIDE = 'RNW_TELEMETRY_PROXY';
38
+ // These are NPM packages we care about, in terms of capturing versions used
39
+ // and getting more details about when reporting errors
40
+ exports.NpmPackagesWeTrack = [
41
+ '@react-native-community/cli',
42
+ '@react-native-windows/cli',
43
+ '@react-native-windows/telemetry',
44
+ 'react',
45
+ 'react-native',
46
+ 'react-native-windows',
47
+ 'react-native-windows-init',
48
+ ];
49
+ // These are NPM packages we care about, in terms of capturing versions used
50
+ exports.NuGetPackagesWeTrack = [
51
+ 'Microsoft.UI.Xaml',
52
+ 'Microsoft.Windows.CppWinRT',
53
+ 'Microsoft.WinUI',
54
+ ];
55
+ /**
56
+ * The Telemetry class is responsible for reporting telemetry for RNW CLI.
57
+ */
36
58
  class Telemetry {
37
- static disable() {
59
+ static getDefaultSetupString() {
60
+ var _a;
61
+ // Enable overriding the default setup string via an environment variable
62
+ return (_a = process.env[ENV_SETUP_OVERRIDE]) !== null && _a !== void 0 ? _a : RNWSetupString;
63
+ }
64
+ static reset() {
65
+ // Reset client
38
66
  if (Telemetry.client) {
39
- Telemetry.client.config.disableAppInsights = true;
67
+ Telemetry.client.flush();
68
+ Telemetry.client = undefined;
40
69
  }
41
- Telemetry.shouldDisable = true;
70
+ // Reset local members
71
+ Telemetry.options = {
72
+ setupString: Telemetry.getDefaultSetupString(),
73
+ preserveErrorMessages: false,
74
+ };
75
+ Telemetry.commandInfo = {};
76
+ Telemetry.versionsProp = {};
77
+ Telemetry.projectProp = undefined;
78
+ }
79
+ static isEnabled() {
80
+ return Telemetry.client !== undefined;
42
81
  }
43
- static setup(preserveMessages) {
44
- if (Telemetry.isCI()) {
45
- this.disable();
82
+ static getSessionId() {
83
+ return basePropUtils.getSessionId();
84
+ }
85
+ /** Sets up the Telemetry static to be used elsewhere. */
86
+ static async setup(options) {
87
+ if (Telemetry.client) {
88
+ // Bail since we've already setup
46
89
  return;
47
90
  }
48
- if (Telemetry.client) {
91
+ // Bail if we're in CI and not capturing CI
92
+ if (!this.isTest && basePropUtils.isCI() && !basePropUtils.captureCI()) {
49
93
  return;
50
94
  }
51
- if (!process.env.RNW_CLI_TEST) {
52
- appInsights.Configuration.setInternalLogging(false, false);
95
+ // Save off options for later
96
+ Object.assign(Telemetry.options, options);
97
+ Telemetry.setupClient();
98
+ await Telemetry.setupBaseProperties();
99
+ Telemetry.setupTelemetryProcessors();
100
+ }
101
+ /** Sets up Telemetry.client. */
102
+ static setupClient() {
103
+ appInsights.Configuration.setInternalLogging(Telemetry.isTest, Telemetry.isTest);
104
+ Telemetry.client = new appInsights.TelemetryClient(Telemetry.options.setupString);
105
+ // Allow overriding the proxy server via an environment variable
106
+ const proxyServer = process.env[ENV_PROXY_OVERRIDE];
107
+ if (proxyServer) {
108
+ Telemetry.client.config.proxyHttpUrl = proxyServer;
109
+ Telemetry.client.config.proxyHttpsUrl = proxyServer;
53
110
  }
54
- appInsights.setup('795006ca-cf54-40ee-8bc6-03deb91401c3');
55
- Telemetry.client = appInsights.defaultClient;
56
- if (Telemetry.shouldDisable) {
57
- Telemetry.disable();
111
+ Telemetry.client.config.disableAppInsights = Telemetry.isTest;
112
+ Telemetry.client.channel.setUseDiskRetryCaching(!Telemetry.isTest);
113
+ }
114
+ /** Sets up any base properties that all telemetry events require. */
115
+ static async setupBaseProperties() {
116
+ Telemetry.client.commonProperties.deviceId = await basePropUtils.deviceId();
117
+ Telemetry.client.commonProperties.deviceLocale = await basePropUtils.deviceLocale();
118
+ Telemetry.client.commonProperties.deviceNumCPUs = basePropUtils
119
+ .deviceNumCPUs()
120
+ .toString();
121
+ Telemetry.client.commonProperties.deviceTotalMemory = basePropUtils
122
+ .deviceTotalMemory()
123
+ .toString();
124
+ Telemetry.client.commonProperties.deviceDiskFreeSpace = basePropUtils
125
+ .deviceDiskFreeSpace()
126
+ .toString();
127
+ Telemetry.client.commonProperties.ciCaptured = basePropUtils
128
+ .captureCI()
129
+ .toString();
130
+ Telemetry.client.commonProperties.ciType = basePropUtils.ciType();
131
+ Telemetry.client.commonProperties.isMsftInternal = basePropUtils
132
+ .isMsftInternal()
133
+ .toString();
134
+ Telemetry.client.config.samplingPercentage = basePropUtils.sampleRate();
135
+ if (Telemetry.isTest) {
136
+ Telemetry.client.commonProperties.isTest = true.toString();
58
137
  }
59
- Telemetry.preserveMessages = preserveMessages ? true : false;
60
- if (process.env.RNW_CLI_TEST) {
61
- Telemetry.client.commonProperties.isTest = process.env.RNW_CLI_TEST;
138
+ Telemetry.client.commonProperties.sessionId = Telemetry.getSessionId();
139
+ await Telemetry.populateToolsVersions();
140
+ await Telemetry.populateNpmPackageVersions();
141
+ }
142
+ /** Sets up any telemetry processors. */
143
+ static setupTelemetryProcessors() {
144
+ Telemetry.client.addTelemetryProcessor(Telemetry.basicTelemetryProcessor);
145
+ Telemetry.client.addTelemetryProcessor(Telemetry.errorTelemetryProcessor);
146
+ }
147
+ /**
148
+ * Performs the processing necessary (mostly PII sanitization) for all events.
149
+ * @param envelope The ApplicationInsights event envelope.
150
+ * @param _contextObjects An optional context object.
151
+ * @returns Whether to kee
152
+ */
153
+ static basicTelemetryProcessor(envelope, _contextObjects) {
154
+ delete envelope.tags['ai.cloud.roleInstance'];
155
+ return true;
156
+ }
157
+ /**
158
+ * Performs the processing necessary (mostly PII sanitization) for error events.
159
+ * @param envelope
160
+ * @param _contextObjects
161
+ * @returns
162
+ */
163
+ static errorTelemetryProcessor(envelope, _contextObjects) {
164
+ if (envelope.data.baseType === 'ExceptionData') {
165
+ const data = envelope.data.baseData;
166
+ if (data === null || data === void 0 ? void 0 : data.exceptions) {
167
+ for (const exception of data.exceptions) {
168
+ for (const frame of exception.parsedStack) {
169
+ errorUtils.sanitizeErrorStackFrame(frame);
170
+ }
171
+ // CodedError has non-PII information in its 'type' member, plus optionally some more info in its 'data'.
172
+ // The message may contain PII information. This can be sanitized, but for now delete it.
173
+ // Note that the type of data.exceptions[0] is always going to be ExceptionDetails. It is not the original thrown exception.
174
+ // https://github.com/microsoft/ApplicationInsights-node.js/issues/707
175
+ if (Telemetry.options.preserveErrorMessages) {
176
+ exception.message = errorUtils.sanitizeErrorMessage(exception.message);
177
+ }
178
+ else {
179
+ delete exception.message;
180
+ }
181
+ }
182
+ }
62
183
  }
63
- if (!Telemetry.client.commonProperties.sessionId) {
64
- Telemetry.client.commonProperties.sessionId = crypto_1.randomBytes(16).toString('hex');
65
- Telemetry.client.addTelemetryProcessor(sanitizeEnvelope);
184
+ return true;
185
+ }
186
+ /** Tries to update the version of the named package/tool by calling getValue(). */
187
+ static async tryUpdateVersionsProp(name, getValue, forceRefresh) {
188
+ if (!Telemetry.client) {
189
+ return true;
66
190
  }
191
+ if (forceRefresh === true || !Telemetry.versionsProp[name]) {
192
+ const value = await getValue();
193
+ if (value) {
194
+ Telemetry.versionsProp[name] = value;
195
+ return true;
196
+ }
197
+ }
198
+ return false;
67
199
  }
68
- static isCI() {
69
- return (process.env.AGENT_NAME !== undefined || // Azure DevOps
70
- process.env.CIRCLECI === 'true' || // CircleCI
71
- process.env.TRAVIS === 'true' || // Travis
72
- process.env.CI === 'true' // other CIs
73
- );
200
+ /** Populates the versions property of tools we care to track. */
201
+ static async populateToolsVersions(refresh) {
202
+ await Telemetry.tryUpdateVersionsProp('node', versionUtils.getNodeVersion, refresh);
203
+ await Telemetry.tryUpdateVersionsProp('npm', versionUtils.getNpmVersion, refresh);
204
+ await Telemetry.tryUpdateVersionsProp('yarn', versionUtils.getYarnVersion, refresh);
205
+ await Telemetry.tryUpdateVersionsProp('VisualStudio', versionUtils.getVisualStudioVersion, refresh);
74
206
  }
75
- static trackException(e, properties) {
76
- var _a;
77
- const props = {};
78
- if (e instanceof CodedError_1.CodedError) {
79
- Object.assign(props, e.data);
207
+ /** Populates the versions property of npm packages we care to track. */
208
+ static async populateNpmPackageVersions(refresh) {
209
+ for (const npmPackage of exports.NpmPackagesWeTrack) {
210
+ await Telemetry.tryUpdateVersionsProp(npmPackage, async () => await versionUtils.getVersionOfNpmPackage(npmPackage), refresh);
80
211
  }
81
- const syscallExceptionFieldsToCopy = ['errno', 'syscall', 'code'];
82
- for (const f of syscallExceptionFieldsToCopy) {
83
- if (e[f]) {
84
- props[f] = [f];
85
- }
212
+ }
213
+ /** Populates the versions property of nuget packages we care to track. */
214
+ static async populateNuGetPackageVersions(projectFile, refresh) {
215
+ const nugetVersions = await versionUtils.getVersionsOfNuGetPackages(projectFile, exports.NuGetPackagesWeTrack);
216
+ for (const nugetPackage of exports.NuGetPackagesWeTrack) {
217
+ await Telemetry.tryUpdateVersionsProp(nugetPackage, async () => nugetVersions[nugetPackage], refresh);
86
218
  }
87
- Object.assign(props, props, properties);
88
- (_a = Telemetry.client) === null || _a === void 0 ? void 0 : _a.trackException({
89
- exception: e,
90
- properties: props,
91
- });
92
219
  }
93
- }
94
- exports.Telemetry = Telemetry;
95
- Telemetry.client = undefined;
96
- Telemetry.shouldDisable = false;
97
- Telemetry.preserveMessages = false;
98
- function getAnonymizedPath(filepath) {
99
- const projectRoot = process.cwd().toLowerCase();
100
- filepath = filepath.replace(/\//g, '\\');
101
- const knownPathsVars = ['AppData', 'LocalAppData', 'UserProfile'];
102
- if (filepath.toLowerCase().startsWith(projectRoot)) {
103
- const ext = path_1.default.extname(filepath);
104
- const rest = filepath.slice(projectRoot.length);
105
- const nodeModules = '\\node_modules\\';
106
- // this is in the project dir but not under node_modules
107
- if (rest.toLowerCase().startsWith('\\windows\\')) {
108
- return `[windows]\\???${ext}(${filepath.length})`;
109
- }
110
- else if (rest.toLowerCase().startsWith(nodeModules)) {
111
- return 'node_modules' + rest.slice(nodeModules.length - 1);
112
- }
113
- else {
114
- return `[project_dir]\\???${ext}(${filepath.length})`;
115
- }
116
- }
117
- else {
118
- for (const knownPath of knownPathsVars) {
119
- if (process.env[knownPath] &&
120
- filepath.toLowerCase().startsWith(process.env[knownPath].toLowerCase())) {
121
- return `[${knownPath}]\\???(${filepath.length})`;
122
- }
220
+ static setProjectInfo(info) {
221
+ if (!Telemetry.client) {
222
+ return;
123
223
  }
224
+ Telemetry.projectProp = info;
124
225
  }
125
- return '[path]';
126
- }
127
- /**
128
- * Sanitize any paths that appear between quotes (''), brackets ([]), or double quotes ("").
129
- * @param msg the string to sanitize
130
- */
131
- function sanitizeMessage(msg) {
132
- const cpuThreadId = /^\d+(:\d+)?>/g;
133
- msg = msg.replace(cpuThreadId, '');
134
- const parts = msg.split(/['[\]"]/g);
135
- const clean = [];
136
- const pathRegEx = /([A-Za-z]:|\\)[\\/]([^<>:;,?"*\t\r\n|/\\]+[\\/])+([^<>:;,?"*\t\r\n|]+\/?)/gi;
137
- for (const part of parts) {
138
- if (pathRegEx.test(part)) {
139
- pathRegEx.lastIndex = -1;
140
- let matches;
141
- let noPath = '';
142
- let last = 0;
143
- while ((matches = pathRegEx.exec(part))) {
144
- noPath +=
145
- part.substr(last, matches.index - last) +
146
- getAnonymizedPath(matches[0]);
147
- last = matches.index + matches[0].length;
148
- }
149
- clean.push(noPath);
226
+ static startCommand(info) {
227
+ if (!Telemetry.client) {
228
+ return;
150
229
  }
151
- else if (part !== '') {
152
- clean.push(part);
230
+ if (Telemetry.commandInfo.startInfo) {
231
+ return;
153
232
  }
233
+ Telemetry.commandInfo.startTime = Date.now();
234
+ Telemetry.commandInfo.startInfo = info;
235
+ // Set common command props
236
+ Telemetry.client.commonProperties.commandName = info.commandName;
154
237
  }
155
- return clean.join(' ').trim();
156
- }
157
- exports.sanitizeMessage = sanitizeMessage;
158
- function sanitizeFrame(frame) {
159
- const parens = frame.method.indexOf('(');
160
- if (parens !== -1) {
161
- // case 1: method === 'methodName (rootOfThePath'
162
- frame.method = frame.method.substr(0, parens).trim();
163
- }
164
- else {
165
- // case 2: method === <no_method> or something without '(', fileName is full path
166
- }
167
- // preserve only the last_directory/filename
168
- frame.fileName = path_1.default.join(path_1.default.basename(path_1.default.dirname(frame.fileName)), path_1.default.basename(frame.fileName));
169
- frame.assembly = '';
170
- }
171
- exports.sanitizeFrame = sanitizeFrame;
172
- function tryGetErrorCode(msg) {
173
- const errorRegEx = /error (\w+\d+):/gi;
174
- const m = errorRegEx.exec(msg);
175
- return m ? m[1] : undefined;
176
- }
177
- exports.tryGetErrorCode = tryGetErrorCode;
178
- /**
179
- * Remove PII from exceptions' stack traces and messages
180
- * @param envelope the telemetry envelope. Provided by AppInsights.
181
- */
182
- function sanitizeEnvelope(envelope /*context: any*/) {
183
- if (envelope.data.baseType === 'ExceptionData') {
184
- const data = envelope.data.baseData;
185
- for (const exception of data.exceptions || []) {
186
- for (const frame of exception.parsedStack) {
187
- sanitizeFrame(frame);
188
- }
189
- const errorCode = tryGetErrorCode(exception.message);
190
- data.properties.errorCode = errorCode;
191
- // CodedError has non-PII information in its 'type' member, plus optionally some more info in its 'data'.
192
- // The message may contain PII information. This can be sanitized, but for now delete it.
193
- // Note that the type of data.exceptions[0] is always going to be ExceptionDetails. It is not the original thrown exception.
194
- // https://github.com/microsoft/ApplicationInsights-node.js/issues/707
195
- if (Telemetry.preserveMessages) {
196
- exception.message = sanitizeMessage(exception.message);
197
- }
198
- else {
199
- delete exception.message;
238
+ static endCommand(info, extraProps) {
239
+ if (!Telemetry.client) {
240
+ return;
241
+ }
242
+ if (!Telemetry.commandInfo.startInfo) {
243
+ return;
244
+ }
245
+ Telemetry.commandInfo.endTime = Date.now();
246
+ Telemetry.commandInfo.endInfo = info;
247
+ Telemetry.trackCommandEvent(extraProps);
248
+ }
249
+ static trackCommandEvent(extraProps) {
250
+ var _a, _b, _c, _d;
251
+ const props = {
252
+ eventName: 'RNWCLI.Command',
253
+ };
254
+ // Set command props
255
+ props.command = {
256
+ options: (_a = Telemetry.commandInfo.startInfo) === null || _a === void 0 ? void 0 : _a.options,
257
+ defaultOptions: (_b = Telemetry.commandInfo.startInfo) === null || _b === void 0 ? void 0 : _b.defaultOptions,
258
+ args: (_c = Telemetry.commandInfo.startInfo) === null || _c === void 0 ? void 0 : _c.args,
259
+ durationInSecs: (Telemetry.commandInfo.endTime - Telemetry.commandInfo.startTime) /
260
+ 1000,
261
+ resultCode: (_d = Telemetry.commandInfo.endInfo) === null || _d === void 0 ? void 0 : _d.resultCode,
262
+ };
263
+ // Set remaining common props
264
+ Object.assign(props, extraProps);
265
+ props.project = Telemetry.projectProp;
266
+ props.versions = Telemetry.versionsProp;
267
+ // Fire event
268
+ Telemetry.client.trackEvent({ name: props.eventName, properties: props });
269
+ Telemetry.client.flush();
270
+ }
271
+ static trackException(error, extraProps) {
272
+ var _a, _b, _c;
273
+ if (!Telemetry.client) {
274
+ return;
275
+ }
276
+ const props = {
277
+ eventName: 'RNWCLI.CodedError',
278
+ };
279
+ // Save off CodedError info
280
+ const codedError = error instanceof errorUtils.CodedError
281
+ ? error
282
+ : null;
283
+ props.codedError = {
284
+ type: (_a = codedError === null || codedError === void 0 ? void 0 : codedError.type) !== null && _a !== void 0 ? _a : 'Unknown',
285
+ rawErrorCode: (_b = errorUtils.tryGetErrorCode(error.message)) !== null && _b !== void 0 ? _b : '',
286
+ data: (_c = codedError === null || codedError === void 0 ? void 0 : codedError.data) !== null && _c !== void 0 ? _c : {},
287
+ };
288
+ if (codedError === null || codedError === void 0 ? void 0 : codedError.data) {
289
+ Object.assign(props.codedError.data, codedError.data);
290
+ }
291
+ // Copy miscellaneous system error fields into the codedError.data object
292
+ const syscallExceptionFieldsToCopy = ['errno', 'syscall', 'code'];
293
+ for (const f of syscallExceptionFieldsToCopy) {
294
+ if (error[f]) {
295
+ props.codedError.data[f] = error[f];
200
296
  }
201
297
  }
298
+ // Set remaining common props
299
+ Object.assign(props, extraProps);
300
+ props.project = Telemetry.projectProp;
301
+ props.versions = Telemetry.versionsProp;
302
+ // Fire event
303
+ Telemetry.client.trackException({
304
+ exception: error,
305
+ properties: props,
306
+ });
307
+ Telemetry.client.flush();
202
308
  }
203
- delete envelope.tags['ai.cloud.roleInstance'];
204
- return true;
205
- }
206
- exports.sanitizeEnvelope = sanitizeEnvelope;
207
- function isMSFTInternal() {
208
- return (process.env.UserDNSDomain !== undefined &&
209
- process.env.UserDNSDomain.toLowerCase().endsWith('.microsoft.com'));
210
- }
211
- exports.isMSFTInternal = isMSFTInternal;
212
- function getDiskFreeSpace(drivePath) {
213
- const out = child_process_1.execSync(`dir /-C ${drivePath}`)
214
- .toString()
215
- .split('\r\n');
216
- const line = out[out.length - 2];
217
- const result = line.match(/(\d+) [^\d]+(\d+) /);
218
- if (result && result.length > 2) {
219
- return Number(result[2]);
220
- }
221
- return -1;
222
309
  }
223
- exports.getDiskFreeSpace = getDiskFreeSpace;
310
+ exports.Telemetry = Telemetry;
311
+ Telemetry.client = undefined;
312
+ Telemetry.options = {
313
+ setupString: Telemetry.getDefaultSetupString(),
314
+ preserveErrorMessages: false,
315
+ };
316
+ Telemetry.isTest = basePropUtils.isCliTest();
317
+ Telemetry.commandInfo = {};
318
+ Telemetry.versionsProp = {};
319
+ Telemetry.projectProp = undefined;
224
320
  //# sourceMappingURL=telemetry.js.map