-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathgenerate-tracking-plan.ts
343 lines (281 loc) · 9.1 KB
/
generate-tracking-plan.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import path from 'path';
import * as ts from 'typescript';
import * as fs from 'fs';
type PropertyInfo = {
name: string;
comment: string;
type?: string;
required: boolean;
};
type TelemetryEventInfo = {
typeAlias: string;
category: string;
name: string;
comment: string;
props: PropertyInfo[];
};
const TELEMETRY_EVENTS_SOURCE_FILE = path.resolve(
__dirname,
'..',
'packages/compass-telemetry/src/telemetry-events.ts'
);
function main() {
const originalSource = ts.createSourceFile(
TELEMETRY_EVENTS_SOURCE_FILE,
fs.readFileSync(TELEMETRY_EVENTS_SOURCE_FILE, 'utf8'),
ts.ScriptTarget.Latest,
true
);
// get all of the event types names from the original source
const eventTypeNames = getTelemetryEventNames(originalSource);
// for each event and for the IdentifyTraits add a new type `Reduced${typeName}`
// with any intersection and reference types resolved.
const { sourceFile: sourceFileWithReducedTypes, checker } =
getSourceWithReducedTypes(originalSource, eventTypeNames);
// get event info from the modified sources
const events = eventTypeNames.map((eventTypeName) =>
parseTelemetryEventType(eventTypeName, sourceFileWithReducedTypes, checker)
);
const identify = parseTelemetryEventType(
'IdentifyTraits',
sourceFileWithReducedTypes,
checker
);
// render the markdown plan
const markdown = generateMarkdownPlan(events, identify);
console.info(markdown);
}
main();
// --
function getTelemetryEventNames(sourceFile: ts.SourceFile): string[] {
const eventNames: string[] = [];
// find TelemetryEvent and collect all of the event type names in the union.
ts.forEachChild(sourceFile, (node: ts.Node) => {
if (
ts.isTypeAliasDeclaration(node) &&
node.name.text === 'TelemetryEvent'
) {
const type = node.type;
if (!ts.isUnionTypeNode(type)) {
throw new Error('TelemetryEvent is not a union type');
}
for (const typeElement of type.types) {
if (
ts.isTypeReferenceNode(typeElement) &&
ts.isIdentifier(typeElement.typeName)
) {
eventNames.push(typeElement.typeName.text);
} else {
throw new Error('Unexpected type in TelemetryEvent union');
}
}
}
});
return eventNames;
}
function extractNamePropValue(
node: ts.TypeAliasDeclaration,
checker: ts.TypeChecker
) {
const type = checker.getTypeAtLocation(node);
const properties = type.getProperties();
const nameProp = properties.find((prop) => prop.getName() === 'name');
if (nameProp) {
const nameType = checker.getTypeOfSymbolAtLocation(nameProp, node);
if (nameType.isStringLiteral()) {
return nameType.value;
} else {
return checker.typeToString(nameType); // for template literals
}
}
throw new Error('Unable to extract type name');
}
function extractPayloadPropertiesAndComments(
node: ts.TypeAliasDeclaration,
checker: ts.TypeChecker
) {
const props: PropertyInfo[] = [];
const type = checker.getTypeAtLocation(node);
const properties = type.getProperties();
const payloadProp = properties.find((prop) => prop.getName() === 'payload');
if (payloadProp) {
const payloadType = checker.getTypeOfSymbolAtLocation(payloadProp, node);
payloadType.getProperties().forEach((prop) => {
const propType = checker.getTypeOfSymbolAtLocation(prop, node);
const isOptionalFlag = (prop.getFlags() & ts.SymbolFlags.Optional) !== 0;
const allowsUndefinedInUnion =
propType.isUnion() &&
propType.types.some((type) => type.flags & ts.TypeFlags.Undefined);
props.push({
name: prop.getName(),
type: checker.typeToString(
checker.getTypeOfSymbolAtLocation(prop, node),
undefined,
ts.TypeFormatFlags.NoTruncation
),
comment: ts.displayPartsToString(prop.getDocumentationComment(checker)),
required: !isOptionalFlag && !allowsUndefinedInUnion,
});
});
}
return props;
}
function parseTelemetryEventType(
eventTypeName: string,
sourceFile: ts.SourceFile,
checker: ts.TypeChecker
): TelemetryEventInfo {
let originalType: ts.TypeAliasDeclaration | undefined = undefined;
let targetResolvedType: ts.TypeAliasDeclaration | undefined = undefined;
sourceFile.forEachChild((node) => {
if (ts.isTypeAliasDeclaration(node) && node.name.text === eventTypeName) {
originalType = node;
return;
}
if (
ts.isTypeAliasDeclaration(node) &&
node.name.text === `Resolved${eventTypeName}`
) {
targetResolvedType = node;
}
});
if (!originalType) {
throw new Error('cannot find originalType');
}
if (!targetResolvedType) {
throw new Error('cannot find targetResolvedType');
}
const originalSymbol = checker.getSymbolAtLocation(
(originalType as ts.TypeAliasDeclaration).name
);
const comment = originalSymbol
? ts.displayPartsToString(originalSymbol.getDocumentationComment(checker))
: '';
const categoryTag = ts
.getJSDocTags(originalType)
.find((value: ts.JSDocTag) => {
return value.tagName.getText() === 'category';
});
return {
typeAlias: (originalType as ts.TypeAliasDeclaration)?.name.text,
category: categoryTag?.comment?.toString() ?? 'Other',
name: extractNamePropValue(targetResolvedType, checker),
comment: comment,
props: extractPayloadPropertiesAndComments(targetResolvedType, checker),
};
}
function getSourceWithReducedTypes(
originalSource: ts.SourceFile,
eventTypeNames: string[]
) {
// Creates a new source file with new types for the events with a "squashed" payload,
// resolving any type reference to basic types.
// We then use the type checker to read the simplified types for each property.
// This allows us to write event types more freely, refactoring common interfaces, while
// being able to generate a readable tracking plan.
const modifiedSourceText = `
type ResolveType<T> = T extends (...args: infer A) => infer R
? (...args: ResolveType<A>) => ResolveType<R>
: T extends object
? T extends infer O
? { [K in keyof O]: ResolveType<O[K]> }
: never
: T;
${originalSource.text}
type ResolvedIdentifyTraits = {
name: 'Identify Traits',
payload: ResolveType<IdentifyTraits>
};
${eventTypeNames
.map((nodeName: string) => {
return `
type Resolved${nodeName} = {
name: ${nodeName}['name'],
payload: ResolveType<${nodeName}['payload']>
};
`;
})
.join('\n')}
`;
const sourceFile = ts.createSourceFile(
'inMemoryFile.ts',
modifiedSourceText,
ts.ScriptTarget.Latest,
true
);
const compilerOptions = {
// this is needed otherwise the type checker will remove undefined from any union
strictNullChecks: true,
};
const host = ts.createCompilerHost(compilerOptions);
host.getSourceFile = (fileName) =>
fileName === 'inMemoryFile.ts' ? sourceFile : undefined;
const program = ts.createProgram(['inMemoryFile.ts'], compilerOptions, host);
const checker = program.getTypeChecker();
return { sourceFile, checker };
}
function generateMarkdownPlan(
events: TelemetryEventInfo[],
identifyTraits: TelemetryEventInfo
) {
const categoryNames = Array.from(
new Set(events.map((e) => e.category))
).sort();
const categoryEntries: [string, TelemetryEventInfo[]][] = categoryNames.map(
(category) => {
const categoryEvents = events
.filter((e) => e.category === category)
.sort();
return [category, categoryEvents];
}
);
const categories: [string, TelemetryEventInfo[]][] = [
['Identify', [identifyTraits]],
...categoryEntries,
];
let toc = '';
let eventsMarkdown = '';
for (const [category, categoryEvents] of categories) {
toc += `\n### ${category}\n`;
eventsMarkdown += `\n## ${category}\n\n`;
for (const event of categoryEvents) {
const eventLink = `event--${event.typeAlias}`;
toc += `- [${event.name}](#${eventLink})\n`;
eventsMarkdown += `<a name="${eventLink}"></a>\n\n`;
eventsMarkdown += `### ${event.name}\n\n`;
eventsMarkdown += `${event.comment}\n\n`;
if (event.props.length > 0) {
eventsMarkdown += `**Properties**:\n\n`;
for (const prop of event.props) {
eventsMarkdown += `- **${prop.name}** (${
prop.required ? 'required' : 'optional'
}): \`${prop.type || 'unknown'}\`\n`;
if (prop.comment) {
eventsMarkdown += ` - ${prop.comment}\n`;
}
}
eventsMarkdown += '\n';
}
}
}
const now = new Date();
const formattedDate = now.toLocaleDateString('en-US', {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
});
const markdown = `
# Compass Tracking Plan
> [!NOTE]
> This plan represents the tracking plan for the current branch / commit that
> you have selected (\`main\` by default), it might not be released yet. To find
> the tracking plan for the specific Compass version you can use the following
> URL: \`https://github.com/mongodb-js/compass/blob/<compass version>/docs/tracking-plan.md\`
Generated on ${formattedDate}
## Table of Contents
${toc}
${eventsMarkdown}
`;
return markdown;
}