UNPKG

1.81 kBJavaScriptView Raw
1'use strict'
2
3let NoWorkResult = require('./no-work-result')
4let LazyResult = require('./lazy-result')
5let Document = require('./document')
6let Root = require('./root')
7
8class Processor {
9 constructor(plugins = []) {
10 this.version = '8.4.21'
11 this.plugins = this.normalize(plugins)
12 }
13
14 use(plugin) {
15 this.plugins = this.plugins.concat(this.normalize([plugin]))
16 return this
17 }
18
19 process(css, opts = {}) {
20 if (
21 this.plugins.length === 0 &&
22 typeof opts.parser === 'undefined' &&
23 typeof opts.stringifier === 'undefined' &&
24 typeof opts.syntax === 'undefined'
25 ) {
26 return new NoWorkResult(this, css, opts)
27 } else {
28 return new LazyResult(this, css, opts)
29 }
30 }
31
32 normalize(plugins) {
33 let normalized = []
34 for (let i of plugins) {
35 if (i.postcss === true) {
36 i = i()
37 } else if (i.postcss) {
38 i = i.postcss
39 }
40
41 if (typeof i === 'object' && Array.isArray(i.plugins)) {
42 normalized = normalized.concat(i.plugins)
43 } else if (typeof i === 'object' && i.postcssPlugin) {
44 normalized.push(i)
45 } else if (typeof i === 'function') {
46 normalized.push(i)
47 } else if (typeof i === 'object' && (i.parse || i.stringify)) {
48 if (process.env.NODE_ENV !== 'production') {
49 throw new Error(
50 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' +
51 'one of the syntax/parser/stringifier options as outlined ' +
52 'in your PostCSS runner documentation.'
53 )
54 }
55 } else {
56 throw new Error(i + ' is not a PostCSS plugin')
57 }
58 }
59 return normalized
60 }
61}
62
63module.exports = Processor
64Processor.default = Processor
65
66Root.registerProcessor(Processor)
67Document.registerProcessor(Processor)