@mintlify/common
Version:
Commonly shared code within Mintlify
44 lines (43 loc) • 1.65 kB
JavaScript
/**
* Canonicalize an OpenAPI path for comparison: strip a trailing slash except on
* the root `/`. Used only for lookup — the original spec key is preserved in the
* return value so downstream callers render the URL the spec declared.
*/
function canonicalize(path) {
if (path.length > 1 && path.endsWith('/')) {
return path.slice(0, -1);
}
return path;
}
/**
* Look up an OpenAPI path from a `paths` or `webhooks` object, tolerating
* trailing-slash mismatches. Returns the spec's original key and path item.
*
* Exact matches always win: if the spec declares both `/users` and `/users/`,
* a reference to either resolves to the correctly keyed operation. Only when
* there is no exact match do we fall back to a canonicalized (trailing-slash
* insensitive) lookup.
*
* Typed loosely on purpose — the OpenAPI type definitions vary between v3 and
* v3.1 in ways that confuse generic constraints, but at this layer we only
* care about identifying the matching key/value pair.
*/
export function findOpenApiPath(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
paths, endpoint) {
if (!paths)
return undefined;
const exact = paths[endpoint];
if (exact && typeof exact === 'object') {
return { pathKey: endpoint, pathItem: exact };
}
const target = canonicalize(endpoint);
for (const [specKey, pathItem] of Object.entries(paths)) {
if (!pathItem || typeof pathItem !== 'object')
continue;
if (canonicalize(specKey) === target) {
return { pathKey: specKey, pathItem: pathItem };
}
}
return undefined;
}