@@ -393,6 +393,8 @@ interface CollectedSchemas {
393393 requestSchemas : Record < string , SchemaInfo >
394394 responseSchemas : Record < string , SchemaInfo >
395395 errorSchemas : Record < string , SchemaInfo >
396+ /** Schemas referenced via $ref within category schemas but not themselves a category schema */
397+ dependencySchemas : Record < string , SchemaInfo >
396398 pathMappings : Record <
397399 'get' | 'post' | 'put' | 'delete' | 'patch' ,
398400 Record < string , PathSchemaMapping >
@@ -621,7 +623,45 @@ function generateSchemasForDocument(
621623 }
622624 }
623625
624- return { requestSchemas, responseSchemas, errorSchemas, pathMappings }
626+ // Collect all transitively referenced schemas from category schemas
627+ const allCategoryNames = new Set ( [
628+ ...requestSchemaNames ,
629+ ...responseSchemaNames ,
630+ ...errorSchemaNames ,
631+ ] )
632+ const allReferencedNames = new Set < string > ( )
633+ for ( const schemaName of allCategoryNames ) {
634+ const schemaDef = schema . components ?. schemas ?. [ schemaName ]
635+ if ( schemaDef ) {
636+ collectSchemaNames (
637+ schemaDef as OpenAPIV3_1 . SchemaObject | OpenAPIV3_1 . ReferenceObject ,
638+ allReferencedNames ,
639+ { followComponentRefs : true , document : schema } ,
640+ )
641+ }
642+ }
643+
644+ // Generate dependency schemas (referenced via $ref but need _Name variables)
645+ const dependencySchemas : Record < string , SchemaInfo > = { }
646+ for ( const name of allReferencedNames ) {
647+ const schemaDef = schema . components ?. schemas ?. [ name ]
648+ if ( ! schemaDef ) continue
649+ const schemaRef = schemaDef as
650+ | OpenAPIV3_1 . SchemaObject
651+ | OpenAPIV3_1 . ReferenceObject
652+ dependencySchemas [ name ] = {
653+ code : schemaToZod ( schemaRef , schema , schemaRefs ) ,
654+ type : schemaToZodType ( schemaRef , schema ) ,
655+ }
656+ }
657+
658+ return {
659+ requestSchemas,
660+ responseSchemas,
661+ errorSchemas,
662+ dependencySchemas,
663+ pathMappings,
664+ }
625665}
626666
627667// =============================================================================
@@ -657,6 +697,17 @@ export function generateZodSchemas(
657697 for ( const [ serverName , collected ] of Object . entries ( serverSchemas ) ) {
658698 const safeServerName = serverName . replace ( / [ ^ a - z A - Z 0 - 9 ] / g, '_' )
659699
700+ // Dependency schemas (referenced via $ref, need _Name variables for z.lazy)
701+ if ( Object . keys ( collected . dependencySchemas ) . length > 0 ) {
702+ lines . push ( `// Shared dependency schemas for ${ serverName } ` )
703+ for ( const [ name , schemaInfo ] of Object . entries (
704+ collected . dependencySchemas ,
705+ ) ) {
706+ lines . push ( `const _${ name } = ${ schemaInfo . code } ;` )
707+ }
708+ lines . push ( '' )
709+ }
710+
660711 // Request schemas
661712 if ( Object . keys ( collected . requestSchemas ) . length > 0 ) {
662713 lines . push ( `// Request schemas for ${ serverName } ` )
0 commit comments