index.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. const report = require('../../utils/report');
  3. const ruleMessages = require('../../utils/ruleMessages');
  4. const validateOptions = require('../../utils/validateOptions');
  5. const ruleName = 'no-empty-first-line';
  6. const noEmptyFirstLineTest = /^\s*[\r\n]/;
  7. const messages = ruleMessages(ruleName, {
  8. rejected: 'Unexpected empty line',
  9. });
  10. const meta = {
  11. url: 'https://stylelint.io/user-guide/rules/no-empty-first-line',
  12. fixable: true,
  13. };
  14. /** @type {import('stylelint').Rule} */
  15. const rule = (primary, _secondaryOptions, context) => {
  16. return (root, result) => {
  17. const validOptions = validateOptions(result, ruleName, { actual: primary });
  18. // @ts-expect-error -- TS2339: Property 'inline' does not exist on type 'Source'. Property 'lang' does not exist on type 'Source'.
  19. if (!validOptions || root.source.inline || root.source.lang === 'object-literal') {
  20. return;
  21. }
  22. const rootString = context.fix ? root.toString() : (root.source && root.source.input.css) || '';
  23. if (!rootString.trim()) {
  24. return;
  25. }
  26. if (noEmptyFirstLineTest.test(rootString)) {
  27. if (context.fix) {
  28. if (root.first == null) {
  29. throw new Error('The root node must have the first node.');
  30. }
  31. if (root.first.raws.before == null) {
  32. throw new Error('The first node must have spaces before.');
  33. }
  34. root.first.raws.before = root.first.raws.before.trimStart();
  35. return;
  36. }
  37. report({
  38. message: messages.rejected,
  39. node: root,
  40. result,
  41. ruleName,
  42. });
  43. }
  44. };
  45. };
  46. rule.ruleName = ruleName;
  47. rule.messages = messages;
  48. rule.meta = meta;
  49. module.exports = rule;