-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
2003 lines (1733 loc) · 65.6 KB
/
cli.ts
File metadata and controls
2003 lines (1733 loc) · 65.6 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
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
import * as fs from 'fs'
import * as path from 'path'
import { exec } from 'child_process'
import { promisify } from 'util'
import { HttpMethod } from './types.js'
const execAsync = promisify(exec)
/**
* Standard HTTP methods used in OpenAPI specifications.
*/
const HTTP_METHODS = ['get', 'post', 'put', 'delete', 'patch', 'options', 'head', 'trace'] as const
interface OpenAPIOperation {
operationId?: string
[key: string]: unknown
}
interface OpenAPIPath {
[method: string]: OpenAPIOperation
}
interface OpenAPISpec {
paths: {
[path: string]: OpenAPIPath
}
components?: {
schemas?: Record<string, OpenAPISchema>
}
}
interface OpenAPISchema {
type?: string
enum?: (string | number)[]
$ref?: string
properties?: Record<string, OpenAPISchema>
items?: OpenAPISchema
[key: string]: unknown
}
interface OperationInfo {
path: string
method: HttpMethod
summary?: string
description?: string
pathParams?: Array<{ name: string; type: string }>
queryParams?: Array<{ name: string; type: string }>
requestBodySchema?: string // Schema name like "NewPet"
responseSchema?: string // Schema name like "Pet"
}
interface EnumInfo {
name: string // e.g., "PetStatus"
values: (string | number)[]
sourcePath: string // e.g., "components.schemas.Pet.properties.status"
aliases?: string[] // Alternative names for this enum (for duplicates)
}
async function fetchOpenAPISpec(input: string): Promise<string> {
// Check if input is a URL
if (input.startsWith('http://') || input.startsWith('https://')) {
console.log(`📡 Fetching OpenAPI spec from URL: ${input}`)
// Use node's built-in fetch (available in Node 18+)
try {
const response = await fetch(input)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const content = await response.text()
return content
} catch (error) {
throw new Error(`Failed to fetch OpenAPI spec from URL: ${error}`)
}
} else {
// Local file
console.log(`📂 Reading OpenAPI spec from file: ${input}`)
if (!fs.existsSync(input)) {
throw new Error(`File not found: ${input}`)
}
return fs.readFileSync(input, 'utf8')
}
}
async function generateTypes(openapiContent: string, outputDir: string): Promise<void> {
console.log('🔨 Generating TypeScript types using openapi-typescript...')
// Write the OpenAPI spec to a temporary file
const tempSpecPath = path.join(outputDir, 'temp-openapi.json')
fs.writeFileSync(tempSpecPath, openapiContent)
try {
// Run openapi-typescript
const typesOutputPath = path.join(outputDir, 'openapi-types.ts')
const command = `npx openapi-typescript "${tempSpecPath}" --output "${typesOutputPath}"`
await execAsync(command)
console.log(`✅ Generated types file: ${typesOutputPath}`)
// Format the generated file using eslint --fix
console.log('🎨 Formatting generated types file with ESLint...')
const eslintCommand = `npx eslint --fix "${typesOutputPath}"`
await execAsync(eslintCommand)
console.log(`✅ Formatted types file: ${typesOutputPath}`)
} finally {
// Clean up temp file
if (fs.existsSync(tempSpecPath)) {
fs.unlinkSync(tempSpecPath)
}
}
}
/**
* Converts a snake_case string to PascalCase.
* Works with strings that have no underscores (just capitalizes them).
*
* @param str - The snake_case string (e.g., 'give_treats' or 'pets')
* @returns PascalCase string (e.g., 'GiveTreats' or 'Pets')
*/
function snakeToPascalCase(str: string): string {
return str
.split('_')
.filter((part) => part.length > 0)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
.join('')
}
/**
* Generates an operationId based on the HTTP method and path.
* Uses heuristics to create meaningful operation names.
*
* @param pathUrl - The OpenAPI path (e.g., '/pets/{petId}')
* @param method - The HTTP method (e.g., 'get', 'post')
* @param prefixToStrip - Optional prefix to strip from path (e.g., '/api')
* @returns A generated operationId (e.g., 'getPet', 'listPets', 'createPet')
*/
function generateOperationId(
pathUrl: string,
method: string,
prefixToStrip: string = '',
existingIds: Set<string>,
): string {
const methodLower = method.toLowerCase()
// Strip prefix if provided and path starts with it
let effectivePath = pathUrl
if (prefixToStrip && pathUrl.startsWith(prefixToStrip)) {
effectivePath = pathUrl.substring(prefixToStrip.length)
}
// Remove leading/trailing slashes, replace slashes and periods with underscores
// Filter out path parameters (e.g., {petId})
// split by '/' or '.'
const pathSegments = effectivePath.split(/[/.]/)
const isParam = (segment: string) => segment.startsWith('{') && segment.endsWith('}')
const entityName = snakeToPascalCase(
pathSegments
.filter((s) => !isParam(s))
.join('_')
.replace(/[^a-zA-Z0-9]/g, '_'), // Replace non-alphanumeric characters with underscores
)
// A collection is when there is a trailing slash
const isCollection = pathUrl.endsWith('/')
// Determine prefix based on method and whether it's a collection or single resource
let prefix = ''
switch (methodLower) {
case 'get':
// GET on file extension -> get, GET on collection -> list, GET on resource -> get
prefix = isCollection ? 'list' : 'get'
break
case 'post':
prefix = isCollection ? 'create' : 'post'
break
case 'put':
case 'patch':
prefix = 'update'
break
case 'delete':
prefix = 'delete'
break
case 'head':
prefix = 'head'
break
case 'options':
prefix = 'options'
break
case 'trace':
prefix = 'trace'
break
default:
prefix = methodLower
}
// Combine prefix and entity name
let generatedId = prefix + entityName
// Handle collisions by appending path segments
if (existingIds.has(generatedId)) {
console.log(`⚠️ Collision detected: '${generatedId}' already used`)
// add parameters from the last to the first until not colliding
const params = pathSegments
.filter(isParam)
.map((s) => snakeToPascalCase(s.replace(/[{}]/g, '').replace(/[.:-]/g, '_')))
while (params.length > 0) {
generatedId += params.pop()
if (!existingIds.has(generatedId)) {
console.log(` ➜ Resolved collision with: '${generatedId}'`)
break
}
}
if (existingIds.has(generatedId)) {
// If still colliding, append a counter
let counter = 2
let uniqueId = `${generatedId}${counter}`
while (existingIds.has(uniqueId)) {
counter++
uniqueId = `${generatedId}${counter}`
}
generatedId = uniqueId
console.log(` ➜ Resolved collision with counter: '${generatedId}'`)
}
}
return generatedId
}
/**
* Adds operationId to operations that don't have one.
* Modifies the OpenAPI spec in place.
* Handles collisions by appending disambiguating segments.
*
* @param openApiSpec - The OpenAPI specification object
* @param prefixToStrip - Optional prefix to strip from paths (defaults to '/api')
*/
function addMissingOperationIds(openApiSpec: OpenAPISpec, prefixToStrip: string = '/api'): void {
if (!openApiSpec.paths) {
return
}
// Log the prefix that will be stripped
if (prefixToStrip) {
console.log(`🔍 Path prefix '${prefixToStrip}' will be stripped from operation IDs`)
}
// Track used operationIds to detect collisions
const usedOperationIds = new Set<string>()
// First pass: collect existing operationIds
Object.entries(openApiSpec.paths).forEach(([_, pathItem]) => {
Object.entries(pathItem).forEach(([method, op]) => {
if (!HTTP_METHODS.includes(method.toLowerCase() as (typeof HTTP_METHODS)[number])) {
return
}
if (op.operationId) {
usedOperationIds.add(op.operationId)
}
})
})
// Second pass: generate operationIds for missing ones
Object.entries(openApiSpec.paths).forEach(([pathUrl, pathItem]) => {
Object.entries(pathItem).forEach(([method, op]) => {
if (!HTTP_METHODS.includes(method.toLowerCase() as (typeof HTTP_METHODS)[number])) {
return
}
if (!op.operationId) {
// Generate operationId with prefix stripped
let generatedId = generateOperationId(pathUrl, method, prefixToStrip, usedOperationIds)
op.operationId = generatedId
usedOperationIds.add(generatedId)
console.log(`🏷️ Generated operationId '${generatedId}' for ${method.toUpperCase()} ${pathUrl}`)
}
})
})
}
function _parseOperationsFromSpec(
openapiContent: string,
excludePrefix: string | null = '_deprecated',
): {
operationIds: string[]
operationInfoMap: Record<string, OperationInfo>
} {
const openApiSpec: OpenAPISpec = JSON.parse(openapiContent)
if (!openApiSpec.paths) {
throw new Error('Invalid OpenAPI spec: missing paths')
}
const operationIds: string[] = []
const operationInfoMap: Record<string, OperationInfo> = {}
// Iterate through all paths and methods to extract operationIds
Object.entries(openApiSpec.paths).forEach(([pathUrl, pathItem]) => {
Object.entries(pathItem).forEach(([method, operation]) => {
// Skip non-HTTP methods (like parameters)
if (!HTTP_METHODS.includes(method.toLowerCase() as (typeof HTTP_METHODS)[number])) {
return
}
const op = operation as OpenAPIOperation
if (op.operationId) {
// Skip operations with excluded prefix
if (excludePrefix && op.operationId.startsWith(excludePrefix)) {
console.log(`⏭️ Excluding operation: ${op.operationId} (matches prefix '${excludePrefix}')`)
return
}
operationIds.push(op.operationId)
operationInfoMap[op.operationId] = {
path: pathUrl,
method: method.toUpperCase() as HttpMethod,
}
}
})
})
operationIds.sort()
return { operationIds, operationInfoMap }
}
/**
* Converts a string to camelCase or PascalCase.
* Handles snake_case, kebab-case, space-separated strings, and mixed cases.
* Single source of truth for case conversion logic.
*
* @param str - Input string to convert
* @param capitalize - If true, returns PascalCase; if false, returns camelCase
* @returns Converted string in the requested case
*/
function toCase(str: string, capitalize: boolean): string {
// If already camelCase or PascalCase, just adjust first letter
if (/[a-z]/.test(str) && /[A-Z]/.test(str)) {
return capitalize ? str.charAt(0).toUpperCase() + str.slice(1) : str.charAt(0).toLowerCase() + str.slice(1)
}
// Handle snake_case, kebab-case, spaces, etc.
const parts = str
.split(/[-_\s]+/)
.filter((part) => part.length > 0)
.map((part) => {
// If this part is already in camelCase, just capitalize the first letter
if (/[a-z]/.test(part) && /[A-Z]/.test(part)) {
return part.charAt(0).toUpperCase() + part.slice(1)
}
// Otherwise, capitalize and lowercase to normalize
return part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()
})
if (parts.length === 0) return str
// Apply capitalization rule to first part
if (!capitalize) {
parts[0] = parts[0].charAt(0).toLowerCase() + parts[0].slice(1)
}
return parts.join('')
}
/**
* Converts a string to PascalCase.
* Handles snake_case, kebab-case, space-separated strings, and preserves existing camelCase.
*/
function toPascalCase(str: string): string {
return toCase(str, true)
}
/**
* Converts a string value to a valid TypeScript property name.
* - Strings that are valid identifiers are used as-is (capitalized)
* - Invalid identifiers are wrapped in quotes
* - Numbers are prefixed with underscore
*/
function toEnumMemberName(value: string | number | null): string {
if (value === null) {
return 'Null' // Handle null enum values
}
if (typeof value === 'number') {
return `_${value}` // Numbers can't be property names, prefix with underscore
}
// Map common operator symbols to readable names
const operatorMap: Record<string, string> = {
'=': 'Equals',
'!=': 'NotEquals',
'<': 'LessThan',
'>': 'GreaterThan',
'<=': 'LessThanOrEqual',
'>=': 'GreaterThanOrEqual',
'!': 'Not',
'&&': 'And',
'||': 'Or',
'+': 'Plus',
'-': 'Minus',
'*': 'Multiply',
'/': 'Divide',
'%': 'Modulo',
'^': 'Caret',
'&': 'Ampersand',
'|': 'Pipe',
'~': 'Tilde',
'<<': 'LeftShift',
'>>': 'RightShift',
}
if (operatorMap[value]) {
return operatorMap[value]
}
// Check if it's a valid TypeScript identifier
const isValidIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(value)
if (isValidIdentifier) {
// Capitalize first letter for convention
return value.charAt(0).toUpperCase() + value.slice(1)
}
// For non-identifier strings, replace special characters with underscores
const cleaned = toPascalCase(value.replace(/[^a-zA-Z0-9_$]/g, '_'))
// If the result is empty or still invalid, prefix with underscore to make it valid
if (cleaned.length === 0 || !/^[a-zA-Z_$]/.test(cleaned)) {
return `_Char${value.charCodeAt(0)}`
}
return cleaned
}
/**
* Helper function to add enum values to the enums list with deduplication.
* If a duplicate is found, it adds the new name as an alias instead of creating a separate enum.
*/
function addEnumIfUnique(
enumName: string,
enumValues: (string | number)[],
sourcePath: string,
enums: EnumInfo[],
seenEnumValues: Map<string, string>,
): void {
const valuesKey = JSON.stringify(enumValues.sort())
// Check if we've seen this exact set of values before
const existingName = seenEnumValues.get(valuesKey)
if (existingName) {
// Find the existing enum and add this as an alias
const existingEnum = enums.find((e) => e.name === existingName)
if (existingEnum) {
if (!existingEnum.aliases) {
existingEnum.aliases = []
}
existingEnum.aliases.push(enumName)
console.log(` ↳ Adding alias ${enumName} → ${existingName}`)
}
return
}
seenEnumValues.set(valuesKey, enumName)
enums.push({
name: enumName,
values: enumValues,
sourcePath,
})
}
/**
* Extracts all enums from an OpenAPI spec.
* Walks through:
* 1. components.schemas and their properties (inline enum or $ref to enum schema)
* 2. Operation parameters (query, header, path, cookie)
* Deduplicates by comparing enum value sets.
*/
function extractEnumsFromSpec(openApiSpec: OpenAPISpec): EnumInfo[] {
const enums: EnumInfo[] = []
const seenEnumValues = new Map<string, string>() // Maps JSON stringified values -> enum name (for deduplication)
// Build lookup of schemas that ARE enums (have enum property on the schema itself)
const schemaEnumLookup: Map<string, (string | number)[]> = new Map()
if (openApiSpec.components?.schemas) {
for (const [schemaName, schema] of Object.entries(openApiSpec.components.schemas)) {
if (schema.enum && Array.isArray(schema.enum)) {
const enumValues = (schema.enum as (string | number | null)[]).filter((v) => v !== null) as (string | number)[]
if (enumValues.length > 0) {
schemaEnumLookup.set(schemaName, enumValues)
}
}
}
}
// Helper to resolve enum values from a schema (inline or $ref)
function resolveEnumValues(schema: OpenAPISchema): (string | number)[] | null {
// Inline enum
if (schema.enum && Array.isArray(schema.enum)) {
const enumValues = (schema.enum as (string | number | null)[]).filter((v) => v !== null) as (string | number)[]
return enumValues.length > 0 ? enumValues : null
}
// $ref to an enum schema
if (typeof schema.$ref === 'string') {
const refName = schema.$ref.split('/').pop()!
return schemaEnumLookup.get(refName) ?? null
}
return null
}
// Extract from components.schemas
if (openApiSpec.components?.schemas) {
for (const [schemaName, schema] of Object.entries(openApiSpec.components.schemas)) {
if (!schema.properties) continue
for (const [propName, propSchema] of Object.entries(schema.properties)) {
const enumValues = resolveEnumValues(propSchema)
if (!enumValues) continue
// Use schema name as-is (already PascalCase), convert property name from snake_case
const enumName = schemaName + toPascalCase(propName)
addEnumIfUnique(
enumName,
enumValues,
`components.schemas.${schemaName}.properties.${propName}`,
enums,
seenEnumValues,
)
}
}
}
// Extract from operation parameters
if (openApiSpec.paths) {
for (const [pathUrl, pathItem] of Object.entries(openApiSpec.paths)) {
for (const [method, operation] of Object.entries(pathItem)) {
// Skip non-HTTP methods
if (!HTTP_METHODS.includes(method.toLowerCase() as (typeof HTTP_METHODS)[number])) {
continue
}
const op = operation as OpenAPIOperation
// Check parameters (query, header, path, cookie)
if (op.parameters && Array.isArray(op.parameters)) {
for (const param of op.parameters) {
const paramObj = param as Record<string, unknown>
const paramName = paramObj.name as string | undefined
const paramIn = paramObj.in as string | undefined
const paramSchema = paramObj.schema as OpenAPISchema | undefined
if (!paramName || !paramIn || !paramSchema) continue
const enumValues = resolveEnumValues(paramSchema)
if (!enumValues) continue
// Create a descriptive name: OperationName + ParamName
const operationName = op.operationId
? toPascalCase(op.operationId)
: toPascalCase(pathUrl.split('/').pop() || 'param')
const paramNamePascal = toPascalCase(paramName)
// Rule 1: Don't duplicate suffix if operation name already ends with param name
let enumName: string
if (operationName.endsWith(paramNamePascal)) {
enumName = operationName
} else {
enumName = operationName + paramNamePascal
}
const sourcePath = `paths.${pathUrl}.${method}.parameters[${paramName}]`
addEnumIfUnique(enumName, enumValues, sourcePath, enums, seenEnumValues)
}
}
}
}
}
// Sort by name for consistent output
enums.sort((a, b) => a.name.localeCompare(b.name))
// Rule 2: Create short aliases for common suffixes (>2 words, appears >2 times)
addCommonSuffixAliases(enums)
return enums
}
/**
* Rule 2: Analyzes enum names and creates short aliases for common suffixes.
* Algorithm:
* 1. Find all suffixes > 2 words that appear 3+ times
* 2. Sort by number of occurrences (descending)
* 3. Remove any suffix that is a suffix of a MORE common one
* 4. Create aliases for remaining suffixes
*/
function addCommonSuffixAliases(enums: EnumInfo[]): void {
// Split enum names into words (by capital letters)
const splitIntoWords = (name: string): string[] => {
return name.split(/(?=[A-Z])/).filter((w) => w.length > 0)
}
// Collect ALL enum names (primary + aliases)
const allEnumNames: string[] = []
for (const enumInfo of enums) {
allEnumNames.push(enumInfo.name)
if (enumInfo.aliases) {
allEnumNames.push(...enumInfo.aliases)
}
}
// Extract all possible multi-word suffixes from ALL names
const suffixCounts = new Map<string, Set<string>>() // suffix -> set of full enum names
for (const name of allEnumNames) {
const words = splitIntoWords(name)
// Try all suffixes with 3+ words
for (let wordCount = 3; wordCount <= words.length - 1; wordCount++) {
// -1 to exclude the full name
const suffix = words.slice(-wordCount).join('')
if (!suffixCounts.has(suffix)) {
suffixCounts.set(suffix, new Set())
}
suffixCounts.get(suffix)!.add(name)
}
}
// Step 1: Find suffixes appearing 3+ times
const commonSuffixes: Array<{ suffix: string; count: number; names: string[] }> = []
for (const [suffix, enumNames] of suffixCounts.entries()) {
if (enumNames.size > 2) {
// Skip if this suffix is already present as a primary enum name or alias
if (allEnumNames.includes(suffix)) {
continue
}
commonSuffixes.push({
suffix,
count: enumNames.size,
names: Array.from(enumNames),
})
}
}
// Step 2: Sort by occurrence count (descending - most common first)
commonSuffixes.sort((a, b) => b.count - a.count)
// Step 3: Remove suffixes that are suffixes of MORE common ones
const filteredSuffixes: typeof commonSuffixes = []
for (const current of commonSuffixes) {
let shouldKeep = true
// Check if this suffix is a suffix of any MORE common suffix already in the filtered list
for (const existing of filteredSuffixes) {
if (existing.suffix.endsWith(current.suffix)) {
// current is a suffix of existing (which is more common)
shouldKeep = false
break
}
}
if (shouldKeep) {
filteredSuffixes.push(current)
}
}
// Step 4: PROMOTE common suffixes to be PRIMARY enum names
// Process promotions from most common to least common
const promotions = new Map<EnumInfo, { newName: string; allAliases: string[] }>()
for (const { suffix, names } of filteredSuffixes) {
// Find all primary enums that have this suffix (either as primary name or alias)
const affectedEnums: EnumInfo[] = []
for (const name of names) {
const enumInfo = enums.find((e) => e.name === name || (e.aliases && e.aliases.includes(name)))
if (enumInfo && !affectedEnums.includes(enumInfo) && !promotions.has(enumInfo)) {
affectedEnums.push(enumInfo)
}
}
if (affectedEnums.length === 0) continue
// Use the first affected enum as the base (it has the values we need)
const primaryEnum = affectedEnums[0]
// Collect all names that should become aliases
const allAliases = new Set<string>()
for (const enumInfo of affectedEnums) {
// Add the primary name as an alias
allAliases.add(enumInfo.name)
// Add all existing aliases
if (enumInfo.aliases) {
enumInfo.aliases.forEach((alias) => allAliases.add(alias))
}
}
// Remove the suffix itself from aliases (it will be the primary name)
allAliases.delete(suffix)
// Record this promotion to apply later
promotions.set(primaryEnum, {
newName: suffix,
allAliases: Array.from(allAliases),
})
console.log(` ↳ Promoting ${suffix} to PRIMARY (was ${primaryEnum.name}, ${names.length} occurrences)`)
// Mark other affected enums for removal
for (let i = 1; i < affectedEnums.length; i++) {
promotions.set(affectedEnums[i], { newName: '', allAliases: [] }) // Mark for deletion
}
}
// Apply all promotions
for (const [enumInfo, promotion] of promotions.entries()) {
if (promotion.newName === '') {
// Remove this enum (it was consolidated)
const index = enums.indexOf(enumInfo)
if (index > -1) {
enums.splice(index, 1)
}
} else {
// Update the enum name and aliases
enumInfo.name = promotion.newName
enumInfo.aliases = promotion.allAliases
enumInfo.sourcePath = `common suffix (promoted)`
}
}
}
/**
* Generates the content for api-enums.ts file.
*/
function generateApiEnumsContent(enums: EnumInfo[]): string {
if (enums.length === 0) {
return `// Auto-generated from OpenAPI specification
// Do not edit this file manually
// No enums found in the OpenAPI specification
`
}
// Generate the generic enum helper utility
const helperUtility = `/**
* Generic utility for working with enums
*
* @example
* import { EnumHelper, RequestedValuationType } from './api-enums'
*
* // Get all values
* const allTypes = EnumHelper.values(RequestedValuationType)
*
* // Validate a value
* if (EnumHelper.isValid(RequestedValuationType, userInput)) {
* // TypeScript knows userInput is RequestedValuationType
* }
*
* // Reverse lookup
* const key = EnumHelper.getKey(RequestedValuationType, 'cat') // 'Cat'
*/
export const EnumHelper = {
/**
* Get all enum values as an array
*/
values<T extends Record<string, string | number>>(enumObj: T): Array<T[keyof T]> {
return Object.values(enumObj) as Array<T[keyof T]>
},
/**
* Get all enum keys as an array
*/
keys<T extends Record<string, string | number>>(enumObj: T): Array<keyof T> {
return Object.keys(enumObj) as Array<keyof T>
},
/**
* Check if a value is valid for the given enum
*/
isValid<T extends Record<string, string | number>>(
enumObj: T,
value: unknown,
): value is T[keyof T] {
return typeof value === 'string' && (Object.values(enumObj) as string[]).includes(value)
},
/**
* Get the enum key from a value (reverse lookup)
*/
getKey<T extends Record<string, string | number>>(enumObj: T, value: T[keyof T]): keyof T | undefined {
const entry = Object.entries(enumObj).find(([_, v]) => v === value)
return entry?.[0] as keyof T | undefined
},
} as const
`
const enumExports = enums
.map((enumInfo) => {
const members = enumInfo.values
.map((value) => {
const memberName = toEnumMemberName(value)
const valueStr = typeof value === 'string' ? `'${value}'` : value
return ` ${memberName}: ${valueStr} as const,`
})
.join('\n')
let output = `/**
* Enum values from ${enumInfo.sourcePath}
*/
export const ${enumInfo.name} = {
${members}
} as const
export type ${enumInfo.name} = typeof ${enumInfo.name}[keyof typeof ${enumInfo.name}]
`
// Generate type aliases for duplicates
if (enumInfo.aliases && enumInfo.aliases.length > 0) {
output += '\n// Type aliases for duplicate enum values\n'
for (const alias of enumInfo.aliases) {
output += `export const ${alias} = ${enumInfo.name}\n`
output += `export type ${alias} = ${enumInfo.name}\n`
}
}
return output
})
.join('\n')
return `// Auto-generated from OpenAPI specification
// Do not edit this file manually
${helperUtility}
${enumExports}
`
}
/**
* Generates the api-enums.ts file from the OpenAPI spec.
*/
async function generateApiEnums(
openapiContent: string,
outputDir: string,
_excludePrefix: string | null = '_deprecated',
): Promise<void> {
console.log('🔨 Generating api-enums.ts file...')
const openApiSpec: OpenAPISpec = JSON.parse(openapiContent)
const enums = extractEnumsFromSpec(openApiSpec)
const tsContent = generateApiEnumsContent(enums)
const outputPath = path.join(outputDir, 'api-enums.ts')
fs.writeFileSync(outputPath, tsContent)
console.log(`✅ Generated api-enums file: ${outputPath}`)
console.log(`📊 Found ${enums.length} unique enums`)
}
/**
* Removes trailing `_schema` or `Schema` suffix from a string (case-insensitive).
* Examples: `nuts_schema` → `nuts`, `addressSchema` → `address`, `Pet` → `Pet`
*/
function removeSchemaSuffix(name: string): string {
return name.replace(/(_schema|Schema)$/i, '')
}
/**
* Generates the content for api-schemas.ts file.
* Creates type aliases for all schema objects with cleaned names.
*/
function generateApiSchemasContent(openApiSpec: OpenAPISpec): string {
if (!openApiSpec.components?.schemas || Object.keys(openApiSpec.components.schemas).length === 0) {
return `// Auto-generated from OpenAPI specification
// Do not edit this file manually
import type { components } from './openapi-types'
// No schemas found in the OpenAPI specification
`
}
const header = `// Auto-generated from OpenAPI specification
// Do not edit this file manually
import type { components } from './openapi-types'
/**
* Type aliases for schema objects from the API spec.
* These are references to components['schemas'] for convenient importing.
*
* @example
* import type { Nuts, Address, BorrowerInfo } from './api-schemas'
*
* const nutsData: Nuts = { NUTS_ID: 'BE241', ... }
*/
`
const schemaExports = Object.keys(openApiSpec.components.schemas)
.sort()
.map((schemaName) => {
// Remove schema suffix and convert to PascalCase
const cleanedName = removeSchemaSuffix(schemaName)
const exportedName = toPascalCase(cleanedName)
// Only add comment if the name changed
const comment = exportedName !== schemaName ? `// Schema: ${schemaName}\n` : ''
return `${comment}export type ${exportedName} = components['schemas']['${schemaName}']`
})
.join('\n\n')
return header + '\n' + schemaExports + '\n'
}
/**
* Generates the api-schemas.ts file from the OpenAPI spec.
*/
async function generateApiSchemas(
openapiContent: string,
outputDir: string,
_excludePrefix: string | null = '_deprecated',
): Promise<void> {
console.log('🔨 Generating api-schemas.ts file...')
const openApiSpec: OpenAPISpec = JSON.parse(openapiContent)
const schemaCount = Object.keys(openApiSpec.components?.schemas ?? {}).length
const tsContent = generateApiSchemasContent(openApiSpec)
const outputPath = path.join(outputDir, 'api-schemas.ts')
fs.writeFileSync(outputPath, tsContent)
console.log(`✅ Generated api-schemas file: ${outputPath}`)
console.log(`📊 Found ${schemaCount} schemas`)
}
// ============================================================================
// List path computation (ported from openapi-helpers.ts for code-gen time use)
// ============================================================================
const PLURAL_ES_SUFFIXES_CLI = ['s', 'x', 'z', 'ch', 'sh', 'o'] as const
function pluralizeResourceCli(name: string): string {
if (name.endsWith('y')) return name.slice(0, -1) + 'ies'
if (PLURAL_ES_SUFFIXES_CLI.some((s) => name.endsWith(s))) return name + 'es'
return name + 's'
}
/**
* Computes the list path for a mutation operation (used for cache invalidation).
* Returns null if no matching list operation is found.
*/
function computeListPath(
operationId: string,
opInfo: OperationInfo,
operationMap: Record<string, OperationInfo>,
): string | null {
const method = opInfo.method
if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) return null
const prefixes: Partial<Record<HttpMethod, string>> = {
[HttpMethod.POST]: 'create',
[HttpMethod.PUT]: 'update',
[HttpMethod.PATCH]: 'update',
[HttpMethod.DELETE]: 'delete',
}
const prefix = prefixes[method]
if (!prefix) return null
let resourceName: string | null = null
if (operationId.startsWith(prefix)) {
const remaining = operationId.slice(prefix.length)
if (remaining.length > 0 && /^[A-Z]/.test(remaining)) resourceName = remaining
}
if (resourceName) {
const tryList = (name: string): string | null => {
const listId = `list${name}`
if (listId in operationMap && operationMap[listId].method === HttpMethod.GET) return operationMap[listId].path
return null
}
const found = tryList(resourceName) || tryList(pluralizeResourceCli(resourceName))
if (found) return found
}
// Fallback: strip last path param segment
const segments = opInfo.path.split('/').filter((s) => s.length > 0)
if (segments.length >= 2 && /^\{[^}]+\}$/.test(segments[segments.length - 1])) {
return '/' + segments.slice(0, -1).join('/') + '/'