-
Notifications
You must be signed in to change notification settings - Fork 38
/
parser-helpers.ts
384 lines (348 loc) · 10.1 KB
/
parser-helpers.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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import {
ArrayLiteralExpression,
ClassDeclaration,
Decorator,
JSDoc,
JSDocableNode,
MethodDeclaration,
NumericLiteral,
ObjectLiteralExpression,
ParameterDeclaration,
PropertyAssignment,
PropertyDeclaration,
PropertySignature,
SourceFile,
StringLiteral,
ts,
Node,
TypeNode
} from "ts-morph";
import { HttpMethod, QueryParamArrayStrategy } from "../definitions";
import { getTargetDeclarationFromTypeReference } from "./type-parser";
// FILE HELPERS
/**
* Retrieve all local dependencies of a file recursively including itself.
*
* @param file the source file
* @param visitedFiles visisted files
*/
export function getSelfAndLocalDependencies(
file: SourceFile,
visitedFiles: SourceFile[] = []
): SourceFile[] {
return (
file
.getImportDeclarations()
// We only care about local imports.
.filter(id => id.isModuleSpecifierRelative())
// will throw on file with no import/export statements
// TODO: provide a warning
.map(id => id.getModuleSpecifierSourceFileOrThrow())
.reduce<SourceFile[]>((acc, curr) => {
if (acc.some(f => f.getFilePath() === curr.getFilePath())) {
return acc;
} else {
return getSelfAndLocalDependencies(curr, acc);
}
}, visitedFiles.concat(file))
);
}
/**
* Retrieve a class from a file with a particular decorator or throw.
*
* @param file the source file
* @param decoratorName name of decorator to search for
*/
export function getClassWithDecoratorOrThrow(
file: SourceFile,
decoratorName: string
): ClassDeclaration {
const matchingKlasses = file
.getClasses()
.filter(k => k.getDecorator(decoratorName) !== undefined);
if (matchingKlasses.length !== 1) {
throw new Error(
`expected a decorator @${decoratorName} to be used once, found ${matchingKlasses.length} usages`
);
}
return matchingKlasses[0];
}
// CLASS HELPERS
/**
* Retrieve a property from a class declaration with a particular decorator.
*
* @param klass class declaration
* @param decoratorName name of decorator to search for
*/
export function getPropertyWithDecorator(
klass: ClassDeclaration,
decoratorName: string
): PropertyDeclaration | undefined {
const matchingProps = klass
.getProperties()
.filter(p => p.getDecorator(decoratorName) !== undefined);
if (matchingProps.length > 1) {
throw new Error(
`expected a decorator @${decoratorName} to be used only once, found ${matchingProps.length} usages`
);
}
return matchingProps.length === 1 ? matchingProps[0] : undefined;
}
/**
* Retrieve a method from a class declaration with a particular decorator.
*
* @param klass class declaration
* @param decoratorName name of the decorator to search for
*/
export function getMethodWithDecorator(
klass: ClassDeclaration,
decoratorName: string
): MethodDeclaration | undefined {
const matchingMethods = klass
.getMethods()
.filter(m => m.getDecorator(decoratorName) !== undefined);
if (matchingMethods.length > 1) {
throw new Error(
`expected a decorator @${decoratorName} to be used only once, found ${matchingMethods.length} usages`
);
}
return matchingMethods.length === 1 ? matchingMethods[0] : undefined;
}
// METHOD HELPERS
/**
* Retrieve a parameter from a method declaration with a particular decorator.
*
* @param method method declaration
* @param decoratorName name of decorator to search for
*/
export function getParamWithDecorator(
method: MethodDeclaration,
decoratorName: string
): ParameterDeclaration | undefined {
const matchingParams = method
.getParameters()
.filter(p => p.getDecorator(decoratorName) !== undefined);
if (matchingParams.length > 1) {
throw new Error(
`expected a decorator @${decoratorName} to be used only once, found ${matchingParams.length} usages`
);
}
return matchingParams.length === 1 ? matchingParams[0] : undefined;
}
// PARAMETER HELPERS
/**
* Retrieve a parameter's property signatures or throw.
*
* @param parameter a parameter declaration
*/
export function getParameterPropertySignaturesOrThrow(
parameter: ParameterDeclaration
): PropertySignature[] {
const typeNode = parameter.getTypeNodeOrThrow();
return parseTypeReferencePropertySignaturesOrThrow(typeNode);
}
export function parseTypeReferencePropertySignaturesOrThrow(
typeNode: TypeNode
): PropertySignature[] {
if (Node.isTypeReference(typeNode)) {
const typeReferenceNode = getTargetDeclarationFromTypeReference(typeNode);
if (typeReferenceNode.isErr()) throw typeReferenceNode;
const declaration = typeReferenceNode.unwrap();
// return early if the declaration is an interface
if (Node.isInterfaceDeclaration(declaration)) {
return declaration.getProperties();
}
const declarationAliasTypeNode = declaration.getTypeNodeOrThrow();
return parseTypeReferencePropertySignaturesOrThrow(
declarationAliasTypeNode
);
} else if (Node.isTypeLiteral(typeNode)) {
return typeNode.getProperties();
} else if (Node.isIntersectionTypeNode(typeNode)) {
return typeNode
.getTypeNodes()
.map(parseTypeReferencePropertySignaturesOrThrow)
.flat();
}
throw new Error(
"expected parameter value to be an type literal or interface object"
);
}
// DECORATOR HELPERS
/**
* Retrieve a decorator factory's configuration. The configuration is
* the first parameter of the decorator and is expected to be an object
* literal.
*
* @param decorator the source decorator
*/
export function getDecoratorConfigOrThrow(
decorator: Decorator
): ObjectLiteralExpression {
// expect a decorator factory
if (!decorator.isDecoratorFactory()) {
throw new Error("expected decorator factory");
}
// expect a single argument
const decoratorArgs = decorator.getArguments();
if (decoratorArgs.length !== 1) {
throw new Error(
`expected exactly one argument, got ${decoratorArgs.length}`
);
}
// expect the argument to be an object literal expression
const decoratorArg = decoratorArgs[0];
if (!Node.isObjectLiteralExpression(decoratorArg)) {
throw new Error(
`expected decorator factory configuration argument to be an object literal`
);
}
return decoratorArg;
}
// EXPRESSION HELPERS
/**
* Retrieves a property from an object literal expression. If provided,
* the generic parameter will narrow down the available property names
* allowed.
*
* @param objectLiteral a ts-morph object literal expression
* @param propertyName name of the property
*/
export function getObjLiteralProp<T>(
objectLiteral: ObjectLiteralExpression,
propertyName: Extract<keyof T, string>
): PropertyAssignment | undefined {
const property = objectLiteral.getProperty(propertyName);
if (!property) {
return undefined;
}
if (!Node.isPropertyAssignment(property)) {
throw new Error("expected property assignment");
}
return property;
}
/**
* Retrieves a property from an object literal expression or error. If
* provided, the generic parameter will narrow down the available
* property names allowed.
*
* @param objectLiteral a ts-morph object literal expression
* @param propertyName name of the property
*/
export function getObjLiteralPropOrThrow<T>(
objectLiteral: ObjectLiteralExpression,
propertyName: Extract<keyof T, string>
): PropertyAssignment {
const property = objectLiteral.getPropertyOrThrow(propertyName);
if (!Node.isPropertyAssignment(property)) {
throw new Error("expected property assignment");
}
return property;
}
// PROPERTY ASSIGNMENT HELPERS
/**
* Retrieve a property's value as a string or error.
*
* @param property the source property
*/
export function getPropValueAsStringOrThrow(
property: PropertyAssignment
): StringLiteral {
return property.getInitializerIfKindOrThrow(ts.SyntaxKind.StringLiteral);
}
/**
* Retrieve a property's value as a number or error.
*
* @param property the source property
*/
export function getPropValueAsNumberOrThrow(
property: PropertyAssignment
): NumericLiteral {
return property.getInitializerIfKindOrThrow(ts.SyntaxKind.NumericLiteral);
}
/**
* Retrieve a property's value as an array or error.
*
* @param property the source property
*/
export function getPropValueAsArrayOrThrow(
property: PropertyAssignment
): ArrayLiteralExpression {
return property.getInitializerIfKindOrThrow(
ts.SyntaxKind.ArrayLiteralExpression
);
}
/**
* Retrieve a property's value as an object or error.
*
* @param property the source property
*/
export function getPropValueAsObjectOrThrow(
property: PropertyAssignment
): ObjectLiteralExpression {
return property.getInitializerIfKindOrThrow(
ts.SyntaxKind.ObjectLiteralExpression
);
}
// PROPERTY SIGNATURE/DECLARATION HELPERS
/**
* Retrieve a property's name. This will remove any quotes surrounding the name.
*
* @param property property signature
*/
export function getPropertyName(
property: PropertyDeclaration | PropertySignature
): string {
return property.getNameNode().getSymbolOrThrow().getEscapedName();
}
// JSDOC HELPERS
/**
* Retrieve a JSDoc for a ts-morph node. The node is expected
* to have no more than one JSDoc.
*
* @param node a JSDocable ts-morph node
*/
export function getJsDoc(node: JSDocableNode): JSDoc | undefined {
const jsDocs = node.getJsDocs();
if (jsDocs.length > 1) {
throw new Error(`expected at most 1 jsDoc node, got ${jsDocs.length}`);
} else if (jsDocs.length === 1) {
return jsDocs[0];
}
return undefined;
}
// TYPE GUARDS
/**
* Determine if a HTTP method is a supported HttpMethod.
*
* @param method the method to check
*/
export function isHttpMethod(method: string): method is HttpMethod {
switch (method) {
case "GET":
case "POST":
case "PUT":
case "PATCH":
case "DELETE":
case "HEAD":
return true;
default:
return false;
}
}
/**
* Determine if a query param array strategy is a supported QueryParamArrayStrategy.
*
* @param strategy the strategy to check
*/
export function isQueryParamArrayStrategy(
strategy: string
): strategy is QueryParamArrayStrategy {
switch (strategy) {
case "ampersand":
case "comma":
return true;
default:
return false;
}
}