UNPKG

2.87 kBJavaScriptView Raw
1'use strict';
2
3const _ = require('lodash');
4
5/** @typedef {import('stylelint').PostcssResult} PostcssResult */
6/** @typedef {import('postcss').NodeSource} NodeSource */
7/** @typedef {import('stylelint').StylelintResult} StylelintResult */
8
9/**
10 * @param {PostcssResult} [postcssResult]
11 * @param {import('stylelint').StylelintCssSyntaxError} [cssSyntaxError]
12 * @return {StylelintResult}
13 */
14module.exports = function (postcssResult, cssSyntaxError) {
15 /** @type {StylelintResult} */
16 let stylelintResult;
17 /** @type {string | undefined} */
18 let source;
19
20 if (postcssResult && postcssResult.root) {
21 if (postcssResult.root.source) {
22 source = postcssResult.root.source.input.file;
23
24 if (!source && 'id' in postcssResult.root.source.input) {
25 source = postcssResult.root.source.input.id;
26 }
27 }
28
29 // Strip out deprecation warnings from the messages
30 const deprecationMessages = _.remove(postcssResult.messages, {
31 stylelintType: 'deprecation',
32 });
33 const deprecations = deprecationMessages.map((deprecationMessage) => {
34 return {
35 text: deprecationMessage.text,
36 reference: deprecationMessage.stylelintReference,
37 };
38 });
39
40 // Also strip out invalid options
41 const invalidOptionMessages = _.remove(postcssResult.messages, {
42 stylelintType: 'invalidOption',
43 });
44 const invalidOptionWarnings = invalidOptionMessages.map((invalidOptionMessage) => {
45 return {
46 text: invalidOptionMessage.text,
47 };
48 });
49
50 const parseErrors = _.remove(postcssResult.messages, {
51 stylelintType: 'parseError',
52 });
53
54 // This defines the stylelint result object that formatters receive
55 stylelintResult = {
56 source,
57 deprecations,
58 invalidOptionWarnings,
59 // TODO TYPES check which types are valid? postcss? stylelint?
60 /* eslint-disable-next-line object-shorthand */
61 parseErrors: /** @type {any} */ (parseErrors),
62 errored: postcssResult.stylelint.stylelintError,
63 warnings: postcssResult.messages.map((message) => {
64 return {
65 line: message.line,
66 column: message.column,
67 rule: message.rule,
68 severity: message.severity,
69 text: message.text,
70 };
71 }),
72 ignored: postcssResult.stylelint.ignored,
73 _postcssResult: postcssResult,
74 };
75 } else if (cssSyntaxError) {
76 if (cssSyntaxError.name !== 'CssSyntaxError') {
77 throw cssSyntaxError;
78 }
79
80 stylelintResult = {
81 source: cssSyntaxError.file || '<input css 1>',
82 deprecations: [],
83 invalidOptionWarnings: [],
84 parseErrors: [],
85 errored: true,
86 warnings: [
87 {
88 line: cssSyntaxError.line,
89 column: cssSyntaxError.column,
90 rule: cssSyntaxError.name,
91 severity: 'error',
92 text: `${cssSyntaxError.reason} (${cssSyntaxError.name})`,
93 },
94 ],
95 };
96 } else {
97 throw new Error(
98 'createPartialStylelintResult must be called with either postcssResult or CssSyntaxError',
99 );
100 }
101
102 return stylelintResult;
103};