1- import { type AnyApiDefinitionFormat , validate } from '@scalar/openapi-parser' ;
1+ import { validate } from '@scalar/openapi-parser' ;
22import { OpenAPIParseError } from './error' ;
33import { createFileSystem } from './filesystem' ;
44import type { Filesystem , OpenAPIV3xDocument } from './types' ;
5+ import type { ParseOpenAPIInput } from './parse' ;
56
67/**
78 * Parse a raw string into an OpenAPI document.
89 * It will also convert Swagger 2.0 to OpenAPI 3.0.
910 * It can throw an `OpenAPIFetchError` if the document is invalid.
1011 */
11- export async function parseOpenAPIV3 ( input : {
12- /**
13- * The API definition to parse.
14- */
15- value : AnyApiDefinitionFormat ;
16- /**
17- * The root URL of the specified OpenAPI document.
18- */
19- rootURL : string | null ;
20- } ) : Promise < Filesystem < OpenAPIV3xDocument > > {
12+ export async function parseOpenAPIV3 (
13+ input : ParseOpenAPIInput ,
14+ ) : Promise < Filesystem < OpenAPIV3xDocument > > {
15+ const { value, rootURL, trust } = input ;
16+ const specification = trust
17+ ? trustedValidate ( { value, rootURL } )
18+ : await untrustedValidate ( { value, rootURL } ) ;
19+
20+ const filesystem = await createFileSystem ( { value : specification , rootURL } ) ;
21+
22+ return filesystem ;
23+ }
24+
25+ type ValidateOpenAPIV3Input = Pick < ParseOpenAPIInput , 'value' | 'rootURL' > ;
26+
27+ /**
28+ * Validate an untrusted OpenAPI v3 document.
29+ */
30+ async function untrustedValidate ( input : ValidateOpenAPIV3Input ) {
2131 const { value, rootURL } = input ;
2232 const result = await validate ( value ) ;
2333
@@ -36,7 +46,36 @@ export async function parseOpenAPIV3(input: {
3646 } ) ;
3747 }
3848
39- const filesystem = await createFileSystem ( { value : result . specification , rootURL } ) ;
49+ return result . specification ;
50+ }
4051
41- return filesystem ;
52+ /**
53+ * Validate a trusted OpenAPI v3 document.
54+ * It assumes the specification is already a valid specification.
55+ * It's faster than `untrustedValidate`.
56+ */
57+ function trustedValidate ( input : ValidateOpenAPIV3Input ) {
58+ const { value, rootURL } = input ;
59+ const result = ( ( ) => {
60+ if ( typeof value === 'string' ) {
61+ try {
62+ return JSON . parse ( value ) ;
63+ } catch ( error ) {
64+ throw new OpenAPIParseError ( 'Invalid JSON' , {
65+ code : 'invalid' ,
66+ rootURL,
67+ } ) ;
68+ }
69+ }
70+ return value ;
71+ } ) ( ) ;
72+
73+ if ( 'swagger' in result && result . swagger ) {
74+ throw new OpenAPIParseError ( 'Only OpenAPI v3 is supported' , {
75+ code : 'parse-v2-in-v3' ,
76+ rootURL,
77+ } ) ;
78+ }
79+
80+ return result ;
4281}
0 commit comments