@antebudimir/eslint-plugin-vanilla-extract 1.1.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +44 -7
  2. package/dist/css-rules/alphabetical-order/property-order-enforcer.js +1 -11
  3. package/dist/css-rules/alphabetical-order/rule-definition.js +2 -1
  4. package/dist/css-rules/concentric-order/property-order-enforcer.js +2 -2
  5. package/dist/css-rules/concentric-order/rule-definition.js +3 -1
  6. package/dist/css-rules/custom-order/rule-definition.js +1 -0
  7. package/dist/css-rules/shared-utils/alphabetical-property-comparator.d.ts +8 -0
  8. package/dist/css-rules/shared-utils/alphabetical-property-comparator.js +19 -0
  9. package/dist/css-rules/shared-utils/font-face-property-order-enforcer.d.ts +10 -0
  10. package/dist/css-rules/shared-utils/font-face-property-order-enforcer.js +39 -0
  11. package/dist/css-rules/shared-utils/font-face-style-processor.d.ts +10 -0
  12. package/dist/css-rules/shared-utils/font-face-style-processor.js +17 -0
  13. package/dist/css-rules/shared-utils/order-strategy-visitor-creator.js +22 -7
  14. package/dist/css-rules/theme-tokens/ast-helpers.d.ts +12 -0
  15. package/dist/css-rules/theme-tokens/ast-helpers.js +80 -0
  16. package/dist/css-rules/theme-tokens/index.d.ts +2 -0
  17. package/dist/css-rules/theme-tokens/index.js +2 -0
  18. package/dist/css-rules/theme-tokens/rule-definition.d.ts +3 -0
  19. package/dist/css-rules/theme-tokens/rule-definition.js +29 -0
  20. package/dist/css-rules/theme-tokens/theme-loader.d.ts +10 -0
  21. package/dist/css-rules/theme-tokens/theme-loader.js +71 -0
  22. package/dist/css-rules/theme-tokens/theme-token-visitor.d.ts +2 -0
  23. package/dist/css-rules/theme-tokens/theme-token-visitor.js +113 -0
  24. package/dist/css-rules/theme-tokens/theme-tokens-enforcer.d.ts +1 -0
  25. package/dist/css-rules/theme-tokens/theme-tokens-enforcer.js +1 -0
  26. package/dist/css-rules/theme-tokens/value-comparison.d.ts +1 -0
  27. package/dist/css-rules/theme-tokens/value-comparison.js +1 -0
  28. package/dist/index.js +1 -1
  29. package/package.json +4 -5
  30. package/dist/css-sample/sample.css.d.ts +0 -161
  31. package/dist/css-sample/sample.css.js +0 -551
package/README.md CHANGED
@@ -2,8 +2,7 @@
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/@antebudimir/eslint-plugin-vanilla-extract.svg)](https://www.npmjs.com/package/@antebudimir/eslint-plugin-vanilla-extract)
4
4
 
5
- An ESLint plugin for enforcing CSS ordering in [vanilla-extract](https://github.com/vanilla-extract-css/vanilla-extract) css styles. Available presets are for alphabetical and
6
- [concentric](https://rhodesmill.org/brandon/2011/concentric-css/) CSS ordering. The plugin also supports a custom group ordering option based on groups available in concentric CSS.
5
+ An ESLint plugin for enforcing best practices in [vanilla-extract](https://github.com/vanilla-extract-css/vanilla-extract) CSS styles, including CSS property ordering and additional linting rules. Available presets are for alphabetical and [concentric](https://rhodesmill.org/brandon/2011/concentric-css/) CSS ordering. The plugin also supports a custom group ordering option based on groups available in [concentric CSS](src/css-rules/concentric-order/concentric-groups.ts).
7
6
 
8
7
  ## Features
9
8
 
@@ -16,11 +15,13 @@ An ESLint plugin for enforcing CSS ordering in [vanilla-extract](https://github.
16
15
  - Handles multiple vanilla-extract APIs (style, styleVariants, recipe, globalStyle, etc.)
17
16
  - Handles complex cases like nested objects, arrays of styles, and pseudo selectors
18
17
  - Works with camelCase properties as used in vanilla-extract
18
+ - Additional linting rules for enhanced code quality (see roadmap for upcoming features)
19
19
 
20
20
  ## Requirements
21
21
 
22
22
  - ESLint 9.0.0 or higher
23
23
  - Node.js 18.18.0 or higher
24
+ - ESM (ECMAScript Modules) only
24
25
 
25
26
  ## Installation
26
27
 
@@ -37,6 +38,8 @@ pnpm add -D @antebudimir/eslint-plugin-vanilla-extract
37
38
 
38
39
  ## Usage
39
40
 
41
+ **Note: This plugin is ESM-only.** It must be used with ESM configurations and can't be used with CommonJS `require()`.
42
+
40
43
  ### ESLint Flat Config (ESLint 9+)
41
44
 
42
45
  Create or update your `eslint.config.js` or `eslint.config.mjs` file:
@@ -177,9 +180,37 @@ export const myStyle = style({
177
180
  });
178
181
  ```
179
182
 
183
+ ## Font Face Declarations
184
+
185
+ For `fontFace` and `globalFontFace` API calls, all three ordering rules (alphabetical, concentric, and custom) enforce the same special ordering:
186
+
187
+ 1. The `src` property always appears first
188
+ 2. All remaining properties are sorted alphabetically
189
+
190
+ This special handling is applied because:
191
+
192
+ - The `src` property is the most critical property in font face declarations
193
+ - Consistent ordering improves readability for these specific APIs
194
+ - Font-related properties are specialized and benefit from standardized ordering
195
+
196
+ ```typescript
197
+ // ✅ Correct ordering for font faces
198
+ export const theFont = fontFace({
199
+ src: ['url("/fonts/MyFont.woff2") format("woff2")', 'url("/fonts/MyFont.woff") format("woff")'],
200
+ ascentOverride: '90%',
201
+ descentOverride: '10%',
202
+ fontDisplay: 'swap',
203
+ fontFeatureSettings: '"liga" 1',
204
+ fontStretch: 'normal',
205
+ // ...other properties in alphabetical order
206
+ });
207
+ ```
208
+
209
+ Opinionated, but it is what it is. If someone has a suggestion for a better ordering, let me know!
210
+
180
211
  ## Concentric CSS Model
181
212
 
182
- Here's a list of all available groups from the provided concentricGroups array:
213
+ Here's a list of all available groups from the provided [concentricGroups](src/css-rules/concentric-order/concentric-groups.ts) array:
183
214
 
184
215
  1. boxSizing
185
216
  2. position
@@ -221,16 +252,22 @@ The roadmap outlines the project's current status and future plans:
221
252
 
222
253
  - Initial release with support for alphabetical, concentric, and custom group CSS ordering.
223
254
  - Auto-fix capability integrated into ESLint.
224
- - Support for multiple vanilla-extract APIs (e.g., `style`, `styleVariants`, `recipe`, `globalStyle` etc.).
255
+ - Support for multiple vanilla-extract APIs (e.g., `style`, `styleVariants`, `recipe`, `globalStyle`, `fontFace`, etc.).
225
256
 
226
257
  ### Current Work
227
258
 
228
- - Compatibility testing to determine if the plugin works with ESLint v8. **Note**: There are no immediate plans to ensure compatibility if issues arise. Upcoming features will be prioritized.
259
+ - Test coverage.
229
260
 
230
261
  ### Upcoming Features
231
262
 
232
- - Begin work on test coverage.
233
- - Support for additional vanilla-extract APIs, including `fontFace`, `globalFontFace`, `globalKeyframes`, and `keyframes`.
263
+ - `no-empty-blocks` rule to disallow empty blocks.
264
+ - `no-unknown-units` rule to disallow unknown units.
265
+ - `no-number-trailing-zeros` rule to disallow trailing zeros in numbers.
266
+ - `no-zero-unit` rule to disallow units when the value is zero.
267
+ - `no-px-unit` rule to disallow use of `px` units with configurable whitelist.
268
+ - `prefer-logical-properties` rule to enforce use of logical properties.
269
+ - `prefer-theme-tokens` rule to enforce use of theme tokens instead of hard-coded values when available.
270
+ - `no-global-style` rule to disallow use of `globalStyle` function.
234
271
  - Option to sort properties within user-defined concentric groups alphabetically instead of following the concentric order. **Note**: This feature will only be implemented if there's sufficient interest from the community.
235
272
 
236
273
  ## Contributing
@@ -1,17 +1,7 @@
1
1
  import { TSESTree } from '@typescript-eslint/utils';
2
+ import { comparePropertiesAlphabetically } from '../shared-utils/alphabetical-property-comparator.js';
2
3
  import { generateFixesForCSSOrder } from '../shared-utils/css-order-fixer.js';
3
4
  import { getPropertyName } from '../shared-utils/property-separator.js';
4
- /**
5
- * Compares two CSS properties alphabetically.
6
- * @param firstProperty The first property to compare.
7
- * @param secondProperty The second property to compare.
8
- * @returns A number indicating the relative order of the properties (-1, 0, or 1).
9
- */
10
- const comparePropertiesAlphabetically = (firstProperty, secondProperty) => {
11
- const firstName = getPropertyName(firstProperty);
12
- const secondName = getPropertyName(secondProperty);
13
- return firstName.localeCompare(secondName);
14
- };
15
5
  /**
16
6
  * Reports an ordering issue to ESLint and generates fixes.
17
7
  * @param ruleContext The ESLint rule context.
@@ -10,7 +10,8 @@ const alphabeticalOrderRule = {
10
10
  fixable: 'code',
11
11
  schema: [],
12
12
  messages: {
13
- alphabeticalOrder: "Property '{{next}}' should come before '{{current}}' in alphabetical order.",
13
+ alphabeticalOrder: "Property '{{nextProperty}}' should come before '{{currentProperty}}' in alphabetical order.",
14
+ fontFaceOrder: "Properties in fontFace should be ordered with 'src' first, followed by other properties in alphabetical order. Property '{{nextProperty}}' should come before '{{currentProperty}}'.",
14
15
  },
15
16
  },
16
17
  create(context) {
@@ -12,8 +12,8 @@ const reportOrderingIssue = (ruleContext, currentProperty, nextProperty, cssProp
12
12
  node: nextProperty.node,
13
13
  messageId: 'incorrectOrder',
14
14
  data: {
15
- next: nextProperty.name,
16
- current: currentProperty.name,
15
+ nextProperty: nextProperty.name,
16
+ currentProperty: currentProperty.name,
17
17
  },
18
18
  fix: (fixer) => generateFixesForCSSOrder(fixer, ruleContext, cssPropertyInfoList, compareProperties, (propertyInfo) => propertyInfo.node),
19
19
  });
@@ -6,11 +6,13 @@ const concentricOrderRule = {
6
6
  description: 'enforce concentric CSS property ordering in vanilla-extract styles',
7
7
  category: 'Stylistic Issues',
8
8
  recommended: true,
9
+ url: 'https://rhodesmill.org/brandon/2011/concentric-css/',
9
10
  },
10
11
  fixable: 'code',
11
12
  schema: [],
12
13
  messages: {
13
- incorrectOrder: "Property '{{next}}' should come before '{{current}}' according to concentric CSS ordering.",
14
+ incorrectOrder: "Property '{{nextProperty}}' should come before '{{currentProperty}}' according to concentric CSS ordering.",
15
+ fontFaceOrder: "Properties in fontFace should be ordered with 'src' first, followed by other properties in alphabetical order. Property '{{nextProperty}}' should come before '{{currentProperty}}'.",
14
16
  },
15
17
  },
16
18
  create(context) {
@@ -28,6 +28,7 @@ const customGroupOrderRule = {
28
28
  ],
29
29
  messages: {
30
30
  incorrectOrder: "Property '{{nextProperty}}' should come before '{{currentProperty}}' according to custom CSS group ordering.",
31
+ fontFaceOrder: "Properties in fontFace should be ordered with 'src' first, followed by other properties in alphabetical order. Property '{{nextProperty}}' should come before '{{currentProperty}}'.",
31
32
  },
32
33
  },
33
34
  create(ruleContext) {
@@ -0,0 +1,8 @@
1
+ import type { TSESTree } from '@typescript-eslint/utils';
2
+ /**
3
+ * Compares two CSS properties alphabetically.
4
+ * @param firstProperty The first property to compare.
5
+ * @param secondProperty The second property to compare.
6
+ * @returns A number indicating the relative order of the properties (-1, 0, or 1).
7
+ */
8
+ export declare const comparePropertiesAlphabetically: (firstProperty: TSESTree.Property, secondProperty: TSESTree.Property) => number;
@@ -0,0 +1,19 @@
1
+ import { getPropertyName } from './property-separator.js';
2
+ /**
3
+ * Compares two CSS properties alphabetically.
4
+ * @param firstProperty The first property to compare.
5
+ * @param secondProperty The second property to compare.
6
+ * @returns A number indicating the relative order of the properties (-1, 0, or 1).
7
+ */
8
+ export const comparePropertiesAlphabetically = (firstProperty, secondProperty) => {
9
+ const firstName = getPropertyName(firstProperty);
10
+ const secondName = getPropertyName(secondProperty);
11
+ // Special handling for 'src' property - it should always come first (relates to font face APIs only)
12
+ if (firstName === 'src') {
13
+ return -1;
14
+ }
15
+ if (secondName === 'src') {
16
+ return 1;
17
+ }
18
+ return firstName.localeCompare(secondName);
19
+ };
@@ -0,0 +1,10 @@
1
+ import type { Rule } from 'eslint';
2
+ import { TSESTree } from '@typescript-eslint/utils';
3
+ /**
4
+ * Processes a font face declaration to enforce property ordering:
5
+ * 'src' first, then other properties alphabetically.
6
+ *
7
+ * @param ruleContext The ESLint rule context for reporting and fixing issues.
8
+ * @param fontFaceObject The object expression representing the font face declaration.
9
+ */
10
+ export declare const enforceFontFaceOrder: (ruleContext: Rule.RuleContext, fontFaceObject: TSESTree.ObjectExpression) => void;
@@ -0,0 +1,39 @@
1
+ import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
2
+ import { generateFixesForCSSOrder } from '../shared-utils/css-order-fixer.js';
3
+ import { getPropertyName, separateProperties } from '../shared-utils/property-separator.js';
4
+ import { comparePropertiesAlphabetically } from './alphabetical-property-comparator.js';
5
+ /**
6
+ * Processes a font face declaration to enforce property ordering:
7
+ * 'src' first, then other properties alphabetically.
8
+ *
9
+ * @param ruleContext The ESLint rule context for reporting and fixing issues.
10
+ * @param fontFaceObject The object expression representing the font face declaration.
11
+ */
12
+ export const enforceFontFaceOrder = (ruleContext, fontFaceObject) => {
13
+ if (!fontFaceObject || fontFaceObject.type !== AST_NODE_TYPES.ObjectExpression) {
14
+ return;
15
+ }
16
+ const { regularProperties } = separateProperties(fontFaceObject.properties);
17
+ if (regularProperties.length <= 1) {
18
+ return;
19
+ }
20
+ // Create pairs of consecutive properties
21
+ const propertyPairs = regularProperties.slice(0, -1).map((currentProperty, index) => ({
22
+ currentProperty,
23
+ nextProperty: regularProperties[index + 1],
24
+ }));
25
+ const violatingPair = propertyPairs.find(({ currentProperty, nextProperty }) => comparePropertiesAlphabetically(currentProperty, nextProperty) > 0);
26
+ if (violatingPair) {
27
+ const nextPropertyName = getPropertyName(violatingPair.nextProperty);
28
+ const currentPropertyName = getPropertyName(violatingPair.currentProperty);
29
+ ruleContext.report({
30
+ node: violatingPair.nextProperty,
31
+ messageId: 'fontFaceOrder',
32
+ data: {
33
+ nextProperty: nextPropertyName,
34
+ currentProperty: currentPropertyName,
35
+ },
36
+ fix: (fixer) => generateFixesForCSSOrder(fixer, ruleContext, regularProperties, comparePropertiesAlphabetically, (property) => property),
37
+ });
38
+ }
39
+ };
@@ -0,0 +1,10 @@
1
+ import type { Rule } from 'eslint';
2
+ import { TSESTree } from '@typescript-eslint/utils';
3
+ /**
4
+ * Processes a font face style object to enforce special ordering:
5
+ * 'src' first, then other properties alphabetically.
6
+ *
7
+ * @param ruleContext The ESLint rule context for reporting and fixing issues.
8
+ * @param styleObject The object expression representing the style object.
9
+ */
10
+ export declare const enforceFontFaceOrderInStyleObject: (ruleContext: Rule.RuleContext, styleObject: TSESTree.ObjectExpression) => void;
@@ -0,0 +1,17 @@
1
+ import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
2
+ import { separateProperties } from '../shared-utils/property-separator.js';
3
+ import { enforceFontFaceOrder } from './font-face-property-order-enforcer.js';
4
+ /**
5
+ * Processes a font face style object to enforce special ordering:
6
+ * 'src' first, then other properties alphabetically.
7
+ *
8
+ * @param ruleContext The ESLint rule context for reporting and fixing issues.
9
+ * @param styleObject The object expression representing the style object.
10
+ */
11
+ export const enforceFontFaceOrderInStyleObject = (ruleContext, styleObject) => {
12
+ // if (!styleObject || styleObject.type !== AST_NODE_TYPES.ObjectExpression) {
13
+ // return;
14
+ // }
15
+ // const { regularProperties } = separateProperties(styleObject.properties);
16
+ // enforceFontFaceOrder(ruleContext, regularProperties);
17
+ };
@@ -5,6 +5,7 @@ import { enforceConcentricCSSOrderInRecipe } from '../concentric-order/recipe-or
5
5
  import { enforceConcentricCSSOrderInStyleObject } from '../concentric-order/style-object-processor.js';
6
6
  import { enforceUserDefinedGroupOrderInRecipe } from '../custom-order/recipe-order-enforcer.js';
7
7
  import { enforceUserDefinedGroupOrderInStyleObject } from '../custom-order/style-object-processor.js';
8
+ import { enforceFontFaceOrder } from './font-face-property-order-enforcer.js';
8
9
  import { processStyleNode } from './style-node-processor.js';
9
10
  /**
10
11
  * Creates an ESLint rule listener with visitors for style-related function calls.
@@ -43,17 +44,31 @@ export const createNodeVisitors = (ruleContext, orderingStrategy, userDefinedGro
43
44
  if (node.callee.type !== 'Identifier') {
44
45
  return;
45
46
  }
47
+ const fontFaceFunctionArgumentIndexMap = {
48
+ fontFace: 0, // First argument (index 0)
49
+ globalFontFace: 1, // Second argument (index 1)
50
+ };
51
+ // Handle font face functions with special ordering
52
+ if (node.callee.name in fontFaceFunctionArgumentIndexMap &&
53
+ node.arguments.length >
54
+ fontFaceFunctionArgumentIndexMap[node.callee.name]) {
55
+ const argumentIndex = fontFaceFunctionArgumentIndexMap[node.callee.name];
56
+ const styleArguments = node.arguments[argumentIndex];
57
+ enforceFontFaceOrder(ruleContext, styleArguments);
58
+ return;
59
+ }
46
60
  // Handle style-related functions
47
- if (['style', 'styleVariants', 'createVar', 'createTheme', 'createThemeContract'].includes(node.callee.name)) {
61
+ if (['createThemeContract', 'createVar', 'createTheme', 'keyframes', 'style', 'styleVariants'].includes(node.callee.name)) {
48
62
  if (node.arguments.length > 0) {
49
- const styleArg = node.arguments[0];
50
- processStyleNode(ruleContext, styleArg, processProperty);
63
+ const styleArguments = node.arguments[0];
64
+ processStyleNode(ruleContext, styleArguments, processProperty);
51
65
  }
52
66
  }
53
- // Handle globalStyle function
54
- if (node.callee.name === 'globalStyle' && node.arguments.length >= 2) {
55
- const styleArg = node.arguments[1];
56
- processStyleNode(ruleContext, styleArg, processProperty);
67
+ // Handle global functions
68
+ if ((node.callee.name === 'globalKeyframes' || node.callee.name === 'globalStyle') &&
69
+ node.arguments.length >= 2) {
70
+ const styleArguments = node.arguments[1];
71
+ processStyleNode(ruleContext, styleArguments, processProperty);
57
72
  }
58
73
  // Handle recipe function
59
74
  if (node.callee.name === 'recipe') {
@@ -0,0 +1,12 @@
1
+ import { TSESTree } from '@typescript-eslint/utils';
2
+ export type ThemeValue = string | number | null;
3
+ export type ThemeObject = {
4
+ [key: string]: ThemeValue | ThemeObject;
5
+ };
6
+ export interface ThemeTokenMatch {
7
+ token: string;
8
+ path: string[];
9
+ }
10
+ export declare function isVanillaExtractStyleCall(node: TSESTree.CallExpression): boolean;
11
+ export declare function findThemeTokenForValue(value: ThemeValue, themeObj: ThemeObject | null, path?: string[]): ThemeTokenMatch | null;
12
+ export declare function findThemeTokenForPropertyValue(property: string, value: ThemeValue, themeObj: ThemeObject, path?: string[]): ThemeTokenMatch | null;
@@ -0,0 +1,80 @@
1
+ // import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
2
+ // export function isVanillaExtractStyleCall(node: TSESTree.CallExpression): boolean {
3
+ // return (
4
+ // node.callee.type === AST_NODE_TYPES.Identifier &&
5
+ // ['style', 'createVar', 'styleVariants', 'globalStyle'].includes(node.callee.name) &&
6
+ // node.arguments.length > 0 &&
7
+ // node.arguments[0] !== undefined &&
8
+ // node.arguments[0].type === AST_NODE_TYPES.ObjectExpression
9
+ // );
10
+ // }
11
+ // type ThemeValue = string | number | null;
12
+ // type ThemeObject = { [key: string]: ThemeValue | ThemeObject };
13
+ // interface ThemeTokenMatch {
14
+ // token: string;
15
+ // path: string[];
16
+ // }
17
+ // export function findThemeTokenForValue(
18
+ // value: ThemeValue,
19
+ // themeObj: ThemeObject | null,
20
+ // path: string[] = [],
21
+ // ): ThemeTokenMatch | null {
22
+ // if (!themeObj || typeof themeObj !== 'object') {
23
+ // return null;
24
+ // }
25
+ // for (const [key, val] of Object.entries(themeObj)) {
26
+ // const currentPath = [...path, key];
27
+ // if (String(val) === String(value)) {
28
+ // return { token: currentPath.join('.'), path: currentPath };
29
+ // }
30
+ // if (typeof val === 'object' && val !== null) {
31
+ // const result = findThemeTokenForValue(value, val, currentPath);
32
+ // if (result) {
33
+ // return result;
34
+ // }
35
+ // }
36
+ // }
37
+ // return null;
38
+ // }
39
+ // TODO 2nd
40
+ import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
41
+ export function isVanillaExtractStyleCall(node) {
42
+ return (node.callee.type === AST_NODE_TYPES.Identifier &&
43
+ ['style', 'createVar', 'styleVariants', 'globalStyle', 'createThemeContract', 'createTheme', 'keyframes'].includes(node.callee.name) &&
44
+ node.arguments.length > 0 &&
45
+ (node.arguments[0]?.type === AST_NODE_TYPES.ObjectExpression ||
46
+ node.arguments[0]?.type === AST_NODE_TYPES.ArrayExpression));
47
+ }
48
+ export function findThemeTokenForValue(value, themeObj, path = []) {
49
+ if (!themeObj || typeof themeObj !== 'object') {
50
+ return null;
51
+ }
52
+ for (const [key, val] of Object.entries(themeObj)) {
53
+ const currentPath = [...path, key];
54
+ if (String(val) === String(value)) {
55
+ return {
56
+ token: currentPath.join('.'),
57
+ path: currentPath,
58
+ };
59
+ }
60
+ if (typeof val === 'object' && val !== null) {
61
+ const result = findThemeTokenForValue(value, val, currentPath);
62
+ if (result) {
63
+ return result;
64
+ }
65
+ }
66
+ }
67
+ return null;
68
+ }
69
+ export function findThemeTokenForPropertyValue(property, value, themeObj, path = []) {
70
+ if (themeObj && typeof themeObj === 'object' && themeObj[property]) {
71
+ const group = themeObj[property];
72
+ if (typeof group === 'object' && group !== null) {
73
+ const result = findThemeTokenForValue(value, group, [property]);
74
+ if (result) {
75
+ return result;
76
+ }
77
+ }
78
+ }
79
+ return findThemeTokenForValue(value, themeObj, path);
80
+ }
@@ -0,0 +1,2 @@
1
+ import preferThemeTokensRule from './rule-definition.js';
2
+ export default preferThemeTokensRule;
@@ -0,0 +1,2 @@
1
+ import preferThemeTokensRule from './rule-definition.js';
2
+ export default preferThemeTokensRule;
@@ -0,0 +1,3 @@
1
+ import type { Rule } from 'eslint';
2
+ declare const preferThemeTokensRule: Rule.RuleModule;
3
+ export default preferThemeTokensRule;
@@ -0,0 +1,29 @@
1
+ import { createThemeTokenVisitor } from './theme-token-visitor.js';
2
+ const preferThemeTokensRule = {
3
+ meta: {
4
+ type: 'suggestion',
5
+ docs: {
6
+ description: 'enforce the use of theme tokens instead of direct values in vanilla-extract styles',
7
+ category: 'Best Practices',
8
+ recommended: true,
9
+ },
10
+ fixable: 'code',
11
+ schema: [
12
+ {
13
+ type: 'object',
14
+ properties: {
15
+ themeImportPath: { type: 'string' },
16
+ themeVarName: { type: 'string' },
17
+ },
18
+ additionalProperties: false,
19
+ },
20
+ ],
21
+ messages: {
22
+ preferThemeTokens: 'Use theme token "{{token}}" instead of direct value "{{value}}"',
23
+ },
24
+ },
25
+ create(context) {
26
+ return createThemeTokenVisitor(context);
27
+ },
28
+ };
29
+ export default preferThemeTokensRule;
@@ -0,0 +1,10 @@
1
+ type ThemeValue = string | number | null;
2
+ type ThemeObject = {
3
+ [key: string]: ThemeValue | ThemeObject;
4
+ };
5
+ export declare function loadThemeTokens(themeFilePath: string): ThemeObject | null;
6
+ export declare function findThemeTokenForValue(value: ThemeValue, themeObj: ThemeObject, path?: string[]): {
7
+ token: string;
8
+ path: string[];
9
+ } | null;
10
+ export {};
@@ -0,0 +1,71 @@
1
+ /* eslint-disable no-console */
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ export function loadThemeTokens(themeFilePath) {
5
+ try {
6
+ console.log(`Attempting to load theme from: ${themeFilePath}`);
7
+ const resolvedPath = path.resolve(process.cwd(), themeFilePath);
8
+ console.log(`Resolved path: ${resolvedPath}`);
9
+ if (!fs.existsSync(resolvedPath)) {
10
+ console.error(`Theme file not found: ${resolvedPath}`);
11
+ return null;
12
+ }
13
+ const content = fs.readFileSync(resolvedPath, 'utf8');
14
+ console.log(`File content loaded. Length: ${content.length} characters`);
15
+ const themeMatch = content.match(/createTheme\([^,]+,\s*(\{[\s\S]+?\})\s*\);/);
16
+ if (!themeMatch || !themeMatch[1]) {
17
+ console.error('No theme implementation found in the file');
18
+ return null;
19
+ }
20
+ const themeStr = themeMatch[1];
21
+ console.log(`Theme implementation extracted. Length: ${themeStr.length} characters`);
22
+ // Use a safe evaluation method to parse the theme object
23
+ const themeObj = Function(`return ${themeStr}`)();
24
+ console.log('Parsed theme structure:', JSON.stringify(themeObj, null, 2));
25
+ return themeObj;
26
+ }
27
+ catch (error) {
28
+ console.error('Error loading theme tokens:', error);
29
+ return null;
30
+ }
31
+ }
32
+ // function parseThemeObject(str: string): ThemeObject {
33
+ // const result: ThemeObject = {};
34
+ // const lines = str.split('\n');
35
+ // const stack: ThemeObject[] = [result];
36
+ // for (const line of lines) {
37
+ // const trimmed = line.trim();
38
+ // if (!trimmed || trimmed.startsWith('//')) {
39
+ // continue;
40
+ // }
41
+ // if (trimmed.endsWith('{')) {
42
+ // const key = trimmed.slice(0, -1).trim();
43
+ // const newObj: ThemeObject = {};
44
+ // stack[stack.length - 1]![key] = newObj;
45
+ // stack.push(newObj);
46
+ // } else if (trimmed === '},') {
47
+ // stack.pop();
48
+ // } else {
49
+ // const [key, value] = trimmed.split(':').map((s) => s.trim());
50
+ // if (key && value) {
51
+ // stack[stack.length - 1]![key] = value === 'null' ? null : value.replace(/,$/, '');
52
+ // }
53
+ // }
54
+ // }
55
+ // return result;
56
+ // }
57
+ export function findThemeTokenForValue(value, themeObj, path = []) {
58
+ for (const [key, val] of Object.entries(themeObj)) {
59
+ const currentPath = [...path, key];
60
+ if (String(val) === String(value)) {
61
+ return { token: currentPath.join('.'), path: currentPath };
62
+ }
63
+ if (typeof val === 'object' && val !== null) {
64
+ const result = findThemeTokenForValue(value, val, currentPath);
65
+ if (result) {
66
+ return result;
67
+ }
68
+ }
69
+ }
70
+ return null;
71
+ }
@@ -0,0 +1,2 @@
1
+ import type { Rule } from 'eslint';
2
+ export declare function createThemeTokenVisitor(context: Rule.RuleContext): Rule.RuleListener;