makestatic-verify-id
Version:
Verify id attributes are unique
56 lines (51 loc) • 1.41 kB
JavaScript
/**
* Verify `id` attributes in HTML documents are unique.
*
* @class VerifyId
*
* @see /docs/api/graph-resources/
*/
class VerifyId {
/**
* Verifies that `id` attributes are unique in each HTML document.
*
* When `strict` is disabled an error is not thrown but a warning message is
* logged.
*
* @function after
* @member VerifyId
*
* @param {Object} context the processing context.
* @param {Object} options the plugin options.
*
* @option {Boolean=true} [strict] warn rather than error when `false`.
*
* @throws Error if no resource graph is available.
* @throws Error when a duplicate id attribute is detected in `strict` mode.
*/
after (context, options = {}) {
const log = context.log
const strict = options.strict === undefined ? true : options.strict
if (!context.graph) {
throw new Error(`verify-id expects a resource graph, use graph-resources`)
}
function error (err) {
if (!strict) {
return log.warn(err.message)
}
throw err
}
context.graph.htmlDocuments.forEach((doc) => {
const identifiers = doc.identifiers
let k
let v
for (k in identifiers) {
v = identifiers[k]
if (v.length > 1) {
error(new Error(`duplicate id attribute '${k}' in ${doc.file.path}`))
}
}
})
}
}
module.exports = VerifyId