forked from elastic/elasticsearch-specification
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
1432 lines (1296 loc) · 55.3 KB
/
utils.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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* eslint-disable no-empty */
import { deepStrictEqual } from 'assert'
import {
ts,
ClassDeclaration,
InterfaceDeclaration,
HeritageClause,
TypeParameterDeclaration,
EnumDeclaration,
TypeAliasDeclaration,
PropertySignature,
PropertyDeclaration,
ExpressionWithTypeArguments,
JSDoc,
Node,
Project
} from 'ts-morph'
import { closest } from 'fastest-levenshtein'
import semver from 'semver'
import chalk from 'chalk'
import * as model from './metamodel'
import { EOL } from 'os'
import { dirname, join, sep } from 'path'
import { readFileSync } from 'fs'
const docIds: string[][] = readFileSync(join(__dirname, '..', '..', '..', 'specification', '_doc_ids', 'table.csv'), 'utf8')
.split('\n')
.map(line => line.split(','))
/**
* Behaviors that the compiler recognized
* and can act on. If a behavior is not defined
* here, it will be handled as normal `implements`.
*/
export const knownBehaviors = [
'AdditionalProperties',
'AdditionalProperty',
'CommonQueryParameters',
'CommonCatQueryParameters',
'OverloadOf'
]
/**
* Custom types that we use in the compiler
* to help contributors shape the specification.
* This types should not go in the final output.
*/
export const customTypes = [
'SingleKeyDictionary',
'Dictionary',
'UserDefinedValue'
]
/**
* Given a ts-morph Node element, it models it according to
* our metamodel. It automatically models nested types as well.
*/
export function modelType (node: Node): model.ValueOf {
switch (node.getKind()) {
case ts.SyntaxKind.BooleanKeyword: {
const type: model.InstanceOf = {
kind: 'instance_of',
type: {
name: 'boolean',
namespace: '_builtins'
}
}
return type
}
case ts.SyntaxKind.StringKeyword: {
const type: model.InstanceOf = {
kind: 'instance_of',
type: {
name: 'string',
namespace: '_builtins'
}
}
return type
}
case ts.SyntaxKind.NumberKeyword: {
const type: model.InstanceOf = {
kind: 'instance_of',
type: {
name: 'number',
namespace: '_builtins'
}
}
return type
}
case ts.SyntaxKind.NullKeyword: {
const type: model.InstanceOf = {
kind: 'instance_of',
type: {
name: 'null',
namespace: '_builtins'
}
}
return type
}
case ts.SyntaxKind.VoidKeyword: {
const type: model.InstanceOf = {
kind: 'instance_of',
type: {
name: 'void',
namespace: '_builtins'
}
}
return type
}
// TODO: this should not be used in the specification
// we should throw an error
case ts.SyntaxKind.AnyKeyword: {
const type: model.InstanceOf = {
kind: 'instance_of',
type: {
name: 'object',
namespace: '_builtins'
}
}
return type
}
case ts.SyntaxKind.ArrayType: {
const kinds: ts.SyntaxKind[] = [
ts.SyntaxKind.StringKeyword,
ts.SyntaxKind.BooleanKeyword,
ts.SyntaxKind.AnyKeyword,
ts.SyntaxKind.ArrayType,
ts.SyntaxKind.TypeReference
]
let children: Node[] = []
node.forEachChild(child => children.push(child))
children = children.filter(child => kinds.some(kind => kind === child.getKind()))
assert(node, children.length === 1, `Expected array to have 1 usable child but saw ${children.length}`)
const type: model.ArrayOf = {
kind: 'array_of',
value: modelType(children[0])
}
return type
}
case ts.SyntaxKind.UnionType: {
assert(node, Node.isUnionTypeNode(node), `The node is not of type ${ts.SyntaxKind[ts.SyntaxKind.UnionType]} but ${ts.SyntaxKind[node.getKind()]} instead`)
const type: model.UnionOf = {
kind: 'union_of',
items: node.getTypeNodes().map(node => modelType(node))
}
return type
}
case ts.SyntaxKind.LiteralType: {
assert(node, Node.isLiteralTypeNode(node), `The node is not of type ${ts.SyntaxKind[ts.SyntaxKind.LiteralType]} but ${ts.SyntaxKind[node.getKind()]} instead`)
return modelType(node.getLiteral())
}
case ts.SyntaxKind.StringLiteral: {
assert(node, Node.isStringLiteral(node), `The node is not of type ${ts.SyntaxKind[ts.SyntaxKind.StringLiteral]} but ${ts.SyntaxKind[node.getKind()]} instead`)
const type: model.LiteralValue = {
kind: 'literal_value',
value: node.getText().replace(/'/g, '')
}
return type
}
case ts.SyntaxKind.TrueKeyword: {
assert(node, Node.isTrueLiteral(node), `The node is not of type ${ts.SyntaxKind[ts.SyntaxKind.TrueKeyword]} but ${ts.SyntaxKind[node.getKind()]} instead`)
const type: model.LiteralValue = {
kind: 'literal_value',
value: true
}
return type
}
case ts.SyntaxKind.FalseKeyword: {
assert(node, Node.isFalseLiteral(node), `The node is not of type ${ts.SyntaxKind[ts.SyntaxKind.FalseKeyword]} but ${ts.SyntaxKind[node.getKind()]} instead`)
const type: model.LiteralValue = {
kind: 'literal_value',
value: false
}
return type
}
case ts.SyntaxKind.NumericLiteral: {
assert(node, Node.isNumericLiteral(node), `The node is not of type ${ts.SyntaxKind[ts.SyntaxKind.NumericLiteral]} but ${ts.SyntaxKind[node.getKind()]} instead`)
const type: model.LiteralValue = {
kind: 'literal_value',
value: Number(node.getText())
}
return type
}
case ts.SyntaxKind.PrefixUnaryExpression: {
// Negative number
const type: model.LiteralValue = {
kind: 'literal_value',
value: Number(node.getText())
}
return type
}
case ts.SyntaxKind.TypeParameter: {
assert(node, Node.isTypeParameterDeclaration(node), `The node is not of type ${ts.SyntaxKind[ts.SyntaxKind.TypeReference]} but ${ts.SyntaxKind[node.getKind()]} instead`)
const name = node.compilerNode.getText()
const type: model.InstanceOf = {
kind: 'instance_of',
type: {
name,
namespace: getNameSpace(node)
}
}
return type
}
case ts.SyntaxKind.TypeReference: {
// TypeReferences are fun types, it's basically how TypeScript defines
// everything that is not a basic type, an interface or a class will
// appear here when used for instance.
// For some reason also the `Array` type (the one defined with `Array<T>` and not `T[]`)
// is interpreted as TypeReference as well.
// The two most important fields of a TypeReference are `typeName` and `typeArguments`,
// the first one is the name of the type (eg: `Foo`), while the second is the
// possible generics (eg: Foo<T> => T will be in typeArguments).
assert(node, Node.isTypeReference(node), `The node is not of type ${ts.SyntaxKind[ts.SyntaxKind.TypeReference]} but ${ts.SyntaxKind[node.getKind()]} instead`)
const identifier = node.getTypeName()
assert(node, Node.isIdentifier(identifier), 'Should be an identifier')
const name = identifier.compilerNode.escapedText as string
switch (name) {
case 'Array': {
assert(node, node.getTypeArguments().length === 1, 'An array must have one argument')
const [value] = node.getTypeArguments().map(node => modelType(node))
const type: model.ArrayOf = {
kind: 'array_of',
value
}
return type
}
case 'ArrayBuffer': {
const type: model.InstanceOf = {
kind: 'instance_of',
type: {
name: 'binary',
namespace: '_builtins'
}
}
return type
}
case 'Dictionary':
case 'AdditionalProperties': {
assert(node, node.getTypeArguments().length === 2, 'A Dictionary must have two arguments')
const [key, value] = node.getTypeArguments().map(node => modelType(node))
const type: model.DictionaryOf = {
kind: 'dictionary_of',
key,
value,
singleKey: false
}
return type
}
case 'SingleKeyDictionary':
case 'AdditionalProperty': {
assert(node, node.getTypeArguments().length === 2, 'A SingleKeyDictionary must have two arguments')
const [key, value] = node.getTypeArguments().map(node => modelType(node))
const type: model.DictionaryOf = {
kind: 'dictionary_of',
key,
value,
singleKey: true
}
return type
}
case 'UserDefinedValue': {
const type: model.UserDefinedValue = {
kind: 'user_defined_value'
}
return type
}
default: {
const generics = node.getTypeArguments().map(node => modelType(node))
const identifier = node.getTypeName()
assert(node, Node.isIdentifier(identifier), 'Not an identifier')
assert(node, identifier.getDefinitions().length > 0, 'Unknown definition (missing import?)')
const declaration = identifier.getDefinitions()[0].getDeclarationNode()
// We are looking at a generic parameter
if (declaration == null) {
const type: model.InstanceOf = {
kind: 'instance_of',
...(generics.length > 0 && { generics }),
type: {
name,
namespace: getNameSpace(node)
}
}
return type
}
assert(
node,
Node.isClassDeclaration(declaration) ||
Node.isInterfaceDeclaration(declaration) ||
Node.isEnumDeclaration(declaration) ||
Node.isTypeAliasDeclaration(declaration) ||
Node.isTypeParameterDeclaration(declaration),
'It should be a class, interface, enum, type alias, or type parameter declaration'
)
const type: model.InstanceOf = {
kind: 'instance_of',
...(generics.length > 0 && { generics }),
type: {
name: declaration.getName() as string,
namespace: getNameSpace(node)
}
}
return type
}
}
}
default:
assert(node, false, `Unhandled node kind: ${ts.SyntaxKind[node.getKind()]}`)
}
}
/**
* Given an InterfaceDeclaration, returns `true` if the Node
* represents a rest spec name by looking at the js doc tag.
*/
export function isApi (declaration: InterfaceDeclaration): boolean {
const tags = parseJsDocTags(declaration.getJsDocs())
return tags.rest_spec_name !== undefined
}
/**
* Given the extended class or interface definition and the HeritageClause node
* returns an Inherits structure.
*/
export function modelInherits (node: InterfaceDeclaration | ClassDeclaration, inherit: HeritageClause): model.Inherits {
const generics = inherit.getTypeNodes()
.flatMap(node => node.getTypeArguments())
.map(node => modelType(node))
return {
type: {
name: node.getName() as string,
namespace: getNameSpace(node)
},
...(generics.length > 0 && { generics })
}
}
/**
* Given a HeritageClause node returns an Implements structure.
* A class could implement from multiple classes, which are
* defined inside the node typeArguments.
*/
export function modelImplements (node: ExpressionWithTypeArguments): model.Inherits {
const generics = node.getTypeArguments().map(node => modelType(node))
return {
type: {
name: node.getExpression().getText(),
namespace: getNameSpace(node)
},
...(generics.length > 0 && { generics })
}
}
/**
* Given a HeritageClause node returns an Implements structure.
* A class could have multiple behaviors from multiple classes,
* which are defined inside the node typeArguments.
*/
export function modelBehaviors (node: ExpressionWithTypeArguments): model.Inherits {
const generics = node.getTypeArguments().map(node => modelType(node))
return {
type: {
name: node.getExpression().getText(),
namespace: getNameSpace(node)
},
...(generics.length > 0 && { generics })
}
}
/**
* Generics are compiles as TypeParameterDeclarations by TypeScript,
* but all we really need is the name of the parameter, that we will
* use as generic. This method given a TypeParameterDeclaration node
* will return its name as a string.
*/
export function modelGenerics (node: TypeParameterDeclaration): string {
return node.getName()
}
/**
* Given a EnumDeclaration node, returns an Enum strcture.
* An enum can be visited with `forEachChild`, but it will
* become more complex to handle, as one of the children is the enum
* name as well. An EnumDeclaration node has a getMembers method
* which returns an array that only contains the member of the Enum.
*/
export function modelEnumDeclaration (declaration: EnumDeclaration): model.Enum {
const type: model.Enum = {
specLocation: sourceLocation(declaration),
name: {
name: declaration.getName(),
namespace: getNameSpace(declaration)
},
kind: 'enum',
members: declaration.getMembers()
.map(m => {
// names that contains `.` or `-` will be wrapped inside single quotes
const name = m.getName().replace(/'/g, '')
const member: model.EnumMember = {
name: name
}
const value = m.getValue()
if (value != null && (typeof value === 'string')) {
member.name = value
member.codegenName = name
}
hoistEnumMemberAnnotations(member, m.getJsDocs())
return member
})
}
const tags = parseJsDocTags(declaration.getJsDocs())
if (typeof tags.non_exhaustive === 'string') {
type.isOpen = true
}
if (typeof tags.es_quirk === 'string') {
type.esQuirk = tags.es_quirk
}
return type
}
/**
* Given a TypeAliasDeclaration node, returns a TypeAlias structure.
* A TypeAliasDeclaration has two main properties, `name` and `type`.
* The first one is the alias name, the second one is the type that
* still needs to be modeled.
*/
export function modelTypeAlias (declaration: TypeAliasDeclaration): model.TypeAlias {
const type = declaration.getTypeNode()
assert(declaration, type != null, 'Type alias without a referenced type')
const generics = declaration.getTypeParameters().map(typeParameter => ({
name: modelGenerics(typeParameter),
namespace: getNameSpace(typeParameter)
}))
const alias = modelType(type)
const typeAlias: model.TypeAlias = {
specLocation: sourceLocation(declaration),
name: {
name: declaration.getName(),
namespace: getNameSpace(declaration)
},
kind: 'type_alias',
type: alias,
...(generics.length > 0 && { generics })
}
if (alias.kind === 'union_of') {
const variants = parseVariantsTag(declaration.getJsDocs())
if (variants != null) {
assert(
declaration.getJsDocs(),
variants.kind === 'internal_tag' || variants.kind === 'external_tag',
'Type Aliases can only have internal or external variants'
)
typeAlias.variants = variants
}
}
hoistTypeAnnotations(typeAlias, declaration.getJsDocs())
return typeAlias
}
/**
* Given a PropertySignature or PropertyDeclaration node, returns a Property strcture.
* A property signature/declaration has two main properties, `symbol` and `type`.
* The first one is the property name, the second one is the type that
* still needs to be modeled.
*/
export function modelProperty (declaration: PropertySignature | PropertyDeclaration): model.Property {
const type = declaration.getTypeNode()
assert(declaration, type != null, 'Type alias without a referenced type')
// names that contains `.` or `-` will be wrapped inside single quotes
const name = declaration.getName().replace(/'/g, '')
const property = {
name,
required: !declaration.hasQuestionToken(),
type: modelType(type)
}
hoistPropertyAnnotations(property, declaration.getJsDocs())
return property
}
/**
* Pulls @deprecated from types and properties
*/
function setDeprecated (type: model.BaseType | model.Property | model.EnumMember, tags: Record<string, string>, jsDocs: JSDoc[]): void {
if (tags.deprecated !== undefined) {
const [version, ...description] = tags.deprecated.split(' ')
assert(jsDocs, semver.valid(version), 'Invalid semver value')
type.deprecation = { version, description: description.join(' ') }
}
delete tags.deprecated
}
/**
* Validates ands sets jsDocs tags used throughout the input specification
*/
function setTags<TType extends model.BaseType | model.Property | model.EnumMember> (
jsDocs: JSDoc[],
type: TType,
tags: Record<string, string>,
validTags: string[],
setter: ((tags: Record<string, string>, tag: string, value: string) => void)
): void {
if (Object.keys(tags).length === 0) return
setDeprecated(type, tags, jsDocs)
const badTags = Object.keys(tags).filter(tag => !validTags.includes(tag))
assert(
jsDocs,
badTags.length === 0,
`'${getName(type)}' has the following unknown annotations: ${badTags.join(', ')}`
)
for (const tag of validTags) {
if (tag === 'behavior') continue
if (tags[tag] !== undefined) {
setter(tags, tag, tags[tag])
}
}
function getName (type: TType): string {
if (typeof type.name === 'string') {
return type.name
} else {
return type.name.name
}
}
}
/** Lifts jsDoc type annotations to request properties */
export function hoistRequestAnnotations (
request: model.Request, jsDocs: JSDoc[], mappings: Record<string, model.Endpoint>, response: model.TypeName | null
): void {
const knownRequestAnnotations = [
'rest_spec_name', 'behavior', 'class_serializer', 'index_privileges', 'cluster_privileges', 'doc_id', 'availability'
]
// in most of the cases the jsDocs comes in a single block,
// but it can happen that the user defines multiple single line jsDoc.
// We want to enforce a single jsDoc block.
assert(jsDocs, jsDocs.length < 2, 'Use a single multiline jsDoc block instead of multiple single line blocks')
if (jsDocs.length === 1) {
const description = jsDocs[0].getDescription()
if (description.length > 0) request.description = description.trim().replace(/\r/g, '')
}
const tags = parseJsDocTags(jsDocs)
const apiName = tags.rest_spec_name
// TODO (@typescript-eslint/strict-boolean-expressions) is no fun
assert(jsDocs, apiName !== '' && apiName !== null && apiName !== undefined,
`Request ${request.name.name} does not declare the @rest_spec_name to link back to`)
const endpoint = mappings[apiName]
assert(jsDocs, endpoint != null, `The api '${apiName}' does not exists, did you mean '${closest(apiName, Object.keys(mappings))}'?`)
endpoint.request = request.name
endpoint.response = response
// This ensures the tags from request end up on the endpoint
setTags(jsDocs, request, tags, knownRequestAnnotations, (tags, tag, value) => {
if (tag.endsWith('_serializer')) {
} else if (tag === 'rest_spec_name') {
} else if (tag === 'index_privileges') {
const privileges = [
'all', 'auto_configure', 'create', 'create_doc', 'create_index', 'delete', 'delete_index', 'index',
'maintenance', 'manage', 'manage_follow_index', 'manage_ilm', 'manage_leader_index', 'monitor',
'read', 'read_cross_cluster', 'view_index_metadata', 'write'
]
const values = parseCommaSeparated(value)
for (const v of values) {
assert(jsDocs, privileges.includes(v), `The index privilege '${v}' does not exists.`)
}
endpoint.privileges = endpoint.privileges ?? {}
endpoint.privileges.index = values
} else if (tag === 'cluster_privileges') {
const privileges = [
'all', 'cancel_task', 'create_snapshot', 'grant_api_key', 'manage', 'manage_api_key', 'manage_ccr',
'manage_enrich', 'manage_ilm', 'manage_index_templates', 'manage_ingest_pipelines', 'manage_logstash_pipelines',
'manage_ml', 'manage_oidc', 'manage_own_api_key', 'manage_pipeline', 'manage_rollup', 'manage_saml',
'manage_security', 'manage_service_account', 'manage_slm', 'manage_token', 'manage_transform', 'manage_user_profile',
'manage_watcher', 'monitor', 'monitor_ml', 'monitor_rollup', 'monitor_snapshot', 'monitor_text_structure',
'monitor_transform', 'monitor_watcher', 'read_ccr', 'read_ilm', 'read_pipeline', 'read_security', 'read_slm', 'transport_client'
]
const values = parseCommaSeparated(value)
for (const v of values) {
assert(jsDocs, privileges.includes(v), `The cluster privilege '${v}' does not exists.`)
}
endpoint.privileges = endpoint.privileges ?? {}
endpoint.privileges.cluster = values
} else if (tag === 'doc_id') {
assert(jsDocs, value.trim() !== '', `Request ${request.name.name}'s @doc_id is cannot be empty`)
endpoint.docId = value.trim()
const docUrl = docIds.find(entry => entry[0] === value.trim())
assert(jsDocs, docUrl != null, `The @doc_id '${value.trim()}' is not present in _doc_ids/table.csv`)
endpoint.docUrl = docUrl[1].replace(/\r/g, '')
} else if (tag === 'availability') {
// The @availability jsTag is different than most because it allows
// multiple values within the same docstring, hence needing to parse
// the values again in order to preserve multiple values.
const jsDocsMulti = parseJsDocTagsAllowDuplicates(jsDocs)
const availabilities = parseAvailabilityTags(jsDocs, jsDocsMulti.availability)
// Apply the availabilities to the Endpoint.
for (const [availabilityName, availabilityValue] of Object.entries(availabilities)) {
endpoint.availability[availabilityName] = availabilityValue
// Backfilling deprecated fields on an endpoint.
if (availabilityName === 'stack') {
if (availabilityValue.since !== undefined) {
endpoint.since = availabilityValue.since
}
if (availabilityValue.stability !== undefined) {
endpoint.stability = availabilityValue.stability
}
if (availabilityValue.visibility !== undefined) {
endpoint.visibility = availabilityValue.visibility
}
if (availabilityValue.featureFlag !== undefined) {
endpoint.featureFlag = availabilityValue.featureFlag
}
}
}
} else {
assert(jsDocs, false, `Unhandled tag: '${tag}' with value: '${value}' on request ${request.name.name}`)
}
})
}
/** Lifts jsDoc type annotations to fixed properties on Type */
export function hoistTypeAnnotations (type: model.TypeDefinition, jsDocs: JSDoc[]): void {
// in most of the cases the jsDocs comes in a single block,
// but it can happen that the user defines multiple single line jsDoc.
// We want to enforce a single jsDoc block.
assert(jsDocs, jsDocs.length < 2, 'Use a single multiline jsDoc block instead of multiple single line blocks')
const validTags = ['class_serializer', 'doc_url', 'doc_id', 'behavior', 'variants', 'variant', 'shortcut_property',
'codegen_names', 'non_exhaustive', 'es_quirk']
const tags = parseJsDocTags(jsDocs)
if (jsDocs.length === 1) {
const description = jsDocs[0].getDescription()
if (description.length > 0) type.description = description.trim().replace(/\r/g, '')
}
setTags(jsDocs, type, tags, validTags, (tags, tag, value) => {
if (tag === 'stability') {
} else if (tag.endsWith('_serializer')) {
} else if (tag === 'shortcut_property') {
if (type.kind === 'interface') {
type.shortcutProperty = value
} else {
assert(jsDocs, false, 'Request and Responses cannot have @shortcut_property')
}
} else if (tag === 'variants') {
} else if (tag === 'variant') {
} else if (tag === 'non_exhaustive') {
assert(jsDocs, typeof tags.variants === 'string', '@non_exhaustive only applies to enums and @variants')
} else if (tag === 'doc_url') {
assert(jsDocs, isValidUrl(value), '@doc_url is not a valid url')
type.docUrl = value.replace(/\r/g, '')
} else if (tag === 'doc_id') {
assert(jsDocs, value.trim() !== '', `Type ${type.name.namespace}.${type.name.name}'s @doc_id cannot be empty`)
type.docId = value.trim()
const docUrl = docIds.find(entry => entry[0] === value.trim())
assert(jsDocs, docUrl != null, `The @doc_id '${value.trim()}' is not present in _doc_ids/table.csv`)
type.docUrl = docUrl[1].replace(/\r/g, '')
} else if (tag === 'codegen_names') {
type.codegenNames = parseCommaSeparated(value)
assert(jsDocs,
type.kind === 'type_alias' && type.type.kind === 'union_of' && type.type.items.length === type.codegenNames.length,
'@codegen_names must have the number of items as the union definition'
)
} else if (tag === 'es_quirk') {
type.esQuirk = value
} else {
assert(jsDocs, false, `Unhandled tag: '${tag}' with value: '${value}' on type ${type.name.name}`)
}
})
}
/** Lifts jsDoc type annotations to fixed properties on Property */
function hoistPropertyAnnotations (property: model.Property, jsDocs: JSDoc[]): void {
// in most of the cases the jsDocs comes in a single block,
// but it can happen that the user defines multiple single line jsDoc.
// We want to enforce a single jsDoc block.
assert(jsDocs, jsDocs.length < 2, 'Use a single multiline jsDoc block instead of multiple single line blocks')
const validTags = ['prop_serializer', 'doc_url', 'aliases', 'codegen_name', 'server_default',
'variant', 'doc_id', 'es_quirk', 'availability']
const tags = parseJsDocTags(jsDocs)
if (jsDocs.length === 1) {
const description = jsDocs[0].getDescription()
if (description.length > 0) property.description = description.trim().replace(/\r/g, '')
}
if (tags.doc_id != null) {
assert(
jsDocs,
tags.doc_url == null,
'You can\'t define @doc_id and @doc_url at the same time'
)
}
setTags(jsDocs, property, tags, validTags, (tags, tag, value) => {
if (tag.endsWith('_serializer')) {
} else if (tag === 'aliases') {
property.aliases = parseCommaSeparated(value)
} else if (tag === 'codegen_name') {
property.codegenName = value
} else if (tag === 'doc_url') {
assert(jsDocs, isValidUrl(value), '@doc_url is not a valid url')
property.docUrl = value.replace(/\r/g, '')
} else if (tag === 'availability') {
// The @availability jsTag is different than most because it allows
// multiple values within the same docstring, hence needing to parse
// the values again in order to preserve multiple values.
const jsDocsMulti = parseJsDocTagsAllowDuplicates(jsDocs)
const availabilities = parseAvailabilityTags(jsDocs, jsDocsMulti.availability)
// The absence of an 'availability' field on a property implies that
// the property is available in all flavors.
property.availability = {}
for (const [availabilityName, availabilityValue] of Object.entries(availabilities)) {
property.availability[availabilityName] = availabilityValue
// Backfilling deprecated fields on a property.
if (availabilityName === 'stack') {
if (availabilityValue.since !== undefined) {
property.since = availabilityValue.since
}
if (availabilityValue.stability !== undefined) {
property.stability = availabilityValue.stability
}
}
}
} else if (tag === 'doc_id') {
assert(jsDocs, value.trim() !== '', `Property ${property.name}'s @doc_id is cannot be empty`)
property.docId = value
const docUrl = docIds.find(entry => entry[0] === value)
if (docUrl != null) {
property.docUrl = docUrl[1].replace(/\r/g, '')
}
} else if (tag === 'server_default') {
assert(jsDocs, property.type.kind === 'instance_of' || property.type.kind === 'union_of' || property.type.kind === 'array_of', `Default values can only be configured for instance_of or union_of types, you are using ${property.type.kind}`)
assert(jsDocs, !property.required, 'Default values can only be specified on optional properties')
if (property.type.kind === 'union_of') {
let valueType = ''
if (value === 'true' || value === 'false') {
valueType = 'boolean'
} else if (!isNaN(Number(value))) {
valueType = 'number'
} else {
valueType = 'string'
}
const unionTypes = property.type.items.map(item => {
assert(jsDocs, item.kind === 'instance_of', `Default values in unions can only be configured for instance_of types, you are using ${property.type.kind}`)
if (['short', 'byte', 'integer', 'uint', 'long', 'ulong', 'float', 'double', 'Percentage'].includes(item.type.name)) {
return 'number'
}
return item.type.name
})
assert(jsDocs, unionTypes.includes(valueType), `The configured server_default value is not present in the union value: ${unionTypes.join(' | ')}`)
property.serverDefault = value
} else if (property.type.kind === 'array_of') {
try {
value = eval(value) // eslint-disable-line
} catch (err) {
assert(jsDocs, false, 'The default value is not formatted properly')
}
assert(jsDocs, Array.isArray(value), 'The default value should be an array')
property.serverDefault = value
} else {
switch (property.type.type.name) {
case 'boolean':
assert(jsDocs, value === 'true' || value === 'false', `The default value for ${property.name} should be a boolean`)
property.serverDefault = value === 'true'
break
case 'number':
case 'short':
case 'byte':
case 'integer':
case 'uint':
case 'long':
case 'ulong':
case 'float':
case 'double':
case 'Percentage':
assert(jsDocs, !isNaN(Number(value)), `The default value for ${property.name} should be a number`)
property.serverDefault = Number(value)
break
default:
property.serverDefault = value
}
}
} else if (tag === 'variant') {
assert(jsDocs, value === 'container_property', `Unknown 'variant' value '${value}' on property ${property.name}`)
property.containerProperty = true
} else if (tag === 'es_quirk') {
property.esQuirk = value
} else {
assert(jsDocs, false, `Unhandled tag: '${tag}' with value: '${value}' on property ${property.name}`)
}
})
}
/** Lifts jsDoc type annotations to fixed properties on Property */
function hoistEnumMemberAnnotations (member: model.EnumMember, jsDocs: JSDoc[]): void {
// in most of the cases the jsDocs comes in a single block,
// but it can happen that the user defines multiple single line jsDoc.
// We want to enforce a single jsDoc block.
assert(jsDocs, jsDocs.length < 2, 'Use a single multiline jsDoc block instead of multiple single line blocks')
const validTags = ['obsolete', 'obsolete_description', 'codegen_name', 'availability', 'aliases']
const tags = parseJsDocTags(jsDocs)
if (jsDocs.length === 1) {
const description = jsDocs[0].getDescription()
if (description.length > 0) member.description = description.trim().replace(/\r/g, '')
}
setTags(jsDocs, member, tags, validTags, (tags, tag, value) => {
if (tag === 'codegen_name') {
member.codegenName = value
} else if (tag === 'aliases') {
member.aliases = parseCommaSeparated(value)
} else if (tag === 'availability') {
// The @availability jsTag is different than most because it allows
// multiple values within the same docstring, hence needing to parse
// the values again in order to preserve multiple values.
const jsDocsMulti = parseJsDocTagsAllowDuplicates(jsDocs)
const availabilities = parseAvailabilityTags(jsDocs, jsDocsMulti.availability)
// The absence of an 'availability' field on a property implies that
// the property is available in all flavors.
member.availability = {}
for (const [availabilityName, availabilityValue] of Object.entries(availabilities)) {
member.availability[availabilityName] = availabilityValue
// Backfilling deprecated fields on a property.
if (availabilityName === 'stack') {
if (availabilityValue.since !== undefined) {
member.since = availabilityValue.since
}
}
}
} else {
assert(jsDocs, false, `Unhandled tag: '${tag}' with value: '${value}' on enum member ${member.name}`)
}
})
}
/**
* Returns true if the passed HeritageClause node contains
* a single type that is a known behavior.
*/
export function isKnownBehavior (node: HeritageClause | ExpressionWithTypeArguments): boolean {
if (Node.isHeritageClause(node)) {
if (node.getTypeNodes().length !== 1) return false
for (const knownBehavior of knownBehaviors) {
if (node.getTypeNodes()[0].getExpression().getText() === knownBehavior) {
return true
}
}
} else {
for (const knownBehavior of knownBehaviors) {
if (node.getExpression().getText() === knownBehavior) {
return true
}
}
}
return false
}
/**
* Given a Node, it returns its namespace computed from the symbol declarations.
* If it can't compute it, defaults to `_builtins`.
*/
export function getNameSpace (node: Node): string {
// if the node we are checking is a TypeReferenceNode,
// then we can get the codegen_name and find where
// it has been defined and compute the namespace from that.
if (Node.isTypeReference(node)) {
const identifier = node.getTypeName()
if (Node.isIdentifier(identifier)) {
const name = identifier.compilerNode.escapedText as string
// the Array object is defined by TypeScript
if (name === 'Array') return '_builtins'
const definition = identifier.getDefinitions()[0]
assert(identifier, definition != null, 'Cannot find codegen_name')
return cleanPath(definition.getSourceFile().getFilePath())
}
}
// if the node we are checking is a TypeAliasDeclaration
// then we can directly get the source file as we are visiting
// its definition, and from it compute the namespace.
if (Node.isTypeAliasDeclaration(node)) {
return cleanPath(node.getSourceFile().getFilePath())
}
const declaration = node.getType().getSymbol()?.getDeclarations()[0]
if (declaration == null) {
return '_builtins'
}
return cleanPath(declaration.getSourceFile().getFilePath())
function cleanPath (path: string): string {
path = dirname(path)
.replace(/.*[/\\]specification[^/\\]*[/\\]?/, '')
.replace(/[/\\]/g, '.')
if (path === '') path = '_builtins'
return path
}
}
/**
* Given a node, it searches the node and its ancestors for behavior definitons.
* It then collects the behavior names and returns an unique array of behaviors.
* A behavior can be found in the current node or in one of the ancestors.
*/
export function getAllBehaviors (node: ClassDeclaration | InterfaceDeclaration): string[] {
const behaviors = getBehaviors(node.getHeritageClauses())
const extended = getExtended(node.getHeritageClauses()).flatMap(clause => clause.getTypeNodes())
.map(t => t.getExpression())
for (const extend of extended) {
assert(extend, Node.isReferenceFindable(extend), 'Should be a reference node')
const declaration = extend.getType().getSymbol()?.getDeclarations()[0]
assert(extend, declaration != null, `Cannot find declaration for ${extend.getText()}`)
if (Node.isClassDeclaration(declaration) || Node.isInterfaceDeclaration(declaration)) {
if (declaration.getHeritageClauses().length > 0) {
behaviors.push(...getAllBehaviors(declaration))
}
} else if (Node.isImportSpecifier(declaration)) {
const sourceFile = declaration.getImportDeclaration().getModuleSpecifierSourceFile()
assert(declaration, sourceFile != null, 'Cannot find source file')
const name = declaration.getName()
for (const declaration of [...sourceFile.getClasses(), ...sourceFile.getInterfaces()]) {
if (declaration.getName() === name && declaration.getHeritageClauses().length > 0) {
behaviors.push(...getAllBehaviors(declaration))
}
}
} else {
assert(declaration, false, `Unhandled extended declaration ${declaration?.getText() ?? ''}`)
}
}
return Array.from(new Set(behaviors))
function getExtended (clauses: HeritageClause[]): HeritageClause[] {
return clauses.filter(clause => clause.getToken() === ts.SyntaxKind.ExtendsKeyword)
}
function getBehaviors (clauses: HeritageClause[]): string[] {