-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-schema.ts
More file actions
553 lines (493 loc) · 15.9 KB
/
generate-schema.ts
File metadata and controls
553 lines (493 loc) · 15.9 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
548
549
550
551
552
553
import type { OpenAPIV3_1 } from 'openapi-types'
import type { ParameterDefinition } from './generate-interface'
import { wrapInterfaceKeyGuard } from './wrap-interface-key-guard'
/**
* Check if a schema is nullable (OpenAPI 3.0 or 3.1)
* OpenAPI 3.0: uses `nullable: true`
* OpenAPI 3.1: uses type array like `["string", "null"]`
*/
function isNullable(schema: OpenAPIV3_1.SchemaObject): boolean {
// OpenAPI 3.0 style: nullable: true
if ('nullable' in schema && schema.nullable === true) {
return true
}
// OpenAPI 3.1 style: type is an array containing "null"
if (Array.isArray(schema.type) && schema.type.includes('null')) {
return true
}
return false
}
/**
* Get the non-null type from OpenAPI 3.1 type array
* e.g., ["string", "null"] -> "string"
*/
function getNonNullType(
types: (OpenAPIV3_1.NonArraySchemaObjectType | 'array')[],
): OpenAPIV3_1.NonArraySchemaObjectType | 'array' | undefined {
return types.find((t) => t !== 'null')
}
/**
* Resolve $ref reference in OpenAPI schema
*/
function resolveSchemaRef<
T extends OpenAPIV3_1.SchemaObject | OpenAPIV3_1.ParameterObject,
>(ref: string, document: OpenAPIV3_1.Document): T | null {
if (!ref.startsWith('#/')) {
return null
}
const parts = ref.slice(2).split('/')
let current: unknown = document
for (const part of parts) {
if (current && typeof current === 'object' && part in current) {
current = (current as Record<string, unknown>)[part]
} else {
return null
}
}
if (current && typeof current === 'object' && !('$ref' in current)) {
return current as T
}
return null
}
/**
* Convert OpenAPI schema to TypeScript type representation
*/
export function getTypeFromSchema(
schema: OpenAPIV3_1.SchemaObject | OpenAPIV3_1.ReferenceObject,
document: OpenAPIV3_1.Document,
options?: {
defaultNonNullable?: boolean
},
): { type: unknown; default?: unknown } {
const defaultNonNullable = options?.defaultNonNullable ?? false
// Handle $ref
if ('$ref' in schema) {
const resolved = resolveSchemaRef<OpenAPIV3_1.SchemaObject>(
schema.$ref,
document,
)
if (resolved) {
return getTypeFromSchema(resolved, document, options)
}
return { type: 'unknown', default: undefined }
}
const schemaObj = schema as OpenAPIV3_1.SchemaObject
// Handle allOf, anyOf, oneOf
if (schemaObj.allOf) {
const types = schemaObj.allOf.map((s) =>
getTypeFromSchema(s, document, options),
)
return {
type:
types.length > 0
? types.map((t) => formatTypeValue(t.type)).join(' & ')
: 'unknown',
default: schemaObj.default,
}
}
if (schemaObj.anyOf || schemaObj.oneOf) {
const types = (schemaObj.anyOf || schemaObj.oneOf || []).map((s) =>
getTypeFromSchema(s, document, options),
)
return {
type:
types.length > 0
? `(${types.map((t) => formatTypeValue(t.type)).join(' | ')})`
: 'unknown',
default: schemaObj.default,
}
}
// Check if schema is nullable
const nullable = isNullable(schemaObj)
// Handle enum
if (schemaObj.enum) {
const enumType = schemaObj.enum.map((v) => `"${String(v)}"`).join(' | ')
return {
type: nullable ? `${enumType} | null` : enumType,
default: schemaObj.default,
}
}
// Get the actual type (handle OpenAPI 3.1 type arrays)
const actualType = Array.isArray(schemaObj.type)
? getNonNullType(schemaObj.type)
: schemaObj.type
// Handle primitive types
if (actualType === 'string') {
return {
type: nullable ? 'string | null' : 'string',
default: schemaObj.default,
}
}
if (actualType === 'number' || actualType === 'integer') {
return {
type: nullable ? 'number | null' : 'number',
default: schemaObj.default,
}
}
if (actualType === 'boolean') {
return {
type: nullable ? 'boolean | null' : 'boolean',
default: schemaObj.default,
}
}
// Handle array
if (actualType === 'array') {
const items = 'items' in schemaObj ? schemaObj.items : undefined
if (items) {
const itemType = getTypeFromSchema(items, document, options)
return {
type: nullable
? { __isArray: true, items: itemType.type, __nullable: true }
: { __isArray: true, items: itemType.type },
default: schemaObj.default,
}
}
return {
type: nullable ? 'unknown[] | null' : 'unknown[]',
default: schemaObj.default,
}
}
// Handle object
if (actualType === 'object' || schemaObj.properties) {
const props: Record<string, { type: unknown; default?: unknown }> = {}
const required = schemaObj.required || []
if (schemaObj.properties) {
for (const [key, value] of Object.entries(schemaObj.properties)) {
const propType = getTypeFromSchema(value, document, options)
// Check if property has default value
// Need to resolve $ref if present to check for default
let hasDefault = false
if ('$ref' in value) {
const resolved = resolveSchemaRef<OpenAPIV3_1.SchemaObject>(
value.$ref,
document,
)
if (resolved) {
hasDefault = resolved.default !== undefined
}
} else {
const propSchema = value as OpenAPIV3_1.SchemaObject
hasDefault = propSchema.default !== undefined
}
const isInRequired = required.includes(key)
// If defaultNonNullable is true and has default, treat as required
// Otherwise, mark as optional if not in required array
if (defaultNonNullable && hasDefault && !isInRequired) {
props[key] = propType
} else if (!isInRequired) {
props[`${key}?`] = propType
} else {
props[key] = propType
}
}
}
// Handle additionalProperties
if (schemaObj.additionalProperties) {
if (schemaObj.additionalProperties === true) {
props['[key: string]'] = { type: 'unknown', default: undefined }
} else if (typeof schemaObj.additionalProperties === 'object') {
const additionalType = getTypeFromSchema(
schemaObj.additionalProperties,
document,
options,
)
props['[key: string]'] = {
type: additionalType.type,
default: additionalType.default,
}
}
}
return {
type: nullable ? { ...props, __nullable: true } : { ...props },
default: schemaObj.default,
}
}
// Handle oneOf/anyOf already handled above, but check again for safety
return { type: 'unknown', default: undefined }
}
/**
* Check if a value is a ParameterDefinition
*/
function isParameterDefinition(value: unknown): value is ParameterDefinition {
return (
typeof value === 'object' &&
value !== null &&
'type' in value &&
'in' in value &&
'name' in value
)
}
/**
* Check if all properties in an object are optional
*/
function areAllPropertiesOptional(obj: Record<string, unknown>): boolean {
const entries = Object.entries(obj)
if (entries.length === 0) {
return true
}
return entries.every(([key, value]) => {
// If key ends with '?', it's optional (from getTypeFromSchema)
if (key.endsWith('?')) {
return true
}
// If it's a ParameterDefinition, check required field
if (isParameterDefinition(value)) {
return value.required === false
}
// If it's a type object, check if the type itself is optional
if (isTypeObject(value)) {
// // For type objects, check if the type is an object with all optional properties
// if (
// typeof value.type === 'object' &&
// value.type !== null &&
// !Array.isArray(value.type)
// ) {
// return areAllPropertiesOptional(value.type as Record<string, unknown>)
// }
return false
}
// For nested objects, recursively check
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
return areAllPropertiesOptional(value as Record<string, unknown>)
}
return false
})
}
/**
* Format a type object to TypeScript interface/type string
*/
function formatType(obj: Record<string, unknown>, indent: number = 0): string {
const indentStr = ' '.repeat(indent)
const nextIndent = indent + 1
const nextIndentStr = ' '.repeat(nextIndent)
const entries = Object.entries(obj)
.map(([key, value]) => {
// Handle string values (e.g., component references)
if (typeof value === 'string') {
return `${nextIndentStr}${wrapInterfaceKeyGuard(key)}: ${value}`
}
// Handle ParameterDefinition for params and query
if (isParameterDefinition(value)) {
const typeStr = formatTypeValue(value.type, nextIndent)
const isOptional = value.required === false
const wrappedKey = wrapInterfaceKeyGuard(key)
const keyWithOptional = isOptional ? `${wrappedKey}?` : wrappedKey
let description = ''
if (value.description) {
description += `${nextIndentStr}/**\n${nextIndentStr} * ${value.description}`
if (typeof value.default !== 'undefined') {
description += `\n${nextIndentStr} * @default {${value.default}}`
}
description = `${description}\n${nextIndentStr} */\n${nextIndentStr}`
} else if (typeof value.default !== 'undefined') {
description += `${nextIndentStr}/** @default {${value.default}} */\n${nextIndentStr}`
} else {
description = nextIndentStr
}
return `${description}${keyWithOptional}: ${typeStr}`
}
// Handle { type: unknown, default?: unknown } structure (from getTypeFromSchema)
if (isTypeObject(value)) {
const formattedValue = formatTypeValue(value.type, nextIndent)
// Key already has '?' if it's optional (from getTypeFromSchema), keep it as is
return `${nextIndentStr}${wrapInterfaceKeyGuard(key)}: ${formattedValue}`
}
// Check if value is an object (like params, query) with all optional properties
const valueAllOptional =
typeof value === 'object' &&
value !== null &&
!Array.isArray(value) &&
areAllPropertiesOptional(value as Record<string, unknown>)
const optionalMarker = valueAllOptional ? '?' : ''
const formattedValue = formatTypeValue(value, nextIndent)
return `${nextIndentStr}${wrapInterfaceKeyGuard(key)}${optionalMarker}: ${formattedValue}`
})
.join(';\n')
if (entries.length === 0) {
return '{}'
}
return `{\n${entries};\n${indentStr}}`
}
/**
* Check if a value is a type object with { type, default? } structure
*/
function isTypeObject(
value: unknown,
): value is { type: unknown; default?: unknown } {
return (
typeof value === 'object' &&
value !== null &&
'type' in value &&
Object.keys(value).length <= 2 &&
(!('default' in value) || Object.keys(value).length === 2)
)
}
/**
* Check if a value is an array type marker
*/
function isArrayType(
value: unknown,
): value is { __isArray: true; items: unknown; __nullable?: boolean } {
return (
typeof value === 'object' &&
value !== null &&
'__isArray' in value &&
(value as Record<string, unknown>).__isArray === true
)
}
/**
* Check if a value is a nullable object type marker
*/
function isNullableObject(
value: unknown,
): value is Record<string, unknown> & { __nullable: true } {
return (
typeof value === 'object' &&
value !== null &&
'__nullable' in value &&
(value as Record<string, unknown>).__nullable === true
)
}
/**
* Format a type value to TypeScript type string
*/
export function formatTypeValue(value: unknown, indent: number = 0): string {
if (typeof value === 'string') {
return value
}
// Handle array type marker
if (isArrayType(value)) {
const itemsFormatted = formatTypeValue(value.items, indent)
const arrayType = `Array<${itemsFormatted}>`
return value.__nullable ? `${arrayType} | null` : arrayType
}
// Handle { type: unknown, default?: unknown } structure
if (isTypeObject(value)) {
return formatTypeValue(value.type, indent)
}
// Handle nullable object type marker
if (isNullableObject(value)) {
// Remove __nullable from the object before formatting
const { __nullable, ...rest } = value
const objectType = formatType(rest as Record<string, unknown>, indent)
return `${objectType} | null`
}
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
return formatType(value as Record<string, unknown>, indent)
}
return String(value)
}
/**
* Extract parameters from OpenAPI operation
*/
export function extractParameters(
pathItem: OpenAPIV3_1.PathItemObject | undefined,
operation: OpenAPIV3_1.OperationObject | undefined,
document: OpenAPIV3_1.Document,
): {
pathParams: Record<string, ParameterDefinition>
queryParams: Record<string, ParameterDefinition>
headerParams: Record<string, ParameterDefinition>
} {
const pathParams: Record<string, ParameterDefinition> = {}
const queryParams: Record<string, ParameterDefinition> = {}
const headerParams: Record<string, ParameterDefinition> = {}
const allParams = [
...(pathItem?.parameters || []),
...(operation?.parameters || []),
]
for (const param of allParams) {
if ('$ref' in param) {
// Resolve $ref parameter
const resolved = resolveSchemaRef<OpenAPIV3_1.ParameterObject>(
param.$ref,
document,
)
if (
resolved &&
'in' in resolved &&
'name' in resolved &&
typeof resolved.in === 'string' &&
typeof resolved.name === 'string'
) {
const paramSchema =
'schema' in resolved && resolved.schema ? resolved.schema : {}
const { type: paramType, default: paramDefault } = getTypeFromSchema(
paramSchema,
document,
{ defaultNonNullable: false },
)
const result = {
...resolved,
type: paramType,
default: paramDefault,
}
if (resolved.in === 'path') {
pathParams[resolved.name] = result
} else if (resolved.in === 'query') {
queryParams[resolved.name] = result
} else if (resolved.in === 'header') {
headerParams[resolved.name] = result
}
}
continue
}
const paramSchema = param.schema || {}
const { type: paramType, default: paramDefault } = getTypeFromSchema(
paramSchema,
document,
{ defaultNonNullable: false },
)
const result = {
...param,
type: paramType,
default: paramDefault,
}
if (param.in === 'path') {
pathParams[param.name] = result
} else if (param.in === 'query') {
queryParams[param.name] = result
} else if (param.in === 'header') {
headerParams[param.name] = result
}
}
return { pathParams, queryParams, headerParams }
}
/**
* Extract request body from OpenAPI operation
*/
export function extractRequestBody(
requestBody:
| OpenAPIV3_1.RequestBodyObject
| OpenAPIV3_1.ReferenceObject
| undefined,
document: OpenAPIV3_1.Document,
): unknown {
if (!requestBody) {
return undefined
}
if ('$ref' in requestBody) {
const resolved = resolveSchemaRef(requestBody.$ref, document)
if (resolved && 'content' in resolved && resolved.content) {
const content =
resolved.content as OpenAPIV3_1.RequestBodyObject['content']
const jsonContent = content['application/json']
if (jsonContent && 'schema' in jsonContent && jsonContent.schema) {
return getTypeFromSchema(jsonContent.schema, document, {
defaultNonNullable: false,
}).type
}
}
return 'unknown'
}
const content = requestBody.content
if (content) {
const jsonContent = content['application/json']
if (jsonContent && 'schema' in jsonContent && jsonContent.schema) {
return getTypeFromSchema(jsonContent.schema, document, {
defaultNonNullable: false,
}).type
}
}
return undefined
}