UNPKG

@mintlify/common

Version:

Commonly shared code within Mintlify

54 lines (53 loc) 3.06 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { MdxImportSpecifier } from '../../../types/mdx/snippets/import.js'; import { getAST } from '../../remark.js'; import { findExport } from './findExport.js'; import { injectToTopOfFileOfTree } from './injectToTopOfFile.js'; import { resolveComponentWithContent } from './resolveComponentWithContent.js'; export { findExport } from './findExport.js'; export { injectToTopOfFileOfTree } from './injectToTopOfFile.js'; const VALID_SPECIFIERS = [ MdxImportSpecifier.ImportSpecifier, MdxImportSpecifier.RenamedImportSpecifier, ]; const OTHER_SPECIFIERS = [ MdxImportSpecifier.ImportDefaultSpecifier, MdxImportSpecifier.ImportNamespaceSpecifier, ]; /** * * @param importSpecifier The name of the imported component we want to replace * @param destinationPageContent The content of the page we want to inject the import into * @param importedFileContent The content of the file we are importing from * @returns */ export const resolveImport = (importSpecifier, destinationPageContent, importedFileContent, exportMap) => __awaiter(void 0, void 0, void 0, function* () { if (VALID_SPECIFIERS.includes(importSpecifier.type)) { // normal import: import { Component } from '/snippets/Component.mdx' or jsx file if ((importSpecifier.renamedName && exportMap[importSpecifier.renamedName]) || exportMap[importSpecifier.name]) { // TODO: Handle collisions return destinationPageContent; } // find "Component" in "/snippets/Component.mdx" or jsx files const exportContent = findExport(importSpecifier.name, importedFileContent, importSpecifier.renamedName); if (exportContent == undefined) throw new Error(`Could not find export ${importSpecifier.name} in snippet`); // Inject "export const Component = `...`" into the top of the destination page injectToTopOfFileOfTree(destinationPageContent, getAST(exportContent).children); return destinationPageContent; } else if (OTHER_SPECIFIERS.includes(importSpecifier.type)) { // default export: import DefaultComponent from '/snippets/DefaultComponent.mdx' // replace every instance of DefaultComponent with the content of the imported file return yield resolveComponentWithContent(destinationPageContent, importSpecifier.name, importedFileContent, exportMap); } });