1 | /* eslint-disable camelcase */
|
---|
2 | import YAML, { JSON_SCHEMA } from 'js-yaml';
|
---|
3 | import { ParseResultElement } from '@swagger-api/apidom-core';
|
---|
4 | import { ParserError, Parser } from '@swagger-api/apidom-reference/configuration/empty';
|
---|
5 | import { mediaTypes, OpenApi3_1Element, OpenAPIMediaTypes } from '@swagger-api/apidom-ns-openapi-3-1';
|
---|
6 | const OpenApiYaml3_1Parser = Parser.compose({
|
---|
7 | props: {
|
---|
8 | name: 'openapi-yaml-3-1-swagger-client',
|
---|
9 | fileExtensions: ['.yaml', '.yml'],
|
---|
10 | mediaTypes: new OpenAPIMediaTypes(...mediaTypes.filterByFormat('generic'), ...mediaTypes.filterByFormat('yaml')),
|
---|
11 | detectionRegExp: /(?<YAML>^(["']?)openapi\2\s*:\s*(["']?)(?<version_yaml>3\.1\.(?:[1-9]\d*|0))\3(?:\s+|$))|(?<JSON>"openapi"\s*:\s*"(?<version_json>3\.1\.(?:[1-9]\d*|0))")/m
|
---|
12 | },
|
---|
13 | methods: {
|
---|
14 | async canParse(file) {
|
---|
15 | const hasSupportedFileExtension = this.fileExtensions.length === 0 ? true : this.fileExtensions.includes(file.extension);
|
---|
16 | const hasSupportedMediaType = this.mediaTypes.includes(file.mediaType);
|
---|
17 | if (!hasSupportedFileExtension) return false;
|
---|
18 | if (hasSupportedMediaType) return true;
|
---|
19 | if (!hasSupportedMediaType) {
|
---|
20 | try {
|
---|
21 | const source = file.toString();
|
---|
22 | YAML.load(source);
|
---|
23 | return this.detectionRegExp.test(source);
|
---|
24 | } catch (error) {
|
---|
25 | return false;
|
---|
26 | }
|
---|
27 | }
|
---|
28 | return false;
|
---|
29 | },
|
---|
30 | async parse(file) {
|
---|
31 | if (this.sourceMap) {
|
---|
32 | throw new ParserError("openapi-yaml-3-1-swagger-client parser plugin doesn't support sourceMaps option");
|
---|
33 | }
|
---|
34 | const parseResultElement = new ParseResultElement();
|
---|
35 | const source = file.toString();
|
---|
36 | try {
|
---|
37 | const pojo = YAML.load(source, {
|
---|
38 | schema: JSON_SCHEMA
|
---|
39 | });
|
---|
40 | if (this.allowEmpty && typeof pojo === 'undefined') {
|
---|
41 | return parseResultElement;
|
---|
42 | }
|
---|
43 | const element = OpenApi3_1Element.refract(pojo, this.refractorOpts);
|
---|
44 | element.classes.push('result');
|
---|
45 | parseResultElement.push(element);
|
---|
46 | return parseResultElement;
|
---|
47 | } catch (error) {
|
---|
48 | throw new ParserError(`Error parsing "${file.uri}"`, {
|
---|
49 | cause: error
|
---|
50 | });
|
---|
51 | }
|
---|
52 | }
|
---|
53 | }
|
---|
54 | });
|
---|
55 | export default OpenApiYaml3_1Parser;
|
---|
56 | /* eslint-enable camelcase */ |
---|