@mintlify/common
Version:
Commonly shared code within Mintlify
47 lines (46 loc) • 1.81 kB
JavaScript
import { divisions } from '@mintlify/validation';
import { isPage } from '../navigation/isPage.js';
import { optionallyRemoveLeadingSlash } from '../optionallyRemoveLeadingSlash.js';
/**
* Assumes page hrefs in navWithPageContext have a leading / but config page paths do not.
* Outputted dictionary will NOT have a leading / in the dictionary keys.
*/
export function generatePathToVersionDict(decoratedNav) {
const pathToVersionDict = new Map();
generatePathToVersionDictRecursive(pathToVersionDict, decoratedNav);
return pathToVersionDict;
}
function generatePathToVersionDictRecursive(pathToVersionDict, nav, nearestVersion) {
if (typeof nav !== 'object')
return;
if (isPage(nav)) {
const key = optionallyRemoveLeadingSlash(nav.href);
const existingVersion = pathToVersionDict.get(key);
if (!pathToVersionDict.has(key)) {
pathToVersionDict.set(key, nearestVersion);
}
else if (existingVersion !== undefined && existingVersion !== nearestVersion) {
pathToVersionDict.set(key, undefined);
}
}
if ('pages' in nav) {
for (const page of nav.pages) {
if (typeof page === 'object') {
generatePathToVersionDictRecursive(pathToVersionDict, page, nearestVersion);
}
}
}
for (const key of ['groups', ...divisions]) {
if (key in nav) {
const items = nav[key];
if (Array.isArray(items)) {
for (const item of items) {
let version = nearestVersion;
if (key === 'versions')
version = item.version;
generatePathToVersionDictRecursive(pathToVersionDict, item, version);
}
}
}
}
}