UNPKG

@mintlify/common

Version:

Commonly shared code within Mintlify

61 lines (60 loc) 2.49 kB
import { getAST } from '../mdx/remark.js'; export const resolveSnippets = (ast, snippets) => { const snippetTreeMap = buildSnippetTreeMap(snippets); const newChildren = []; for (const child of ast.children) { if (child.type === 'mdxJsxFlowElement' && 'name' in child && child.name) { const componentName = String(child.name); if (componentName === 'Snippet' && 'attributes' in child) { const fileAttr = child.attributes.find((attr) => attr.type === 'mdxJsxAttribute' && attr.name === 'file'); if (fileAttr && fileAttr.value) { const fileName = typeof fileAttr.value === 'string' ? fileAttr.value : fileAttr.value.value; if (snippetTreeMap[fileName]) { const snippetAst = snippetTreeMap[fileName]; newChildren.push(...snippetAst.children); continue; } const fileNameOnly = fileName.split('/').pop(); if (fileNameOnly && snippetTreeMap[fileNameOnly]) { const snippetAst = snippetTreeMap[fileNameOnly]; newChildren.push(...snippetAst.children); continue; } } } if (snippetTreeMap[componentName]) { const snippetAst = snippetTreeMap[componentName]; newChildren.push(...snippetAst.children); continue; } newChildren.push(child); } else { newChildren.push(child); } } ast.children = newChildren; return ast; }; const buildSnippetTreeMap = (snippets) => { const map = {}; for (const snippet of snippets) { try { const snippetAst = getAST(snippet.content); if ('importNames' in snippet && snippet.importNames && snippet.importNames.length > 0) { for (const importName of snippet.importNames) { map[importName] = snippetAst; } } map[snippet.path] = snippetAst; const filename = snippet.path.split('/').pop(); if (filename && filename !== snippet.path) { map[filename] = snippetAst; } } catch (error) { console.error('Failed to parse snippet:', snippet.path, error); } } return map; };