diff --git a/src/helpers/apidom/reference/parse/parsers/openapi-yaml-3-1/index.js b/src/helpers/apidom/reference/parse/parsers/openapi-yaml-3-1/index.js new file mode 100644 index 000000000..305862a4f --- /dev/null +++ b/src/helpers/apidom/reference/parse/parsers/openapi-yaml-3-1/index.js @@ -0,0 +1,68 @@ +/* eslint-disable camelcase */ +import YAML from 'js-yaml'; +import { ParseResultElement } from '@swagger-api/apidom-core'; +import { ParserError, Parser } from '@swagger-api/apidom-reference/configuration/empty'; +import { + mediaTypes, + OpenApi3_1Element, + OpenAPIMediaTypes, +} from '@swagger-api/apidom-ns-openapi-3-1'; + +// eslint-disable-next-line camelcase +const OpenApiYaml3_1Parser = Parser.compose(Parser, { + props: { + name: 'openapi-yaml-3-1-swagger-client', + fileExtensions: ['.yaml', '.yml'], + mediaTypes: new OpenAPIMediaTypes( + ...mediaTypes.filterByFormat('generic'), + ...mediaTypes.filterByFormat('yaml') + ), + detectionRegExp: + /(?^(["']?)openapi\2\s*:\s*(["']?)(?3\.1\.(?:[1-9]\d*|0))\3(?:\s+|$))|(?"openapi"\s*:\s*"(?3\.1\.(?:[1-9]\d*|0))")/m, + }, + methods: { + async canParse(file) { + const hasSupportedFileExtension = + this.fileExtensions.length === 0 ? true : this.fileExtensions.includes(file.extension); + const hasSupportedMediaType = this.mediaTypes.includes(file.mediaType); + + if (!hasSupportedFileExtension) return false; + if (hasSupportedMediaType) return true; + if (!hasSupportedMediaType) { + try { + const source = file.toString(); + YAML.load(source); + return this.detectionRegExp.test(source); + } catch (error) { + return false; + } + } + return false; + }, + async parse(file) { + if (this.sourceMap) { + // eslint-disable-next-line no-console + console.warn( + "openapi-yaml-3-1-swagger-client parser plugin doesn't support sourceMaps option" + ); + } + + const source = file.toString(); + + try { + const pojo = YAML.load(source); + const element = OpenApi3_1Element.refract(pojo, this.refractorOpts); + const parseResultElement = new ParseResultElement(); + + element.classes.push('result'); + parseResultElement.push(element); + return parseResultElement; + } catch (error) { + throw new ParserError(`Error parsing "${file.uri}"`, error); + } + }, + }, +}); + +export default OpenApiYaml3_1Parser; +/* eslint-enable camelcase */