UNPKG

@atlaskit/eslint-plugin-design-system

Version:

The essential plugin for use with the Atlassian Design System.

232 lines (229 loc) • 10.3 kB
import _defineProperty from "@babel/runtime/helpers/defineProperty"; 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; } 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; } import { isNodeOfType } from 'eslint-codemod-utils'; import renameMapping from '@atlaskit/tokens/rename-mapping'; import tokenDefaultValues from '@atlaskit/tokens/token-default-values'; import tokens from '@atlaskit/tokens/token-names'; import { getTokenId } from '@atlaskit/tokens/utils/get-token-id'; import { createLintRule } from '../utils/create-lint-rule'; import { getPrimitiveTokenUsage } from '../utils/get-primitive-token-usage'; import { isDecendantOfStyleBlock } from '../utils/is-decendant-of-style-block'; import { isDecendantOfStyleJsxAttribute } from '../utils/is-decendant-of-style-jsx-attribute'; import { isToken } from '../utils/is-token'; import { isXcssValue } from './is-xcss-value'; var rule = createLintRule({ meta: { name: 'no-unsafe-design-token-usage', docs: { description: 'Enforces design token usage is statically and locally analyzable.', recommended: true, severity: 'error' }, fixable: 'code', type: 'problem', messages: { directTokenUsage: "Access the global theme using the token function.\n\n```\nimport { token } from '@atlaskit/tokens';\n\ntoken('{{tokenKey}}');\n```\n", staticToken: "Token string should be inlined directly into the function call.\n\n```\ntoken('color.background.blanket');\n```\n", invalidToken: 'The token "{{name}}" does not exist. Choose an existing semantic token from @atlaskit/tokens/token-names or https://atlassian.design/components/tokens/all-tokens and replace the invalid name.', tokenRemoved: 'The token "{{name}}" is removed in favour of "{{replacement}}".', tokenIsExperimental: 'The token "{{name}}" is experimental and should not be used directly at this time. It should be replaced by "{{replacement}}".', tokenFallbackEnforced: "This configuration requires a fallback argument. Add the token's light-theme default as the second argument; use the rule's fix when available.", tokenFallbackRestricted: "Remove the second argument from token() for this configuration, for example token('color.background.blanket'); retain the token name." }, schema: [{ type: 'object', properties: { shouldEnforceFallbacks: { type: 'boolean' }, fallbackUsage: { enum: ['forced', 'optional', 'none'] }, UNSAFE_ignoreTokens: { type: 'array', items: { type: 'string' } } } }] }, create: function create(context) { // TODO: JFP-2823 - this type cast was added due to Jira's ESLint v9 migration var config = _objectSpread({}, context.options[0]); if (!config.fallbackUsage) { config.fallbackUsage = config.shouldEnforceFallbacks ? 'forced' : 'none'; } var UNSAFE_ignoreTokens = new Set(config.UNSAFE_ignoreTokens); var tokenMigrations = new Map(renameMapping.filter(function (t) { return (t.state === 'deleted' || t.state === 'experimental') && t.replacement; }).map(function (t) { return [getTokenId(t.path), t]; })); var reportTokenMigration = function reportTokenMigration(tokenKey, node, tokenArgument) { var getReplacementValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function (name) { return name; }; if (typeof tokenKey !== 'string') { return false; } var migrationMeta = tokenMigrations.get(tokenKey); if (!(migrationMeta !== null && migrationMeta !== void 0 && migrationMeta.replacement)) { return false; } var replacement = getTokenId(migrationMeta.replacement); var isReplacementAToken = (replacement in tokens); context.report({ messageId: migrationMeta.state === 'deleted' ? 'tokenRemoved' : 'tokenIsExperimental', node: node, data: { name: tokenKey, replacement: replacement }, fix: function fix(fixer) { if (tokenArgument) { return fixer.replaceText(migrationMeta.state === 'deleted' || isReplacementAToken ? tokenArgument : node, "'".concat(replacement, "'")); } // Token-valued props cannot necessarily accept raw CSS or a different token family. var value = isReplacementAToken ? getReplacementValue(replacement) : undefined; return value ? fixer.replaceText(node, "'".concat(value, "'")) : null; } }); return true; }; return { JSXAttribute: function JSXAttribute(node) { var usage = getPrimitiveTokenUsage(node, context); if (usage) { reportTokenMigration(usage.tokenName, usage.node, undefined, usage.getReplacementValue); } }, 'TaggedTemplateExpression[tag.name="css"],TaggedTemplateExpression[tag.object.name="styled"]': function TaggedTemplateExpressionTagNameCssTaggedTemplateExpressionTagObjectNameStyled(node) { if (!isNodeOfType(node, 'TaggedTemplateExpression')) { return; } var value = node.quasi.quasis.map(function (q) { return q.value.raw; }).join(''); var tokenKey = isToken(value, tokens); if (tokenKey) { context.report({ messageId: 'directTokenUsage', node: node, data: { tokenKey: tokenKey } }); return; } }, 'ObjectExpression > Property > Literal': function ObjectExpression__Property__Literal(node) { if (node.type !== 'Literal') { return; } if (typeof node.value !== 'string') { return; } if (tokenMigrations.has(node.value) && isXcssValue(node, context)) { reportTokenMigration(node.value, node); return; } if (!isDecendantOfStyleBlock(node) && !isDecendantOfStyleJsxAttribute(node)) { return; } var tokenKey = isToken(node.value, tokens); var isCSSVar = node.value.startsWith('var('); if (tokenKey) { context.report({ messageId: 'directTokenUsage', node: node, data: { tokenKey: tokenKey }, fix: function fix(fixer) { return isCSSVar ? fixer.replaceText(node, "token('".concat(tokenKey, "')")) : null; } }); return; } }, 'CallExpression:matches([callee.name="token"], [callee.name="getTokenValue"])': function CallExpressionMatchesCalleeNameToken_CalleeNameGetTokenValue(node) { if (!isNodeOfType(node, 'CallExpression')) { return; } var isGetTokenValueCall = isNodeOfType(node.callee, 'Identifier') && node.callee.name === 'getTokenValue'; // Skip processing if it's a `getTokenValue` call and config.fallbackUsage is `none` if (isGetTokenValueCall && config.fallbackUsage === 'none') { return; } if (node.arguments.length < 2 && config.fallbackUsage === 'forced') { var fix; if (node.arguments[0].type === 'Literal') { var value = node.arguments[0].value; var tokenName = value; var fallbackValue = tokenDefaultValues[tokenName] || null; if (fallbackValue) { fix = function fix(fixer) { return fixer.replaceText(node, "".concat(isNodeOfType(node.callee, 'Identifier') ? node.callee.name : 'token', "('").concat(tokenName, "', '").concat(fallbackValue, "')")); }; } } context.report({ messageId: 'tokenFallbackEnforced', node: node, fix: fix }); } else if (node.arguments.length > 1 && config.fallbackUsage === 'none') { if (node.arguments[0].type === 'Literal') { var _value = node.arguments[0].value; /** * This check allows ADS tokens to be passed in via UNSAFE_ignoreTokens and allow fallbacks even if `fallbackUsage` is set to 'none'. * Temporary solution introduced to allow fallbacks for shape tokens in Jira during migration */ if (_value && UNSAFE_ignoreTokens.has(_value)) { return; } context.report({ messageId: 'tokenFallbackRestricted', node: node.arguments[1], fix: function fix(fixer) { return fixer.replaceText(node, "".concat(isNodeOfType(node.callee, 'Identifier') ? node.callee.name : 'token', "('").concat(_value, "')")); } }); } else { context.report({ messageId: 'tokenFallbackRestricted', node: node.arguments[1] }); } } if (node.arguments[0] && node.arguments[0].type !== 'Literal') { context.report({ messageId: 'staticToken', node: node }); return; } var tokenKey = node.arguments[0].value; if (!tokenKey) { return; } if (reportTokenMigration(tokenKey, node, node.arguments[0])) { return; } if (typeof tokenKey !== 'string' || typeof tokenKey === 'string' && !tokens[tokenKey] && !UNSAFE_ignoreTokens.has(tokenKey)) { context.report({ messageId: 'invalidToken', node: node, data: { name: tokenKey.toString() } }); return; } } }; } }); export default rule;