-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathopenapi.ts
More file actions
547 lines (499 loc) · 18.7 KB
/
openapi.ts
File metadata and controls
547 lines (499 loc) · 18.7 KB
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
import { OpenAPIV3 } from 'openapi-types';
import { STATUS_CODES } from 'http';
import { parseCommentBlock } from './jsdoc';
import { optimize } from './optimize';
import type { Route } from './route';
import type { Schema } from './ir';
import { Block } from 'comment-parser';
export type ComponentNameMapping = Record<string, Record<string, string>>;
export function schemaToOpenAPI(
schema: Schema,
componentNameMapping?: ComponentNameMapping,
): OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject | undefined {
schema = optimize(schema);
const createOpenAPIObject = (
schema: Schema,
): OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject | undefined => {
const defaultOpenAPIObject = buildDefaultOpenAPIObject(schema);
switch (schema.type) {
case 'boolean':
case 'string':
case 'number': {
const result: any = {
type: schema.type,
...(schema.enum ? { enum: schema.enum } : {}),
...defaultOpenAPIObject,
};
if (schema.enum && schema.enumDescriptions) {
result['x-enumDescriptions'] = schema.enumDescriptions;
}
if (schema.enum && schema.enumsDeprecated) {
result['x-enumsDeprecated'] = schema.enumsDeprecated;
}
return result;
}
case 'integer': {
const result: any = {
type: 'number',
...(schema.enum ? { enum: schema.enum } : {}),
...defaultOpenAPIObject,
};
if (schema.enum && schema.enumDescriptions) {
result['x-enumDescriptions'] = schema.enumDescriptions;
}
if (schema.enum && schema.enumsDeprecated) {
result['x-enumsDeprecated'] = schema.enumsDeprecated;
}
return result;
}
case 'null':
// TODO: OpenAPI v3 does not have an explicit null type, is there a better way to represent this?
// Or should we just conflate explicit null and undefined properties?
return { nullable: true, enum: [] };
case 'ref':
// Resolve the component name using the mapping (handles collisions)
const resolvedName =
componentNameMapping?.[schema.location]?.[schema.name] ?? schema.name;
// if defaultOpenAPIObject is empty, no need to wrap the $ref in an allOf array
if (Object.keys(defaultOpenAPIObject).length === 0) {
return { $ref: `#/components/schemas/${resolvedName}` };
}
return {
allOf: [{ $ref: `#/components/schemas/${resolvedName}` }],
...defaultOpenAPIObject,
};
case 'array':
const innerSchema = schemaToOpenAPI(schema.items, componentNameMapping);
if (innerSchema === undefined) {
return undefined;
}
const { example, minItems, maxItems, ...rest } = defaultOpenAPIObject;
const isArrayExample = example && Array.isArray(example);
const siblings = {
...rest,
...(!isArrayExample && example ? { example } : {}),
};
// Handle case where innerSchema is a $ref with siblings
const wrappedInnerSchema =
'$ref' in innerSchema && Object.keys(siblings).length > 0
? // When there's a $ref with siblings, we need to wrap it in allOf to preserve other properties
{
allOf: [innerSchema],
}
: {
...innerSchema,
};
const items = {
...wrappedInnerSchema,
...siblings,
};
return {
type: 'array',
...(minItems ? { minItems } : {}),
...(maxItems ? { maxItems } : {}),
...(isArrayExample ? { example } : {}),
items,
};
case 'object':
return {
type: 'object',
...defaultOpenAPIObject,
properties: Object.entries(schema.properties).reduce(
(acc, [name, prop]) => {
const innerSchema = schemaToOpenAPI(prop, componentNameMapping);
if (innerSchema === undefined) {
return acc;
}
return { ...acc, [name]: innerSchema };
},
{} as Record<string, OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject>,
),
...(schema.required.length > 0 ? { required: schema.required } : {}),
};
case 'intersection':
return {
allOf: schema.schemas.flatMap((s) => {
const innerSchema = schemaToOpenAPI(s, componentNameMapping);
if (innerSchema === undefined) {
return [];
}
return [innerSchema];
}),
...defaultOpenAPIObject,
};
case 'union':
let nullable = false;
let oneOf: (OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject)[] = [];
// If there are two schemas and one of the schemas is undefined, that means the union is a case of `optional` type
const undefinedSchema = schema.schemas.find((s) => s.type === 'undefined');
const nonUndefinedSchema = schema.schemas.find((s) => s.type !== 'undefined');
// If nullSchema exists, that means that the union is also nullable
const nullSchema = schema.schemas.find((s) => s.type === 'null');
// If any schema exists and it is in union with another schema - we can remove the any schema as an optimization
const unknownSchema = schema.schemas.find((s) => s.type === 'any');
// and we can just return the other schema (while attaching the comment to that schema)
const isOptional =
schema.schemas.length >= 2 && undefinedSchema && nonUndefinedSchema;
if (isOptional) {
return schemaToOpenAPI(
{
...nonUndefinedSchema,
comment: schema.comment,
...(nullSchema ? { nullable: true } : {}),
},
componentNameMapping,
);
}
// This is an edge case for something like this -> t.union([WellDefinedCodec, t.unknown])
// It doesn't make sense to display the unknown codec in the OpenAPI spec so this essentially strips it out of the generation
// so that we don't present useless information to the user
const isUnionWithUnknown = schema.schemas.length >= 2 && unknownSchema;
if (isUnionWithUnknown) {
const nonUnknownSchemas = schema.schemas.filter((s) => s.type !== 'any');
if (nonUnknownSchemas.length === 1 && nonUnknownSchemas[0] !== undefined) {
return schemaToOpenAPI(
{
...nonUnknownSchemas[0],
comment: schema.comment,
...(nullSchema ? { nullable: true } : {}),
},
componentNameMapping,
);
} else if (nonUnknownSchemas.length > 1) {
return schemaToOpenAPI(
{
type: 'union',
schemas: nonUnknownSchemas,
comment: schema.comment,
...(nullSchema ? { nullable: true } : {}),
},
componentNameMapping,
);
}
}
for (const s of schema.schemas) {
if (s.type === 'null') {
nullable = true;
continue;
}
const innerSchema = schemaToOpenAPI(s, componentNameMapping);
if (innerSchema !== undefined) {
oneOf.push(innerSchema);
}
}
if (oneOf.length === 0) {
return undefined;
} else if (oneOf.length === 1) {
const singleSchema = oneOf[0];
if (singleSchema === undefined) {
return undefined;
}
// Check if the schema is a $ref
if ('$ref' in singleSchema) {
// OpenAPI spec doesn't allow $ref properties to have siblings, so they're wrapped in an 'allOf' array
return {
...(nullable ? { nullable } : {}),
allOf: [singleSchema],
...defaultOpenAPIObject,
};
} else {
return {
...(nullable ? { nullable } : {}),
...singleSchema,
...defaultOpenAPIObject,
};
}
} else {
return { ...(nullable ? { nullable } : {}), oneOf, ...defaultOpenAPIObject };
}
case 'record':
const additionalProperties = schemaToOpenAPI(
schema.codomain,
componentNameMapping,
);
if (additionalProperties === undefined) return undefined;
if (schema.domain !== undefined) {
const keys = schemaToOpenAPI(
schema.domain,
componentNameMapping,
) as OpenAPIV3.SchemaObject;
if (keys.type === 'string' && keys.enum !== undefined) {
const properties = keys.enum.reduce((acc, key) => {
return { ...acc, [key]: additionalProperties };
}, {});
return {
type: 'object',
properties,
...defaultOpenAPIObject,
required: keys.enum,
};
}
}
return {
type: 'object',
additionalProperties,
...defaultOpenAPIObject,
};
case 'undefined':
return undefined;
case 'any':
return { ...defaultOpenAPIObject };
default:
return {};
}
};
/**
* This function will return the field value parsed as the type of the schema. i.e. if the schema is a number, it will return the field as a JS number.
*
* @param schema A schema object
* @param fieldValue The value to parse
* @returns the parsed value
*/
const parseField = (schema: Schema, fieldValue: string): any => {
if (schema.type === 'number' || schema.type === 'integer') {
return Number(fieldValue);
} else if (schema.type === 'boolean') {
return fieldValue === 'true';
} else if (schema.type === 'null') {
return null;
} else if (schema.type === 'string') {
// Remove extraneous double quotes around the fieldValue
return fieldValue?.replace(/^"(.*)"$/, '$1');
} else {
return fieldValue;
}
};
function buildDefaultOpenAPIObject(schema: Schema): OpenAPIV3.SchemaObject {
const emptyBlock: Block = { description: '', tags: [], source: [], problems: [] };
const jsdoc = parseCommentBlock(schema.comment ?? emptyBlock);
const defaultValue = jsdoc?.tags?.default ?? schema.default;
const example = jsdoc?.tags?.example ?? schema.example;
const maxLength = jsdoc?.tags?.maxLength ?? schema.maxLength;
const minLength = jsdoc?.tags?.minLength ?? schema.minLength;
const pattern = jsdoc?.tags?.pattern ?? schema.pattern;
const minimum = jsdoc?.tags?.minimum ?? schema.maximum;
const maximum = jsdoc?.tags?.maximum ?? schema.minimum;
const minItems = jsdoc?.tags?.minItems ?? schema.minItems;
const maxItems = jsdoc?.tags?.maxItems ?? schema.maxItems;
const minProperties = jsdoc?.tags?.minProperties ?? schema.minProperties;
const maxProperties = jsdoc?.tags?.maxProperties ?? schema.maxProperties;
const exclusiveMinimum = jsdoc?.tags?.exclusiveMinimum ?? schema.exclusiveMinimum;
const exclusiveMaximum = jsdoc?.tags?.exclusiveMaximum ?? schema.exclusiveMaximum;
const multipleOf = jsdoc?.tags?.multipleOf ?? schema.multipleOf;
const uniqueItems = jsdoc?.tags?.uniqueItems ?? schema.uniqueItems;
const readOnly = jsdoc?.tags?.readOnly ?? schema.readOnly;
const writeOnly = jsdoc?.tags?.writeOnly ?? schema.writeOnly;
const format = jsdoc?.tags?.format ?? schema.format ?? schema.format;
const title = jsdoc?.tags?.title ?? schema.title;
const keys = Object.keys(jsdoc?.tags || {});
const deprecated = keys.includes('deprecated') || !!schema.deprecated;
const isPrivate = keys.includes('private');
const isPublic = keys.includes('public');
if (isPrivate && isPublic) {
throw new Error('Cannot use both @public and @private on the same schema field');
}
const description = schema.comment?.description ?? schema.description;
const defaultOpenAPIObject = {
...(defaultValue ? { default: parseField(schema, defaultValue) } : {}),
...(deprecated ? { deprecated: true } : {}),
...(description ? { description } : {}),
...(example ? { example: parseField(schema, example) } : {}),
...(maxLength ? { maxLength: Number(maxLength) } : {}),
...(minLength ? { minLength: Number(minLength) } : {}),
...(pattern ? { pattern } : {}),
...(minimum ? { minimum: Number(minimum) } : {}),
...(maximum ? { maximum: Number(maximum) } : {}),
...(minItems ? { minItems: Number(minItems) } : {}),
...(maxItems ? { maxItems: Number(maxItems) } : {}),
...(minProperties ? { minProperties: Number(minProperties) } : {}),
...(maxProperties ? { maxProperties: Number(maxProperties) } : {}),
...(exclusiveMinimum ? { exclusiveMinimum: true } : {}),
...(exclusiveMaximum ? { exclusiveMaximum: true } : {}),
...(multipleOf ? { multipleOf: Number(multipleOf) } : {}),
...(uniqueItems ? { uniqueItems: true } : {}),
...(readOnly ? { readOnly: true } : {}),
...(writeOnly ? { writeOnly: true } : {}),
...(format ? { format } : {}),
...(title ? { title } : {}),
...(isPrivate ? { 'x-internal': true } : isPublic ? { 'x-internal': false } : {}),
};
return defaultOpenAPIObject;
}
let openAPIObject = createOpenAPIObject(schema);
return openAPIObject;
}
function routeToOpenAPI(
route: Route,
componentNameMapping?: ComponentNameMapping,
): [string, string, OpenAPIV3.OperationObject] {
const jsdoc = route.comment !== undefined ? parseCommentBlock(route.comment) : {};
const operationId = jsdoc.tags?.operationId;
const tag = jsdoc.tags?.tag ?? '';
const isInternal = jsdoc.tags?.private !== undefined;
const isPublic = jsdoc.tags?.public !== undefined;
if (isInternal && isPublic) {
throw new Error(
`Cannot use both @public and @private on route ${route.method.toUpperCase()} ${route.path}`,
);
}
const isUnstable = jsdoc.tags?.unstable !== undefined;
const example = jsdoc.tags?.example;
const knownTags = new Set([
'operationId',
'summary',
'private',
'public',
'unstable',
'example',
'tag',
'description',
'url',
]);
const unknownTagsObject = Object.entries(jsdoc.tags ?? {}).reduce(
(acc, [key, value]) => {
if (!knownTags.has(key)) {
return { ...acc, [key]: value || true };
}
return acc;
},
{},
);
const requestBody =
route.body === undefined
? {}
: {
requestBody: {
content: {
'application/json': {
schema: schemaToOpenAPI(route.body, componentNameMapping),
},
},
},
};
return [
route.path,
route.method.toLowerCase(),
{
...(jsdoc.summary !== undefined ? { summary: jsdoc.summary } : {}),
...(jsdoc.description !== undefined ? { description: jsdoc.description } : {}),
...(operationId !== undefined ? { operationId } : {}),
...(tag !== '' ? { tags: [tag] } : {}),
...(isInternal
? { 'x-internal': true }
: isPublic
? { 'x-internal': false }
: {}),
...(isUnstable ? { 'x-unstable': true } : {}),
...(Object.keys(unknownTagsObject).length > 0
? { 'x-unknown-tags': unknownTagsObject }
: {}),
parameters: route.parameters.map((p) => {
// Array types not allowed here
const schema = schemaToOpenAPI(p.schema, componentNameMapping);
if (schema && 'description' in schema) {
delete schema.description;
}
const hasInternalFlag = schema && 'x-internal' in schema;
const internalValue = hasInternalFlag ? schema['x-internal'] : undefined;
if (hasInternalFlag) {
delete schema['x-internal'];
}
return {
name: p.name,
...(p.schema?.comment?.description !== undefined
? { description: p.schema.comment.description }
: {}),
in: p.type,
...(hasInternalFlag ? { 'x-internal': internalValue } : {}),
...(p.required ? { required: true } : {}),
...(p.explode ? { style: 'form', explode: true } : {}),
schema: schema as any, // TODO: Something to disallow arrays
};
}),
...requestBody,
responses: Object.entries(route.response).reduce((acc, [code, response]) => {
const description = STATUS_CODES[code] ?? '';
return {
...acc,
[Number(code)]: {
description,
content: {
'application/json': {
schema: schemaToOpenAPI(response, componentNameMapping),
...(example !== undefined ? { example } : undefined),
},
},
},
};
}, {}),
},
];
}
export function convertRoutesToOpenAPI(
info: OpenAPIV3.InfoObject,
servers: OpenAPIV3.ServerObject[],
routes: Route[],
schemas: Record<string, Schema>,
componentNameMapping?: ComponentNameMapping,
): OpenAPIV3.Document {
const paths = routes.reduce(
(acc, route) => {
const [path, method, pathItem] = routeToOpenAPI(route, componentNameMapping);
let pathObject = acc[path] ?? {};
pathObject[method] = pathItem;
return { ...acc, [path]: pathObject };
},
{} as Record<string, Record<string, OpenAPIV3.PathItemObject>>,
);
const openapiSchemas = Object.entries(schemas).reduce(
(acc, [name, schema]) => {
const openapiSchema = schemaToOpenAPI(schema, componentNameMapping);
if (openapiSchema === undefined) {
return acc;
} else if ('$ref' in openapiSchema) {
return {
...acc,
[name]: {
allOf: [{ title: name }, openapiSchema],
},
};
} else {
return {
...acc,
[name]: {
title: name,
...openapiSchema,
},
};
}
},
{} as Record<string, OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject>,
);
const sortedPaths = Object.keys(paths)
.sort((a, b) => a.localeCompare(b))
.reduce(
(acc, key) => {
const sortedMethods = Object.keys(paths[key]!)
.sort((a, b) => a.localeCompare(b))
.reduce(
(methodAcc, methodKey) => {
methodAcc[methodKey] = paths[key]![methodKey]!;
return methodAcc;
},
{} as Record<string, OpenAPIV3.PathItemObject>,
);
acc[key] = sortedMethods;
return acc;
},
{} as Record<string, OpenAPIV3.PathItemObject>,
);
return {
openapi: '3.0.3',
info,
...(servers.length > 0 ? { servers } : {}),
paths: sortedPaths,
components: {
schemas: openapiSchemas,
},
};
}