postcssPlugin.mjs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { isAbsolute, join } from 'node:path';
  2. import process from 'node:process';
  3. import createStylelint from './createStylelint.mjs';
  4. import { isString } from './utils/validateTypes.mjs';
  5. import lintSource from './lintSource.mjs';
  6. /** @import {Config as StylelintConfig, PostcssPluginOptions} from 'stylelint' */
  7. /**
  8. * @type {import('postcss').PluginCreator<PostcssPluginOptions>}
  9. */
  10. export default function postcssPlugin(options = {}) {
  11. const [cwd, tailoredOptions] = isConfig(options)
  12. ? [process.cwd(), { config: options }]
  13. : [('cwd' in options && isString(options.cwd) && options.cwd) || process.cwd(), options];
  14. const stylelint = createStylelint(tailoredOptions);
  15. return {
  16. postcssPlugin: 'stylelint',
  17. /**
  18. * @param {import('postcss').Root} root
  19. * @param {import('postcss').Helpers} helpers
  20. * @returns {Promise<void>}
  21. */
  22. async Once(root, { result }) {
  23. let filePath = root.source && root.source.input.file;
  24. if (filePath && !isAbsolute(filePath)) {
  25. filePath = join(cwd, filePath);
  26. }
  27. await lintSource(stylelint, {
  28. filePath,
  29. existingPostcssResult: result,
  30. });
  31. },
  32. };
  33. }
  34. postcssPlugin.postcss = true;
  35. /**
  36. * @param {PostcssPluginOptions} options
  37. * @returns {options is StylelintConfig}
  38. */
  39. function isConfig(options) {
  40. return 'rules' in options;
  41. }