forked from elastic/elasticsearch-specification
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
331 lines (292 loc) · 12.7 KB
/
index.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
/*
* 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 @typescript-eslint/restrict-template-expressions */
import assert from 'assert'
import { writeFileSync, readFileSync } from 'fs'
import { join } from 'path'
import * as M from '../compiler/model/metamodel'
const model: M.Model = JSON.parse(readFileSync(join(__dirname, '..', 'output', 'schema', 'schema.json'), 'utf8'))
// We don't skip `CommonQueryParameters` and `CommonCatQueryParameters`
// behaviors because we ue them for sharing common query parameters
// among most requests.
const skipBehaviors = [
'ArrayResponseBase',
'EmptyResponseBase',
'AdditionalProperties'
]
let definitions = `/*
* 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.
*/
`
for (const type of model.types) {
definitions += buildType(type) + '\n'
}
writeFileSync(
join(__dirname, '..', 'output', 'typescript', 'types.ts'),
definitions,
'utf8'
)
function buildType (type: M.TypeDefinition): string {
switch (type.kind) {
case 'interface':
return buildInterface(type)
case 'request':
return buildRequest(type)
case 'enum':
return buildEnum(type)
case 'type_alias':
return buildTypeAlias(type)
}
}
// This function always returns a string, unless we are visitin
// a literal_value, which can also be a number or boolean.
function buildValue (type: M.ValueOf, openGenerics?: string[]): string | number | boolean {
switch (type.kind) {
case 'instance_of':
if (Array.isArray(openGenerics) && openGenerics.includes(type.type.name)) {
return type.type.name
}
return `${createName(type.type)}${buildGenerics(type.generics, openGenerics)}`
case 'array_of':
return type.value.kind === 'union_of'
? `(${buildValue(type.value, openGenerics)})[]`
: `${buildValue(type.value, openGenerics)}[]`
case 'union_of':
return type.items.map(t => buildValue(t, openGenerics)).join(' | ')
case 'dictionary_of':
return `Record<${buildValue(type.key, openGenerics)}, ${buildValue(type.value, openGenerics)}>`
case 'user_defined_value':
return 'any'
case 'literal_value':
return typeof type.value === 'string' ? `'${type.value}'` : type.value
}
}
function buildGenerics (types: M.ValueOf[] | M.TypeName[] | undefined, openGenerics?: string[], noDefault = false): string {
if (!Array.isArray(types) || types.length === 0) return ''
return `<${types.map(buildGeneric).join(', ')}>`
// generics can either be a value/instance_of or a named generics
function buildGeneric (type: M.ValueOf | M.TypeName): string | number | boolean {
if (isTypeName(type)) {
return noDefault ? type.name : `${type.name} = unknown`
} else {
if (type.kind === 'instance_of' && Array.isArray(openGenerics) && openGenerics.includes(type.type.name)) {
return type.type.name
}
return buildValue(type, openGenerics)
}
}
function isTypeName (type: any): type is M.TypeName {
return typeof type.name === 'string' && typeof type.namespace === 'string'
}
}
function buildInherits (type: M.Interface | M.Request, openGenerics?: string[]): string {
const inherits = (type.inherits != null ? [type.inherits] : []).filter(type => !skipBehaviors.includes(type.type.name))
const interfaces = (type.implements ?? []).filter(type => !skipBehaviors.includes(type.type.name))
const behaviors = (type.behaviors ?? []).filter(type => !skipBehaviors.includes(type.type.name))
const extendAll = inherits.concat(interfaces).concat(behaviors)
if (extendAll.length === 0) return ''
return ` extends ${extendAll.map(buildInheritType).join(', ')}`
function buildInheritType (type: M.Inherits): string {
return `${createName(type.type)}${buildGenerics(type.generics, openGenerics)}`
}
}
function buildInterface (type: M.Interface): string {
if (implementsBehavior(type)) {
return buildBehaviorInterface(type)
}
const openGenerics = type.generics?.map(t => t.name) ?? []
let code = `export interface ${createName(type.name)}${buildGenerics(type.generics, openGenerics)}${buildInherits(type, openGenerics)} {\n`
for (const property of type.properties) {
code += ` ${cleanPropertyName(property.name)}${required(property)}: ${buildValue(property.type, openGenerics)}\n`
if (Array.isArray(property.aliases)) {
for (const alias of property.aliases) {
code += ` ${cleanPropertyName(alias)}${required(property)}: ${buildValue(property.type, openGenerics)}\n`
}
}
}
code += '}\n'
return code
function required (p: M.Property): string {
return p.required ? '' : '?'
}
}
function implementsBehavior (type: M.Interface): boolean {
if (Array.isArray(type.attachedBehaviors)) {
// assume types ending with Base are abstract
// and are not the ones doing the implements
if (type.name.name.endsWith('Base')) {
return false
}
return type.attachedBehaviors.length > 0
}
return type.name.name === 'DictionaryResponseBase'
}
function buildBehaviorInterface (type: M.Interface): string {
if (Array.isArray(type.attachedBehaviors)) {
if (type.attachedBehaviors.includes('AdditionalProperties')) {
return serializeAdditionalPropertiesType(type)
}
if (type.attachedBehaviors.includes('ArrayResponseBase')) {
const behavior = lookupBehavior(type, 'ArrayResponseBase')
assert(behavior)
let generic = behavior.generics?.[0]
assert(generic?.kind === 'instance_of')
if (generic.type.name === 'TCatRecord') {
const g = type.inherits?.generics?.[0]
assert(g?.kind === 'instance_of')
generic = g
}
// In the input spec the Cat* responses are represented as an object
// that contains a `records` key, which is an array of the inherited generic.
// What ES actually sends back, is an array of the inherited generic.
return `export type ${createName(type.name)} = ${createName(generic.type)}[]\n`
}
if (type.attachedBehaviors.includes('EmptyResponseBase')) {
return `export type ${createName(type.name)} = boolean\n`
}
}
switch (type.name.name) {
case 'DictionaryResponseBase':
return `export interface DictionaryResponseBase<TKey = unknown, TValue = unknown> extends ResponseBase {
[key: string]: TValue
}\n`
default:
throw new Error(`Unknown interface ${type.name.name}`)
}
}
function serializeAdditionalPropertiesType (type: M.Interface): string {
const dictionaryOf = lookupBehavior(type, 'AdditionalProperties')
if (dictionaryOf == null) throw new Error(`Unknown implements ${type.name.name}`)
let code = `export interface ${createName(type.name)}Keys${buildGenerics(type.generics)}${buildInherits(type)} {\n`
function required (property: M.Property): string {
return property.required ? '' : '?'
}
const openGenerics = type.generics?.map(t => t.name) ?? []
for (const property of type.properties) {
code += ` ${cleanPropertyName(property.name)}${required(property)}: ${buildValue(property.type, openGenerics)}\n`
}
code += '}\n'
code += `export type ${createName(type.name)}${buildGenerics(type.generics, openGenerics)} = ${createName(type.name)}Keys${buildGenerics(type.generics, openGenerics, true)} |\n`
code += ` { ${buildIndexer(dictionaryOf, openGenerics)} }\n`
return code
function buildIndexer (type: M.Inherits, openGenerics: string[]): string {
if (!Array.isArray(type.generics)) return ''
assert(type.generics.length === 2)
return `[property: string]: ${buildGeneric(type.generics[1])}`
// generics can either be a value/instance_of or a named generics
function buildGeneric (type: M.ValueOf): string | number | boolean {
const t = typeof type === 'string' ? type : buildValue(type, openGenerics)
// indexers do not allow type aliases so here we translate known
// type aliases back to string
return t === 'AggregateName' ? 'string' : t
}
}
}
function lookupBehavior (type: M.Interface, name: string): M.Inherits | null {
if (!type.attachedBehaviors?.includes(name)) return null // eslint-disable-line
if (Array.isArray(type.behaviors)) {
const behavior = type.behaviors.find(i => i.type.name === name)
if (behavior != null) return behavior
}
if (type.inherits == null) return null
const parentType = model.types.find(t => t.name.name === type.inherits?.type.name)
if (parentType == null) return null
if (parentType.kind === 'interface') {
return lookupBehavior(parentType, name)
}
throw new Error('Should inherit from an interface')
}
function buildRequest (type: M.Request): string {
const openGenerics = type.generics?.map(t => t.name) ?? []
let code = `export interface ${createName(type.name)}${buildGenerics(type.generics, openGenerics)}${buildInherits(type, openGenerics)} {\n`
for (const property of type.path) {
code += ` ${cleanPropertyName(property.name)}${property.required ? '' : '?'}: ${buildValue(property.type, openGenerics)}\n`
}
// It might happen that the same property is present in both
// path and query parameters, we should keep only one
const pathPropertiesNames = type.path.map(property => property.name)
for (const property of type.query) {
if (pathPropertiesNames.includes(property.name)) continue
code += ` ${cleanPropertyName(property.name)}${property.required ? '' : '?'}: ${buildValue(property.type, openGenerics)}\n`
}
if ((type.body != null) && type.body.kind === 'properties') {
code += ` body${isBodyRequired() ? '' : '?'}: {\n`
for (const property of type.body.properties) {
code += ` ${cleanPropertyName(property.name)}${property.required ? '' : '?'}: ${buildValue(property.type, openGenerics)}\n`
}
code += ' }\n'
} else if (type.body != null && type.body.kind === 'value') {
code += ` body${isBodyRequired() ? '' : '?'}: ${buildValue(type.body.value, openGenerics)}\n`
}
code += '}\n'
return code
function isBodyRequired (): boolean {
for (const endpoint of model.endpoints) {
if ((endpoint.request != null) && endpoint.request.name === type.name.name) {
return endpoint.requestBodyRequired
}
}
return false
}
}
function buildEnum (type: M.Enum): string {
return `export type ${createName(type.name)} = ${type.members.map(m => `'${m.name}'`).join(' | ')}\n`
}
function buildTypeAlias (type: M.TypeAlias): string {
const openGenerics = type.generics?.map(t => t.name) ?? []
return `export type ${createName(type.name)}${buildGenerics(type.generics)} = ${buildValue(type.type, openGenerics)}\n`
}
function createName (type: M.TypeName): string {
if (type.namespace === 'internal') return type.name
const namespace = strip(type.namespace).replace(/_([a-z])/g, k => k[1].toUpperCase())
return `${namespace.split('.').map(TitleCase).join('')}${type.name}`
function strip (namespace: string): string {
if (namespace.startsWith('_global')) {
return namespace.slice(8)
}
if (namespace.includes('_types')) {
return namespace.split('.').filter(n => n !== '_types').join('.')
}
return namespace
}
function TitleCase (str: string): string {
if (str.length === 0) return ''
return str[0].toUpperCase() + str.slice(1)
}
}
function cleanPropertyName (name: string): string {
return name.includes('.') || name.includes('-') || (name.match(/^(\d|\W)/) != null)
? `'${name}'`
: name
}