@vscode/telemetry-extractor 1.9.5

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 (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +29 -0
  3. package/SECURITY.md +41 -0
  4. package/documentation/comment-code-annotations.md +197 -0
  5. package/documentation/typescript-code-annotations.md +187 -0
  6. package/documentation/using-the-tool.md +106 -0
  7. package/out/cli-help.js +30 -0
  8. package/out/cli-help.js.map +1 -0
  9. package/out/cli-options.js +52 -0
  10. package/out/cli-options.js.map +1 -0
  11. package/out/extractor.js +83 -0
  12. package/out/extractor.js.map +1 -0
  13. package/out/index.js +10 -0
  14. package/out/index.js.map +1 -0
  15. package/out/lib/common-properties.js +32 -0
  16. package/out/lib/common-properties.js.map +1 -0
  17. package/out/lib/debug-patch.js +17 -0
  18. package/out/lib/debug-patch.js.map +1 -0
  19. package/out/lib/declarations.js +121 -0
  20. package/out/lib/declarations.js.map +1 -0
  21. package/out/lib/events.js +55 -0
  22. package/out/lib/events.js.map +1 -0
  23. package/out/lib/file-writer.js +77 -0
  24. package/out/lib/file-writer.js.map +1 -0
  25. package/out/lib/fragments.js +21 -0
  26. package/out/lib/fragments.js.map +1 -0
  27. package/out/lib/keywords.js +11 -0
  28. package/out/lib/keywords.js.map +1 -0
  29. package/out/lib/logger.js +10 -0
  30. package/out/lib/logger.js.map +1 -0
  31. package/out/lib/object-converter.js +107 -0
  32. package/out/lib/object-converter.js.map +1 -0
  33. package/out/lib/operations.js +118 -0
  34. package/out/lib/operations.js.map +1 -0
  35. package/out/lib/parser.js +191 -0
  36. package/out/lib/parser.js.map +1 -0
  37. package/out/lib/save-declarations.js +94 -0
  38. package/out/lib/save-declarations.js.map +1 -0
  39. package/out/lib/source-spec.js +77 -0
  40. package/out/lib/source-spec.js.map +1 -0
  41. package/out/lib/telemetry-interfaces.js +3 -0
  42. package/out/lib/telemetry-interfaces.js.map +1 -0
  43. package/out/lib/ts-parser.js +219 -0
  44. package/out/lib/ts-parser.js.map +1 -0
  45. package/package.json +39 -0
  46. package/src/cli-help.ts +29 -0
  47. package/src/cli-options.ts +31 -0
  48. package/src/extractor.ts +57 -0
  49. package/src/index.ts +4 -0
  50. package/src/lib/common-properties.ts +41 -0
  51. package/src/lib/debug-patch.ts +13 -0
  52. package/src/lib/declarations.ts +131 -0
  53. package/src/lib/events.ts +56 -0
  54. package/src/lib/file-writer.ts +54 -0
  55. package/src/lib/fragments.ts +24 -0
  56. package/src/lib/keywords.ts +7 -0
  57. package/src/lib/logger.ts +5 -0
  58. package/src/lib/object-converter.ts +85 -0
  59. package/src/lib/operations.ts +89 -0
  60. package/src/lib/parser.ts +184 -0
  61. package/src/lib/save-declarations.ts +71 -0
  62. package/src/lib/source-spec.ts +67 -0
  63. package/src/lib/telemetry-interfaces.ts +40 -0
  64. package/src/lib/ts-parser.ts +206 -0
  65. package/tsconfig.json +67 -0
  66. package/vscode-telemetry-extractor.d.ts +72 -0
@@ -0,0 +1,206 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import { Project, SyntaxKind, Symbol, Node, CallExpression } from "ts-morph";
4
+ import * as fs from 'fs';
5
+ import * as cp from 'child_process';
6
+ import * as path from 'path';
7
+ import { rgPath } from "vscode-ripgrep";
8
+ import { makeExclusionsRelativeToSource } from "./operations";
9
+
10
+ interface IGDPRProperty {
11
+ propName: string;
12
+ classification: 'SystemMetaData' | 'CallstackOrException';
13
+ purpose: 'PerformanceAndHealth' | 'FeatureInsight';
14
+ expiration?: string;
15
+ owner?: string;
16
+ comment?: string;
17
+ endpoint?: string;
18
+ isMeasurement?: boolean;
19
+ }
20
+ class GDPREvent {
21
+ public eventName: string;
22
+ public properties: Array<IGDPRProperty>;
23
+ constructor(name: string) {
24
+ this.eventName = name;
25
+ this.properties = [];
26
+ }
27
+ }
28
+
29
+ class NodeVisitor {
30
+
31
+ private pl_node: Node;
32
+ private prop_name: string;
33
+ private inline: boolean = false;
34
+ private original_prop_name: string;
35
+ private applyEndpoints: boolean;
36
+ public properties: Array<any> = [];
37
+ private resolved_property: any = Object.create(null);
38
+ constructor(callexpress_node: Node, prop_name: string, applyEndpoints: boolean) {
39
+ this.pl_node = callexpress_node;
40
+ this.prop_name = prop_name;
41
+ this.original_prop_name = prop_name;
42
+ this.applyEndpoints = applyEndpoints;
43
+ }
44
+
45
+ private visitNode(currentNode: Symbol, previousNode?: Symbol) {
46
+ let type = currentNode.getTypeAtLocation(this.pl_node);
47
+ // If we mark a property as optional then it is nullable, however we want all properties
48
+ // So we want its non nullable type tl;dr this chops off the | undefined
49
+ if (type.isNullable()) {
50
+ type = type.getNonNullableType();
51
+ }
52
+ if (type.isStringLiteral() || type.isBooleanLiteral()) {
53
+ if (previousNode) {
54
+ // This means it is an inline because we had to recurse deeper than the first level to find the properties
55
+ if (this.prop_name !== previousNode.getEscapedName().toLowerCase() && !this.prop_name.includes(`.${previousNode.getEscapedName().toLowerCase()}`)) {
56
+ this.prop_name = `${this.prop_name}.${previousNode.getEscapedName().toLowerCase()}`;
57
+ this.inline = true;
58
+ }
59
+ }
60
+ // If we don't want endpoints skip them
61
+ if (currentNode.getEscapedName().toLowerCase() === "endpoint" && !this.applyEndpoints) return;
62
+
63
+ // If it's a string we strip the quotes
64
+ if (type.isStringLiteral()) {
65
+ this.resolved_property[currentNode.getEscapedName()] = type.getText().substring(1, type.getText().length - 1);
66
+ } else {
67
+ this.resolved_property[currentNode.getEscapedName()] = type.getText() === 'true';
68
+ }
69
+ return;
70
+ }
71
+ const properties = type.getProperties();
72
+ properties.forEach((prop) => {
73
+ this.visitNode(prop, currentNode);
74
+ });
75
+ // 95% of the time there is only one property in this array but inlines allow
76
+ // for the number of properties found to be unpredictable so we must return an array
77
+ if (this.inline && this.prop_name === this.original_prop_name) {
78
+ // This handles the case where the recursion will cause the inline to be counted one too many times
79
+ return;
80
+ }
81
+ const resolved = Object.create(null);
82
+ if (this.applyEndpoints) {
83
+ this.resolved_property['endPoint'] = this.resolved_property['endPoint'] ? this.resolved_property['endPoint'] : 'none';
84
+ }
85
+ resolved[this.prop_name] = this.resolved_property;
86
+ this.properties.push(resolved);
87
+ this.prop_name = this.original_prop_name;
88
+ }
89
+
90
+ public resolveProperties(currentNode: Symbol) {
91
+ this.visitNode(currentNode);
92
+ return this.properties;
93
+ }
94
+ }
95
+
96
+ export class TsParser {
97
+ private sourceDir: string;
98
+ private excludedDirs: string[];
99
+ private applyEndpoints: boolean;
100
+ private lowerCaseEvents: boolean;
101
+ private project: Project;
102
+ constructor(sourceDir: string, excludedDirs: string[], applyEndpoints: boolean, lowerCaseEvents: boolean) {
103
+ this.sourceDir = sourceDir;
104
+ this.excludedDirs = excludedDirs;
105
+ this.applyEndpoints = applyEndpoints;
106
+ this.lowerCaseEvents = lowerCaseEvents;
107
+ // We search for a TS config as that allows the language service to handle weird imports
108
+ if (fs.existsSync(path.join(this.sourceDir, 'src/tsconfig.json'))) {
109
+ this.project = new Project({
110
+ tsConfigFilePath: path.join(this.sourceDir, 'src/tsconfig.json'),
111
+ skipAddingFilesFromTsConfig: true
112
+ });
113
+ } else if (fs.existsSync(path.join(this.sourceDir, 'tsconfig.json'))) {
114
+ this.project = new Project({
115
+ tsConfigFilePath: path.join(this.sourceDir, 'tsconfig.json'),
116
+ skipAddingFilesFromTsConfig: true
117
+ });
118
+ } else {
119
+ this.project = new Project({});
120
+ }
121
+ const fileGlobs: string[] = [];
122
+ fileGlobs.push(`'**/*.ts'`);
123
+ // Excluded added lasts because order determines what takes effect
124
+ this.excludedDirs = makeExclusionsRelativeToSource(this.sourceDir, this.excludedDirs);
125
+ this.excludedDirs.forEach((dir) => {
126
+ fileGlobs.push(`'!${dir}/**'`);
127
+ });
128
+ let rg_glob = '';
129
+ for (const fg of fileGlobs) {
130
+ rg_glob += ` --glob ${fg}`;
131
+ }
132
+ const cmd = `${rgPath} --files-with-matches ${rg_glob} --no-ignore 'publicLog2|publicLogError2' ${this.sourceDir}`;
133
+ try {
134
+ const retrieved_paths = cp.execSync(cmd, { encoding: 'ascii' });
135
+ // Split the paths into an array
136
+ retrieved_paths.split(/(?:\r\n|\r|\n)/g).filter(path => path && path.length > 0).map((f) => {
137
+ this.project.addSourceFileAtPathIfExists(f);
138
+ return f;
139
+ });
140
+ // Empty catch because this fails when there are no typescript annotations which causes weird error messages
141
+ } catch { }
142
+ }
143
+
144
+ public parseFiles() {
145
+ let publicLogUse: Array<CallExpression> = [];
146
+ this.project.getSourceFiles().forEach((source) => {
147
+ const descendants = source.getDescendantsOfKind(SyntaxKind.CallExpression).filter((c) => c.getExpression().getText().includes('publicLog2'));
148
+ const descendants2 = source.getDescendantsOfKind(SyntaxKind.CallExpression).filter((c) => c.getExpression().getText().includes('publicLogError2'));
149
+ publicLogUse = descendants.concat(publicLogUse, descendants2);
150
+ });
151
+
152
+ const events = Object.create(null);
153
+ publicLogUse.forEach((pl) => {
154
+ try {
155
+ const typeArgs = pl.getTypeArguments();
156
+ if (typeArgs.length != 2) {
157
+ throw new Error(`Missing generic arguments on public log call ${pl}`);
158
+ }
159
+ if (pl.getArguments()[0].getText() === "eventName") {
160
+ return;
161
+ }
162
+ // Create an event from the name of the first argument passed in
163
+ let event_name = pl.getArguments()[0].getType().isStringLiteral() ? pl.getArguments()[0].getType().getText() : '';
164
+ // If we can't resolve the event_name there is no use continuing
165
+ if (event_name === '') {
166
+ console.error('Unable to resolve event name, skipping....');
167
+ return;
168
+ } else {
169
+ event_name = event_name.substring(1, event_name.length - 1);
170
+ }
171
+ event_name = this.lowerCaseEvents ? event_name.toLowerCase() : event_name;
172
+ const created_event = new GDPREvent(event_name);
173
+ // We want the second one because public log is in the form <Event, Classification> and we care about the classification
174
+ const type_properties = typeArgs[1].getType().getProperties();
175
+ type_properties.forEach((prop) => {
176
+ const propName = prop.getEscapedName().toLowerCase();
177
+ const node_visitor = new NodeVisitor(pl, propName, this.applyEndpoints);
178
+ created_event.properties = created_event.properties.concat(node_visitor.resolveProperties(prop));
179
+ });
180
+ // We don't want to overwrite an event if we have already defined it, we just want to add to it
181
+ if (!events[event_name]) {
182
+ events[event_name] = Object.create(null);
183
+ }
184
+ created_event.properties.forEach((prop) => {
185
+ Object.assign(events[event_name], prop);
186
+ });
187
+ } catch (err) {
188
+ if (pl.getArguments()[0].getText() === "eventName") {
189
+ return;
190
+ }
191
+ // If the publicLog call isn't generic that means we're just sending an event name with no classifications
192
+ // that are unique to that event (it just has common properties)
193
+ let event_name = pl.getArguments()[0].getType().isStringLiteral() ? pl.getArguments()[0].getType().getText() : '';
194
+ // If we can't resolve the event_name this is most likely because it is not a public log call and therefore we skip it
195
+ if (event_name === '') {
196
+ return;
197
+ } else {
198
+ event_name = event_name.substring(1, event_name.length - 1);
199
+ }
200
+ event_name = this.lowerCaseEvents ? event_name.toLowerCase() : event_name;
201
+ events[event_name] = {};
202
+ }
203
+ });
204
+ return events;
205
+ }
206
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Basic Options */
4
+ "target": "esnext", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
5
+ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
6
+ // "lib": [], /* Specify library files to be included in the compilation. */
7
+ // "allowJs": true, /* Allow javascript files to be compiled. */
8
+ // "checkJs": true, /* Report errors in .js files. */
9
+ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
10
+ //"declaration": false, /* Generates corresponding '.d.ts' file. */
11
+ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
12
+ "sourceMap": true, /* Generates corresponding '.map' file. */
13
+ // "outFile": "./", /* Concatenate and emit output to single file. */
14
+ "outDir": "./out", /* Redirect output structure to the directory. */
15
+ "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
16
+ // "composite": true, /* Enable project compilation */
17
+ // "incremental": true, /* Enable incremental compilation */
18
+ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
19
+ // "removeComments": true, /* Do not emit comments to output. */
20
+ // "noEmit": true, /* Do not emit outputs. */
21
+ // "importHelpers": true, /* Import emit helpers from 'tslib'. */
22
+ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
23
+ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
24
+
25
+ /* Strict Type-Checking Options */
26
+ "strict": true, /* Enable all strict type-checking options. */
27
+ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
28
+ // "strictNullChecks": true, /* Enable strict null checks. */
29
+ // "strictFunctionTypes": true, /* Enable strict checking of function types. */
30
+ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
31
+ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
32
+ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
33
+ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
34
+
35
+ /* Additional Checks */
36
+ // "noUnusedLocals": true, /* Report errors on unused locals. */
37
+ // "noUnusedParameters": true, /* Report errors on unused parameters. */
38
+ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
39
+ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
40
+
41
+ /* Module Resolution Options */
42
+ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
43
+ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
44
+ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
45
+ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
46
+ // "typeRoots": [], /* List of folders to include type definitions from. */
47
+ // "types": [], /* Type declaration files to be included in compilation. */
48
+ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
49
+ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
50
+ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
51
+
52
+ /* Source Map Options */
53
+ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
54
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
55
+ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
56
+ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
57
+
58
+ /* Experimental Options */
59
+ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
60
+ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
61
+ },
62
+ "exclude": [
63
+ "./src/telemetry-sources",
64
+ "./src/tests/mocha/resources",
65
+ "**/*.d.ts"
66
+ ]
67
+ }
@@ -0,0 +1,72 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import { PathLike } from "fs";
4
+ /**
5
+ * The options which the parser takes in
6
+ * evenetPrefix: The prefix to append to all telemetry event names
7
+ * applyEndpoints: Whether to include the endPoints property on events in the final report
8
+ */
9
+ export interface ParserOptions {
10
+ eventPrefix: string;
11
+ applyEndpoints: boolean;
12
+ patchDebugEvents: boolean;
13
+ lowerCaseEvents: boolean;
14
+ silenceOutput: boolean;
15
+ verbose: boolean;
16
+ }
17
+
18
+ /**
19
+ * Allows specifying different options for groups of sources
20
+ * sourceDirs: The directories to extract from
21
+ * excludedDirs: The sub directories to exclude from the telemetry extraction
22
+ * parserOptions: The parser options to apply to these set of directories
23
+ */
24
+ export interface SourceSpec {
25
+ sourceDirs: string[],
26
+ excludedDirs: string[],
27
+ parserOptions: ParserOptions
28
+ }
29
+
30
+ export interface CommonProperties {
31
+ [key: string]: CommonProperty;
32
+ }
33
+
34
+ export interface CommonProperty {
35
+ name: string;
36
+ classification: string;
37
+ purpose: string;
38
+ endPoint?: string;
39
+ isMeasurement?: boolean;
40
+ }
41
+
42
+ export interface Events {
43
+ [key: string]: Event;
44
+ }
45
+
46
+ export interface Event {
47
+ [key: string]: Properties;
48
+ }
49
+
50
+ export interface Properties {
51
+ [key: string]: Property;
52
+ }
53
+
54
+ export interface Property {
55
+ name: string;
56
+ classification: string;
57
+ purpose: string;
58
+ endPoint?: string;
59
+ isMeasurement?: boolean;
60
+ }
61
+
62
+ /**
63
+ * Extracts and resolves all typescript declarations from a series of different sources into a formatted object
64
+ * @param sourceSpecs The various sources and their options which you would like to extract from
65
+ */
66
+ export declare function extractAndResolveDeclarations(sourceSpecs: Array<SourceSpec>): Promise<{ events: Events, commonProperties: CommonProperties }>;
67
+
68
+ /**
69
+ * Parses a valid extractor config file into an array of sourceSpecs that can be passed into an extract function
70
+ * @param file The path to the configuration file
71
+ */
72
+ export declare function convertConfigToSourceSpecs(file: PathLike): SourceSpec[]