UNPKG

2.17 kBJavaScriptView Raw
1const VFile = require('vfile');
2const { walk } = require('./walk');
3const vfileSort = require('vfile-sort');
4const reporter = require('vfile-reporter');
5const nest = require('./nest');
6
7const CANONICAL = {
8 String: 'string',
9 Boolean: 'boolean',
10 Undefined: 'undefined',
11 Number: 'number',
12 array: 'Array',
13 date: 'Date',
14 object: 'Object'
15};
16
17/**
18 * Passively lints and checks documentation data.
19 *
20 * @name lint
21 * @param {Object} comment parsed comment
22 * @returns {Array<Object>} array of errors
23 */
24function lintComments(comment) {
25 comment.tags.forEach(function(tag) {
26 function nameInvariant(name) {
27 if (name && typeof CANONICAL[name] === 'string') {
28 comment.errors.push({
29 message:
30 'type ' + name + ' found, ' + CANONICAL[name] + ' is standard',
31 commentLineNumber: tag.lineNumber
32 });
33 }
34 }
35
36 function checkCanonical(type) {
37 if (type.type === 'NameExpression') {
38 nameInvariant(type.name);
39 }
40
41 if (type.elements) {
42 checkSubtypes(type.elements);
43 }
44 if (type.applications) {
45 checkSubtypes(type.applications);
46 }
47 }
48
49 function checkSubtypes(subtypes) {
50 if (Array.isArray(subtypes)) {
51 subtypes.forEach(checkCanonical);
52 }
53 }
54
55 if (tag.type && typeof tag.type === 'object') {
56 checkCanonical(tag.type);
57 }
58 });
59 nest(comment);
60
61 return comment;
62}
63
64/**
65 * @private
66 * Extract lint instructions from comments and generate user-readable output.
67 * @param {Array<Object>} comments a list of comments
68 * @returns {string} user-readable output
69 */
70function formatLint(comments) {
71 const vFiles = {};
72 walk(comments, function(comment) {
73 comment.errors.forEach(function(error) {
74 const p = comment.context.file;
75 vFiles[p] =
76 vFiles[p] ||
77 new VFile({
78 path: p
79 });
80 vFiles[p].warn(error.message, {
81 line: comment.loc.start.line + (error.commentLineNumber || 0)
82 });
83 });
84 });
85 return reporter(Object.keys(vFiles).map(p => vfileSort(vFiles[p])));
86}
87
88module.exports.lintComments = lintComments;
89module.exports.formatLint = formatLint;