@alfalab/stylelint-core-vars 2.0.0 → 2.1.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,40 @@
1
+ # stylelint-core-vars
2
+
3
+ ## 2.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#118](https://github.com/core-ds/arui-presets-lint/pull/118) [`1057d60`](https://github.com/core-ds/arui-presets-lint/commit/1057d601f36fb1f06f70741f0f15b49aa1ed3c98) Thanks [@kiskv](https://github.com/kiskv)! - Библиотека переписана на typescript и перенесена в монорепозиторий
8
+
9
+ ## 2.0.0
10
+
11
+ ### Major Changes
12
+
13
+ - [#12](https://github.com/core-ds/stylelint-core-vars/pull/12) [`42f7125`](https://github.com/core-ds/stylelint-core-vars/commit/42f7125ff2feb3b90bb685c1d91b053e74618d19) Thanks [@hextion](https://github.com/hextion)! - Добавлена поддержка [`stylelint@16`](https://github.com/stylelint/stylelint/blob/5d642e9c9b6b8c7a453903350f112f991cdd9430/docs/migration-guide/to-16.md)
14
+
15
+ Пакет переведен на `esm` модули
16
+
17
+ ## 1.7.2
18
+
19
+ ### Patch Changes
20
+
21
+ - [#6](https://github.com/core-ds/stylelint-core-vars/pull/6) [`d02a5c5`](https://github.com/core-ds/stylelint-core-vars/commit/d02a5c51acba50165669aefc1cc7b7886246d3ab) Thanks [@hextion](https://github.com/hextion)! - Добавлена поддержка `@alfalab/core-components` 49 версии и выше
22
+
23
+ Добавлена поддержка `node.js` 24 версии
24
+
25
+ ## [1.7.1](https://github.com/core-ds/stylelint-core-vars/compare/v1.7.0...v1.7.1) (2024-11-28)
26
+
27
+ ### Bug Fixes
28
+
29
+ - **utils:** fix project root path definition ([ae8bd73](https://github.com/core-ds/stylelint-core-vars/commit/ae8bd732db71fc70405237294e789123c1e3ce07))
30
+
31
+ # [1.7.0](https://github.com/core-ds/stylelint-core-vars/compare/v1.6.0...v1.7.0) (2024-07-05)
32
+
33
+ ### Features
34
+
35
+ - add git hooks, prettier, lint-staged, commitlint ([2571ebf](https://github.com/core-ds/stylelint-core-vars/commit/2571ebfe9820750b301984b7a32c0f0833e663db))
36
+ - bump dependecies ([39bc322](https://github.com/core-ds/stylelint-core-vars/commit/39bc32255c322a88a1c1ff248bf0c3fc2f88f30d))
37
+ - bump dependencies ([9c82766](https://github.com/core-ds/stylelint-core-vars/commit/9c82766a1502a2d80c0c076873407f69e7658deb))
38
+ - bump yarn to 4.3.1 ([2d36bf4](https://github.com/core-ds/stylelint-core-vars/commit/2d36bf4ec3b63fd70ec23f6ce8cf14dc108b257a))
39
+ - **ci:** add ci configs ([65f6996](https://github.com/core-ds/stylelint-core-vars/commit/65f69963e036b51adb7495a5d8218ab639b0f016))
40
+ - move plugin to lib folder, tests to test folder ([d214494](https://github.com/core-ds/stylelint-core-vars/commit/d214494db42e3804030321a3fbf238db31b568d0))
package/README.md CHANGED
@@ -60,29 +60,3 @@ npm install --save-dev stylelint @alfalab/stylelint-core-vars
60
60
  },
61
61
  }
62
62
  ```
63
-
64
- ## Лицензия
65
-
66
- ```
67
- The MIT License (MIT)
68
-
69
- Copyright (c) 2024 core-ds contributors
70
-
71
- Permission is hereby granted, free of charge, to any person obtaining a copy
72
- of this software and associated documentation files (the "Software"), to deal
73
- in the Software without restriction, including without limitation the rights
74
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
75
- copies of the Software, and to permit persons to whom the Software is
76
- furnished to do so, subject to the following conditions:
77
-
78
- The above copyright notice and this permission notice shall be included in
79
- all copies or substantial portions of the Software.
80
-
81
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
82
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
83
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
84
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
85
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
86
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
87
- THE SOFTWARE.
88
- ```
@@ -0,0 +1,2 @@
1
+ import plugin from './lib/index.js';
2
+ export default plugin;
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import plugin from './lib/index.js';
2
+ export default plugin;
@@ -0,0 +1,32 @@
1
+ import stylelint from 'stylelint';
2
+ import { type MixinDef } from './utils.js';
3
+ export declare const RULE_USE_VARS = "stylelint-core-vars/use-vars";
4
+ export declare const RULE_USE_ONE_OF_VARS = "stylelint-core-vars/use-one-of-vars";
5
+ export declare const RULE_USE_MIXINS = "stylelint-core-vars/use-mixins";
6
+ export declare const RULE_USE_ONE_OF_MIXINS = "stylelint-core-vars/use-one-of-mixins";
7
+ export declare const RULE_DO_NOT_USE_DARK_COLORS = "stylelint-core-vars/do-not-use-dark-colors";
8
+ export declare const RULE_DO_NOT_USE_OLD_VARS = "stylelint-core-vars/do-not-use-old-vars";
9
+ export declare const messages: {
10
+ "stylelint-core-vars/use-vars": {
11
+ expected: (variable: string | string[], value: string) => string;
12
+ };
13
+ "stylelint-core-vars/use-one-of-vars": {
14
+ expected: (variables: string[], value: string) => string;
15
+ };
16
+ "stylelint-core-vars/do-not-use-old-vars": {
17
+ expected: (variables: string[], value: string | string[], fixable?: boolean) => string;
18
+ };
19
+ "stylelint-core-vars/use-mixins": {
20
+ expected: ([mixin]: Array<{
21
+ name: string;
22
+ }>) => string;
23
+ };
24
+ "stylelint-core-vars/use-one-of-mixins": {
25
+ expected: (foundMixins: MixinDef[]) => string;
26
+ };
27
+ "stylelint-core-vars/do-not-use-dark-colors": {
28
+ expected: () => string;
29
+ };
30
+ };
31
+ declare const _default: stylelint.Plugin[];
32
+ export default _default;
@@ -1,178 +1,133 @@
1
+ import {} from 'postcss';
1
2
  import stylelint from 'stylelint';
2
- import {
3
- findOldVars,
4
- toOneLine,
5
- VARS_AVAILABLE,
6
- findTypographyMixins,
7
- colorsSet,
8
- findVars,
9
- } from './utils.js';
10
-
3
+ import { colorsSet, findOldVars, findTypographyMixins, findVars, toOneLine, VARS_AVAILABLE, } from './utils.js';
11
4
  export const RULE_USE_VARS = 'stylelint-core-vars/use-vars';
12
5
  export const RULE_USE_ONE_OF_VARS = 'stylelint-core-vars/use-one-of-vars';
13
6
  export const RULE_USE_MIXINS = 'stylelint-core-vars/use-mixins';
14
7
  export const RULE_USE_ONE_OF_MIXINS = 'stylelint-core-vars/use-one-of-mixins';
15
8
  export const RULE_DO_NOT_USE_DARK_COLORS = 'stylelint-core-vars/do-not-use-dark-colors';
16
9
  export const RULE_DO_NOT_USE_OLD_VARS = 'stylelint-core-vars/do-not-use-old-vars';
17
-
10
+ const typedRuleMessages = (ruleName, msgs) => stylelint.utils.ruleMessages(ruleName, msgs);
18
11
  export const messages = {
19
- [RULE_USE_VARS]: stylelint.utils.ruleMessages(RULE_USE_VARS, {
20
- expected: (variable, value) => {
21
- return `Use variable 'var(${variable})' instead of plain value '${value}'`;
22
- },
12
+ [RULE_USE_VARS]: typedRuleMessages(RULE_USE_VARS, {
13
+ expected: (variable, value) => `Use variable 'var(${String(variable)})' instead of plain value '${value}'`,
23
14
  }),
24
- [RULE_USE_ONE_OF_VARS]: stylelint.utils.ruleMessages(RULE_USE_ONE_OF_VARS, {
15
+ [RULE_USE_ONE_OF_VARS]: typedRuleMessages(RULE_USE_ONE_OF_VARS, {
25
16
  expected: (variables, value) => {
26
17
  const variablesPart = variables.map((v) => `var(${v})`).join('\n');
27
-
28
18
  return `Use variables instead of plain value '${value}':\n${variablesPart}\n`;
29
19
  },
30
20
  }),
31
- [RULE_DO_NOT_USE_OLD_VARS]: stylelint.utils.ruleMessages(RULE_DO_NOT_USE_OLD_VARS, {
21
+ [RULE_DO_NOT_USE_OLD_VARS]: typedRuleMessages(RULE_DO_NOT_USE_OLD_VARS, {
32
22
  expected: (variables, value, fixable = true) => {
33
- if (!variables.length) return `Ask you designer how to replace old token '${value}'`;
34
-
23
+ const valueStr = String(value);
24
+ if (!variables.length)
25
+ return `Ask you designer how to replace old token '${valueStr}'`;
35
26
  const startMsg = fixable ? 'Use' : 'Cant find proper token, but you can use';
36
-
37
27
  if (variables.length === 1) {
38
- return `${startMsg} variable 'var(${variables[0]})' instead of old '${value}'`;
28
+ return `${startMsg} variable 'var(${variables[0]})' instead of old '${valueStr}'`;
39
29
  }
40
-
41
30
  const variablesPart = variables.map((v) => `var(${v})`).join('\n');
42
-
43
- return `${startMsg} one of new variables instead of old '${value}':\n${variablesPart}\n`;
31
+ return `${startMsg} one of new variables instead of old '${valueStr}':\n${variablesPart}\n`;
44
32
  },
45
33
  }),
46
- [RULE_USE_MIXINS]: stylelint.utils.ruleMessages(RULE_USE_MIXINS, {
47
- expected: ([mixin]) => {
48
- return `Use mixin '${mixin.name}' instead of plain values`;
49
- },
34
+ [RULE_USE_MIXINS]: typedRuleMessages(RULE_USE_MIXINS, {
35
+ expected: ([mixin]) => `Use mixin '${mixin.name}' instead of plain values`,
50
36
  }),
51
- [RULE_USE_ONE_OF_MIXINS]: stylelint.utils.ruleMessages(RULE_USE_ONE_OF_MIXINS, {
52
- expected: (mixins) => {
53
- const mixinsPart = mixins
37
+ [RULE_USE_ONE_OF_MIXINS]: typedRuleMessages(RULE_USE_ONE_OF_MIXINS, {
38
+ expected: (foundMixins) => {
39
+ const mixinsPart = foundMixins
54
40
  .map(({ name, props }) => `${name} (${Object.values(props).join('|')})`)
55
41
  .join('\n');
56
42
  return `Use mixins instead of plain values:\n${mixinsPart}\n`;
57
43
  },
58
44
  }),
59
- [RULE_DO_NOT_USE_DARK_COLORS]: stylelint.utils.ruleMessages(RULE_DO_NOT_USE_DARK_COLORS, {
60
- expected: () => {
61
- return 'Do not use dark colors directly. Only light and static colors are allowed';
62
- },
45
+ [RULE_DO_NOT_USE_DARK_COLORS]: typedRuleMessages(RULE_DO_NOT_USE_DARK_COLORS, {
46
+ expected: () => 'Do not use dark colors directly. Only light and static colors are allowed',
63
47
  }),
64
48
  };
65
-
66
49
  const checkVars = (decl, result, context, ruleName, matcher, shouldReport, options = {}) => {
67
50
  const { prop, raws } = decl;
68
-
69
51
  let value = toOneLine(decl.value);
70
52
  let substitution;
71
-
72
53
  const previousValues = [];
73
-
74
54
  while ((substitution = matcher(value, prop, options))) {
75
55
  let fixed = false;
76
-
77
- value = `${value.substring(0, substitution.index)}${substitution.fixedValue}${value.substring(substitution.index + substitution.value.length)}`;
78
-
56
+ value = `${value.slice(0, Math.max(0, substitution.index))}${substitution.fixedValue}${value.slice(Math.max(0, substitution.index + substitution.value.length))}`;
79
57
  if (context.fix && substitution.fixable) {
80
58
  decl.value = value;
81
59
  fixed = true;
82
60
  }
83
-
84
- const originalValueIndex = previousValues.reduce(
85
- (acc, sub) => (acc > sub.index + sub.diff ? acc - sub.diff : acc),
86
- substitution.index,
87
- );
88
-
61
+ const originalValueIndex = previousValues.reduce((acc, sub) => (acc > sub.index + sub.diff ? acc - sub.diff : acc), substitution.index);
89
62
  if (shouldReport(substitution.fixable, fixed)) {
90
- const index =
91
- originalValueIndex + prop.length + raws.between.length + substitution.index;
63
+ const index = originalValueIndex + prop.length + (raws.between?.length ?? 0) + substitution.index;
92
64
  const endIndex = index + substitution.value.length;
93
-
65
+ const messageFn = messages[ruleName].expected;
94
66
  stylelint.utils.report({
95
67
  result,
96
68
  ruleName,
97
- message: messages[ruleName].expected(
98
- substitution.variables,
99
- substitution.value,
100
- substitution.fixable,
101
- ),
69
+ message: messageFn(substitution.variables, substitution.value, substitution.fixable),
102
70
  node: decl,
103
71
  word: value,
104
72
  index,
105
73
  endIndex,
106
74
  });
107
75
  }
108
-
109
76
  previousValues.unshift({
110
77
  ...substitution,
111
78
  diff: substitution.fixedValue.length - substitution.value.length,
112
79
  });
113
80
  }
114
81
  };
115
-
116
82
  const checkTypography = (rule, result, context, ruleName) => {
117
- const typographyProps = rule.nodes.reduce((acc, node) => {
118
- if (['font-size', 'line-height', 'font-weight'].includes(node.prop)) {
83
+ const typographyProps = (rule.nodes ?? []).reduce((acc, node) => {
84
+ if (node.type === 'decl' &&
85
+ ['font-size', 'line-height', 'font-weight'].includes(node.prop)) {
119
86
  acc[node.prop] = node.value;
120
87
  }
121
88
  return acc;
122
89
  }, {});
123
-
124
90
  const hasTypography = 'font-size' in typographyProps;
125
- if (!hasTypography) return;
126
-
127
- const mixins = findTypographyMixins(typographyProps);
128
-
129
- if (!mixins || !mixins.length) return;
130
-
131
- const exactMixin = mixins.length === 1;
132
-
91
+ if (!hasTypography)
92
+ return;
93
+ const foundMixins = findTypographyMixins(typographyProps);
94
+ if (!foundMixins || !foundMixins.length)
95
+ return;
96
+ const exactMixin = foundMixins.length === 1;
133
97
  let fixed = false;
134
98
  if (context.fix && exactMixin) {
135
99
  fixed = true;
136
- const { name, props } = mixins[0];
137
-
138
- const before = rule.nodes[0].raws.before;
100
+ const { name, props } = foundMixins[0];
101
+ const before = rule.nodes?.[0]?.raws.before ?? '';
139
102
  rule.walkDecls((decl) => {
140
103
  if (decl.prop in props) {
141
104
  decl.remove();
142
105
  }
143
106
  });
144
-
145
107
  rule.prepend(`${before}@mixin ${name};\n`);
146
108
  }
147
-
148
- const shouldReport =
149
- !fixed &&
109
+ const shouldReport = !fixed &&
150
110
  ((ruleName === RULE_USE_ONE_OF_MIXINS && !exactMixin) ||
151
111
  (ruleName === RULE_USE_MIXINS && exactMixin));
152
-
153
112
  if (shouldReport) {
113
+ const messageFn = messages[ruleName].expected;
154
114
  stylelint.utils.report({
155
115
  result,
156
116
  ruleName,
157
- message: messages[ruleName].expected(mixins),
117
+ message: messageFn(foundMixins),
158
118
  node: rule,
159
119
  word: 'font-size',
160
120
  });
161
121
  }
162
122
  };
163
-
164
- const checkDarkColorsUsage = (decl, result, context, ruleName) => {
123
+ const checkDarkColorsUsage = (decl, result) => {
165
124
  const { prop, raws } = decl;
166
-
167
- let value = toOneLine(decl.value);
168
-
125
+ const value = toOneLine(decl.value);
169
126
  const matches = /--color-dark-[\w-]+/.exec(value);
170
-
171
127
  if (matches && colorsSet.has(matches[0])) {
172
128
  const [match] = matches;
173
- const index = prop.length + raws.between.length + decl.value.indexOf(match);
129
+ const index = prop.length + (raws.between?.length ?? 0) + decl.value.indexOf(match);
174
130
  const endIndex = index + match.length;
175
-
176
131
  stylelint.utils.report({
177
132
  result,
178
133
  ruleName: RULE_DO_NOT_USE_DARK_COLORS,
@@ -184,99 +139,73 @@ const checkDarkColorsUsage = (decl, result, context, ruleName) => {
184
139
  });
185
140
  }
186
141
  };
187
-
142
+ // stylelint.Rule = function & { ruleName, messages }. Хелпер навешивает
143
+ // нужные поля на rule-функцию и приводит к ожидаемому типу.
144
+ const makeRule = (ruleName, fn) => Object.assign(fn, {
145
+ ruleName,
146
+ messages: messages[ruleName],
147
+ });
188
148
  export default [
189
- stylelint.createPlugin(RULE_USE_VARS, (enabled, config, context) => {
149
+ stylelint.createPlugin(RULE_USE_VARS, makeRule(RULE_USE_VARS, (enabled, config, context) => {
190
150
  if (!enabled || !VARS_AVAILABLE) {
191
- return () => {};
151
+ return () => { };
192
152
  }
193
-
194
153
  const allowNumericValues = config?.allowNumericValues || false;
195
-
196
154
  return (root, result) => {
197
155
  root.walkDecls((decl) => {
198
- checkVars(
199
- decl,
200
- result,
201
- context,
202
- RULE_USE_VARS,
203
- findVars,
204
- (fixable, fixed) => fixable && !fixed,
205
- { allowNumericValues },
206
- );
156
+ checkVars(decl, result, context, RULE_USE_VARS, findVars, (fixable, fixed) => fixable && !fixed, { allowNumericValues });
207
157
  });
208
158
  };
209
- }),
210
- stylelint.createPlugin(RULE_USE_ONE_OF_VARS, (enabled, config, context) => {
159
+ })),
160
+ stylelint.createPlugin(RULE_USE_ONE_OF_VARS, makeRule(RULE_USE_ONE_OF_VARS, (enabled, config, context) => {
211
161
  if (!enabled || !VARS_AVAILABLE) {
212
- return () => {};
162
+ return () => { };
213
163
  }
214
-
215
164
  const allowNumericValues = config?.allowNumericValues || false;
216
-
217
165
  return (root, result) => {
218
166
  root.walkDecls((decl) => {
219
- checkVars(
220
- decl,
221
- result,
222
- context,
223
- RULE_USE_ONE_OF_VARS,
224
- findVars,
225
- (fixable, fixed) => !fixable && !fixed,
226
- { allowNumericValues },
227
- );
167
+ checkVars(decl, result, context, RULE_USE_ONE_OF_VARS, findVars, (fixable, fixed) => !fixable && !fixed, { allowNumericValues });
228
168
  });
229
169
  };
230
- }),
231
- stylelint.createPlugin(RULE_DO_NOT_USE_OLD_VARS, (enabled, _, context) => {
170
+ })),
171
+ stylelint.createPlugin(RULE_DO_NOT_USE_OLD_VARS, makeRule(RULE_DO_NOT_USE_OLD_VARS, (enabled, _config, context) => {
232
172
  if (!enabled || !VARS_AVAILABLE) {
233
- return () => {};
173
+ return () => { };
234
174
  }
235
-
236
175
  return (root, result) => {
237
176
  root.walkDecls((decl) => {
238
- checkVars(
239
- decl,
240
- result,
241
- context,
242
- RULE_DO_NOT_USE_OLD_VARS,
243
- findOldVars,
244
- (_, fixed) => !fixed,
245
- );
177
+ checkVars(decl, result, context, RULE_DO_NOT_USE_OLD_VARS, findOldVars, (_fixable, fixed) => !fixed);
246
178
  });
247
179
  };
248
- }),
249
- stylelint.createPlugin(RULE_USE_MIXINS, (enabled, _, context) => {
180
+ })),
181
+ stylelint.createPlugin(RULE_USE_MIXINS, makeRule(RULE_USE_MIXINS, (enabled, _config, context) => {
250
182
  if (!enabled || !VARS_AVAILABLE) {
251
- return () => {};
183
+ return () => { };
252
184
  }
253
-
254
185
  return (root, result) => {
255
186
  root.walkRules((rule) => {
256
187
  checkTypography(rule, result, context, RULE_USE_MIXINS);
257
188
  });
258
189
  };
259
- }),
260
- stylelint.createPlugin(RULE_USE_ONE_OF_MIXINS, (enabled, _, context) => {
190
+ })),
191
+ stylelint.createPlugin(RULE_USE_ONE_OF_MIXINS, makeRule(RULE_USE_ONE_OF_MIXINS, (enabled, _config, context) => {
261
192
  if (!enabled || !VARS_AVAILABLE) {
262
- return () => {};
193
+ return () => { };
263
194
  }
264
-
265
195
  return (root, result) => {
266
196
  root.walkRules((rule) => {
267
197
  checkTypography(rule, result, context, RULE_USE_ONE_OF_MIXINS);
268
198
  });
269
199
  };
270
- }),
271
- stylelint.createPlugin(RULE_DO_NOT_USE_DARK_COLORS, (enabled, _, context) => {
200
+ })),
201
+ stylelint.createPlugin(RULE_DO_NOT_USE_DARK_COLORS, makeRule(RULE_DO_NOT_USE_DARK_COLORS, (enabled) => {
272
202
  if (!enabled || !VARS_AVAILABLE) {
273
- return () => {};
203
+ return () => { };
274
204
  }
275
-
276
205
  return (root, result) => {
277
206
  root.walkDecls((decl) => {
278
- checkDarkColorsUsage(decl, result, context);
207
+ checkDarkColorsUsage(decl, result);
279
208
  });
280
209
  };
281
- }),
210
+ })),
282
211
  ];
@@ -0,0 +1,2 @@
1
+ declare const oldNewMap: Record<string, string[]>;
2
+ export default oldNewMap;
@@ -1,4 +1,4 @@
1
- export default {
1
+ const oldNewMap = {
2
2
  '--color-dark-indigo': [
3
3
  '--color-light-text-primary',
4
4
  '--color-light-bg-primary-inverted',
@@ -120,3 +120,4 @@ export default {
120
120
  '--color-bg-corporate-60': ['--color-static-corpbg-tertiary'],
121
121
  '--color-bg-corporate-30': ['--color-static-corpbg-neutral'],
122
122
  };
123
+ export default oldNewMap;
@@ -0,0 +1,30 @@
1
+ export type VarsMap = Record<string, string[]>;
2
+ export type MixinPropsMap = Record<string, string>;
3
+ export type MixinDef = {
4
+ name: string;
5
+ props: MixinPropsMap;
6
+ };
7
+ export type SubstitutionResult = {
8
+ index: number;
9
+ value: string;
10
+ variables: string[];
11
+ fixedValue: string;
12
+ fixable: boolean;
13
+ };
14
+ export declare const vars: {
15
+ gaps: VarsMap;
16
+ shadows: VarsMap;
17
+ colors: VarsMap;
18
+ borderRadiuses: VarsMap;
19
+ };
20
+ export declare const colorsSet: Set<string>;
21
+ export declare const mixins: {
22
+ typography: Record<string, MixinPropsMap>;
23
+ };
24
+ export declare const VARS_AVAILABLE: boolean;
25
+ export declare function findVars(cssValue: string, prop: string, options: {
26
+ allowNumericValues?: boolean;
27
+ }): SubstitutionResult | undefined;
28
+ export declare function findOldVars(cssValue: string, prop: string): SubstitutionResult | undefined;
29
+ export declare function findTypographyMixins(ruleProps: MixinPropsMap): MixinDef[] | null;
30
+ export declare function toOneLine(value: string): string;
@@ -1,33 +1,28 @@
1
+ import { getPackagesSync } from '@manypkg/get-packages';
1
2
  import fs from 'node:fs';
3
+ import { createRequire } from 'node:module';
2
4
  import path from 'node:path';
3
- import oldNewMap from './old-new-map.js';
4
- import { getPackagesSync } from '@manypkg/get-packages';
5
5
  import postcss from 'postcss';
6
- import { createRequire } from 'node:module';
7
-
6
+ import oldNewMap from './old-new-map.js';
8
7
  const require = createRequire(import.meta.url);
9
- const packages = getPackagesSync(process.cwd()).packages;
8
+ const { packages } = getPackagesSync(process.cwd());
10
9
  const CORE_COMPONENTS_PACKAGE = '@alfalab/core-components';
11
10
  const CORE_COMPONENTS_VARS_PACKAGE = '@alfalab/core-components-vars';
12
11
  const TYPOGRAPHY_PROPS = ['font-size', 'line-height', 'font-weight'];
13
-
14
12
  export const vars = {
15
13
  gaps: loadVars('gaps.css'),
16
14
  shadows: loadVars('shadows-indigo.css'),
17
15
  colors: loadVars('colors-indigo.css'),
18
16
  borderRadiuses: loadVars('border-radius.css'),
19
17
  };
20
-
21
- export const colorsSet = Object.values(vars.colors).reduce((acc, vars) => {
22
- vars.forEach((colorVar) => acc.add(colorVar));
23
-
18
+ export const colorsSet = Object.values(vars.colors).reduce((acc, colorVars) => {
19
+ for (const colorVar of colorVars)
20
+ acc.add(colorVar);
24
21
  return acc;
25
22
  }, new Set());
26
-
27
23
  export const mixins = {
28
24
  typography: loadMixins('typography.css'),
29
25
  };
30
-
31
26
  const varsByProperties = {
32
27
  padding: vars.gaps,
33
28
  'padding-top': vars.gaps,
@@ -55,136 +50,106 @@ const varsByProperties = {
55
50
  'border-bottom-left-radius': vars.borderRadiuses,
56
51
  'border-bottom-right-radius': vars.borderRadiuses,
57
52
  };
58
-
59
53
  export const VARS_AVAILABLE = isCoreComponentsMonorepo() || isVarsPackagedInstalled();
60
-
61
54
  function isCoreComponentsMonorepo() {
62
55
  return packages.some(({ packageJson: { name } }) => name === CORE_COMPONENTS_PACKAGE);
63
56
  }
64
-
65
57
  function isVarsPackagedInstalled() {
66
58
  function resolveVarsPackage() {
67
59
  try {
68
60
  require.resolve(`${CORE_COMPONENTS_VARS_PACKAGE}/package.json`);
69
61
  return true;
70
- } catch (e) {
62
+ }
63
+ catch {
71
64
  return false;
72
65
  }
73
66
  }
74
-
75
67
  try {
76
- const rootPkg = require.resolve(`${CORE_COMPONENTS_PACKAGE}/package.json`);
68
+ const rootPkgPath = require.resolve(`${CORE_COMPONENTS_PACKAGE}/package.json`);
69
+ const rootPkg = JSON.parse(fs.readFileSync(rootPkgPath, 'utf8'));
77
70
  const [coreComponentsVersion] = rootPkg.version.split('.');
78
-
79
- if (parseInt(coreComponentsVersion) >= 49) {
71
+ if (Number.parseInt(coreComponentsVersion, 10) >= 49) {
80
72
  return resolveVarsPackage();
81
73
  }
82
-
83
74
  return true;
84
- } catch (e) {
75
+ }
76
+ catch {
85
77
  return resolveVarsPackage();
86
78
  }
87
79
  }
88
-
89
80
  function resolveVarsFile(file) {
90
81
  let filepath;
91
-
92
82
  if (isCoreComponentsMonorepo()) {
93
- const pkg = packages.find((pkg) => pkg.packageJson.name === CORE_COMPONENTS_VARS_PACKAGE);
94
-
83
+ const pkg = packages.find((p) => p.packageJson.name === CORE_COMPONENTS_VARS_PACKAGE);
84
+ if (!pkg) {
85
+ throw new Error(`${CORE_COMPONENTS_VARS_PACKAGE} not found in monorepo`);
86
+ }
95
87
  filepath = path.join(pkg.dir, 'src', file);
96
- } else {
88
+ }
89
+ else {
97
90
  try {
98
91
  filepath = require.resolve(`${CORE_COMPONENTS_VARS_PACKAGE}/${file}`);
99
- } catch {
92
+ }
93
+ catch {
100
94
  filepath = require.resolve(`${CORE_COMPONENTS_PACKAGE}/vars/${file}`);
101
95
  }
102
96
  }
103
-
104
97
  return filepath;
105
98
  }
106
-
107
99
  function loadVars(file) {
108
100
  const result = {};
109
-
110
101
  if (isCoreComponentsMonorepo() || isVarsPackagedInstalled()) {
111
102
  const filepath = resolveVarsFile(file);
112
103
  const content = fs.readFileSync(filepath, { encoding: 'utf8' });
113
104
  const root = postcss.parse(content, { from: filepath });
114
-
115
105
  root.walkDecls((decl) => {
116
106
  (result[toOneLine(decl.value)] ||= []).push(decl.prop);
117
107
  });
118
- } else {
108
+ }
109
+ else {
119
110
  console.error('Add @alfalab/core-components to project dependencies');
120
111
  }
121
-
122
112
  return result;
123
113
  }
124
-
125
114
  function loadMixins(file) {
126
115
  const result = {};
127
-
128
116
  if (isCoreComponentsMonorepo() || isVarsPackagedInstalled()) {
129
117
  const filepath = resolveVarsFile(file);
130
118
  const content = fs.readFileSync(filepath, { encoding: 'utf8' });
131
119
  const root = postcss.parse(content, { from: filepath });
132
-
133
120
  root.walkAtRules('define-mixin', (atRule) => {
134
121
  const params = atRule.params.split(/\s/);
135
122
  const name = params[0];
136
-
137
- if (
138
- name.startsWith('system_') ||
123
+ if (name.startsWith('system_') ||
139
124
  name.startsWith('styrene_') ||
140
- name.startsWith('legacy_')
141
- ) {
125
+ name.startsWith('legacy_')) {
142
126
  return;
143
127
  }
144
-
145
128
  const decls = {};
146
-
147
129
  atRule.walkDecls((decl) => {
148
130
  decls[decl.prop] = decl.value;
149
131
  });
150
-
151
132
  result[name] = decls;
152
133
  });
153
- } else {
134
+ }
135
+ else {
154
136
  console.error('Add @alfalab/core-components to project dependencies');
155
137
  }
156
-
157
138
  return result;
158
139
  }
159
-
160
140
  function formatVar(variable) {
161
141
  return variable.startsWith('var(') ? variable : `var(${variable})`;
162
142
  }
163
-
164
- /**
165
- * @param {string} str
166
- * @param {string} substr
167
- * @param {string} [sep]
168
- * @param {number} [pos]
169
- */
170
143
  function findSubstring(str, substr, sep = ' ', pos = 0) {
171
- for (
172
- let index = str.indexOf(substr, pos);
173
- index !== -1;
174
- index = str.indexOf(substr, index + substr.length)
175
- ) {
176
- if (
177
- (index === 0 || str.slice(index - sep.length, index) === sep) &&
144
+ for (let index = str.indexOf(substr, pos); index !== -1; index = str.indexOf(substr, index + substr.length)) {
145
+ if ((index === 0 || str.slice(index - sep.length, index) === sep) &&
178
146
  (index + substr.length === str.length ||
179
- str.slice(index + substr.length, index + substr.length + sep.length) === sep)
180
- ) {
147
+ str.slice(index + substr.length, index + substr.length + sep.length) === sep)) {
181
148
  return index;
182
149
  }
183
150
  }
184
-
185
151
  return -1;
186
152
  }
187
-
188
153
  function getColorVariants(prop) {
189
154
  switch (prop) {
190
155
  case 'color':
@@ -202,39 +167,27 @@ function getColorVariants(prop) {
202
167
  return [];
203
168
  }
204
169
  }
205
-
206
170
  function choiceVars(variables, prop, group) {
207
171
  if (group === 'colors') {
208
172
  const variants = getColorVariants(prop);
209
-
210
- const condition = (variable) =>
211
- variants.some((variant) => variable.startsWith(`--color-light-${variant}`));
212
-
173
+ const condition = (variable) => variants.some((variant) => variable.startsWith(`--color-light-${variant}`));
213
174
  return sortVarsByUsage(variables, variants).filter(condition);
214
175
  }
215
-
216
176
  return variables;
217
177
  }
218
-
219
178
  export function findVars(cssValue, prop, options) {
220
- const vars = varsByProperties[prop];
221
- if (!vars) return;
222
-
223
- const group = getVarsGroup(vars);
224
-
225
- if (group === 'gaps' || group === 'borderRadiuses') {
226
- if (options.allowNumericValues) {
227
- return;
228
- }
179
+ const propVars = varsByProperties[prop];
180
+ if (!propVars)
181
+ return undefined;
182
+ const group = getVarsGroup(propVars);
183
+ if ((group === 'gaps' || group === 'borderRadiuses') && options.allowNumericValues) {
184
+ return undefined;
229
185
  }
230
-
231
- for (const [value, variables] of Object.entries(vars)) {
186
+ for (const [value, variables] of Object.entries(propVars)) {
232
187
  const chosen = choiceVars(variables, prop, group);
233
-
234
- if (!chosen || !chosen.length) continue;
235
-
188
+ if (!chosen || !chosen.length)
189
+ continue;
236
190
  const index = findSubstring(cssValue, value);
237
-
238
191
  if (index !== -1) {
239
192
  return {
240
193
  index,
@@ -245,78 +198,61 @@ export function findVars(cssValue, prop, options) {
245
198
  };
246
199
  }
247
200
  }
201
+ return undefined;
248
202
  }
249
-
250
203
  export function findOldVars(cssValue, prop) {
251
- const matches = /var\(([^\),]+)/g.exec(cssValue);
252
-
253
- if (matches) {
254
- const oldVar = matches[1];
255
- const replacements = oldNewMap[oldVar];
256
- if (!replacements) return;
257
-
258
- const variants = getColorVariants(prop);
259
-
260
- let variables = replacements.filter((r) => variants.some((v) => r.includes(v)));
261
- const fixable = variables.length === 1;
262
-
263
- if (!variables.length) {
264
- variables = replacements;
265
- }
266
-
267
- return {
268
- index: cssValue.indexOf(oldVar),
269
- value: oldVar,
270
- variables,
271
- fixedValue: variables.length ? variables[0] : 'NON_FIXABLE',
272
- fixable,
273
- };
204
+ const matches = /var\(([^),]+)/g.exec(cssValue);
205
+ if (!matches)
206
+ return undefined;
207
+ const oldVar = matches[1];
208
+ const replacements = oldNewMap[oldVar];
209
+ if (!replacements)
210
+ return undefined;
211
+ const variants = getColorVariants(prop);
212
+ let variables = replacements.filter((r) => variants.some((v) => r.includes(v)));
213
+ const fixable = variables.length === 1;
214
+ if (!variables.length) {
215
+ variables = replacements;
274
216
  }
217
+ return {
218
+ index: cssValue.indexOf(oldVar),
219
+ value: oldVar,
220
+ variables,
221
+ fixedValue: variables.length ? variables[0] : 'NON_FIXABLE',
222
+ fixable,
223
+ };
275
224
  }
276
-
277
225
  export function findTypographyMixins(ruleProps) {
278
- const findMixin = (exact) => {
279
- return Object.entries(mixins.typography)
280
- .filter(([_, mixinProps]) => {
281
- if (exact) {
282
- return TYPOGRAPHY_PROPS.every((prop) => ruleProps[prop] === mixinProps[prop]);
283
- } else {
284
- return TYPOGRAPHY_PROPS.every(
285
- (prop) => !ruleProps[prop] || ruleProps[prop] === mixinProps[prop],
286
- );
287
- }
288
- })
289
- .map(([name, props]) => ({ name, props }));
290
- };
291
-
226
+ const findMixin = (exact) => Object.entries(mixins.typography)
227
+ .filter(([, mixinProps]) => {
228
+ if (exact) {
229
+ return TYPOGRAPHY_PROPS.every((prop) => ruleProps[prop] === mixinProps[prop]);
230
+ }
231
+ return TYPOGRAPHY_PROPS.every((prop) => !ruleProps[prop] || ruleProps[prop] === mixinProps[prop]);
232
+ })
233
+ .map(([name, props]) => ({ name, props }));
292
234
  const exact = findMixin(true);
293
235
  if (exact.length) {
294
236
  return exact;
295
- } else {
296
- const mixins = findMixin(false);
297
- return mixins.length > 0 ? mixins : null;
298
237
  }
238
+ const fallbackMixins = findMixin(false);
239
+ return fallbackMixins.length > 0 ? fallbackMixins : null;
299
240
  }
300
-
301
- /**
302
- * @param {string} value
303
- * @returns
304
- */
305
241
  export function toOneLine(value) {
306
242
  return value.replace(/\n/, '').replace(/ {2,}/, ' ');
307
243
  }
308
-
309
244
  function getVarsGroup(varsSet) {
310
245
  return Object.keys(vars).find((group) => vars[group] === varsSet);
311
246
  }
312
-
313
247
  function sortVarsByUsage(arr, sortingArr) {
314
- return [...arr].sort(function (a, b) {
248
+ // eslint-disable-next-line unicorn/no-array-sort -- toSorted требует es2023, проект на es2022
249
+ return arr.slice().sort((a, b) => {
315
250
  const aUsage = a.slice(2).split('-')[2];
316
251
  const bUsage = b.slice(2).split('-')[2];
317
252
  const aIndex = sortingArr.indexOf(aUsage);
318
253
  const bIndex = sortingArr.indexOf(bUsage);
319
- if (aIndex === -1 || bIndex === -1) return 0;
254
+ if (aIndex === -1 || bIndex === -1)
255
+ return 0;
320
256
  return aIndex - bIndex;
321
257
  });
322
258
  }
package/package.json CHANGED
@@ -1,33 +1,34 @@
1
1
  {
2
2
  "name": "@alfalab/stylelint-core-vars",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "core-components css linter",
5
5
  "license": "MIT",
6
6
  "author": "core-ds contributors",
7
7
  "type": "module",
8
- "exports": "./index.js",
9
- "scripts": {
10
- "release": "changeset publish",
11
- "release:snapshot": "changeset publish --tag snapshot --no-git-tag",
12
- "test": "cross-env NODE_OPTIONS=\"--experimental-vm-modules --no-warnings\" jest",
13
- "version-package": "changeset version",
14
- "version-package:snapshot": "changeset version --snapshot snapshot"
15
- },
16
- "simple-git-hooks": {
17
- "pre-commit": "./node_modules/.bin/lint-staged",
18
- "commit-msg": "./node_modules/.bin/commitlint --edit $1"
19
- },
20
- "commitlint": {
21
- "extends": "./node_modules/arui-presets-lint/commitlint"
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "CHANGELOG.md"
18
+ ],
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/core-ds/arui-presets-lint.git"
22
22
  },
23
- "lint-staged": {
24
- "*.{js,jsx,ts,tsx,json}": [
25
- "prettier --write"
26
- ]
27
- },
28
- "prettier": "arui-presets-lint/prettier",
29
- "resolutions": {
30
- "@alfalab/stylelint-core-vars": "link:./"
23
+ "scripts": {
24
+ "build": "rimraf dist && tsc -p tsconfig.build.json",
25
+ "test": "tsc --noEmit && yarn lint && yarn test:unit",
26
+ "test:unit": "vitest --run",
27
+ "lint": "yarn lint:scripts && yarn format:check",
28
+ "lint:fix": "yarn lint:scripts --fix && yarn format",
29
+ "lint:scripts": "tsx ../arui-presets-lint/cli/index.mts scripts",
30
+ "format": "tsx ../arui-presets-lint/cli/index.mts format",
31
+ "format:check": "tsx ../arui-presets-lint/cli/index.mts format:check"
31
32
  },
32
33
  "dependencies": {
33
34
  "@manypkg/get-packages": "^3.1.0",
@@ -35,23 +36,22 @@
35
36
  },
36
37
  "devDependencies": {
37
38
  "@alfalab/core-components-vars": "7.0.0",
38
- "@alfalab/stylelint-core-vars": "*",
39
- "@changesets/changelog-github": "^0.5.1",
40
- "@changesets/cli": "^2.29.6",
41
- "arui-presets-lint": "^7.3.0",
42
- "cross-env": "^10.0.0",
43
- "jest": "^30.1.3",
39
+ "@vitest/coverage-istanbul": "4.1.5",
40
+ "arui-presets-lint": "workspace:*",
44
41
  "jest-preset-stylelint": "^8.0.0",
45
- "lint-staged": "^15.2.7",
46
- "prettier": "^3.3.2",
47
- "simple-git-hooks": "^2.11.1",
48
- "stylelint": "^16.23.1"
42
+ "rimraf": "6.1.3",
43
+ "stylelint": "16.23.1",
44
+ "tsx": "4.21.0",
45
+ "typescript": "6.0.3",
46
+ "vitest": "4.1.5"
49
47
  },
50
48
  "peerDependencies": {
51
49
  "stylelint": "^16.0.0"
52
50
  },
53
- "packageManager": "yarn@4.5.3",
54
51
  "engines": {
55
52
  "node": ">=18.12.0"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public"
56
56
  }
57
57
  }
package/index.js DELETED
@@ -1 +0,0 @@
1
- export { default } from './lib/index.js';