Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: conversion of openapi '3.0' to asyncapi '3.0' #269

Merged
merged 16 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 27 additions & 7 deletions src/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,42 @@ import { dump } from 'js-yaml';
import { converters as firstConverters } from "./first-version";
import { converters as secondConverters } from "./second-version";
import { converters as thirdConverters } from "./third-version";
import { converters as openapiConverters } from "./openapi";

import { serializeInput } from "./utils";

import type { AsyncAPIDocument, ConvertVersion, ConvertOptions, ConvertFunction } from './interfaces';
import type { AsyncAPIDocument, ConvertVersion, ConvertOptions, ConvertFunction, ConvertOpenAPIFunction, OpenAPIDocument } from './interfaces';

/**
* Value for key (version) represents the function which converts specification from previous version to the given as key.
*/
const converters: Record<string, ConvertFunction> = {
const converters: Record<string, ConvertFunction | ConvertOpenAPIFunction> = {
...firstConverters,
...secondConverters,
...thirdConverters,
...openapiConverters,
};
console.log(converters)
const conversionVersions = Object.keys(converters);

export function convert(asyncapi: string, version?: ConvertVersion, options?: ConvertOptions): string;
export function convert(asyncapi: AsyncAPIDocument, version?: ConvertVersion, options?: ConvertOptions): AsyncAPIDocument;
export function convert(asyncapi: string | AsyncAPIDocument, version: ConvertVersion = '2.6.0', options: ConvertOptions = {}): string | AsyncAPIDocument {
const { format, document } = serializeInput(asyncapi);
function convertOpenAPIToAsyncAPI(openapiDocument: OpenAPIDocument | AsyncAPIDocument, options: ConvertOptions): AsyncAPIDocument {
const openapiToAsyncapiConverter = converters['openapi'];
if (openapiToAsyncapiConverter) {
return openapiToAsyncapiConverter(openapiDocument as any, options) as AsyncAPIDocument;
} else {
throw new Error(`Unsupported OpenAPI version. This converter only supports OpenAPI 3.0.`);
}
}

// export function convert(asyncapi: string, version?: ConvertVersion, options?: ConvertOptions): string;
// export function convert(asyncapi: AsyncAPIDocument, version?: ConvertVersion, options?: ConvertOptions): AsyncAPIDocument;
export function convert(input: string | AsyncAPIDocument | OpenAPIDocument, version: ConvertVersion , options: ConvertOptions= {}): string | AsyncAPIDocument | OpenAPIDocument {
const { format, document } = serializeInput(input);

if ('openapi' in document) {
let convertedAsyncAPI = convertOpenAPIToAsyncAPI(document, options);
return format === 'yaml' ? dump(convertedAsyncAPI, { skipInvalid: true }) : convertedAsyncAPI;
}

const asyncapiVersion = document.asyncapi;
let fromVersion = conversionVersions.indexOf(asyncapiVersion);
Expand All @@ -42,7 +59,10 @@ export function convert(asyncapi: string | AsyncAPIDocument, version: ConvertVer
let converted = document;
for (let i = fromVersion; i <= toVersion; i++) {
const v = conversionVersions[i] as ConvertVersion;
converted = converters[v](converted, options);
const convertFunction = converters[v];
converted = ('asyncapi' in converted)
? (convertFunction as ConvertFunction)(converted as AsyncAPIDocument, options)
: (convertFunction as ConvertOpenAPIFunction)(converted as OpenAPIDocument, options);
}

if (format === 'yaml') {
Expand Down
4 changes: 3 additions & 1 deletion src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
* PUBLIC TYPES
*/
export type AsyncAPIDocument = { asyncapi: string } & Record<string, any>;
export type ConvertVersion = '1.1.0' | '1.2.0' | '2.0.0-rc1' | '2.0.0-rc2' | '2.0.0' | '2.1.0' | '2.2.0' | '2.3.0' | '2.4.0' | '2.5.0' | '2.6.0' | '3.0.0';
export type OpenAPIDocument = { openapi: string } & Record<string, any>;
export type ConvertVersion = '1.1.0' | '1.2.0' | '2.0.0-rc1' | '2.0.0-rc2' | '2.0.0' | '2.1.0' | '2.2.0' | '2.3.0' | '2.4.0' | '2.5.0' | '2.6.0' | '3.0.0' | 'openapi';
Gmin2 marked this conversation as resolved.
Show resolved Hide resolved
export type ConvertV2ToV3Options = {
idGenerator?: (data: { asyncapi: AsyncAPIDocument, kind: 'channel' | 'operation' | 'message', key: string | number | undefined, path: Array<string | number>, object: any, parentId?: string }) => string,
pointOfView?: 'application' | 'client',
Expand All @@ -18,4 +19,5 @@ export type ConvertOptions = {
* PRIVATE TYPES
*/
export type ConvertFunction = (asyncapi: AsyncAPIDocument, options: ConvertOptions) => AsyncAPIDocument;
export type ConvertOpenAPIFunction = (openapi: OpenAPIDocument, options: ConvertOptions) => AsyncAPIDocument;

120 changes: 120 additions & 0 deletions src/openapi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { sortObjectKeys, isRefObject, isPlainObject } from "./utils";
import { AsyncAPIDocument, ConvertOpenAPIFunction, ConvertOptions, OpenAPIDocument } from "./interfaces";

export const converters: Record<string, ConvertOpenAPIFunction > = {
'openapi': from_openapi_to_asyncapi,
Gmin2 marked this conversation as resolved.
Show resolved Hide resolved
}

function from_openapi_to_asyncapi(openapi: OpenAPIDocument, options: ConvertOptions): AsyncAPIDocument{
convertName(openapi)

convertInfoObject(openapi);
if (isPlainObject(openapi.servers)) {
openapi.servers = convertServerObjects(openapi.servers, openapi);
}

return sortObjectKeys(
openapi,
['asyncapi', 'info', 'defaultContentType', 'servers', 'channels', 'operations', 'components']
)
}

function convertName(openapi: OpenAPIDocument): AsyncAPIDocument {
let { openapi: version } = openapi;
openapi.asyncapi = version;
Gmin2 marked this conversation as resolved.
Show resolved Hide resolved
delete (openapi as any).openapi;;

return sortObjectKeys(
openapi,
['asyncapi', 'info', 'defaultContentType', 'servers', 'channels', 'operations', 'components']
)
}

function convertInfoObject(openapi: OpenAPIDocument) {
if(openapi.tags) {
openapi.info.tags = openapi.tags;
delete openapi.tags;
}

if(openapi.externalDocs) {
openapi.info.externalDocs = openapi.externalDocs;
delete openapi.externalDocs;
}

return (openapi.info = sortObjectKeys(openapi.info, [
"title",
"version",
"description",
"termsOfService",
"contact",
"license",
"tags",
"externalDocs",
]));
}

function convertServerObjects(servers: Record<string, any>, openapi: OpenAPIDocument) {
console.log("security",openapi.security)
const newServers: Record<string, any> = {};
const security: Record<string, any> = openapi.security;
Object.entries(servers).forEach(([serverName, server]: [string, any]) => {
if (isRefObject(server)) {
newServers[serverName] = server;
return;
}

const { host, pathname, protocol } = resolveServerUrl(server.url);
server.host = host;
if (pathname !== undefined) {
server.pathname = pathname;
}

if (protocol !== undefined && server.protocol === undefined) {
server.protocol = protocol;
}
delete server.url;

if (security) {
server.security = security;
delete openapi.security;
}

newServers[serverName] = sortObjectKeys(
server,
['host', 'pathname', 'protocol', 'protocolVersion', 'title', 'summary', 'description', 'variables', 'security', 'tags', 'externalDocs', 'bindings'],
);
});

return newServers
}

function resolveServerUrl(url: string): {
host: string;
pathname: string | undefined;
protocol: string | undefined;
} {
let [maybeProtocol, maybeHost] = url.split("://");
console.log("maybeProtocol", maybeProtocol);
if (!maybeHost) {
maybeHost = maybeProtocol;
}
const [host, ...pathnames] = maybeHost.split("/");
console.log("pathname1", pathnames);
if (pathnames.length) {
return {
host,
pathname: `/${pathnames.join("/")}`,
protocol: maybeProtocol,
};
}
return { host, pathname: undefined, protocol: maybeProtocol };
}

function convertSecurity(security: Record<string, any>) {
if(security.type === 'oauth2' && security.flows.authorizationCode.scopes) {
const availableScopes = security.flows.authorizationCode.scopes;
security.flows.authorizationCode.availableScopes = availableScopes;
delete security.flows.authorizationCode.scopes;
}
return security;
}
23 changes: 15 additions & 8 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { load } from 'js-yaml';

import type { AsyncAPIDocument } from "./interfaces";
import type { AsyncAPIDocument, OpenAPIDocument } from "./interfaces";

export function serializeInput(document: string | AsyncAPIDocument): { format: 'json' | 'yaml', document: AsyncAPIDocument } | never {
export function serializeInput(document: string | AsyncAPIDocument | OpenAPIDocument): { format: 'json' | 'yaml', document: AsyncAPIDocument | OpenAPIDocument } | never {
let triedConvertToYaml = false;
try {
if (typeof document === 'object') {
Expand All @@ -14,18 +14,25 @@ export function serializeInput(document: string | AsyncAPIDocument): { format: '

const maybeJSON = JSON.parse(document);
if (typeof maybeJSON === 'object') {
return {
format: 'json',
document: maybeJSON,
};
if ('openapi' in maybeJSON) {
return {
format: 'json',
document: maybeJSON,
};
} else {
return {
format: 'json',
document: maybeJSON,
};
}
}

triedConvertToYaml = true; // NOSONAR
// if `maybeJSON` is object, then we have 100% sure that we operate on JSON,
// but if it's `string` then we have option that it can be YAML but it doesn't have to be
return {
format: 'yaml',
document: load(document) as AsyncAPIDocument,
document: load(document) as AsyncAPIDocument | OpenAPIDocument,
};
} catch (e) {
try {
Expand All @@ -36,7 +43,7 @@ export function serializeInput(document: string | AsyncAPIDocument): { format: '
// try to parse (again) YAML, because the text itself may not have a JSON representation and cannot be represented as a JSON object/string
return {
format: 'yaml',
document: load(document as string) as AsyncAPIDocument,
document: load(document as string) as AsyncAPIDocument | OpenAPIDocument,
};
} catch (err) {
throw new Error('AsyncAPI document must be a valid JSON or YAML document.');
Expand Down
Loading