|
| 1 | +/* eslint-disable no-console */ |
| 2 | +const fs = require('fs'); |
| 3 | +const path = require('path'); |
| 4 | +const yaml = require('js-yaml'); |
| 5 | + |
| 6 | +const ROOT = path.resolve(__dirname, '..'); |
| 7 | +const IGNORED_DIRS = new Set([ |
| 8 | + '.git', |
| 9 | + 'build', |
| 10 | + 'dist', |
| 11 | + 'node_modules', |
| 12 | +]); |
| 13 | +const MARKDOWN_EXTENSIONS = new Set(['.md', '.mdx']); |
| 14 | + |
| 15 | +function walk(dir, files = []) { |
| 16 | + fs.readdirSync(dir, { withFileTypes: true }).forEach((entry) => { |
| 17 | + if (entry.isDirectory()) { |
| 18 | + if (!IGNORED_DIRS.has(entry.name)) { |
| 19 | + walk(path.join(dir, entry.name), files); |
| 20 | + } |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + if (entry.isFile() && MARKDOWN_EXTENSIONS.has(path.extname(entry.name))) { |
| 25 | + files.push(path.join(dir, entry.name)); |
| 26 | + } |
| 27 | + }); |
| 28 | + |
| 29 | + return files; |
| 30 | +} |
| 31 | + |
| 32 | +function extractFrontmatter(content) { |
| 33 | + if (!content.startsWith('---\n') && !content.startsWith('---\r\n')) { |
| 34 | + return null; |
| 35 | + } |
| 36 | + |
| 37 | + const lines = content.split(/\r?\n/); |
| 38 | + const closingIndex = lines.slice(1).findIndex((line) => line.trim() === '---'); |
| 39 | + if (closingIndex >= 0) { |
| 40 | + return lines.slice(1, closingIndex + 1).join('\n'); |
| 41 | + } |
| 42 | + |
| 43 | + throw new Error('Missing closing frontmatter delimiter'); |
| 44 | +} |
| 45 | + |
| 46 | +function main() { |
| 47 | + const failures = []; |
| 48 | + |
| 49 | + walk(ROOT).forEach((file) => { |
| 50 | + const relativePath = path.relative(ROOT, file); |
| 51 | + const content = fs.readFileSync(file, 'utf8'); |
| 52 | + |
| 53 | + try { |
| 54 | + const frontmatter = extractFrontmatter(content); |
| 55 | + if (frontmatter !== null) { |
| 56 | + yaml.load(frontmatter); |
| 57 | + } |
| 58 | + } catch (error) { |
| 59 | + failures.push(`${relativePath}: ${error.message}`); |
| 60 | + } |
| 61 | + }); |
| 62 | + |
| 63 | + if (failures.length > 0) { |
| 64 | + console.error('Invalid Markdown frontmatter found:\n'); |
| 65 | + failures.forEach((failure) => console.error(`- ${failure}`)); |
| 66 | + process.exit(1); |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +main(); |
0 commit comments