-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathutil.ts
185 lines (157 loc) · 5.03 KB
/
util.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import { readFileSync } from 'fs';
import path from 'path';
import yaml from 'js-yaml';
import { merge } from 'lodash';
import structuredClone from '@ungap/structured-clone';
import { parse } from './parser';
import { ParserError } from './errors';
import type { AsyncAPIObject, Options } from './spec-types';
/**
* @private
*/
export const toJS = (asyncapiYAMLorJSON: string | object) => {
if (!asyncapiYAMLorJSON) {
throw new ParserError({
type: 'null-or-falsy-document',
title: "Document can't be null or falsey.", // eslint-disable-line
});
}
if (
asyncapiYAMLorJSON.constructor &&
asyncapiYAMLorJSON.constructor.name === 'Object'
) {
return asyncapiYAMLorJSON as AsyncAPIObject;
}
if (typeof asyncapiYAMLorJSON !== 'string') {
throw new ParserError({
type: 'invalid-document-type',
title: 'The AsyncAPI document has to be either a string or a JS object.',
});
}
if (JSON.stringify(asyncapiYAMLorJSON).trimStart().startsWith('{')) {
throw new ParserError({
type: 'invalid-yaml',
title: 'The provided yaml is not valid.',
});
}
return yaml.load(asyncapiYAMLorJSON) as AsyncAPIObject;
};
export function getSpecVersion(asyncapiDocument: AsyncAPIObject): number {
const versionString = asyncapiDocument.asyncapi;
return parseInt(versionString, 10);
}
/**
* @private
*
* @param asyncapiDocuments {AsyncAPIObject[]}
* @returns {boolean}
*/
export function versionCheck(asyncapiDocuments: AsyncAPIObject[]): number {
let currentVersion = getSpecVersion(asyncapiDocuments[0]);
for (const asyncapiDocument of asyncapiDocuments) {
const majorVersion = getSpecVersion(asyncapiDocument);
if (majorVersion !== currentVersion) {
throw new Error(
'Unable to bundle specification files of different major versions'
);
}
currentVersion = majorVersion;
}
return currentVersion;
}
export function isExternalReference(ref: string): boolean {
return typeof ref === 'string' && !ref.startsWith('#');
}
/**
*
* @param {string | string[]} files
* @param {Object} options
* @returns {Array<Object>}
* @private
*/
export const resolve = async (files: string | string[], options: Options) => {
const parsedJsons: AsyncAPIObject[] = [];
for (const file of files) {
const prevDir = process.cwd();
let filePath: any = file.split('/');
filePath.pop();
filePath = filePath.join('/');
let readFile: any = readFileSync(file, 'utf-8'); // eslint-disable-line
readFile = toJS(readFile);
if (filePath) {
process.chdir(path.resolve(prevDir, filePath));
}
readFile = await parse(readFile, getSpecVersion(readFile), options);
parsedJsons.push(readFile);
if (prevDir) {
process.chdir(prevDir);
}
}
return parsedJsons;
};
export async function mergeIntoBaseFile(
baseFilePath: string | string[],
bundledDocument: AsyncAPIObject,
majorVersion: number,
options: Options = {}
) {
// The base file's path must be an array of exactly one element to be properly
// iterated in `resolve()`. Even if it was passed to the main script as a
// string or an array of several elements.
const baseFilePathAsArray: string[] = [];
if (typeof baseFilePath === 'string') {
baseFilePathAsArray.push(baseFilePath);
} else if (Array.isArray(baseFilePath) && baseFilePath.length >= 1) {
baseFilePathAsArray.push(baseFilePath[0]);
}
const parsedBaseFile: AsyncAPIObject[] = await resolve(
baseFilePathAsArray,
options
);
if (majorVersion !== getSpecVersion(parsedBaseFile[0])) {
throw new Error(
'Base file has different major version than other specification files'
);
}
return merge(bundledDocument, parsedBaseFile[0]) as AsyncAPIObject;
}
// Purely decorative stuff, just to bring the order of the AsyncAPI Document's
// root properties into a familiar form.
export function orderPropsAccToAsyncAPISpec(
inputAsyncAPIObject: any
): AsyncAPIObject {
const orderOfPropsAccToAsyncAPISpec = [
'asyncapi',
'id',
'info',
'tags', // v2-specific root property
'externalDocs', // v2-specific root property
'defaultContentType',
'servers',
'channels',
'operations',
'components',
];
const outputAsyncAPIObject: any = {};
let i = 0;
// Making the best guess where root properties that are not specified in the
// AsyncAPI Specification were located in the original AsyncAPI Document
// (inserting them between known root properties.)
// DISCLAIMER: The original order is not guaranteed, it is only an
// extrapolating guess.
for (const key of Object.keys(inputAsyncAPIObject)) {
if (!orderOfPropsAccToAsyncAPISpec.includes(key)) {
orderOfPropsAccToAsyncAPISpec.splice(i, 0, key);
}
i++;
}
// Merging of known AsyncAPI Object root properties in a familiar order.
for (const prop of orderOfPropsAccToAsyncAPISpec) {
if (inputAsyncAPIObject[`${prop}`]) {
outputAsyncAPIObject[`${prop}`] = structuredClone(
inputAsyncAPIObject[`${prop}`]
);
}
}
return outputAsyncAPIObject as AsyncAPIObject;
}