UNPKG

micro-mdx-parser

Version:

A tiny parser to convert markdown or html into JSON

71 lines (59 loc) 1.66 kB
const { arrayIncludes } = require('./utils') const { voidTags } = require('./tags') function getValue({ type, content, tagValue }) { if (type === 'text') { return content } if (type === 'comment') { return `<!--${node.content}-->` } return tagValue } function verifyVoidTags({ type, tagName, tagValue }) { if (type !== 'element') return const value = tagValue.trim() if (arrayIncludes(voidTags, tagName.toLowerCase()) && value[value.length-2] !== '/') { return `Missing closing "/>" on "${type}". ${value}` } } const defaultRules = [ verifyVoidTags ] function validator(tree, options = {}) { const allErrors = [] const { rules } = options const checkRules = rules || defaultRules const checkedNodes = tree.map((node) => { const { type, tagName = '', propsRaw, children, position } = node if (!node.tagValue) { node.tagValue = getValue(node) } if (!node.tagName) { node.tagName = '' } // console.log('node', node) /* Run verification rules */ const errorsFound = checkRules.map((execRule) => { // console.log('rule', rule) return execRule(node) }).filter(Boolean) function addError(err) { if (!node.errors) node.errors = [] node.errors.push({ message: err, value: node.tagValue, position }) allErrors.push({ message: err, value: node.tagValue, position }) } if (errorsFound.length) { errorsFound.forEach(err => { addError(err) }) } if (children && children.length) { return validator(children, options) } return node }) return allErrors } module.exports = { validator }