You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.8 KiB

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