Initial commit
[yaffs-website] / node_modules / postcss-load-plugins / lib / plugins.js
1 // ------------------------------------
2 // # POSTCSS - LOAD PLUGINS - PLUGINS
3 // ------------------------------------
4
5 'use strict'
6
7 /**
8  * @method plugins
9  *
10  * @param {Object} config PostCSS Config
11  *
12  * @return {Array} plugins PostCSS Plugins
13  */
14 module.exports = function plugins (config) {
15   var plugins = []
16
17   if (Array.isArray(config.plugins)) {
18     plugins = config.plugins.filter(Boolean)
19
20     if (plugins.length && plugins.length > 0) {
21       plugins.forEach(function (plugin, i) {
22         if (!plugin) throw new Error('Loading PostCSS Plugin failed')
23
24         if (plugin.postcss) plugin = plugin.postcss
25
26         if (plugin.default) plugin = plugin.default
27
28         if (
29           !(typeof plugin === 'object' && Array.isArray(plugin.plugins) ||
30           typeof plugin === 'function')
31         ) {
32           throw new TypeError('Invalid PostCSS Plugin found: ' + '[' + i + ']')
33         }
34       })
35     }
36
37     return plugins
38   } else {
39     config = config.plugins
40
41     var load = function (plugin, options) {
42       if (options === null || Object.keys(options).length === 0) {
43         try {
44           return require(plugin)
45         } catch (err) {
46           err.message = 'Loading PostCSS Plugin failed: ' + err.message
47
48           throw err
49         }
50       } else {
51         try {
52           return require(plugin)(options)
53         } catch (err) {
54           err.message = 'Loading PostCSS Plugin failed: ' + err.message
55
56           throw err
57         }
58       }
59     }
60
61     Object.keys(config)
62       .filter(function (plugin) {
63         return config[plugin] !== false ? plugin : ''
64       })
65       .forEach(function (plugin, i) {
66         plugin = load(plugin, config[plugin])
67
68         if (plugin.postcss) plugin = plugin.postcss
69
70         if (plugin.default) plugin = plugin.default
71
72         if (
73           !(typeof plugin === 'object' && Array.isArray(plugin.plugins) ||
74           typeof plugin === 'function')
75         ) {
76           throw new TypeError('Invalid PostCSS Plugin found: ' + '[' + i + ']')
77         }
78
79         return plugins.push(plugin)
80       })
81
82     return plugins
83   }
84 }