@atlaskit/codemod-cli 0.13.4 → 0.15.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 (89) hide show
  1. package/CHANGELOG.md +71 -52
  2. package/dist/cjs/main.js +3 -3
  3. package/dist/cjs/presets/css-to-design-tokens/css-to-design-tokens.js +65 -135
  4. package/dist/cjs/presets/css-to-design-tokens/lib/colors.js +49 -0
  5. package/dist/cjs/presets/css-to-design-tokens/lib/declaration.js +29 -0
  6. package/dist/cjs/presets/css-to-design-tokens/{utils → lib}/legacy-colors.js +13 -17
  7. package/dist/cjs/presets/css-to-design-tokens/lib/logger.js +18 -0
  8. package/dist/cjs/presets/css-to-design-tokens/lib/meta.js +157 -0
  9. package/dist/cjs/presets/css-to-design-tokens/lib/tokens.js +47 -0
  10. package/dist/cjs/presets/css-to-design-tokens/lib/value.js +80 -0
  11. package/dist/cjs/presets/index.js +1 -2
  12. package/dist/cjs/presets/styled-to-emotion/styled-to-emotion.js +1 -2
  13. package/dist/cjs/presets/theme-remove-deprecated-mixins/utils/replacements.js +2 -3
  14. package/dist/cjs/presets/theme-to-design-tokens/theme-to-design-tokens.js +348 -104
  15. package/dist/cjs/presets/theme-to-design-tokens/utils/ast.js +1 -1
  16. package/dist/cjs/presets/theme-to-design-tokens/utils/color.js +17 -17
  17. package/dist/cjs/presets/theme-to-design-tokens/utils/css-utils.js +38 -0
  18. package/dist/cjs/presets/theme-to-design-tokens/utils/fuzzy-search.js +1 -2
  19. package/dist/cjs/presets/theme-to-design-tokens/utils/legacy-colors.js +4 -7
  20. package/dist/cjs/presets/theme-to-design-tokens/utils/named-colors.js +1 -2
  21. package/dist/cjs/presets/theme-to-design-tokens/utils/string-utils.js +25 -0
  22. package/dist/cjs/presets/theme-to-design-tokens/utils/tokens.js +3 -5
  23. package/dist/cjs/sinceRef.js +1 -2
  24. package/dist/cjs/transforms.js +6 -12
  25. package/dist/cjs/types.js +3 -5
  26. package/dist/cjs/utils.js +2 -3
  27. package/dist/es2019/presets/css-to-design-tokens/css-to-design-tokens.js +61 -115
  28. package/dist/es2019/presets/css-to-design-tokens/lib/colors.js +34 -0
  29. package/dist/es2019/presets/css-to-design-tokens/lib/declaration.js +17 -0
  30. package/dist/es2019/presets/css-to-design-tokens/{utils → lib}/legacy-colors.js +9 -10
  31. package/dist/es2019/presets/css-to-design-tokens/lib/logger.js +11 -0
  32. package/dist/es2019/presets/css-to-design-tokens/lib/meta.js +133 -0
  33. package/dist/es2019/presets/css-to-design-tokens/lib/tokens.js +24 -0
  34. package/dist/es2019/presets/css-to-design-tokens/lib/value.js +68 -0
  35. package/dist/es2019/presets/theme-to-design-tokens/theme-to-design-tokens.js +191 -32
  36. package/dist/es2019/presets/theme-to-design-tokens/utils/ast.js +1 -1
  37. package/dist/es2019/presets/theme-to-design-tokens/utils/color.js +12 -10
  38. package/dist/es2019/presets/theme-to-design-tokens/utils/css-utils.js +31 -0
  39. package/dist/es2019/presets/theme-to-design-tokens/utils/string-utils.js +13 -0
  40. package/dist/esm/main.js +3 -3
  41. package/dist/esm/presets/css-to-design-tokens/css-to-design-tokens.js +65 -135
  42. package/dist/esm/presets/css-to-design-tokens/lib/colors.js +38 -0
  43. package/dist/esm/presets/css-to-design-tokens/lib/declaration.js +19 -0
  44. package/dist/esm/presets/css-to-design-tokens/{utils → lib}/legacy-colors.js +9 -10
  45. package/dist/esm/presets/css-to-design-tokens/lib/logger.js +11 -0
  46. package/dist/esm/presets/css-to-design-tokens/lib/meta.js +146 -0
  47. package/dist/esm/presets/css-to-design-tokens/lib/tokens.js +40 -0
  48. package/dist/esm/presets/css-to-design-tokens/lib/value.js +73 -0
  49. package/dist/esm/presets/theme-to-design-tokens/theme-to-design-tokens.js +346 -100
  50. package/dist/esm/presets/theme-to-design-tokens/utils/ast.js +1 -1
  51. package/dist/esm/presets/theme-to-design-tokens/utils/color.js +12 -10
  52. package/dist/esm/presets/theme-to-design-tokens/utils/css-utils.js +31 -0
  53. package/dist/esm/presets/theme-to-design-tokens/utils/string-utils.js +17 -0
  54. package/dist/types/main.d.ts +0 -1
  55. package/dist/types/presets/css-to-design-tokens/css-to-design-tokens.d.ts +1 -1
  56. package/dist/types/presets/css-to-design-tokens/lib/colors.d.ts +6 -0
  57. package/dist/types/presets/css-to-design-tokens/lib/declaration.d.ts +5 -0
  58. package/dist/types/presets/css-to-design-tokens/{utils → lib}/legacy-colors.d.ts +1 -1
  59. package/dist/types/presets/css-to-design-tokens/lib/logger.d.ts +4 -0
  60. package/dist/types/presets/css-to-design-tokens/lib/meta.d.ts +6 -0
  61. package/dist/types/presets/css-to-design-tokens/lib/tokens.d.ts +7 -0
  62. package/dist/types/presets/css-to-design-tokens/lib/value.d.ts +6 -0
  63. package/dist/types/presets/theme-to-design-tokens/theme-to-design-tokens.d.ts +1 -1
  64. package/dist/types/presets/theme-to-design-tokens/utils/ast.d.ts +1 -1
  65. package/dist/types/presets/theme-to-design-tokens/utils/color.d.ts +2 -1
  66. package/dist/types/presets/theme-to-design-tokens/utils/css-utils.d.ts +2 -0
  67. package/dist/types/presets/theme-to-design-tokens/utils/string-utils.d.ts +3 -0
  68. package/dist/types-ts4.5/main.d.ts +0 -1
  69. package/dist/types-ts4.5/presets/css-to-design-tokens/css-to-design-tokens.d.ts +1 -1
  70. package/dist/types-ts4.5/presets/css-to-design-tokens/lib/colors.d.ts +6 -0
  71. package/dist/types-ts4.5/presets/css-to-design-tokens/lib/declaration.d.ts +5 -0
  72. package/dist/types-ts4.5/presets/css-to-design-tokens/{utils → lib}/legacy-colors.d.ts +1 -1
  73. package/dist/types-ts4.5/presets/css-to-design-tokens/lib/logger.d.ts +4 -0
  74. package/dist/types-ts4.5/presets/css-to-design-tokens/lib/meta.d.ts +6 -0
  75. package/dist/types-ts4.5/presets/css-to-design-tokens/lib/tokens.d.ts +7 -0
  76. package/dist/types-ts4.5/presets/css-to-design-tokens/lib/value.d.ts +6 -0
  77. package/dist/types-ts4.5/presets/theme-to-design-tokens/theme-to-design-tokens.d.ts +1 -1
  78. package/dist/types-ts4.5/presets/theme-to-design-tokens/utils/ast.d.ts +1 -1
  79. package/dist/types-ts4.5/presets/theme-to-design-tokens/utils/color.d.ts +2 -1
  80. package/dist/types-ts4.5/presets/theme-to-design-tokens/utils/css-utils.d.ts +2 -0
  81. package/dist/types-ts4.5/presets/theme-to-design-tokens/utils/string-utils.d.ts +6 -0
  82. package/package.json +2 -2
  83. package/report.api.md +0 -2
  84. package/tmp/api-report-tmp.d.ts +0 -2
  85. package/dist/cjs/presets/css-to-design-tokens/utils/meta.js +0 -53
  86. package/dist/es2019/presets/css-to-design-tokens/utils/meta.js +0 -33
  87. package/dist/esm/presets/css-to-design-tokens/utils/meta.js +0 -46
  88. package/dist/types/presets/css-to-design-tokens/utils/meta.d.ts +0 -1
  89. package/dist/types-ts4.5/presets/css-to-design-tokens/utils/meta.d.ts +0 -1
@@ -0,0 +1,11 @@
1
+ import chalk from 'chalk';
2
+ export const logger = {
3
+ warn(message) {
4
+ // eslint-disable-next-line no-console
5
+ console.warn(chalk.yellow('WARNING'), message);
6
+ },
7
+ error(message) {
8
+ // eslint-disable-next-line no-console
9
+ console.error(chalk.red('ERROR'), message);
10
+ }
11
+ };
@@ -0,0 +1,133 @@
1
+ import designTokens from '@atlaskit/tokens/token-names';
2
+ import { extractCssVarName } from './declaration';
3
+ import { knownVariables, knownRawColors, knownNamedColors } from './legacy-colors';
4
+ const getUniqueWordsFromTokens = Object.keys(designTokens).reduce((accum, val) => [...accum, ...val.split('.')], []).reduce((accum, val) => [...accum, ...val.split(/(?=[A-Z])/g).map(e => e.toLowerCase())], []).reduce((accum, val) => {
5
+ if (!accum.includes(val)) {
6
+ accum.push(val);
7
+ }
8
+ return accum;
9
+ }, []);
10
+ function filterDuplciateFoundations(meta) {
11
+ const foundations = ['text', 'background', 'shadow', 'border'];
12
+ let hasFoundation = false;
13
+ return meta.filter(val => {
14
+ if (!hasFoundation && foundations.includes(val)) {
15
+ hasFoundation = true;
16
+ return true;
17
+ }
18
+ if (hasFoundation && foundations.includes(val)) {
19
+ return false;
20
+ }
21
+ return true;
22
+ });
23
+ }
24
+ const REPLACEMENTS = {
25
+ ':': '',
26
+ ',': '',
27
+ texts: 'text',
28
+ error: 'danger',
29
+ invalid: 'danger',
30
+ removed: 'danger',
31
+ removal: 'danger',
32
+ remove: 'danger',
33
+ focus: 'focused',
34
+ valid: 'success',
35
+ successful: 'success',
36
+ risk: 'warning',
37
+ caution: 'warning',
38
+ warn: 'warning',
39
+ primary: 'bold',
40
+ info: 'bold',
41
+ secondary: 'subtle',
42
+ hyperlink: 'link',
43
+ anchor: 'link',
44
+ active: 'pressed',
45
+ hover: 'hovered',
46
+ dragged: 'overlay',
47
+ dragging: 'overlay',
48
+ drag: 'overlay',
49
+ 'background-color': 'background',
50
+ color: 'text',
51
+ icons: 'icon',
52
+ arrow: 'icon',
53
+ glyph: 'icon',
54
+ stroke: 'border',
55
+ 'border-left': 'border',
56
+ 'border-right': 'border',
57
+ 'border-top': 'border',
58
+ 'border-bottom': 'border',
59
+ 'box-shadow': 'shadow'
60
+ };
61
+ const ADDITIONAL_META = {
62
+ grey: 'neutral',
63
+ red: 'danger'
64
+ };
65
+ export function cleanMeta(meta) {
66
+ const cleanMeta = meta.reduce((accum, val) => [...accum, ...(typeof val === 'string' ? val.split(/(?=[A-Z])/g).map(e => e.toLowerCase()) : [])], []).reduce((accum, val) => {
67
+ if (val in ADDITIONAL_META) {
68
+ accum.push(val, ADDITIONAL_META[val]);
69
+ } else {
70
+ accum.push(val);
71
+ }
72
+ accum.push(val in REPLACEMENTS ? REPLACEMENTS[val] : val);
73
+ return accum;
74
+ }, []).filter(val => getUniqueWordsFromTokens.includes(val)).reduce((accum, val) => {
75
+ if (!accum.includes(val)) {
76
+ accum.push(val);
77
+ }
78
+ return accum;
79
+ }, []);
80
+ return filterDuplciateFoundations(cleanMeta);
81
+ }
82
+ export function getBaseDeclarationMeta(decl) {
83
+ const parentSelectors = getParentSelectors(decl).split(/\-|\.|\,|\ |\:|\&/).filter(Boolean);
84
+ return [getPropertyMeta(decl.prop), ...parentSelectors];
85
+ }
86
+ function getPropertyMeta(prop) {
87
+ if (prop === 'color') {
88
+ return 'text';
89
+ }
90
+ if (prop.startsWith('background')) {
91
+ return 'background';
92
+ }
93
+ if (prop.includes('shadow')) {
94
+ return 'shadow';
95
+ }
96
+ if (prop.includes('border')) {
97
+ return 'border';
98
+ }
99
+ return '';
100
+ }
101
+ function isRule(node) {
102
+ return node.type === 'rule';
103
+ }
104
+ function getParentSelectors(node) {
105
+ if (isRule(node)) {
106
+ // @ts-expect-error
107
+ return getParentSelectors(node.parent) + ' ' + node.selector;
108
+ }
109
+ if (node.parent) {
110
+ return getParentSelectors(node.parent);
111
+ }
112
+ return '';
113
+ }
114
+ export function getCssVarMeta(cssVariable) {
115
+ const tokenName = extractCssVarName(cssVariable);
116
+ const meta = knownVariables[tokenName];
117
+ if (!meta || meta.length === 0) {
118
+ return tokenName.split('-');
119
+ }
120
+ return meta;
121
+ }
122
+ export function getRawColorMeta(rawColor) {
123
+ var _knownRawColors$clean;
124
+ let cleanColor = rawColor.toLowerCase();
125
+ if (cleanColor.length === 4) {
126
+ cleanColor = cleanColor + cleanColor.substring(cleanColor.indexOf('#') + 1);
127
+ }
128
+ return (_knownRawColors$clean = knownRawColors[cleanColor]) !== null && _knownRawColors$clean !== void 0 ? _knownRawColors$clean : [];
129
+ }
130
+ export function getNamedColorMeta(namedColor) {
131
+ var _knownNamedColors$nam;
132
+ return (_knownNamedColors$nam = knownNamedColors[namedColor]) !== null && _knownNamedColors$nam !== void 0 ? _knownNamedColors$nam : [];
133
+ }
@@ -0,0 +1,24 @@
1
+ import designTokens from '@atlaskit/tokens/token-names';
2
+ import { light as rawTokens } from '@atlaskit/tokens/tokens-raw';
3
+ import Search from '../../theme-to-design-tokens/utils/fuzzy-search';
4
+ import { cleanMeta } from './meta';
5
+ const MISSING_TOKEN_NAME = 'MISSING_TOKEN';
6
+ const ACTIVE_TOKENS = rawTokens.filter(token => token.attributes.state === 'active').map(token => token.name.replace(/\.\[default\]/g, '')).filter(token => !token.includes('UNSAFE') && !token.includes('interaction'));
7
+ const COLOR_TOKEN_SEARCH_TYPES = ['text', 'link', 'icon', 'border', 'background', 'blanket', 'skeleton', 'chart', 'surface', 'shadow'];
8
+ const createFuzzySearch = tokens => Search(tokens, false);
9
+ function filterTokens(meta) {
10
+ const commonSearchTypes = COLOR_TOKEN_SEARCH_TYPES.filter(type => meta.includes(type));
11
+ return commonSearchTypes.length !== 0 ? ACTIVE_TOKENS.filter(token => commonSearchTypes.some(type => token.startsWith(`color.${type}`) || token.startsWith(`elevation.${type}`))) : ACTIVE_TOKENS;
12
+ }
13
+ export default function findToken(meta) {
14
+ const filteredTokens = filterTokens(meta);
15
+ const tokenFuzzySearch = createFuzzySearch(filteredTokens);
16
+ const cleanSearchTerms = cleanMeta(meta).join(' ');
17
+ const results = tokenFuzzySearch.get(cleanSearchTerms);
18
+ if (!results) {
19
+ return MISSING_TOKEN_NAME;
20
+ }
21
+ const candidates = results.map(result => result[1]);
22
+ const bestCandidate = designTokens[candidates[0]];
23
+ return bestCandidate;
24
+ }
@@ -0,0 +1,68 @@
1
+ import { extractBetweenParentheses, isGradient, isKnownCssVariable, isLessFunction, isNamedColor, isRawColor } from './colors';
2
+ import { extractCssVarName } from './declaration';
3
+ import { getCssVarMeta, getNamedColorMeta, getRawColorMeta } from './meta';
4
+ import findToken from './tokens';
5
+ import { logger } from './logger';
6
+ export default function parseValue(value) {
7
+ if (isLessFunction(value)) {
8
+ logger.warn('Cannot parse - less function detected, would cause compilation error');
9
+ return null;
10
+ }
11
+ if (isGradient(value)) {
12
+ return {
13
+ getReplacement(additionalMeta = []) {
14
+ const gradientContent = extractBetweenParentheses(value);
15
+ const values = gradientContent.split(',');
16
+ const replacedValues = values.map(val => {
17
+ const parsedValue = parseValue(val.trim());
18
+ return parsedValue ? parsedValue.getReplacement(additionalMeta) : val;
19
+ });
20
+ return value.replace(gradientContent, replacedValues.join(', '));
21
+ },
22
+ getMeta() {
23
+ const BASE_META = [];
24
+ const gradientContent = extractBetweenParentheses(value);
25
+ const values = gradientContent.split(',');
26
+ const metas = values.reduce((acc, val) => {
27
+ const parsedValue = parseValue(val.trim());
28
+ return parsedValue ? [...acc, ...parsedValue.getMeta()] : acc;
29
+ }, BASE_META);
30
+ return metas;
31
+ }
32
+ };
33
+ }
34
+ if (isKnownCssVariable(extractCssVarName(value))) {
35
+ return {
36
+ getReplacement(additionalMeta = []) {
37
+ const token = findToken([...additionalMeta, ...this.getMeta()]);
38
+ return `var(${token}, ${value})`;
39
+ },
40
+ getMeta() {
41
+ return getCssVarMeta(value);
42
+ }
43
+ };
44
+ }
45
+ if (isRawColor(value)) {
46
+ return {
47
+ getReplacement(additionalMeta = []) {
48
+ const token = findToken([...additionalMeta, ...this.getMeta()]);
49
+ return `var(${token}, ${value})`;
50
+ },
51
+ getMeta() {
52
+ return getRawColorMeta(value);
53
+ }
54
+ };
55
+ }
56
+ if (isNamedColor(value)) {
57
+ return {
58
+ getReplacement(additionalMeta = []) {
59
+ const token = findToken([...additionalMeta, ...this.getMeta()]);
60
+ return `var(${token}, ${value})`;
61
+ },
62
+ getMeta() {
63
+ return getNamedColorMeta(value);
64
+ }
65
+ };
66
+ }
67
+ return null;
68
+ }
@@ -3,15 +3,13 @@
3
3
  import { isDecendantOfType, hasImportDeclaration } from '@codeshift/utils';
4
4
  import { isDecendantOfToken, isParentOfToken } from './utils/ast';
5
5
  import { cleanMeta, getMetaFromAncestors } from './utils/ast-meta';
6
- import { includesHardCodedColor, isHardCodedColor, isLegacyColor, isLegacyNamedColor } from './utils/color';
6
+ import { includesHardCodedColor, isHardCodedColor, isLegacyColor, isLegacyNamedColor, isBoldColor } from './utils/color';
7
7
  import Search from './utils/fuzzy-search';
8
8
  import { legacyColorMetaMap } from './utils/legacy-colors';
9
9
  import { tokens } from './utils/tokens';
10
- const kebabize = str => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? '-' : '') + $.toLowerCase());
11
- function isBoldColor(color) {
12
- const number = parseInt(color.replace(/^./, ''), 10);
13
- return number > 300;
14
- }
10
+ import { kebabize, findFirstNonspaceIndexAfter, splitAtIndex } from './utils/string-utils';
11
+ import { containsReplaceableCSSDeclarations, findEndIndexOfCSSExpression } from './utils/css-utils';
12
+ import CSSTransformer from '../css-to-design-tokens/css-to-design-tokens';
15
13
  function insertTokenImport(j, source) {
16
14
  if (hasImportDeclaration(j, source, '@atlaskit/tokens')) {
17
15
  return;
@@ -23,6 +21,23 @@ function buildToken(j, tokenId, node) {
23
21
  const callExpr = j.callExpression(j.identifier('token'), [j.stringLiteral(tokenId), node].filter(Boolean));
24
22
  return callExpr;
25
23
  }
24
+
25
+ // Wrap over the j.templateElement builder to provide a more convenient API.
26
+ function buildTemplateElement(j, text, options = {
27
+ tail: false,
28
+ fromNode: null
29
+ }) {
30
+ let tail;
31
+ if (options.fromNode) {
32
+ tail = options.fromNode.tail;
33
+ } else {
34
+ tail = !!options.tail;
35
+ }
36
+ return j.templateElement({
37
+ raw: text,
38
+ cooked: null
39
+ }, tail);
40
+ }
26
41
  function getColorFromIdentifier(expression) {
27
42
  let value = '';
28
43
  if (expression.type === 'Identifier') {
@@ -126,10 +141,20 @@ function getTokenFromNode(j, path, value, propertyName) {
126
141
  }
127
142
  function parseCSSPropertyName(cssString) {
128
143
  const lastColonIndex = cssString.lastIndexOf(':');
129
- const propertyNameEndIndex = Math.max(cssString.lastIndexOf(';', lastColonIndex), cssString.lastIndexOf(' ', lastColonIndex));
130
- return cssString.slice(propertyNameEndIndex + 1, lastColonIndex).trim();
144
+ if (lastColonIndex === -1) {
145
+ return {
146
+ colonIndex: null,
147
+ cssPropertyName: null
148
+ };
149
+ }
150
+ const propertyNameEndIndex = Math.max(cssString.lastIndexOf(';', lastColonIndex), cssString.lastIndexOf(' ', lastColonIndex), -1);
151
+ const startIndex = propertyNameEndIndex + 1;
152
+ return {
153
+ cssPropertyName: cssString.slice(startIndex, lastColonIndex).trim(),
154
+ colonIndex: lastColonIndex
155
+ };
131
156
  }
132
- export default function transformer(file, api, debug = false) {
157
+ export default async function transformer(file, api, debug = false) {
133
158
  const j = api.jscodeshift;
134
159
  const source = j(file.source);
135
160
  let transformed = false;
@@ -169,29 +194,6 @@ export default function transformer(file, api, debug = false) {
169
194
  transformed = true;
170
195
  });
171
196
 
172
- // Template literals
173
- source.find(j.TemplateLiteral).forEach(path => {
174
- function replaceTemplateLiteralExpressions(j, expression, index) {
175
- if (isDecendantOfToken(j, expression)) {
176
- return;
177
- }
178
- if (index >= path.value.quasis.length) {
179
- return;
180
- }
181
- const quasi = path.value.quasis[index];
182
- const value = getColorFromIdentifier(expression.value);
183
- if (!value || !includesHardCodedColor(value) && !isHardCodedColor(value) && !isLegacyColor(value) && !isLegacyNamedColor(value)) {
184
- return;
185
- }
186
- const tokenId = getTokenFromNode(j, expression, value, parseCSSPropertyName(quasi.value.cooked || ''));
187
- insertTokenImport(j, source);
188
- expression.replace(buildToken(j, tokenId, expression.value));
189
- }
190
- j(path).find(j.Identifier).filter(expression => !isDecendantOfType(j, expression, j.MemberExpression)).forEach((expression, i) => replaceTemplateLiteralExpressions(j, expression, i));
191
- j(path).find(j.MemberExpression).forEach((expression, i) => replaceTemplateLiteralExpressions(j, expression, i));
192
- transformed = true;
193
- });
194
-
195
197
  // JSX props
196
198
  source.find(j.JSXAttribute).forEach(path => {
197
199
  var _path$value, _path$value$value;
@@ -214,5 +216,162 @@ export default function transformer(file, api, debug = false) {
214
216
  });
215
217
  transformed = true;
216
218
  });
219
+
220
+ // Strings
221
+ source.find(j.StringLiteral).forEach(path => {
222
+ j(path).filter(expression => !isDecendantOfType(j, expression, j.ObjectExpression)).forEach(path => {
223
+ const value = path.value.value;
224
+ if (replaceStringLiteralIfItConsistsOnlyOfColor(j, path, value)) {
225
+ transformed = true;
226
+ }
227
+ });
228
+ });
229
+ const templateLiteralPaths = source.find(j.TemplateLiteral).paths();
230
+ for (const path of templateLiteralPaths) {
231
+ // Background: a 'type: TemplateLiteral' Node has quasis and expressions
232
+ // (see ast-types/src/gen/namedTypes.ts), and invariant holds that
233
+ // quasis.length === expression.length + 1.
234
+ //
235
+ // eg `${foo}bar` has quasis [Node(''), Node('bar')] and expressions
236
+ // [Node('foo')]. Each quasi has type: 'TemplateElement'; expressions are
237
+ // probably safe to treat as subtypes of Expression, though ast-types
238
+ // codebase has a more involved definition.
239
+ if (path.value.expressions.length === 0) {
240
+ // A single-quasi (equivalently, no-expression) template literal is
241
+ // basically just a string literal, possibly multi-line. We handle the
242
+ // simple `#ababab` case here, and the multi-line case after.
243
+ const text = path.value.quasis[0].value.raw;
244
+ if (replaceStringLiteralIfItConsistsOnlyOfColor(j, path, text)) {
245
+ transformed = true;
246
+ }
247
+ } else {
248
+ j(path).find(j.Expression).filter(expressionPath => {
249
+ // jscodeshift walks over the whole tree; we are interested only in
250
+ // the direct children: i.e. top-level expressions appearing in ${}.
251
+ return expressionPath.parent === path;
252
+ }).forEach((expressionPath, expressionIndex) => {
253
+ if (replaceTemplateLiteralExpression(j, path, expressionPath, expressionIndex)) {
254
+ transformed = true;
255
+ }
256
+ });
257
+ }
258
+
259
+ // No matter if we have one big quasi or many small chunks between
260
+ // expressions (which potentially have been transformed), try to pass them
261
+ // through the CSS transformer; it's robust enough to understand malformed
262
+ // CSS that would result if we split e.g. this template:
263
+ //
264
+ // `${gridSize}px; color: red;`, giving `px; color: red;` as input; or
265
+ // `@media ${mobile} { color: red }`, giving `{ color: red }`.
266
+ const quasiPaths = j(path).find(j.TemplateElement).filter(quasiPath => {
267
+ return quasiPath.parent === path;
268
+ }).paths();
269
+ for (const quasiPath of quasiPaths) {
270
+ const text = quasiPath.value.value.raw;
271
+ if (includesHardCodedColor(text) && containsReplaceableCSSDeclarations(text)) {
272
+ const newCSS = await CSSTransformer(text);
273
+ j(quasiPath).replaceWith(buildTemplateElement(j, newCSS));
274
+ transformed = true;
275
+ }
276
+ }
277
+ }
278
+ function replaceStringLiteralIfItConsistsOnlyOfColor(j, path, value) {
279
+ if (isDecendantOfToken(j, path)) {
280
+ return false;
281
+ }
282
+ if (isHardCodedColor(value) && !isLegacyColor(value) && !isLegacyNamedColor(value)) {
283
+ const parent = path.parent.value;
284
+ let key = '';
285
+ if (parent.type === 'VariableDeclarator') {
286
+ key = parent.id.name;
287
+ }
288
+ const tokenId = getTokenFromNode(j, path, value, key);
289
+ insertTokenImport(j, source);
290
+ j(path).replaceWith(buildToken(j, tokenId, path.value));
291
+ return true;
292
+ }
293
+ return false;
294
+ }
295
+ function replaceTemplateLiteralExpression(j, mainPath, expressionPath, expressionIndex) {
296
+ const expression = expressionPath.value;
297
+ if (!(expression.type === 'MemberExpression' || expression.type === 'Identifier')) {
298
+ return false;
299
+ }
300
+ if (isDecendantOfToken(j, expressionPath)) {
301
+ return false;
302
+ }
303
+ const value = getColorFromIdentifier(expression);
304
+ if (!value || !includesHardCodedColor(value) && !isHardCodedColor(value) && !isLegacyColor(value) && !isLegacyNamedColor(value)) {
305
+ return false;
306
+ }
307
+ const precedingQuasi = mainPath.value.quasis[expressionIndex];
308
+ const precedingQuasiText = precedingQuasi.value.raw;
309
+ const {
310
+ cssPropertyName,
311
+ colonIndex
312
+ } = parseCSSPropertyName(precedingQuasiText);
313
+ if (!cssPropertyName) {
314
+ return false;
315
+ }
316
+ const tokenId = getTokenFromNode(j, expressionPath, value, cssPropertyName);
317
+ insertTokenImport(j, source);
318
+ const newQuasis = [...mainPath.value.quasis];
319
+ const newExpressions = [...mainPath.value.expressions];
320
+ if (cssPropertyName !== 'box-shadow') {
321
+ const tokenExpression = buildToken(j, tokenId, expressionPath.value);
322
+ newExpressions[expressionIndex] = tokenExpression;
323
+ } else {
324
+ // box-shadow is a multi-part property where the color can appear at any
325
+ // part position (even though the standard suggests that color comes
326
+ // last, browsers' CSS parsers are more lax). If we get here, then the
327
+ // color part is replaceable. Textually, it's something like:
328
+ //
329
+ // <rules before>; box-shadow: 0 1px ${colors.N50} 2rem; <rules after>
330
+ //
331
+ // the fallback value will be multipart, i.e. the token call is
332
+ //
333
+ // token(<replacedValue>, `0 1px ${colors.N50} 2rem`)
334
+ //
335
+ // and it's wrapped in a substitution like this:
336
+ //
337
+ // <rules before>; box-shadow: ${token(<...>)}; <rules after>
338
+ //
339
+ // We stich the fallback from the last part of preceding quasi (after
340
+ // colon) and the first part of the following quasi (before ';' or '}').
341
+ //
342
+ // If multiple box-shadows are comma-separated but only one of them has a
343
+ // replaceable color and others are hard-coded, this logic would still
344
+ // work. When multiple shadows have expressions, it's unfortunately not
345
+ // possible to proceed because we cannot find where the value ends from a
346
+ // single following quasi.
347
+ const valueStartIndex = findFirstNonspaceIndexAfter(precedingQuasiText, colonIndex);
348
+ const [newPrecedingQuasiText, partialValueBeginning] = splitAtIndex(precedingQuasiText, valueStartIndex);
349
+ const followingQuasi = mainPath.value.quasis[expressionIndex + 1];
350
+ const followingQuasiText = followingQuasi.value.raw;
351
+ const valueEndIndex = findEndIndexOfCSSExpression(followingQuasiText, followingQuasi.tail);
352
+ if (!valueEndIndex) {
353
+ console.warn('cannot find end of box-shadow value, please check manually');
354
+ return false;
355
+ }
356
+ const [partialValueEnd, newFollowingQuasiText] = splitAtIndex(followingQuasiText, valueEndIndex + 1);
357
+ const internalQuasis = [buildTemplateElement(j, partialValueBeginning, {
358
+ tail: false
359
+ }), buildTemplateElement(j, partialValueEnd, {
360
+ tail: true
361
+ })];
362
+ const internalExpressions = [expressionPath.value];
363
+ const newFallback = j.templateLiteral(internalQuasis, internalExpressions);
364
+ const newExpression = buildToken(j, tokenId, newFallback);
365
+ newQuasis[expressionIndex] = buildTemplateElement(j, newPrecedingQuasiText, {
366
+ fromNode: newQuasis[expressionIndex]
367
+ });
368
+ newExpressions[expressionIndex] = newExpression;
369
+ newQuasis[expressionIndex + 1] = buildTemplateElement(j, newFollowingQuasiText, {
370
+ fromNode: newQuasis[expressionIndex]
371
+ });
372
+ }
373
+ mainPath.replace(j.templateLiteral(newQuasis, newExpressions));
374
+ return true;
375
+ }
217
376
  return transformed ? source.toSource() : file.source;
218
377
  }
@@ -1,6 +1,6 @@
1
1
  import { isDecendantOfType } from '@codeshift/utils';
2
2
  export function isDecendantOfToken(j, path) {
3
- if (path.type === 'CallExpression' && path.callee.type === 'Identifier' && path.callee.name === 'token') {
3
+ if ('type' in path && path.type === 'CallExpression' && path.callee.type === 'Identifier' && path.callee.name === 'token') {
4
4
  return true;
5
5
  }
6
6
  return j(path).closest(j.CallExpression, {
@@ -2,9 +2,10 @@ import { legacyColorMixins, legacyColors } from './legacy-colors';
2
2
  import { namedColors } from './named-colors';
3
3
  export const isLegacyColor = value => legacyColors.includes(value);
4
4
  export const isLegacyNamedColor = value => legacyColorMixins.includes(value);
5
+ const colorRegexp = /#(?:[a-f0-9]{3}|[a-f0-9]{6}|[a-f0-9]{8})\b|(?:rgb|rgba|hsl|hsla|lch|lab|color)\([^\)]*\)/;
5
6
  export const includesHardCodedColor = raw => {
6
7
  const value = raw.toLowerCase();
7
- if (/#(?:[a-f0-9]{3}|[a-f0-9]{6}|[a-f0-9]{8})\b|(?:rgb|hsl)a?\([^\)]*\)/.exec(value.toLowerCase())) {
8
+ if (colorRegexp.exec(value)) {
8
9
  return true;
9
10
  }
10
11
  for (let i = 0; i < namedColors.length; i++) {
@@ -14,17 +15,18 @@ export const includesHardCodedColor = raw => {
14
15
  }
15
16
  return false;
16
17
  };
17
- export const isHardCodedColor = value => {
18
- if (namedColors.includes(value.toLowerCase())) {
19
- return true;
20
- }
21
- if (value.startsWith('rgb(') || value.startsWith('rgba(') || value.startsWith('hsl(') || value.startsWith('hsla(') || value.startsWith('lch(') || value.startsWith('lab(') || value.startsWith('color(')) {
18
+ export const isHardCodedColor = raw => {
19
+ const value = raw.toLowerCase();
20
+ if (namedColors.includes(value)) {
22
21
  return true;
23
22
  }
24
- if (value.startsWith('#') && (
25
- // short hex, hex, or hex with alpha
26
- value.length === 4 || value.length === 7 || value.length === 9)) {
23
+ const match = value.toLowerCase().match(colorRegexp);
24
+ if (match && match[0] === value) {
27
25
  return true;
28
26
  }
29
27
  return false;
30
- };
28
+ };
29
+ export function isBoldColor(color) {
30
+ const number = parseInt(color.replace(/^./, ''), 10);
31
+ return number > 300;
32
+ }
@@ -0,0 +1,31 @@
1
+ import { isColorRelatedProperty } from '../../css-to-design-tokens/lib/declaration';
2
+ export function containsReplaceableCSSDeclarations(input) {
3
+ const cssPattern = /(\S+)\s*:/g;
4
+ let match;
5
+ while ((match = cssPattern.exec(input)) !== null) {
6
+ if (isColorRelatedProperty(match[1])) {
7
+ return true;
8
+ }
9
+ }
10
+ return false;
11
+ }
12
+ export function findEndIndexOfCSSExpression(text, isAtEndOfInput) {
13
+ // CSS expression can end *on* a semicolon or *before* a brace. In either
14
+ // case we treat the remaining part of the value to cover one character
15
+ // before that symbol.
16
+ const semicolonIndex = text.indexOf(';');
17
+ const braceIndex = text.indexOf('}');
18
+ if (semicolonIndex === -1 && braceIndex === -1) {
19
+ if (isAtEndOfInput) {
20
+ return text.length;
21
+ } else {
22
+ return null;
23
+ }
24
+ } else if (semicolonIndex === -1) {
25
+ return braceIndex - 1;
26
+ } else if (braceIndex === -1) {
27
+ return semicolonIndex - 1;
28
+ } else {
29
+ return Math.min(semicolonIndex, braceIndex) - 1;
30
+ }
31
+ }
@@ -0,0 +1,13 @@
1
+ export const kebabize = str => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? '-' : '') + $.toLowerCase());
2
+ export function findFirstNonspaceIndexAfter(text, index) {
3
+ const rest = text.slice(index + 1);
4
+ const indexInRest = rest.search(/\S/);
5
+ if (indexInRest === -1) {
6
+ return text.length;
7
+ } else {
8
+ return index + 1 + indexInRest;
9
+ }
10
+ }
11
+ export function splitAtIndex(text, index) {
12
+ return [text.slice(0, index), text.slice(index)];
13
+ }
package/dist/esm/main.js CHANGED
@@ -5,8 +5,8 @@ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol
5
5
  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
6
6
  function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
7
7
  import _regeneratorRuntime from "@babel/runtime/regenerator";
8
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
9
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
8
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
9
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
10
10
  import chalk from 'chalk';
11
11
  import fs from 'fs';
12
12
  import spawn from 'projector-spawn';
@@ -291,7 +291,7 @@ function _main() {
291
291
  case 4:
292
292
  _yield$parseArgs = _context5.sent;
293
293
  packages = _yield$parseArgs.packages;
294
- _process$env$_PACKAGE = "0.13.4", _PACKAGE_VERSION_ = _process$env$_PACKAGE === void 0 ? '0.0.0-dev' : _process$env$_PACKAGE;
294
+ _process$env$_PACKAGE = "0.15.0", _PACKAGE_VERSION_ = _process$env$_PACKAGE === void 0 ? '0.0.0-dev' : _process$env$_PACKAGE;
295
295
  logger.log(chalk.bgBlue(chalk.black("\uD83D\uDCDA Atlassian-Frontend codemod library @ ".concat(_PACKAGE_VERSION_, " \uD83D\uDCDA"))));
296
296
  if (packages && packages.length > 0) {
297
297
  logger.log(chalk.gray("Searching for codemods for newer versions of the following packages: ".concat(packages.map(function (pkg) {