UNPKG

next-markdown-blog

Version:

An npm package that allows Next.js users to create blogs using markdown

79 lines (78 loc) 2.91 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseMarkdown = parseMarkdown; exports.markdownToHtml = markdownToHtml; exports.extractSlugFromPath = extractSlugFromPath; exports.extractCategoryFromPath = extractCategoryFromPath; exports.generateRoutePath = generateRoutePath; const gray_matter_1 = __importDefault(require("gray-matter")); const remark_1 = require("remark"); const remark_html_1 = __importDefault(require("remark-html")); /** * Parse markdown content and extract frontmatter metadata */ function parseMarkdown(content) { const { data, content: markdownContent } = (0, gray_matter_1.default)(content); // Validate required metadata fields const metadata = { title: data.title || '', date: data.date || new Date().toISOString().split('T')[0], category: data.category || 'uncategorized', ogImage: data.ogImage, description: data.description, author: data.author, tags: data.tags || [], ...data, }; return { content: markdownContent, metadata, }; } /** * Convert markdown content to HTML */ async function markdownToHtml(markdown) { const processor = (0, remark_1.remark)().use(remark_html_1.default, { sanitize: false }); const result = await processor.process(markdown); return result.toString(); } /** * Extract slug from file path */ function extractSlugFromPath(filePath) { const fileName = filePath.split('/').pop() || ''; return fileName.replace(/\.md$/, ''); } /** * Extract category from file path */ function extractCategoryFromPath(filePath, contentDir) { // Normalize paths to handle different separators and relative paths const normalizedContentDir = contentDir.replace(/\/$/, '').replace(/^\.\//, ''); // Remove trailing slash and ./ prefix const normalizedFilePath = filePath.replace(/\\/g, '/').replace(/^\.\//, ''); // Normalize separators and remove ./ prefix // Remove the content directory from the file path let relativePath = normalizedFilePath; if (normalizedFilePath.startsWith(normalizedContentDir)) { relativePath = normalizedFilePath.substring(normalizedContentDir.length); } // Remove leading slash relativePath = relativePath.replace(/^\//, ''); const pathParts = relativePath.split('/'); // If there's a category directory, use it if (pathParts.length > 1) { return pathParts[0]; } return 'uncategorized'; } /** * Generate route path for a blog post */ function generateRoutePath(slug, _category, basePath) { const cleanBasePath = basePath.replace(/\/$/, ''); // For simplicity, all posts now use the same route structure: /blog/slug return `${cleanBasePath}/${slug}`; }