1 | 'use strict';
|
---|
2 |
|
---|
3 | var csstree = require('css-tree');
|
---|
4 | var syntax = csstree.lexer;
|
---|
5 |
|
---|
6 | function validate(css, filename) {
|
---|
7 | var errors = [];
|
---|
8 | var ast = csstree.parse(css, {
|
---|
9 | filename: filename,
|
---|
10 | positions: true,
|
---|
11 | onParseError: function(error) {
|
---|
12 | errors.push(error);
|
---|
13 | }
|
---|
14 | });
|
---|
15 |
|
---|
16 | csstree.walk(ast, {
|
---|
17 | visit: 'Declaration',
|
---|
18 | enter: function(node) {
|
---|
19 | var match = syntax.matchDeclaration(node);
|
---|
20 | var error = match.error;
|
---|
21 |
|
---|
22 | if (error) {
|
---|
23 | var message = error.rawMessage || error.message || error;
|
---|
24 |
|
---|
25 | // ignore errors except those which make sense
|
---|
26 | if (error.name !== 'SyntaxMatchError' &&
|
---|
27 | error.name !== 'SyntaxReferenceError') {
|
---|
28 | return;
|
---|
29 | }
|
---|
30 |
|
---|
31 | if (message === 'Mismatch') {
|
---|
32 | message = 'Invalid value for `' + node.property + '`';
|
---|
33 | } else if (message === 'Uncomplete match') {
|
---|
34 | message = 'The rest part of value can\'t be matched to `' + node.property + '` syntax';
|
---|
35 | }
|
---|
36 |
|
---|
37 | errors.push({
|
---|
38 | name: error.name,
|
---|
39 | node: node,
|
---|
40 | loc: error.loc || node.loc,
|
---|
41 | line: error.line || node.loc && node.loc.start && node.loc.start.line,
|
---|
42 | column: error.column || node.loc && node.loc.start && node.loc.start.column,
|
---|
43 | property: node.property,
|
---|
44 | message: message,
|
---|
45 | error: error
|
---|
46 | });
|
---|
47 | }
|
---|
48 | }
|
---|
49 | });
|
---|
50 |
|
---|
51 | return errors;
|
---|
52 | }
|
---|
53 |
|
---|
54 | exports.addon = function (renderer) {
|
---|
55 | if (process.env.NODE_ENV !== 'production') {
|
---|
56 | require('./__dev__/warnOnMissingDependencies')('validate', renderer, ['putRaw']);
|
---|
57 | }
|
---|
58 |
|
---|
59 | if (process.env.NODE_ENV === 'production') {
|
---|
60 | console.warn(
|
---|
61 | 'You are using nano-css "validate" in production. ' +
|
---|
62 | 'This addon is meant to be used only in development.'
|
---|
63 | );
|
---|
64 | }
|
---|
65 |
|
---|
66 | var putRaw = renderer.putRaw;
|
---|
67 |
|
---|
68 | renderer.putRaw = function (rawCssRule) {
|
---|
69 | var errors = validate(rawCssRule);
|
---|
70 |
|
---|
71 | if (errors && errors.length) {
|
---|
72 | errors.forEach(function (error) {
|
---|
73 | console.error('nano-css error, ' + error.name + ': ' + error.message);
|
---|
74 | // eslint-disable-next-line
|
---|
75 | console.log(error);
|
---|
76 | console.error(rawCssRule);
|
---|
77 | });
|
---|
78 | }
|
---|
79 |
|
---|
80 | return putRaw.apply(renderer, arguments);
|
---|
81 | };
|
---|
82 | };
|
---|