-
Notifications
You must be signed in to change notification settings - Fork 0
/
Util.ts
544 lines (485 loc) · 15.5 KB
/
Util.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
import * as fs from "fs";
import * as path from "path"
import * as ts from "typescript"
import * as assert from "assert"
// Interfaces with this tag in JSDocs will be
// considered when creating boundary validators
const BOUNDARY_JSDOC_TAG = "@boundary"
export function parseFile(fileName: string) {
return ts.createSourceFile(
fileName,
fs.readFileSync(fileName).toString(),
ts.ScriptTarget.ES2015,
/*setParentNodes */ true
);
}
function flatten(arr: any[]) {
return arr.reduce((flatten, arr) => [...flatten, ...arr])
}
/**
* Maps the input files with function f
*/
export function mapFiles(fileNames: string[], f: (sourceFile: ts.SourceFile) => any): ts.Node[] {
return fileNames.map(fn => f(parseFile(fn)))
}
function makeTypeAliasValidator(tanode: ts.TypeAliasDeclaration): ts.FunctionDeclaration {
const name = tanode.name.getText()
//Validator parameter
const paramName = ts.createIdentifier("data");
const parameter = ts.createParameter(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*dotDotDotToken*/ undefined,
paramName,
/*questionToken*/ undefined,
/*type*/ ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)
);
// Children 5 is the type being assigned to the type alias
const statements = [ts.createReturn(
makeTypeValidator(paramName, tanode.getChildAt(5))
)]
// Type guard magic
const typeAliasSymbol = checker.getSymbolAtLocation(tanode.name)
const typeAliasType = checker.typeToTypeNode(
checker.getDeclaredTypeOfSymbol(typeAliasSymbol)
)
const returnType = ts.createTypePredicateNode(paramName, typeAliasType)
// Build and return validator
return ts.createFunctionDeclaration(
/*decorators*/
undefined,
/*modifiers*/
[ts.createToken(ts.SyntaxKind.ExportKeyword)],
/*asteriskToken*/
undefined,
/*identifier*/
"isValid"+name,
/*typeParameters*/
undefined,
/*parameters*/
[parameter],
/*returnType*/
//ts.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword),
returnType,
ts.createBlock(statements, /*multiline*/ true)
);
}
function symbolIsAlias(symbol: ts.Symbol): boolean {
return !!(symbol.flags & ts.SymbolFlags.TypeAlias)
}
function symbolIsInterface(symbol: ts.Symbol): boolean {
return !!(symbol.flags & ts.SymbolFlags.Interface)
}
function symbolIsEnum(symbol: ts.Symbol): boolean {
return !!(symbol.flags & ts.SymbolFlags.Enum)
}
/**
* Given an <id> to an array, validate all the items with the type <baseType>
*/
function createMultipleValidator(id: ts.Expression, baseType: ts.Node) {
// -Check that every element is of the base type
// <id>.every( x => *childValidator(x)* )
// <id>.every is defined because we know <id> is an array
const everyName = ts.createIdentifier("every");
const everyValidator = ts.createPropertyAccess(id, everyName)
const paramName = ts.createIdentifier("x");
const functionParam = ts.createParameter(
[],
[],
undefined,
paramName,
undefined,
ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)
)
const everyValidatorBody = ts.createArrowFunction(
// Modifiers
[],
// Type params
[],
// Parameters
[functionParam],
undefined,
undefined,
makeTypeValidator(paramName, baseType)
)
return ts.createCall(
everyValidator,
[],
[everyValidatorBody]
)
}
function createArrayValidator(id: ts.Expression, baseType: ts.Node): ts.Expression {
// -Check array type
const arrayGlobal = ts.createIdentifier("Array")
const isArrayId = ts.createPropertyAccess(arrayGlobal, "isArray")
return ts.createLogicalAnd(
ts.createCall(
isArrayId,
[],
[id]
),
createMultipleValidator(id, baseType)
)
}
function createNodeHeritagesValidator(id: ts.Expression, inode: ts.InterfaceDeclaration): ts.Expression {
return flatten(
// For every heritage clause (extends, implements)
inode.heritageClauses.map(clause =>
// For every type in the clause
clause.types.map(type =>
// In this case, we know <inode> is more than just <type>
// so we ignore the type guard by asserting type any
ts.createTypeAssertion(
ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword),
makeTypeValidator(id, type)
)
)
)
).reduce(ts.createLogicalAnd)
}
/**
* Makes an expression to validate a node's members
*/
function createNodeMembersValidator(id: ts.Expression, tnode: ts.TypeLiteralNode | ts.InterfaceDeclaration): ts.Expression {
// must not be undefined nor null, we are going to check its members
let checkUndefined: ts.Expression = ts.createLogicalAnd(
ts.createStrictInequality(
ts.createTypeOf(id),
ts.createStringLiteral("undefined")
),
ts.createStrictInequality(
id,
ts.createNull()
)
)
// List of expressions that validate each member
const memberValidatorCalls: ts.Expression[] = tnode.members.map(
makeMemberValidator(id)
)
// First check undefined
memberValidatorCalls.unshift(checkUndefined)
// All expressions must be true for the interface to be valid
return memberValidatorCalls.reduce(ts.createLogicalAnd)
}
const createTypeLiteralValidator: (id: ts.Expression, tnode: ts.TypeLiteralNode) => ts.Expression = createNodeMembersValidator
/**
* Given the expression to access an object,
* returns a function that, given a object member signature,
* returns an expression that validates that member
*/
function makeMemberValidator(paramName: ts.Expression): (member: ts.PropertySignature) => ts.Expression {
return (member) => {
let validatorCall
// If index signature is present, its type is the union of all the members' types
// This means that validating all the properties with the associated type won't fail
// Also, we don't check for the index type because on the boundary we can only have string indexes (JSON)
if (ts.isIndexSignatureDeclaration(member)) {
// Get all object values
const objectGlobal = ts.createIdentifier("Object")
const valuesMember = ts.createPropertyAccess(objectGlobal, "values")
const valuesCall = ts.createCall(
valuesMember,
[],
[paramName]
)
// Validate all values with the index signature type
validatorCall = createMultipleValidator(valuesCall, member.type)
} else {
// Even if we have an index signature, validating each member separately makes stricter validation
// (i.e. the case of an interface with an index signature member with other explicit members,
// which could have narrower type)
// Expression to access <member>
let memberAccess = ts.createPropertyAccess(paramName, member.name.getText())
// Expression that validates the member's type
validatorCall = makeTypeValidator(memberAccess, member.type)
// undefined is a valid value in optional members
if(member.questionToken)
{
validatorCall = ts.createLogicalOr(
ts.createStrictEquality(
ts.createTypeOf(memberAccess),
// Can't find a way to compare with undefined keyword
ts.createStringLiteral("undefined")
),
validatorCall
)
}
}
return validatorCall
}
}
function makeTypeValidator(id: ts.Expression, tnode: ts.Node): ts.Expression {
// In case of unhandled type
const validatorAny = ts.createIdentifier("isValidany")
let validatorCall: ts.Expression = ts.createCall(validatorAny, [], [id])
if (ts.isArrayTypeNode(tnode)) {
// Array type first child is base type
validatorCall = createArrayValidator(id, tnode.getChildAt(0))
} else if(ts.isTypeLiteralNode(tnode)) {
validatorCall = createTypeLiteralValidator(id, tnode)
} else if (ts.isTypeReferenceNode(tnode)) {
const type = checker.getTypeAtLocation(tnode.getChildAt(0))
const symbol = type.getSymbol() || type.aliasSymbol
// TODO: there's a bug where under unknown circumstances, the symbol doesn't exist
if(!symbol) {
const validatorName = ts.createIdentifier("isValid"+tnode.getChildAt(0).getText())
// isValid<identifierName>(<id>)
validatorCall = ts.createCall(
validatorName,
[],
[id]
)
}
else if (symbolIsInterface(symbol) || symbolIsAlias(symbol)) {
if (symbol.getName() === "Array") {
// Generic types have base type as sibling
// (sibling 1 is '<' token, second sibling is a SytaxList)
validatorCall = createArrayValidator(id, tnode.getChildAt(2).getChildAt(0))
} else {
// if it's an interface or alias, we just call the validator
const validatorName = ts.createIdentifier("isValid"+symbol.getName())
// isValid<typeName>(<id>)
validatorCall = ts.createCall(
validatorName,
[],
[id]
)
}
} else if (symbolIsEnum(symbol)) {
// It it's an enum, we call a generic enum checker with the enum type
const typeName = checker.symbolToEntityName(symbol, ts.SymbolFlags.Enum)
const enumTypeId = ts.createIdentifier(symbol.getName())
const enumValidator = ts.createIdentifier("isValidEnum")
// isValidEnumArray<typeof <enumName>>(<enumName>)
validatorCall = ts.createCall(
enumValidator,
[ts.createTypeQueryNode(typeName)],
[enumTypeId, id]
)
}
} else if (ts.isUnionTypeNode(tnode)) {
const typeValidatorCalls: ts.Expression[] = []
tnode.types.forEach((child) => {
typeValidatorCalls.push(makeTypeValidator(id, child))
})
validatorCall = typeValidatorCalls.reduce(ts.createLogicalOr)
} else if(ts.isToken(tnode)) {
const interfaceValidator = ts.createIdentifier("isValid"+ts.tokenToString(tnode.kind))
// isValid<token>(<id>)
validatorCall = ts.createCall(
interfaceValidator,
[],
[id]
)
} else if (ts.isExpressionWithTypeArguments(tnode)) {
const validatorName = ts.createIdentifier("isValid"+tnode.getChildAt(0).getText())
// isValid<identifierName>(<id>)
validatorCall = ts.createCall(
validatorName,
[],
[id]
)
}
else if(ts.isMappedTypeNode(tnode)) {
// -validate all properties with the index type
// -validate all values with the associated type
const objectGlobal = ts.createIdentifier("Object")
const keysMember = ts.createPropertyAccess(objectGlobal, "keys")
const keysCall = ts.createCall(
keysMember,
[],
[id]
)
const valuesMember = ts.createPropertyAccess(objectGlobal, "values")
const valuesCall = ts.createCall(
valuesMember,
[],
[id]
)
const keyType = tnode.typeParameter.getChildAt(2)
validatorCall = ts.createLogicalAnd(
// -validate all keys with the index type
createMultipleValidator(keysCall, keyType),
// -validate all values with the type
createMultipleValidator(valuesCall, tnode.type)
)
}
return validatorCall
}
/**
* Given an interface I, creates a validator declaration that checks
* if a given object implements I in execution time
*/
function makeInterfaceValidator(inode: ts.InterfaceDeclaration): ts.FunctionDeclaration {
const name = inode.name.getText()
const paramName = ts.createIdentifier("data");
const parameter = ts.createParameter(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*dotDotDotToken*/ undefined,
paramName,
/*questionToken*/ undefined,
/*type*/ ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)
);
let expression: ts.Expression
// The interface has heritage
if(inode.heritageClauses) {
expression = ts.createLogicalAnd(
// Has to validate parent types
createNodeHeritagesValidator(paramName, inode),
// All members must be valid for the interface to be valid
createNodeMembersValidator(paramName, inode)
)
} else {
// Doesn't have heritage
// All members must be valid for the interface to be valid
expression = createNodeMembersValidator(paramName, inode)
}
const statements: ts.Statement[] = [ts.createReturn(expression)]
// Return typescript "is" magic
// This makes the typescript compiler know the type of the data
// in the scope where the call is true
const interfaceSymbol = checker.getSymbolAtLocation(inode.name)
const interfaceType = checker.typeToTypeNode(
checker.getDeclaredTypeOfSymbol(interfaceSymbol)
)
const returnType = ts.createTypePredicateNode(paramName, interfaceType)
return ts.createFunctionDeclaration(
/*decorators*/
undefined,
/*modifiers*/
[ts.createToken(ts.SyntaxKind.ExportKeyword)],
/*asteriskToken*/
undefined,
/*identifier*/
"isValid"+name,
/*typeParameters*/
undefined,
/*parameters*/
[parameter],
/*returnType*/
//ts.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword),
returnType,
ts.createBlock(statements, /*multiline*/ true)
);
}
/**
* Checks whether the statement is an interface declaration
* tagged with the boundary tag
*/
function isBoundary(statement: ts.Statement): boolean {
return ts.getJSDocTags(statement).some(s =>
s.getText() === BOUNDARY_JSDOC_TAG
)
}
let checker: ts.TypeChecker
/**
* Creates validators for the boundary interfaces found in 'file'
*/
export function makeBoundaryValidators(files: string[], outputPath: string) {
// Build a program using the set of root file names in fileNames
const program = ts.createProgram(files, {});
checker = program.getTypeChecker()
const importNodes: ts.Node[] = []
const nodes: ts.Node[] = []
for (let file of program.getSourceFiles()) {
// Filter typescript files
// If this file is not some of the input files, continue
if(!files.some(x => file.fileName.includes(x)))
continue
let imports = []
for (let statement of file.statements) {
if(!isBoundary(statement))
continue
if (ts.isEnumDeclaration(statement)) {
imports.push(statement.name)
}
else if (ts.isInterfaceDeclaration(statement)) {
imports.push(statement.name)
nodes.push(
makeInterfaceValidator(statement)
)
}
else if(ts.isTypeAliasDeclaration(statement)) {
imports.push(statement.name)
nodes.push(
makeTypeAliasValidator(statement)
)
}
}
if (imports.length) {
const pathParts = file.fileName.split("/")
// Module name is filename without extension
const moduleName =
// Get last path part
pathParts.slice(-1)[0]
// Leave out substr after last point (extension)
.split(".").slice(0, -1)
// Get the name with points again (if any)
.join(".")
// Path to file without filename
const pathToFolder = pathParts.slice(0, -1).join("/")
// Get relative path from output to file folder,
// as we are going to create a .ts file that imports it
const relativePath = path.relative(outputPath, pathToFolder)
// Zero length string means same folder
const suffix = relativePath.length !== 0 ? '/' : ''
importNodes.push(
ts.createImportDeclaration(
undefined,
undefined,
ts.createImportClause(
undefined,
ts.createNamedImports(
imports.map(i => ts.createImportSpecifier(
undefined,
i
))
)
),
ts.createStringLiteral(
'./' + relativePath + suffix + moduleName
)
)
)
}
}
return importNodes.concat(nodes)
}
export function createFile(nodes: ts.Node[], output: string) {
const resultFile = ts.createSourceFile(
"someFileName.ts",
"",
ts.ScriptTarget.Latest,
/*setParentNodes*/ false,
ts.ScriptKind.TS
);
const printer = ts.createPrinter({
newLine: ts.NewLineKind.LineFeed
});
const result = printer.printList(
ts.ListFormat.MultiLine,
ts.createNodeArray(nodes, false),
resultFile
);
//TODO: refactor
const pre = printer.printFile(parseFile(__dirname+"/basic_validators.ts"))
fs.writeFileSync(output+"validators.ts", pre+result)
console.log("outputting in: " + output+"validators.ts")
}
/* PRINT */
export function nodeString(node: ts.Node): string {
return `<${ts.SyntaxKind[node.kind]}>`
}
export function printAST(node: ts.Node) {
console.log("_" + nodeString(node) + " - " + node.getText() + "__")
let level = 0
function printSubtree(node: ts.Node) {
level += 1
console.log("|-".repeat(level) + "-" + nodeString(node) + " - " + node.getText())
//console.log(node)
ts.forEachChild(node, printSubtree)
level -= 1
}
ts.forEachChild(node, printSubtree)
}