|
| 1 | +// Copyright 2020 The Chromium Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style license that can be |
| 3 | +// found in the LICENSE file. |
| 4 | + |
| 5 | +import {createRule} from './tsUtils.ts'; |
| 6 | + |
| 7 | +export default createRule({ |
| 8 | + name: 'set-data-type-reference', |
| 9 | + meta: { |
| 10 | + type: 'problem', |
| 11 | + docs: { |
| 12 | + description: 'check data setters have an explicit type reference for their parameter', |
| 13 | + category: 'Possible Errors', |
| 14 | + }, |
| 15 | + fixable: 'code', |
| 16 | + messages: { |
| 17 | + dataSetterMustTakeExplicitlyTypedParameter: 'A data setter must take a parameter that is explicitly typed.', |
| 18 | + dataSetterParamTypeMustBeDefined: 'The type of a parameter in a data setter must be explicitly defined.', |
| 19 | + dataSetterParamTypeMustBeTypeReference: |
| 20 | + 'A data setter parameter’s type must be a type reference, not a literal type defined inline.', |
| 21 | + }, |
| 22 | + schema: [], // no options |
| 23 | + }, |
| 24 | + defaultOptions: [], |
| 25 | + create: function(context) { |
| 26 | + return { |
| 27 | + ClassDeclaration(node) { |
| 28 | + // Only enforce this rule for custom elements |
| 29 | + if (!node.superClass || node.superClass.type !== 'Identifier' || node.superClass.name !== 'HTMLElement') { |
| 30 | + return; |
| 31 | + } |
| 32 | + |
| 33 | + const dataSetterDefinition = node.body.body.find(methodDefinition => { |
| 34 | + return ( |
| 35 | + 'kind' in methodDefinition && methodDefinition.kind === 'set' && 'key' in methodDefinition && |
| 36 | + methodDefinition.key.type === 'Identifier' && methodDefinition.key.name === 'data'); |
| 37 | + }); |
| 38 | + |
| 39 | + if (!dataSetterDefinition || dataSetterDefinition.type === 'StaticBlock') { |
| 40 | + return; |
| 41 | + } |
| 42 | + // @ts-expect-error needs proper check of eslint.type |
| 43 | + const dataSetterParam = dataSetterDefinition.value?.params?.[0]; |
| 44 | + if (!dataSetterParam) { |
| 45 | + context.report({ |
| 46 | + node: dataSetterDefinition, |
| 47 | + messageId: 'dataSetterMustTakeExplicitlyTypedParameter', |
| 48 | + }); |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + if (!dataSetterParam.typeAnnotation) { |
| 53 | + context.report({ |
| 54 | + node: dataSetterDefinition, |
| 55 | + messageId: 'dataSetterParamTypeMustBeDefined', |
| 56 | + }); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + if (dataSetterParam.typeAnnotation.typeAnnotation.type !== 'TSTypeReference') { |
| 61 | + context.report({ |
| 62 | + node: dataSetterDefinition, |
| 63 | + messageId: 'dataSetterParamTypeMustBeTypeReference', |
| 64 | + }); |
| 65 | + } |
| 66 | + }, |
| 67 | + }; |
| 68 | + }, |
| 69 | +}); |
0 commit comments