4 const autoSyntax = require("postcss-html");
5 const dynamicRequire = require("./dynamicRequire");
6 const fs = require("fs");
7 const less = require("postcss-less");
8 const path = require("path");
9 const postcss = require("postcss");
10 const safeParser = require("postcss-safe-parser");
11 const scss = require("postcss-scss");
12 const sugarss = require("sugarss");
14 [syntaxName: string]: postcss$syntax,
17 stringify: postcss.stringify
25 const postcssProcessor = postcss();
27 module.exports = function(
28 stylelint /*: stylelint$internalApi*/
29 ) /*: Promise<?Object>*/ {
32 codeFilename?: string,
34 codeProcessors?: Array<Function>,
35 syntax?: stylelint$syntaxes,
38 arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
40 const cached /*: ?postcss$result*/ = stylelint._postcssResultCache.get(
43 if (cached) return Promise.resolve(cached);
46 if (options.code !== undefined) {
47 getCode = Promise.resolve(options.code);
48 } else if (options.filePath) {
49 getCode = readFile(options.filePath);
53 throw new Error("code or filePath required");
58 const customSyntax = stylelint._options.customSyntax;
59 let syntax = stylelint._options.syntax;
63 syntax = dynamicRequire(customSyntax);
66 `Cannot resolve custom syntax module ${customSyntax}`
70 syntax = syntaxes[syntax];
73 "You must use a valid syntax option, either: scss, less or sugarss"
77 syntaxes.css.parse = stylelint._options.fix
80 const fileExtension = path
81 .extname(options.filePath || "")
84 syntax = syntaxes[fileExtension] || autoSyntax(syntaxes);
87 const postcssOptions /*: postcss$options*/ = {};
89 postcssOptions.from = options.filePath;
92 * PostCSS allows for syntaxes that only contain a parser, however,
93 * it then expects the syntax to be set as the `parser` option rather than `syntax.
95 if (syntax && !syntax.stringify) {
96 postcssOptions.parser = syntax;
98 postcssOptions.syntax = syntax;
101 const source = options.code ? options.codeFilename : options.filePath;
102 let preProcessedCode = code;
103 if (options.codeProcessors) {
104 options.codeProcessors.forEach(codeProcessor => {
105 preProcessedCode = codeProcessor(preProcessedCode, source);
109 return postcssProcessor.process(preProcessedCode, postcssOptions);
111 .then(postcssResult => {
112 stylelint._postcssResultCache.set(options.filePath, postcssResult);
113 return postcssResult;
117 function readFile(filePath /*: string*/) /*: Promise<string>*/ {
118 return new Promise((resolve, reject) => {
119 fs.readFile(filePath, "utf8", (err, content) => {