@@ -3,6 +3,7 @@ import * as DotProp from "dot-prop";
33
44import type { OpenApi } from "../../types" ;
55import { DevelopmentError } from "../Exception" ;
6+ import { FileSystem } from "../FileSystem" ;
67import type * as TypeScriptCodeGenerator from "../TsGenerator" ;
78import type * as ConverterContext from "./ConverterContext" ;
89import * as Reference from "./components/Reference" ;
@@ -30,8 +31,11 @@ export interface ReferencePathSet {
3031 * // 返り値の例: { pathArray: ["Common"], base: "components/schemas" }
3132 */
3233export const generatePath = ( entryPoint : string , currentPoint : string , referencePath : string ) : ReferencePathSet => {
33- const ext = Path . extname ( currentPoint ) ; // .yml
34- const from = Path . relative ( Path . dirname ( entryPoint ) , currentPoint ) . replace ( ext , "" ) ; // components/schemas/A/B
34+ // JSON Pointerのフラグメントはドキュメント内の位置を示すため、ファイルシステム上の相対パス計算には影響させない。
35+ const documentEntryPoint = Reference . getDocumentPoint ( entryPoint ) ;
36+ const documentCurrentPoint = Reference . getDocumentPoint ( currentPoint ) ;
37+ const ext = Path . extname ( documentCurrentPoint ) ; // .yml
38+ const from = Path . relative ( Path . dirname ( documentEntryPoint ) , documentCurrentPoint ) . replace ( ext , "" ) ; // components/schemas/A/B
3539 const base = Path . dirname ( from ) . replace ( Path . sep , "/" ) ;
3640 const result = Path . posix . relative ( base , referencePath ) ; // remoteの場合? localの場合 referencePath.split("/")
3741 const pathArray = result . split ( "/" ) ;
@@ -119,33 +123,50 @@ export const create = (
119123 return calculateReferencePath ( store , base , pathArray , converterContext ) ;
120124 } ;
121125 const findSchemaByPathArray = (
126+ currentPoint : string ,
122127 pathArray : string [ ] ,
123- remainPathArray : string [ ] = [ ] ,
128+ visited : Set < string > = new Set ( ) ,
124129 ) : OpenApi . Schema | OpenApi . Reference | OpenApi . JSONSchemaDefinition => {
125- const schema = DotProp . getProperty ( rootSchema , pathArray . join ( "." ) ) ;
126- if ( ! schema ) {
127- return findSchemaByPathArray ( pathArray . slice ( 0 , pathArray . length - 1 ) , [ pathArray [ pathArray . length - 1 ] , ...remainPathArray ] ) ;
130+ // 参照解決はドキュメント境界をまたぐ可能性があるため、エントリポイントではなく現在の参照を所有するドキュメントを基準に解決する。
131+ const documentPoint = Reference . getDocumentPoint ( currentPoint ) ;
132+ // スキーマが自身を参照する場合にコールスタックがあふれないよう、再帰済みの参照を追跡する。
133+ const visitKey = `${ documentPoint } |${ pathArray . join ( "/" ) } ` ;
134+ if ( visited . has ( visitKey ) ) {
135+ throw new DevelopmentError ( `Circular schema reference \n${ JSON . stringify ( { currentPoint, pathArray } , null , 2 ) } ` ) ;
128136 }
129- if ( Guard . isReference ( schema ) ) {
130- const ref = Reference . generate ( entryPoint , entryPoint , schema ) ;
131- return findSchemaByPathArray ( ref . path . split ( "/" ) , remainPathArray ) ;
132- }
133- if ( remainPathArray . length ) {
134- const moreNestSchema = DotProp . getProperty ( schema , remainPathArray . join ( "." ) ) ;
135- if ( ! moreNestSchema ) {
136- throw new Error ( "Not found" ) ;
137+ visited . add ( visitKey ) ;
138+
139+ // エントリポイントは既に読み込み済みだが、リモートドキュメントは自身のファイルから読み込む。
140+ const isEntryPoint = Path . resolve ( documentPoint ) === Path . resolve ( Reference . getDocumentPoint ( entryPoint ) ) ;
141+ const document = isEntryPoint ? rootSchema : FileSystem . loadJsonOrYaml ( documentPoint ) ;
142+ let schema : unknown = document ;
143+ // パスを1要素ずつたどり、途中で参照が見つかった場合は参照先ドキュメントで残りのパスを解決する。
144+ for ( const [ index , path ] of pathArray . entries ( ) ) {
145+ schema = DotProp . getProperty ( schema , [ path ] ) ;
146+ if ( schema === undefined ) {
147+ throw new DevelopmentError (
148+ `Schema not found \n${ JSON . stringify ( { currentPoint : documentPoint , pathArray, missingPath : pathArray . slice ( 0 , index + 1 ) } , null , 2 ) } ` ,
149+ ) ;
150+ }
151+ if ( Guard . isReference ( schema ) ) {
152+ // 参照をたどると解決対象のドキュメントが変わる可能性がある。
153+ const ref = Reference . generate ( entryPoint , documentPoint , schema ) ;
154+ const nextPoint = ref . type === "local" ? documentPoint : ref . referencePoint ;
155+ return findSchemaByPathArray ( nextPoint , [ ...ref . path . split ( "/" ) , ...pathArray . slice ( index + 1 ) ] , visited ) ;
137156 }
138- return moreNestSchema ;
139157 }
140- return schema ;
158+ if ( schema === document ) {
159+ throw new DevelopmentError ( `Schema path is empty \n${ JSON . stringify ( { currentPoint : documentPoint , pathArray } , null , 2 ) } ` ) ;
160+ }
161+ return schema as OpenApi . Schema | OpenApi . Reference | OpenApi . JSONSchemaDefinition ;
141162 } ;
142163 const setReferenceHandler : ToTypeNode . Context [ "setReferenceHandler" ] = ( currentPoint , reference ) => {
143164 if ( store . hasStatement ( reference . path , [ "interface" , "typeAlias" ] ) ) {
144165 return ;
145166 }
167+ const context = { rootSchema, setReferenceHandler, resolveReferencePath, findSchemaByPathArray } ;
146168 if ( reference . type === "remote" ) {
147169 const data = reference . data ;
148- const context = { rootSchema, setReferenceHandler, resolveReferencePath, findSchemaByPathArray } ;
149170 // Determine if the schema should be treated as an interface equivalent
150171 // (e.g., plain object schemas that are not nullable and don't produce IntersectionTypeNode)
151172 const isInterfaceEquivalent = ( ( ) => {
@@ -208,6 +229,28 @@ export const create = (
208229 store . addStatement ( reference . path , { name : reference . name , kind : "typeAlias" , value } ) ;
209230 }
210231 } else if ( reference . type === "local" ) {
232+ // リモートドキュメント内のローカル参照は、エントリポイントのルートスキーマではなく、
233+ // そのリモートドキュメントを基準に解決する。
234+ const isExternalDocument =
235+ Path . resolve ( Reference . getDocumentPoint ( currentPoint ) ) !== Path . resolve ( Reference . getDocumentPoint ( entryPoint ) ) ;
236+ if ( isExternalDocument ) {
237+ const schema = findSchemaByPathArray ( currentPoint , reference . path . split ( "/" ) ) ;
238+ const declarationName = Path . posix . basename ( reference . path ) ;
239+ if ( typeof schema === "boolean" ) {
240+ store . addStatement ( reference . path , {
241+ name : declarationName ,
242+ kind : "typeAlias" ,
243+ value : factory . TypeAliasDeclaration . create ( {
244+ export : true ,
245+ name : converterContext . escapeDeclarationText ( declarationName ) ,
246+ type : ToTypeNode . convert ( entryPoint , currentPoint , factory , schema , context , converterContext ) ,
247+ } ) ,
248+ } ) ;
249+ } else if ( ! Guard . isReference ( schema ) ) {
250+ Schema . addSchema ( entryPoint , currentPoint , store , factory , reference . path , declarationName , schema , context , converterContext ) ;
251+ }
252+ return ;
253+ }
211254 if ( ! store . isAfterDefined ( reference . path ) ) {
212255 const { maybeResolvedName } = resolveReferencePath ( currentPoint , reference . path ) ;
213256 const value = factory . TypeAliasDeclaration . create ( {
0 commit comments