Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: New rule to disallow certain attribute values #145

Merged
merged 5 commits into from
Oct 13, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions docs/rules/no-restricted-attr-values.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
id: no-restricted-attr-values
title: "no-restricted-attr-values"
---

# no-restricted-attrs

Disallow specified attribute values

## How to use

.eslintrc.js

```js
module.exports = {
rules: {
'@html-eslint/no-restricted-attr-values': ["error", {
attrPatterns: ["class"],
attrValues: ["data-.*"]
Adam-Gillespie345 marked this conversation as resolved.
Show resolved Hide resolved
message: "\'data-x\' is restricted."
}]
}
};
```

## Rule Details

This rule allows you to specify attribute values that you don't want to use in your application.

### Options

This rule takes an array of option objects, where the `attrPatterns` and `attrValues` are specified.

- `attrPatterns`: an array of strings representing regular expression pattern, disallows attribute names that match any of the patterns.
- `attrValues`: an array of strings representing regular expression pattern, disallows attribute values that match any of the patterns.
- `message` (optional): a string for custom message.

```js
module.exports = {
"rules": {
"@html-eslint/no-restricted-attrs": [
"error",
{
attrPatterns: ["class", "alt"],
attrValues: ["data-.*"]
message: "\'data-x\' is restricted."
},
{
attrPatterns: [".*"],
attrValues: ["^foo$"]
message: "\'foo\' is restricted."
}
],
}
};
```

Examples of **incorrect** code for this rule with the option below:

```json
{
"attrPatterns": ["data-.*"],
"attrValues": ["foo"],
"message": "Do not use foo attr value"
}
```

```html
<div data-name="foo"></div>
<img data-name="foo"></div>
```
2 changes: 2 additions & 0 deletions packages/eslint-plugin/lib/rules/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const noAccesskeyAttrs = require("./no-accesskey-attrs");
const noRestrictedAttrs = require("./no-restricted-attrs");
const noTrailingSpaces = require("./no-trailing-spaces");
const requireAttrs = require("./require-attrs");
const noRestrictedAttrValues = require("./no-restricted-attr-values");

module.exports = {
"require-lang": requireLang,
Expand Down Expand Up @@ -64,4 +65,5 @@ module.exports = {
"no-accesskey-attrs": noAccesskeyAttrs,
"no-restricted-attrs": noRestrictedAttrs,
"no-trailing-spaces": noTrailingSpaces,
"no-restricted-attr-values": noRestrictedAttrValues,
};
135 changes: 135 additions & 0 deletions packages/eslint-plugin/lib/rules/no-restricted-attr-values.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/**
* @typedef {import("../types").Rule} Rule
* @typedef {{attrPatterns: string[], attrValues: string[], message?: string}[]} Options
*/

const { RULE_CATEGORY } = require("../constants");

const MESSAGE_IDS = {
RESTRICTED: "restricted",
};

/**
* @type {Rule}
*/
module.exports = {
meta: {
type: "code",

docs: {
description: "Disallow specified attributes",
category: RULE_CATEGORY.BEST_PRACTICE,
recommended: false,
},

fixable: null,
schema: {
type: "array",

items: {
type: "object",
required: ["attrPatterns", "attrValues"],
properties: {
attrPatterns: {
type: "array",
items: {
type: "string",
},
},
attrValues: {
type: "array",
items: {
type: "string",
},
},
message: {
type: "string",
},
},
},
},
messages: {
[MESSAGE_IDS.RESTRICTED]:
"'{{attrValues}}' is restricted from being used.",
},
},

create(context) {
/**
* @type {Options}
*/
const options = context.options;
const checkers = options.map((option) => new PatternChecker(option));

return {
[["Tag", "StyleTag", "ScriptTag"].join(",")](node) {
node.attributes.forEach((attr) => {
if (!attr.key || !attr.value?.value || !attr.key?.value) {
Adam-Gillespie345 marked this conversation as resolved.
Show resolved Hide resolved
return;

Check warning on line 68 in packages/eslint-plugin/lib/rules/no-restricted-attr-values.js

View check run for this annotation

Codecov / codecov/patch

packages/eslint-plugin/lib/rules/no-restricted-attr-values.js#L68

Added line #L68 was not covered by tests
}
const matched = checkers.find((checker) =>
checker.test(attr.key.value, attr.value.value)
);

if (!matched) {
return;
}

const result = {
node: attr,
message: "",
};

const customMessage = matched.getMessage();

if (customMessage) {
result.message = customMessage;
} else {
result.messageId = MESSAGE_IDS.RESTRICTED;
}

context.report({
...result,
data: { attrValues: attr.value.value },
});
});
},
};
},
};

class PatternChecker {
/**
* @param {Options[number]} option
*/
constructor(option) {
this.option = option;
this.attrRegExps = option.attrPatterns.map(
(pattern) => new RegExp(pattern, "u")
);

this.valueRegExps = option.attrValues.map(
(pattern) => new RegExp(pattern, "u")
);
this.message = option.message;
}

/**
* @param {string} attrName
* @param {string} attrValue
* @returns {boolean}
*/
test(attrName, attrValue) {
const result =
this.attrRegExps.some((exp) => exp.test(attrName)) &&
this.valueRegExps.some((exp) => exp.test(attrValue));
return result;
}

/**
* @returns {string}
*/
getMessage() {
return this.message || "";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
const createRuleTester = require("../rule-tester");
const rule = require("../../lib/rules/no-restricted-attr-values");

const ruleTester = createRuleTester();

ruleTester.run("no-restricted-attr-values", rule, {
valid: [
{
code: `<div> </div>`,
options: [
{
attrPatterns: [".*"],
attrValues: ["data-.*"],
},
],
},
{
code: `<div> </div>`,
options: [
{
attrPatterns: ["class"],
attrValues: ["data-.*"],
},
],
},
],
invalid: [
{
code: `<div foo="data-x"> </div>`,
options: [
{
attrPatterns: [".*"],
attrValues: ["data-.*"],
},
],
errors: [
{
messageId: "restricted",
data: {
attrValues: "data-x",
},
},
],
},
{
code: `<div class="foo"> </div> <a alt="foo"></a>`,
options: [
{
attrPatterns: ["alt"],
attrValues: ["foo"],
},
],
errors: [
{
messageId: "restricted",
data: {
attrValues: "foo",
},
},
],
},
{
code: `<div alt="foo"> </div> <custom-element class="foo"></custom-element>`,
options: [
{
attrPatterns: ["alt", "class"],
attrValues: ["^foo$"],
message: "no foo for alt or class",
},
],
errors: [
{
message: "no foo for alt or class",
},
{
message: "no foo for alt or class",
},
],
},
// custom message
{
code: `<div foo="data-x"> </div>`,
options: [
{
attrPatterns: [".*"],
attrValues: ["data.*"],
message: "please do not use 'data-x'",
},
],
errors: [
{
message: "please do not use 'data-x'",
},
],
},
],
});
///^a$/
Adam-Gillespie345 marked this conversation as resolved.
Show resolved Hide resolved
Loading