@mintlify/common
Version:
Commonly shared code within Mintlify
49 lines (48 loc) • 1.78 kB
JavaScript
import { OpenAPIV3 } from 'openapi-types';
import { isAbsoluteUrl } from '../isAbsoluteUrl.js';
import { isDocsConfig } from '../isDocsConfig.js';
export const parseApiString = (apiString, config) => {
const components = apiString.trim().split(/\s+/);
if (!components[0] || !components[1] || components.length > 2) {
throw new Error('improperly formatted api string');
}
const upperMethod = components[0];
const endpointStr = components[1];
const method = upperMethod.toLowerCase();
if (!VALID_METHODS.includes(method)) {
throw new Error('invalid http method');
}
const { origin, path } = parseEndpoint(endpointStr);
const servers = origin ? [{ url: origin }] : parseServers(config);
return {
path,
method: method,
servers,
};
};
const VALID_METHODS = Object.values(OpenAPIV3.HttpMethods);
const parseEndpoint = (endpoint) => {
if (!isAbsoluteUrl(endpoint)) {
return {
origin: undefined,
path: endpoint,
};
}
const url = new URL(endpoint);
return {
origin: decodeURI(url.origin),
path: decodeURI(url.pathname),
};
};
const parseServers = (config) => {
var _a, _b, _c;
const baseUrl = config && isDocsConfig(config) ? (_b = (_a = config.api) === null || _a === void 0 ? void 0 : _a.mdx) === null || _b === void 0 ? void 0 : _b.server : (_c = config === null || config === void 0 ? void 0 : config.api) === null || _c === void 0 ? void 0 : _c.baseUrl;
if (!baseUrl) {
return undefined;
}
if (typeof baseUrl === 'string') {
return [{ url: baseUrl }];
}
const servers = baseUrl.filter(Boolean).map((url) => ({ url }));
return servers.length > 0 ? servers : undefined;
};