From dc5b8337196ab5f708423f51386e88584a052ad6 Mon Sep 17 00:00:00 2001 From: Vladimir Gorej Date: Tue, 27 Dec 2022 16:24:10 +0100 Subject: [PATCH] feat(resolve): add ApiDOM OpenAPI 3.1.0 JSON parser Refs #2717 --- package.json | 1 + .../parse/parsers/openapi-json-3-1/index.js | 66 +++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 src/helpers/apidom/reference/parse/parsers/openapi-json-3-1/index.js diff --git a/package.json b/package.json index 607b200d1..5685a1d33 100644 --- a/package.json +++ b/package.json @@ -112,6 +112,7 @@ "@babel/runtime-corejs3": "^7.11.2", "@swagger-api/apidom-core": "^0.59.0", "@swagger-api/apidom-reference": "^0.59.0", + "@swagger-api/apidom-ns-openapi-3-1": "^0.59.0", "cookie": "~0.5.0", "cross-fetch": "^3.1.5", "deepmerge": "~4.2.2", diff --git a/src/helpers/apidom/reference/parse/parsers/openapi-json-3-1/index.js b/src/helpers/apidom/reference/parse/parsers/openapi-json-3-1/index.js new file mode 100644 index 000000000..23307e4f7 --- /dev/null +++ b/src/helpers/apidom/reference/parse/parsers/openapi-json-3-1/index.js @@ -0,0 +1,66 @@ +/* eslint-disable camelcase */ +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 OpenApiJson3_1Parser = Parser.compose(Parser, { + props: { + name: 'openapi-json-3-1-swagger-client', + fileExtensions: ['.json'], + mediaTypes: new OpenAPIMediaTypes( + ...mediaTypes.filterByFormat('generic'), + ...mediaTypes.filterByFormat('json') + ), + detectionRegExp: /"openapi"\s*:\s*"(?3\.1\.(?:[1-9]\d*|0))"/, + }, + 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(); + JSON.parse(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-json-3-1-swagger-client parser plugin doesn't support sourceMaps option" + ); + } + + const source = file.toString(); + + try { + const pojo = JSON.parse(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 OpenApiJson3_1Parser; +/* eslint-enable camelcase */