initial commit of actions

This commit is contained in:
2026-01-31 18:56:04 +01:00
commit 949ece5785
44660 changed files with 12034344 additions and 0 deletions

View File

@@ -0,0 +1,20 @@
Copyright (c) 2016 GitHub, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,146 @@
# eslint-plugin-github
## Installation
```sh
npm install --save-dev eslint eslint-plugin-github
```
## Setup
### Legacy Configuration (`.eslintrc`)
Add `github` to your list of plugins in your ESLint config.
JSON ESLint config example:
```json
{
"plugins": ["github"]
}
```
Extend the configs you wish to use.
JSON ESLint config example:
```json
{
"extends": ["plugin:github/recommended"]
}
```
### Flat Configuration (`eslint-config.js`)
Import the `eslint-plugin-github`, and extend any of the configurations using `getFlatConfigs()` as needed like so:
```js
import github from 'eslint-plugin-github'
export default [
github.getFlatConfigs().browser,
github.getFlatConfigs().recommended,
github.getFlatConfigs().react,
...github.getFlatConfigs().typescript,
{
files: ['**/*.{js,mjs,cjs,jsx,mjsx,ts,tsx,mtsx}'],
ignores: ['eslint.config.mjs'],
rules: {
'github/array-foreach': 'error',
'github/async-preventdefault': 'warn',
'github/no-then': 'error',
'github/no-blur': 'error',
},
},
]
```
> [!NOTE]
> If you configured the `filenames/match-regex` rule, please note we have adapted the match regex rule into `eslint-plugin-github` as the original `eslint-filenames-plugin` is no longer maintained and needed a flat config support update.
>
> Please update the name to `github/filenames-match-regex`, and note, the default rule is kebab case or camelCase with one hump. For custom configuration, such as matching for camelCase regex, here's an example:
>
> `'github/filenames-match-regex': ['error', '^([a-z0-9]+)([A-Z][a-z0-9]+)*$'],`
The available configs are:
- `internal`
- Rules useful for github applications.
- `browser`
- Useful rules when shipping your app to the browser.
- `react`
- Recommended rules for React applications.
- `recommended`
- Recommended rules for every application.
- `typescript`
- Useful rules when writing TypeScript.
### Component mapping (Experimental)
_Note: This is experimental and subject to change._
The `react` config includes rules which target specific HTML elements. You may provide a mapping of custom components to an HTML element in your `eslintrc` configuration to increase linter coverage.
By default, these eslint rules will check the "as" prop for underlying element changes. If your repo uses a different prop name for polymorphic components provide the prop name in your `eslintrc` configuration under `polymorphicPropName`.
```json
{
"settings": {
"github": {
"polymorphicPropName": "asChild",
"components": {
"Box": "p",
"Link": "a"
}
}
}
}
```
This config will be interpreted in the following way:
- All `<Box>` elements will be treated as a `p` element type.
- `<Link>` without a defined `as` prop will be treated as a `a`.
- `<Link as='button'>` will be treated as a `button` element type.
### Rules
<!-- begin auto-generated rules list -->
💼 Configurations enabled in.\
🔍 Set in the `browser` configuration.\
🔐 Set in the `internal` configuration.\
⚛️ Set in the `react` configuration.\
✅ Set in the `recommended` configuration.\
🔧 Automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/user-guide/command-line-interface#--fix).\
❌ Deprecated.
| Name                                        | Description | 💼 | 🔧 | ❌ |
| :------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------- | :- | :- | :- |
| [a11y-aria-label-is-well-formatted](docs/rules/a11y-aria-label-is-well-formatted.md) | [aria-label] text should be formatted as you would visual text. | ⚛️ | | |
| [a11y-no-generic-link-text](docs/rules/a11y-no-generic-link-text.md) | disallow generic link text | | | ❌ |
| [a11y-no-title-attribute](docs/rules/a11y-no-title-attribute.md) | Guards against developers using the title attribute | ⚛️ | | |
| [a11y-no-visually-hidden-interactive-element](docs/rules/a11y-no-visually-hidden-interactive-element.md) | Ensures that interactive elements are not visually hidden | ⚛️ | | |
| [a11y-role-supports-aria-props](docs/rules/a11y-role-supports-aria-props.md) | Enforce that elements with explicit or implicit roles defined contain only `aria-*` properties supported by that `role`. | ⚛️ | | |
| [a11y-svg-has-accessible-name](docs/rules/a11y-svg-has-accessible-name.md) | SVGs must have an accessible name | ⚛️ | | |
| [array-foreach](docs/rules/array-foreach.md) | enforce `for..of` loops over `Array.forEach` | ✅ | | |
| [async-currenttarget](docs/rules/async-currenttarget.md) | disallow `event.currentTarget` calls inside of async functions | 🔍 | | |
| [async-preventdefault](docs/rules/async-preventdefault.md) | disallow `event.preventDefault` calls inside of async functions | 🔍 | | |
| [authenticity-token](docs/rules/authenticity-token.md) | disallow usage of CSRF tokens in JavaScript | 🔐 | | |
| [filenames-match-regex](docs/rules/filenames-match-regex.md) | ensure filenames match a regex naming convention | | | |
| [get-attribute](docs/rules/get-attribute.md) | disallow wrong usage of attribute names | 🔍 | 🔧 | |
| [js-class-name](docs/rules/js-class-name.md) | enforce a naming convention for js- prefixed classes | 🔐 | | |
| [no-blur](docs/rules/no-blur.md) | disallow usage of `Element.prototype.blur()` | 🔍 | | |
| [no-d-none](docs/rules/no-d-none.md) | disallow usage the `d-none` CSS class | 🔐 | | |
| [no-dataset](docs/rules/no-dataset.md) | enforce usage of `Element.prototype.getAttribute` instead of `Element.prototype.datalist` | 🔍 | | |
| [no-dynamic-script-tag](docs/rules/no-dynamic-script-tag.md) | disallow creating dynamic script tags | ✅ | | |
| [no-implicit-buggy-globals](docs/rules/no-implicit-buggy-globals.md) | disallow implicit global variables | ✅ | | |
| [no-inner-html](docs/rules/no-inner-html.md) | disallow `Element.prototype.innerHTML` in favor of `Element.prototype.textContent` | 🔍 | | |
| [no-innerText](docs/rules/no-innerText.md) | disallow `Element.prototype.innerText` in favor of `Element.prototype.textContent` | 🔍 | 🔧 | |
| [no-then](docs/rules/no-then.md) | enforce using `async/await` syntax over Promises | ✅ | | |
| [no-useless-passive](docs/rules/no-useless-passive.md) | disallow marking a event handler as passive when it has no effect | 🔍 | 🔧 | |
| [prefer-observers](docs/rules/prefer-observers.md) | disallow poorly performing event listeners | 🔍 | | |
| [require-passive-events](docs/rules/require-passive-events.md) | enforce marking high frequency event handlers as passive | 🔍 | | |
| [unescaped-html-literal](docs/rules/unescaped-html-literal.md) | disallow unescaped HTML literals | 🔍 | | |
<!-- end auto-generated rules list -->

View File

@@ -0,0 +1,50 @@
#!/usr/bin/env node
// Disables eslint rules in a JavaScript file with next-line comments. This is
// useful when introducing a new rule that causes many failures. The comments
// can be fixed and removed at while updating the file later.
//
// Usage:
//
// eslint-ignore-errors app/assets/javascripts/something.js
const fs = require('fs')
const execFile = require('child_process').execFile
execFile('eslint', ['--format', 'json', process.argv[2]], (error, stdout) => {
for (const result of JSON.parse(stdout)) {
const filename = result.filePath
const jsLines = fs.readFileSync(filename, 'utf8').split('\n')
const offensesByLine = {}
let addedLines = 0
// Produces {47: ['github/no-d-none', 'github/no-blur'], 83: ['github/no-blur']}
for (const message of result.messages) {
if (offensesByLine[message.line]) {
offensesByLine[message.line].push(message.ruleId)
} else {
offensesByLine[message.line] = [message.ruleId]
}
}
for (const line of Object.keys(offensesByLine)) {
const lineIndex = line - 1 + addedLines
const previousLine = jsLines[lineIndex - 1]
const ruleIds = offensesByLine[line].join(', ')
if (isDisableComment(previousLine)) {
jsLines[lineIndex - 1] = previousLine.replace(/\s?\*\/$/, `, ${ruleIds} */`)
} else {
const leftPad = ' '.repeat(jsLines[lineIndex].match(/^\s*/g)[0].length)
jsLines.splice(lineIndex, 0, `${leftPad}/* eslint-disable-next-line ${ruleIds} */`)
}
addedLines += 1
}
if (result.messages.length !== 0) {
fs.writeFileSync(filename, jsLines.join('\n'), 'utf8')
}
}
})
function isDisableComment(line) {
return line.match(/\/\* eslint-disable-next-line .+\*\//)
}

View File

@@ -0,0 +1,29 @@
module.exports = {
env: {
browser: true,
},
plugins: ['github', 'escompat'],
extends: ['plugin:escompat/recommended'],
rules: {
'escompat/no-dynamic-imports': 'off',
'github/async-currenttarget': 'error',
'github/async-preventdefault': 'error',
'github/get-attribute': 'error',
'github/no-blur': 'error',
'github/no-dataset': 'error',
'github/no-innerText': 'error',
'github/no-inner-html': 'error',
'github/unescaped-html-literal': 'error',
'github/no-useless-passive': 'error',
'github/require-passive-events': 'error',
'github/prefer-observers': 'error',
'import/no-nodejs-modules': 'error',
'no-restricted-syntax': [
'error',
{
selector: "NewExpression[callee.name='URL'][arguments.length=1]",
message: 'Please pass in `window.location.origin` as the 2nd argument to `new URL()`',
},
],
},
}

View File

@@ -0,0 +1,37 @@
const globals = require('globals')
const github = require('../../plugin')
const importPlugin = require('eslint-plugin-import')
const escompatPlugin = require('eslint-plugin-escompat')
const {fixupPluginRules} = require('@eslint/compat')
module.exports = {
...escompatPlugin.configs['flat/recommended'],
languageOptions: {
globals: {
...globals.browser,
},
},
plugins: {importPlugin, escompatPlugin, github: fixupPluginRules(github)},
rules: {
'escompatPlugin/no-dynamic-imports': 'off',
'github/async-currenttarget': 'error',
'github/async-preventdefault': 'error',
'github/get-attribute': 'error',
'github/no-blur': 'error',
'github/no-dataset': 'error',
'github/no-innerText': 'error',
'github/no-inner-html': 'error',
'github/unescaped-html-literal': 'error',
'github/no-useless-passive': 'error',
'github/require-passive-events': 'error',
'github/prefer-observers': 'error',
'importPlugin/no-nodejs-modules': 'error',
'no-restricted-syntax': [
'error',
{
selector: "NewExpression[callee.name='URL'][arguments.length=1]",
message: 'Please pass in `window.location.origin` as the 2nd argument to `new URL()`',
},
],
},
}

View File

@@ -0,0 +1,11 @@
const github = require('../../plugin')
const {fixupPluginRules} = require('@eslint/compat')
module.exports = {
plugins: {github: fixupPluginRules(github)},
rules: {
'github/authenticity-token': 'error',
'github/js-class-name': 'error',
'github/no-d-none': 'error',
},
}

View File

@@ -0,0 +1,48 @@
const github = require('../../plugin')
const jsxA11yPlugin = require('eslint-plugin-jsx-a11y')
const {fixupPluginRules} = require('@eslint/compat')
module.exports = {
...jsxA11yPlugin.flatConfigs.recommended,
languageOptions: {
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
},
plugins: {github: fixupPluginRules(github), jsxA11yPlugin},
rules: {
'jsxA11yPlugin/role-supports-aria-props': 'off', // Override with github/a11y-role-supports-aria-props until https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/issues/910 is resolved
'github/a11y-aria-label-is-well-formatted': 'error',
'github/a11y-no-visually-hidden-interactive-element': 'error',
'github/a11y-no-title-attribute': 'error',
'github/a11y-svg-has-accessible-name': 'error',
'github/a11y-role-supports-aria-props': 'error',
'jsxA11yPlugin/no-aria-hidden-on-focusable': 'error',
'jsxA11yPlugin/no-autofocus': 'off',
'jsxA11yPlugin/anchor-ambiguous-text': [
'error',
{
words: ['this', 'more', 'read here', 'read more'],
},
],
'jsxA11yPlugin/no-interactive-element-to-noninteractive-role': [
'error',
{
tr: ['none', 'presentation'],
td: ['cell'], // TODO: Remove once https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/pull/937#issuecomment-1638128318 is addressed.
canvas: ['img'],
},
],
'jsxA11yPlugin/no-redundant-roles': [
'error',
{
nav: ['navigation'], // default in eslint-plugin-jsx-a11y
tbody: ['rowgroup'],
thead: ['rowgroup'],
},
],
},
}

View File

@@ -0,0 +1,148 @@
const globals = require('globals')
const github = require('../../plugin')
const prettierPlugin = require('eslint-plugin-prettier')
const eslintComments = require('eslint-plugin-eslint-comments')
const importPlugin = require('eslint-plugin-import')
const i18nTextPlugin = require('eslint-plugin-i18n-text')
const noOnlyTestsPlugin = require('eslint-plugin-no-only-tests')
const {fixupPluginRules} = require('@eslint/compat')
module.exports = {
languageOptions: {
ecmaVersion: 6,
sourceType: 'module',
globals: {
...globals.es6,
},
},
plugins: {
prettierPlugin,
eslintComments,
importPlugin,
'i18n-text': fixupPluginRules(i18nTextPlugin),
noOnlyTestsPlugin,
github: fixupPluginRules(github),
},
rules: {
'constructor-super': 'error',
'eslintComments/disable-enable-pair': 'off',
'eslintComments/no-aggregating-enable': 'off',
'eslintComments/no-duplicate-disable': 'error',
'eslintComments/no-unlimited-disable': 'error',
'eslintComments/no-unused-disable': 'error',
'eslintComments/no-unused-enable': 'error',
'eslintComments/no-use': ['error', {allow: ['eslint', 'eslint-disable-next-line', 'eslint-env', 'globals']}],
'github/filenames-match-regex': 'error',
'func-style': ['error', 'declaration', {allowArrowFunctions: true}],
'github/array-foreach': 'error',
'github/no-implicit-buggy-globals': 'error',
'github/no-then': 'error',
'github/no-dynamic-script-tag': 'error',
'i18n-text/no-en': ['error'],
'importPlugin/default': 'error',
'importPlugin/export': 'error',
'importPlugin/extensions': 'error',
'importPlugin/first': 'error',
'importPlugin/named': 'error',
'importPlugin/namespace': 'error',
'importPlugin/no-absolute-path': 'error',
'importPlugin/no-amd': 'error',
'importPlugin/no-anonymous-default-export': [
'error',
{
allowAnonymousClass: false,
allowAnonymousFunction: false,
allowArray: true,
allowArrowFunction: false,
allowLiteral: true,
allowObject: true,
},
],
'importPlugin/no-commonjs': 'error',
'importPlugin/no-deprecated': 'error',
'importPlugin/no-duplicates': 'error',
'importPlugin/no-dynamic-require': 'error',
'importPlugin/no-extraneous-dependencies': [0, {devDependencies: false}],
'importPlugin/no-mutable-exports': 'error',
'importPlugin/no-named-as-default': 'error',
'importPlugin/no-named-as-default-member': 'error',
'importPlugin/no-namespace': 'error',
'importPlugin/no-unresolved': 'error',
'importPlugin/no-webpack-loader-syntax': 'error',
'no-case-declarations': 'error',
'no-class-assign': 'error',
'no-compare-neg-zero': 'error',
'no-cond-assign': 'error',
'no-console': 'error',
'no-const-assign': 'error',
'no-constant-condition': 'error',
'no-control-regex': 'error',
'no-debugger': 'error',
'no-delete-var': 'error',
'no-dupe-args': 'error',
'no-dupe-class-members': 'error',
'no-dupe-keys': 'error',
'no-duplicate-case': 'error',
'no-empty': 'error',
'no-empty-character-class': 'error',
'no-empty-pattern': 'error',
'no-ex-assign': 'error',
'no-extra-boolean-cast': 'error',
'no-fallthrough': 'error',
'no-func-assign': 'error',
'no-global-assign': 'error',
'no-implicit-globals': 'error',
'no-implied-eval': 'error',
'no-inner-declarations': 'error',
'no-invalid-regexp': 'error',
'no-invalid-this': 'error',
'no-irregular-whitespace': 'error',
'no-new-symbol': 'error',
'no-obj-calls': 'error',
'no-octal': 'error',
'noOnlyTestsPlugin/no-only-tests': [
'error',
{
block: ['describe', 'it', 'context', 'test', 'tape', 'fixture', 'serial', 'suite'],
},
],
'no-redeclare': 'error',
'no-regex-spaces': 'error',
'no-return-assign': 'error',
'no-self-assign': 'error',
'no-sequences': ['error'],
'no-shadow': 'error',
'no-sparse-arrays': 'error',
'no-this-before-super': 'error',
'no-throw-literal': 'error',
'no-undef': 'error',
'no-unreachable': 'error',
'no-unsafe-finally': 'error',
'no-unsafe-negation': 'error',
'no-unused-labels': 'error',
'no-unused-vars': 'error',
'no-useless-concat': 'error',
'no-useless-escape': 'error',
'no-var': 'error',
'object-shorthand': ['error', 'always', {avoidQuotes: true}],
'one-var': ['error', 'never'],
'prefer-const': 'error',
'prefer-promise-reject-errors': 'error',
'prefer-rest-params': 'error',
'prefer-spread': 'error',
'prefer-template': 'error',
'prettierPlugin/prettier': 'error',
'require-yield': 'error',
'use-isnan': 'error',
'valid-typeof': 'error',
camelcase: ['error', {properties: 'always'}],
eqeqeq: ['error', 'smart'],
},
settings: {
'importPlugin/resolver': {
node: {
extensions: ['.js', '.ts'],
},
},
},
}

View File

@@ -0,0 +1,28 @@
const eslint = require('@eslint/js')
const tseslint = require('typescript-eslint')
const escompatPlugin = require('eslint-plugin-escompat')
const github = require('../../plugin')
const {fixupPluginRules} = require('@eslint/compat')
module.exports = tseslint.config(eslint.configs.recommended, ...tseslint.configs.recommended, {
languageOptions: {
parser: tseslint.parser,
},
plugins: {'@typescript-eslint': tseslint.plugin, escompatPlugin, github: fixupPluginRules(github)},
rules: {
camelcase: 'off',
'no-unused-vars': 'off',
'no-shadow': 'off',
'no-invalid-this': 'off',
'@typescript-eslint/no-invalid-this': ['error'],
'@typescript-eslint/no-shadow': ['error'],
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/array-type': ['error', {default: 'array-simple'}],
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/explicit-member-accessibility': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-unused-vars': 'error',
'@typescript-eslint/explicit-module-boundary-types': 'off',
},
})

View File

@@ -0,0 +1,8 @@
module.exports = {
plugins: ['github'],
rules: {
'github/authenticity-token': 'error',
'github/js-class-name': 'error',
'github/no-d-none': 'error',
},
}

View File

@@ -0,0 +1,42 @@
module.exports = {
parserOptions: {
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
plugins: ['github', 'jsx-a11y'],
extends: ['plugin:jsx-a11y/recommended'],
rules: {
'jsx-a11y/role-supports-aria-props': 'off', // Override with github/a11y-role-supports-aria-props until https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/issues/910 is resolved
'github/a11y-aria-label-is-well-formatted': 'error',
'github/a11y-no-visually-hidden-interactive-element': 'error',
'github/a11y-no-title-attribute': 'error',
'github/a11y-svg-has-accessible-name': 'error',
'github/a11y-role-supports-aria-props': 'error',
'jsx-a11y/no-aria-hidden-on-focusable': 'error',
'jsx-a11y/no-autofocus': 'off',
'jsx-a11y/anchor-ambiguous-text': [
'error',
{
words: ['this', 'more', 'read here', 'read more'],
},
],
'jsx-a11y/no-interactive-element-to-noninteractive-role': [
'error',
{
tr: ['none', 'presentation'],
td: ['cell'], // TODO: Remove once https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/pull/937#issuecomment-1638128318 is addressed.
canvas: ['img'],
},
],
'jsx-a11y/no-redundant-roles': [
'error',
{
nav: ['navigation'], // default in eslint-plugin-jsx-a11y
tbody: ['rowgroup'],
thead: ['rowgroup'],
},
],
},
}

View File

@@ -0,0 +1,134 @@
module.exports = {
parserOptions: {
ecmaFeatures: {
ecmaVersion: 6,
},
sourceType: 'module',
},
env: {
es6: true,
},
plugins: ['github', 'prettier', 'eslint-comments', 'import', 'filenames', 'i18n-text', 'no-only-tests'],
rules: {
'constructor-super': 'error',
'eslint-comments/disable-enable-pair': 'off',
'eslint-comments/no-aggregating-enable': 'off',
'eslint-comments/no-duplicate-disable': 'error',
'eslint-comments/no-unlimited-disable': 'error',
'eslint-comments/no-unused-disable': 'error',
'eslint-comments/no-unused-enable': 'error',
'eslint-comments/no-use': ['error', {allow: ['eslint', 'eslint-disable-next-line', 'eslint-env', 'globals']}],
'filenames/match-regex': ['error', '^[a-z0-9-]+(.[a-z0-9-]+)?$'],
'func-style': ['error', 'declaration', {allowArrowFunctions: true}],
'github/array-foreach': 'error',
'github/no-implicit-buggy-globals': 'error',
'github/no-then': 'error',
'github/no-dynamic-script-tag': 'error',
'i18n-text/no-en': ['error'],
'import/default': 'error',
'import/export': 'error',
'import/extensions': 'error',
'import/first': 'error',
'import/named': 'error',
'import/namespace': 'error',
'import/no-absolute-path': 'error',
'import/no-amd': 'error',
'import/no-anonymous-default-export': [
'error',
{
allowAnonymousClass: false,
allowAnonymousFunction: false,
allowArray: true,
allowArrowFunction: false,
allowLiteral: true,
allowObject: true,
},
],
'import/no-commonjs': 'error',
'import/no-deprecated': 'error',
'import/no-duplicates': 'error',
'import/no-dynamic-require': 'error',
'import/no-extraneous-dependencies': [0, {devDependencies: false}],
'import/no-mutable-exports': 'error',
'import/no-named-as-default': 'error',
'import/no-named-as-default-member': 'error',
'import/no-namespace': 'error',
'import/no-unresolved': 'error',
'import/no-webpack-loader-syntax': 'error',
'no-case-declarations': 'error',
'no-class-assign': 'error',
'no-compare-neg-zero': 'error',
'no-cond-assign': 'error',
'no-console': 'error',
'no-const-assign': 'error',
'no-constant-condition': 'error',
'no-control-regex': 'error',
'no-debugger': 'error',
'no-delete-var': 'error',
'no-dupe-args': 'error',
'no-dupe-class-members': 'error',
'no-dupe-keys': 'error',
'no-duplicate-case': 'error',
'no-empty': 'error',
'no-empty-character-class': 'error',
'no-empty-pattern': 'error',
'no-ex-assign': 'error',
'no-extra-boolean-cast': 'error',
'no-fallthrough': 'error',
'no-func-assign': 'error',
'no-global-assign': 'error',
'no-implicit-globals': 'error',
'no-implied-eval': 'error',
'no-inner-declarations': 'error',
'no-invalid-regexp': 'error',
'no-invalid-this': 'error',
'no-irregular-whitespace': 'error',
'no-new-symbol': 'error',
'no-obj-calls': 'error',
'no-octal': 'error',
'no-only-tests/no-only-tests': [
'error',
{
block: ['describe', 'it', 'context', 'test', 'tape', 'fixture', 'serial', 'suite'],
},
],
'no-redeclare': 'error',
'no-regex-spaces': 'error',
'no-return-assign': 'error',
'no-self-assign': 'error',
'no-sequences': ['error'],
'no-shadow': 'error',
'no-sparse-arrays': 'error',
'no-this-before-super': 'error',
'no-throw-literal': 'error',
'no-undef': 'error',
'no-unreachable': 'error',
'no-unsafe-finally': 'error',
'no-unsafe-negation': 'error',
'no-unused-labels': 'error',
'no-unused-vars': 'error',
'no-useless-concat': 'error',
'no-useless-escape': 'error',
'no-var': 'error',
'object-shorthand': ['error', 'always', {avoidQuotes: true}],
'one-var': ['error', 'never'],
'prefer-const': 'error',
'prefer-promise-reject-errors': 'error',
'prefer-rest-params': 'error',
'prefer-spread': 'error',
'prefer-template': 'error',
'prettier/prettier': 'error',
'require-yield': 'error',
'use-isnan': 'error',
'valid-typeof': 'error',
camelcase: ['error', {properties: 'always'}],
eqeqeq: ['error', 'smart'],
},
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.ts'],
},
},
},
}

View File

@@ -0,0 +1,21 @@
module.exports = {
extends: ['plugin:@typescript-eslint/recommended', 'prettier', 'plugin:escompat/typescript-2020'],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', 'escompat', 'github'],
rules: {
camelcase: 'off',
'no-unused-vars': 'off',
'no-shadow': 'off',
'no-invalid-this': 'off',
'@typescript-eslint/no-invalid-this': ['error'],
'@typescript-eslint/no-shadow': ['error'],
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/array-type': ['error', {default: 'array-simple'}],
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/explicit-member-accessibility': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-unused-vars': 'error',
'@typescript-eslint/explicit-module-boundary-types': 'off',
},
}

View File

@@ -0,0 +1,86 @@
'use strict'
const childProcess = require('child_process')
const fs = require('fs')
const os = require('os')
const path = require('path')
let SourceCodeFixer = null
try {
SourceCodeFixer = require('eslint/lib/linter/source-code-fixer')
} catch {
SourceCodeFixer = require('eslint/lib/util/source-code-fixer')
}
const getRuleURI = require('eslint-rule-documentation')
module.exports = function (results) {
let output = '\n'
let errors = 0
let warnings = 0
const rootPath = process.cwd()
for (const result of results) {
const messages = result.messages
if (messages.length === 0) {
continue
}
errors += result.errorCount
warnings += result.warningCount
const relativePath = path.relative(rootPath, result.filePath)
output += `${relativePath}\n`
for (const message of messages) {
output += `${message.line}:${message.column} ${message.ruleId || ''}`
if (message.ruleId) {
const ruleURI = getRuleURI(message.ruleId)
if (ruleURI.found) {
output += ` (${ruleURI.url})`
}
}
output += `\n\t${message.message}\n`
}
if (messages.some(msg => msg.fix)) {
const fixResult = SourceCodeFixer.applyFixes(result.source, messages)
output += `\n\n$ eslint --fix ${relativePath}\n`
output += diff(result.source, fixResult.output)
}
output += '\n\n'
}
const total = errors + warnings
if (total > 0) {
output += [
'\u2716 ',
total,
pluralize(' problem', total),
' (',
errors,
pluralize(' error', errors),
', ',
warnings,
pluralize(' warning', warnings),
')\n',
].join('')
}
return total > 0 ? output : ''
}
function pluralize(word, count) {
return count === 1 ? word : `${word}s`
}
function diff(a, b) {
const aPath = path.join(os.tmpdir(), 'a.js')
const bPath = path.join(os.tmpdir(), 'p.js')
fs.writeFileSync(aPath, a, {encoding: 'utf8'})
fs.writeFileSync(bPath, b, {encoding: 'utf8'})
const result = childProcess.spawnSync('diff', ['-U5', aPath, bPath], {encoding: 'utf8'})
return result.stdout.split('\n').slice(2).join('\n')
}

View File

@@ -0,0 +1,21 @@
const github = require('./plugin')
const getFlatConfig = () => ({
browser: require('./configs/flat/browser'),
internal: require('./configs/flat/internal'),
recommended: require('./configs/flat/recommended'),
typescript: require('./configs/flat/typescript'),
react: require('./configs/flat/react'),
})
module.exports = {
rules: github.rules,
configs: {
browser: require('./configs/browser'),
internal: require('./configs/internal'),
recommended: require('./configs/recommended'),
typescript: require('./configs/typescript'),
react: require('./configs/react'),
},
getFlatConfigs: getFlatConfig,
}

View File

@@ -0,0 +1,32 @@
const {name, version} = require('../package.json')
module.exports = {
meta: {name, version},
rules: {
'a11y-no-visually-hidden-interactive-element': require('./rules/a11y-no-visually-hidden-interactive-element'),
'a11y-no-generic-link-text': require('./rules/a11y-no-generic-link-text'),
'a11y-no-title-attribute': require('./rules/a11y-no-title-attribute'),
'a11y-aria-label-is-well-formatted': require('./rules/a11y-aria-label-is-well-formatted'),
'a11y-role-supports-aria-props': require('./rules/a11y-role-supports-aria-props'),
'a11y-svg-has-accessible-name': require('./rules/a11y-svg-has-accessible-name'),
'array-foreach': require('./rules/array-foreach'),
'async-currenttarget': require('./rules/async-currenttarget'),
'async-preventdefault': require('./rules/async-preventdefault'),
'authenticity-token': require('./rules/authenticity-token'),
'filenames-match-regex': require('./rules/filenames-match-regex'),
'get-attribute': require('./rules/get-attribute'),
'js-class-name': require('./rules/js-class-name'),
'no-blur': require('./rules/no-blur'),
'no-d-none': require('./rules/no-d-none'),
'no-dataset': require('./rules/no-dataset'),
'no-implicit-buggy-globals': require('./rules/no-implicit-buggy-globals'),
'no-inner-html': require('./rules/no-inner-html'),
'no-innerText': require('./rules/no-innerText'),
'no-dynamic-script-tag': require('./rules/no-dynamic-script-tag'),
'no-then': require('./rules/no-then'),
'no-useless-passive': require('./rules/no-useless-passive'),
'prefer-observers': require('./rules/prefer-observers'),
'require-passive-events': require('./rules/require-passive-events'),
'unescaped-html-literal': require('./rules/unescaped-html-literal'),
},
}

View File

@@ -0,0 +1,31 @@
const {getProp} = require('jsx-ast-utils')
module.exports = {
meta: {
docs: {
description: '[aria-label] text should be formatted as you would visual text.',
url: require('../url')(module),
},
schema: [],
},
create(context) {
return {
JSXOpeningElement: node => {
const prop = getProp(node.attributes, 'aria-label')
if (!prop) return
const propValue = prop.value
if (propValue.type !== 'Literal') return
const ariaLabel = propValue.value
if (ariaLabel.match(/^[a-z]+.*$/)) {
context.report({
node,
message: '[aria-label] text should be formatted the same as you would visual text. Use sentence case.',
})
}
},
}
},
}

View File

@@ -0,0 +1,73 @@
const {getProp, getPropValue} = require('jsx-ast-utils')
const {getElementType} = require('../utils/get-element-type')
const bannedLinkText = ['read more', 'here', 'click here', 'learn more', 'more']
/* Downcase and strip extra whitespaces and punctuation */
const stripAndDowncaseText = text => {
return text
.toLowerCase()
.replace(/[.,/#!$%^&*;:{}=\-_`~()]/g, '')
.replace(/\s{2,}/g, ' ')
.trim()
}
module.exports = {
meta: {
docs: {
description: 'disallow generic link text',
url: require('../url')(module),
},
deprecated: true,
replacedBy: ['jsx-a11y/anchor-ambiguous-text'],
schema: [],
},
create(context) {
return {
JSXOpeningElement: node => {
const elementType = getElementType(context, node)
if (elementType !== 'a') return
if (getProp(node.attributes, 'aria-labelledby')) return
let cleanTextContent // text content we can reliably fetch
const parent = node.parent
let jsxTextNode
if (parent.children && parent.children.length > 0 && parent.children[0].type === 'JSXText') {
jsxTextNode = parent.children[0]
cleanTextContent = stripAndDowncaseText(parent.children[0].value)
}
const ariaLabel = getPropValue(getProp(node.attributes, 'aria-label'))
const cleanAriaLabelValue = ariaLabel && stripAndDowncaseText(ariaLabel)
if (ariaLabel) {
if (bannedLinkText.includes(cleanAriaLabelValue)) {
context.report({
node,
message:
'Avoid setting generic link text like `Here`, `Click here`, `Read more`. Make sure that your link text is both descriptive and concise.',
})
}
if (cleanTextContent && !cleanAriaLabelValue.includes(cleanTextContent)) {
context.report({
node,
message: 'When using ARIA to set a more descriptive text, it must fully contain the visible label.',
})
}
} else {
if (cleanTextContent) {
if (!bannedLinkText.includes(cleanTextContent)) return
context.report({
node: jsxTextNode,
message:
'Avoid setting generic link text like `Here`, `Click here`, `Read more`. Make sure that your link text is both descriptive and concise.',
})
}
}
},
}
},
}

View File

@@ -0,0 +1,66 @@
const {getProp, getPropValue} = require('jsx-ast-utils')
const {getElementType} = require('../utils/get-element-type')
const SEMANTIC_ELEMENTS = [
'a',
'button',
'summary',
'select',
'option',
'textarea',
'input',
'span',
'div',
'p',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'details',
'summary',
'dialog',
'tr',
'th',
'td',
'label',
]
const ifSemanticElement = (context, node) => {
const elementType = getElementType(context, node.openingElement, true)
for (const semanticElement of SEMANTIC_ELEMENTS) {
if (elementType === semanticElement) {
return true
}
}
return false
}
module.exports = {
meta: {
docs: {
description: 'Guards against developers using the title attribute',
url: require('../url')(module),
},
schema: [],
},
create(context) {
return {
JSXElement: node => {
const elementType = getElementType(context, node.openingElement, true)
if (elementType !== `iframe` && ifSemanticElement(context, node)) {
const titleProp = getPropValue(getProp(node.openingElement.attributes, `title`))
if (titleProp) {
context.report({
node,
message: 'The title attribute is not accessible and should never be used unless for an `<iframe>`.',
})
}
}
},
}
},
}

View File

@@ -0,0 +1,85 @@
const {getProp, getLiteralPropValue} = require('jsx-ast-utils')
const {getElementType} = require('../utils/get-element-type')
const {generateObjSchema} = require('eslint-plugin-jsx-a11y/lib/util/schemas')
const defaultClassName = 'sr-only'
const defaultcomponentName = 'VisuallyHidden'
const schema = generateObjSchema({
className: {type: 'string'},
componentName: {type: 'string'},
})
/** Note: we are not including input elements at this time
* because a visually hidden input field might cause a false positive.
* (e.g. fileUpload https://github.com/primer/react/pull/3492)
*/
const INTERACTIVE_ELEMENTS = ['a', 'button', 'summary', 'select', 'option', 'textarea']
const checkIfInteractiveElement = (context, node) => {
const elementType = getElementType(context, node.openingElement)
for (const interactiveElement of INTERACTIVE_ELEMENTS) {
if (elementType === interactiveElement) {
return true
}
}
return false
}
// if the node is visually hidden recursively check if it has interactive children
const checkIfVisuallyHiddenAndInteractive = (context, options, node, isParentVisuallyHidden) => {
const {className, componentName} = options
if (node.type === 'JSXElement') {
const classes = getLiteralPropValue(getProp(node.openingElement.attributes, 'className'))
const isVisuallyHiddenElement = node.openingElement.name.name === componentName
let hasSROnlyClass = false
if (classes != null) {
hasSROnlyClass = classes.includes(className)
}
let isHidden = false
if (hasSROnlyClass || isVisuallyHiddenElement || !!isParentVisuallyHidden) {
if (checkIfInteractiveElement(context, node)) {
return true
}
isHidden = true
}
if (node.children && node.children.length > 0) {
return (
typeof node.children?.find(child =>
checkIfVisuallyHiddenAndInteractive(context, options, child, !!isParentVisuallyHidden || isHidden),
) !== 'undefined'
)
}
}
return false
}
module.exports = {
meta: {
docs: {
description: 'Ensures that interactive elements are not visually hidden',
url: require('../url')(module),
},
schema: [schema],
},
create(context) {
const {options} = context
const config = options[0] || {}
const className = config.className || defaultClassName
const componentName = config.componentName || defaultcomponentName
return {
JSXElement: node => {
if (checkIfVisuallyHiddenAndInteractive(context, {className, componentName}, node, false)) {
context.report({
node,
message:
'Avoid visually hidding interactive elements. Visually hiding interactive elements can be confusing to sighted keyboard users as it appears their focus has been lost when they navigate to the hidden element.',
})
}
},
}
},
}

View File

@@ -0,0 +1,61 @@
// @ts-check
const {aria, roles} = require('aria-query')
const {getPropValue, propName} = require('jsx-ast-utils')
const {getRole} = require('../utils/get-role')
module.exports = {
meta: {
docs: {
description:
'Enforce that elements with explicit or implicit roles defined contain only `aria-*` properties supported by that `role`.',
url: require('../url')(module),
},
schema: [],
},
create(context) {
return {
JSXOpeningElement(node) {
// Get the elements explicit or implicit role
const role = getRole(context, node)
// Return early if role could not be determined
if (!role) return
// Get allowed ARIA attributes:
// - From the role itself
let allowedProps = Object.keys(roles.get(role)?.props || {})
// - From parent roles
for (const parentRole of roles.get(role)?.superClass.flat() ?? []) {
allowedProps = allowedProps.concat(Object.keys(roles.get(parentRole)?.props || {}))
}
// Dedupe, for performance
allowedProps = Array.from(new Set(allowedProps))
// Get prohibited ARIA attributes:
// - From the role itself
let prohibitedProps = roles.get(role)?.prohibitedProps || []
// - From parent roles
for (const parentRole of roles.get(role)?.superClass.flat() ?? []) {
prohibitedProps = prohibitedProps.concat(roles.get(parentRole)?.prohibitedProps || [])
}
// - From comparing allowed vs all ARIA attributes
prohibitedProps = prohibitedProps.concat(aria.keys().filter(x => !allowedProps.includes(x)))
// Dedupe, for performance
prohibitedProps = Array.from(new Set(prohibitedProps))
for (const prop of node.attributes) {
// Return early if prohibited ARIA attribute is set to an ignorable value
if (getPropValue(prop) == null || prop.type === 'JSXSpreadAttribute') return
if (prohibitedProps?.includes(propName(prop))) {
context.report({
node,
message: `The attribute ${propName(prop)} is not supported by the role ${role}.`,
})
}
}
},
}
},
}

View File

@@ -0,0 +1,45 @@
const {hasProp} = require('jsx-ast-utils')
const {getElementType} = require('../utils/get-element-type')
module.exports = {
meta: {
docs: {
description: 'SVGs must have an accessible name',
url: require('../url')(module),
},
schema: [],
},
create(context) {
return {
JSXOpeningElement: node => {
const elementType = getElementType(context, node)
if (elementType !== 'svg') return
// Check if there is a nested title element that is the first non-whitespace child of the `<svg>`
const childrenWithoutWhitespace = node.parent.children?.filter(({type, value}) =>
type === 'JSXText' ? value.trim() !== '' : type !== 'JSXText',
)
const hasNestedTitleAsFirstChild =
childrenWithoutWhitespace?.[0]?.type === 'JSXElement' &&
childrenWithoutWhitespace?.[0]?.openingElement?.name?.name === 'title'
// Check if `aria-label` or `aria-labelledby` is set
const hasAccessibleName = hasProp(node.attributes, 'aria-label') || hasProp(node.attributes, 'aria-labelledby')
// Check if SVG is decorative
const isDecorative =
hasProp(node.attributes, 'role', 'presentation') || hasProp(node.attributes, 'aria-hidden', 'true')
if (elementType === 'svg' && !hasAccessibleName && !isDecorative && !hasNestedTitleAsFirstChild) {
context.report({
node,
message:
'`<svg>` must have an accessible name. Set `aria-label` or `aria-labelledby`, or nest a `<title>` element. However, if the `<svg>` is purely decorative, hide it with `aria-hidden="true"` or `role="presentation"`.',
})
}
},
}
},
}

View File

@@ -0,0 +1,20 @@
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'enforce `for..of` loops over `Array.forEach`',
url: require('../url')(module),
},
schema: [],
},
create(context) {
return {
CallExpression(node) {
if (node.callee.property && node.callee.property.name === 'forEach') {
context.report({node, message: 'Prefer for...of instead of Array.forEach'})
}
},
}
},
}

View File

@@ -0,0 +1,28 @@
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'disallow `event.currentTarget` calls inside of async functions',
url: require('../url')(module),
},
schema: [],
},
create(context) {
const scopeDidWait = new WeakSet()
return {
AwaitExpression() {
scopeDidWait.add(context.getScope(), true)
},
MemberExpression(node) {
if (node.property && node.property.name === 'currentTarget') {
const scope = context.getScope()
if (scope.block.async && scopeDidWait.has(scope)) {
context.report({node, message: 'event.currentTarget inside an async function is error prone'})
}
}
},
}
},
}

View File

@@ -0,0 +1,28 @@
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'disallow `event.preventDefault` calls inside of async functions',
url: require('../url')(module),
},
schema: [],
},
create(context) {
const scopeDidWait = new WeakSet()
return {
AwaitExpression() {
scopeDidWait.add(context.getScope(), true)
},
CallExpression(node) {
if (node.callee.property && node.callee.property.name === 'preventDefault') {
const scope = context.getScope()
if (scope.block.async && scopeDidWait.has(scope)) {
context.report({node, message: 'event.preventDefault() inside an async function is error prone'})
}
}
},
}
},
}

View File

@@ -0,0 +1,30 @@
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'disallow usage of CSRF tokens in JavaScript',
url: require('../url')(module),
},
schema: [],
},
create(context) {
function checkAuthenticityTokenUsage(node, str) {
if (str.includes('authenticity_token')) {
context.report({
node,
message:
'Form CSRF tokens (authenticity tokens) should not be created in JavaScript and their values should not be used directly for XHR requests.',
})
}
}
return {
Literal(node) {
if (typeof node.value === 'string') {
checkAuthenticityTokenUsage(node, node.value)
}
},
}
},
}

View File

@@ -0,0 +1,52 @@
// This is adapted from https://github.com/selaux/eslint-plugin-filenames since it's no longer actively maintained
// and needed a fix for eslint v9
const path = require('path')
const parseFilename = require('../utils/parse-filename')
const getExportedName = require('../utils/get-exported-name')
const isIgnoredFilename = require('../utils/is-ignored-filename')
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'ensure filenames match a regex naming convention',
url: require('../url')(module),
},
schema: {
type: 'array',
minItems: 0,
maxItems: 1,
items: [
{
type: 'string',
},
],
},
},
create(context) {
// GitHub's default is kebab case or one hump camel case
const defaultRegexp = /^[a-z0-9-]+(.[a-z0-9-]+)?$/
const conventionRegexp = context.options[0] ? new RegExp(context.options[0]) : defaultRegexp
const ignoreExporting = context.options[1] ? context.options[1] : false
return {
Program(node) {
const filename = context.getFilename()
const absoluteFilename = path.resolve(filename)
const parsed = parseFilename(absoluteFilename)
const shouldIgnore = isIgnoredFilename(filename)
const isExporting = Boolean(getExportedName(node))
const matchesRegex = conventionRegexp.test(parsed.name)
if (shouldIgnore) return
if (ignoreExporting && isExporting) return
if (!matchesRegex) {
context.report(node, "Filename '{{name}}' does not match the regex naming convention.", {
name: parsed.base,
})
}
},
}
},
}

View File

@@ -0,0 +1,53 @@
const svgElementAttributes = require('svg-element-attributes')
const attributeCalls = /^(get|has|set|remove)Attribute$/
const validAttributeName = /^[a-z][a-z0-9-]*$/
// these are common SVG attributes that *must* have the correct case to work
const camelCaseAttributes = Object.values(svgElementAttributes)
.reduce((all, elementAttrs) => all.concat(elementAttrs), [])
.filter(name => !validAttributeName.test(name))
const validSVGAttributeSet = new Set(camelCaseAttributes)
// lowercase variants of camelCase SVG attributes are probably an error
const invalidSVGAttributeSet = new Set(camelCaseAttributes.map(name => name.toLowerCase()))
function isValidAttribute(name) {
return validSVGAttributeSet.has(name) || (validAttributeName.test(name) && !invalidSVGAttributeSet.has(name))
}
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'disallow wrong usage of attribute names',
url: require('../url')(module),
},
fixable: 'code',
schema: [],
},
create(context) {
return {
CallExpression(node) {
if (!node.callee.property) return
const calleeName = node.callee.property.name
if (!attributeCalls.test(calleeName)) return
const attributeNameNode = node.arguments[0]
if (!attributeNameNode) return
if (!isValidAttribute(attributeNameNode.value)) {
context.report({
node: attributeNameNode,
message: 'Attributes should be lowercase and hyphen separated, or part of the SVG whitelist.',
fix(fixer) {
return fixer.replaceText(attributeNameNode, `'${attributeNameNode.value.toLowerCase()}'`)
},
})
}
},
}
},
}

View File

@@ -0,0 +1,57 @@
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'enforce a naming convention for js- prefixed classes',
url: require('../url')(module),
},
schema: [],
},
create(context) {
const allJsClassNameRegexp = /\bjs-[_a-zA-Z0-9-]*/g
const validJsClassNameRegexp = /^js(-[a-z0-9]+)+$/g
const endWithJsClassNameRegexp = /\bjs-[_a-zA-Z0-9-]*$/g
function checkStringFormat(node, str) {
const matches = str.match(allJsClassNameRegexp) || []
for (const match of matches) {
if (!match.match(validJsClassNameRegexp)) {
context.report({node, message: 'js- class names should be lowercase and only contain dashes.'})
}
}
}
function checkStringEndsWithJSClassName(node, str) {
if (str.match(endWithJsClassNameRegexp)) {
context.report({node, message: 'js- class names should be statically defined.'})
}
}
return {
Literal(node) {
if (typeof node.value === 'string') {
checkStringFormat(node, node.value)
if (
node.parent &&
node.parent.type === 'BinaryExpression' &&
node.parent.operator === '+' &&
node.parent.left.value
) {
checkStringEndsWithJSClassName(node.parent.left, node.parent.left.value)
}
}
},
TemplateLiteral(node) {
for (const quasi of node.quasis) {
checkStringFormat(quasi, quasi.value.raw)
if (quasi.tail === false) {
checkStringEndsWithJSClassName(quasi, quasi.value.raw)
}
}
},
}
},
}

View File

@@ -0,0 +1,19 @@
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'disallow usage of `Element.prototype.blur()`',
url: require('../url')(module),
},
schema: [],
},
create(context) {
return {
CallExpression(node) {
if (node.callee.property && node.callee.property.name === 'blur') {
context.report({node, message: 'Do not use element.blur(), instead restore the focus of a previous element.'})
}
},
}
},
}

View File

@@ -0,0 +1,31 @@
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'disallow usage the `d-none` CSS class',
url: require('../url')(module),
},
schema: [],
},
create(context) {
return {
CallExpression(node) {
if (
node.callee.type === 'MemberExpression' &&
node.callee.object.property &&
node.callee.object.property.name === 'classList'
) {
const invalidArgument = node.arguments.some(arg => {
return arg.type === 'Literal' && arg.value === 'd-none'
})
if (invalidArgument) {
context.report({
node,
message: 'Prefer hidden property to d-none class',
})
}
}
},
}
},
}

View File

@@ -0,0 +1,20 @@
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'enforce usage of `Element.prototype.getAttribute` instead of `Element.prototype.datalist`',
url: require('../url')(module),
},
schema: [],
},
create(context) {
return {
MemberExpression(node) {
if (node.property && node.property.name === 'dataset') {
context.report({node, message: "Use getAttribute('data-your-attribute') instead of dataset."})
}
},
}
},
}

View File

@@ -0,0 +1,29 @@
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'disallow creating dynamic script tags',
url: require('../url')(module),
},
schema: [],
},
create(context) {
return {
'CallExpression[callee.property.name="createElement"][arguments.length > 0]': function (node) {
if (node.arguments[0].value !== 'script') return
context.report({
node: node.arguments[0],
message: "Don't create dynamic script tags, add them in the server template instead.",
})
},
'AssignmentExpression[left.property.name="type"][right.value="text/javascript"]': function (node) {
context.report({
node: node.right,
message: "Don't create dynamic script tags, add them in the server template instead.",
})
},
}
},
}

View File

@@ -0,0 +1,36 @@
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'disallow implicit global variables',
url: require('../url')(module),
},
schema: [],
},
create(context) {
const sourceCode = context.sourceCode ?? context.getSourceCode()
return {
Program(node) {
const scope = sourceCode.getScope(node) ? sourceCode.getScope(node) : context.getScope()
for (const variable of scope.variables) {
if (variable.writeable) {
return
}
for (const def of variable.defs) {
if (
def.type === 'FunctionName' ||
def.type === 'ClassName' ||
(def.type === 'Variable' && def.parent.kind === 'const') ||
(def.type === 'Variable' && def.parent.kind === 'let')
) {
context.report({node: def.node, message: 'Implicit global variable, assign as global property instead.'})
}
}
}
},
}
},
}

View File

@@ -0,0 +1,21 @@
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'disallow `Element.prototype.innerHTML` in favor of `Element.prototype.textContent`',
url: require('../url')(module),
},
schema: [],
},
create(context) {
return {
'MemberExpression[property.name=innerHTML]': function (node) {
context.report({
node: node.property,
message: 'Using innerHTML poses a potential security risk and should not be used. Prefer using textContent.',
})
},
}
},
}

View File

@@ -0,0 +1,34 @@
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'disallow `Element.prototype.innerText` in favor of `Element.prototype.textContent`',
url: require('../url')(module),
},
fixable: 'code',
schema: [],
},
create(context) {
return {
MemberExpression(node) {
// If the member expression is part of a call expression like `.innerText()` then it is not the same
// as the `Element.innerText` property, and should not trigger a warning
if (node.parent.type === 'CallExpression') return
if (node.property && node.property.name === 'innerText') {
context.report({
meta: {
fixable: 'code',
},
node: node.property,
message: 'Prefer textContent to innerText',
fix(fixer) {
return fixer.replaceText(node.property, 'textContent')
},
})
}
},
}
},
}

View File

@@ -0,0 +1,22 @@
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'enforce using `async/await` syntax over Promises',
url: require('../url')(module),
},
schema: [],
},
create(context) {
return {
MemberExpression(node) {
if (node.property && node.property.name === 'then') {
context.report({node: node.property, message: 'Prefer async/await to Promise.then()'})
} else if (node.property && node.property.name === 'catch') {
context.report({node: node.property, message: 'Prefer async/await to Promise.catch()'})
}
},
}
},
}

View File

@@ -0,0 +1,59 @@
const passiveEventListenerNames = new Set([
'touchstart',
'touchmove',
'touchenter',
'touchend',
'touchleave',
'wheel',
'mousewheel',
])
const propIsPassiveTrue = prop => prop.key && prop.key.name === 'passive' && prop.value && prop.value.value === true
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'disallow marking a event handler as passive when it has no effect',
url: require('../url')(module),
},
fixable: 'code',
schema: [],
},
create(context) {
return {
['CallExpression[callee.property.name="addEventListener"]']: function (node) {
const [name, listener, options] = node.arguments
if (name.type !== 'Literal') return
if (passiveEventListenerNames.has(name.value)) return
if (options && options.type === 'ObjectExpression') {
const i = options.properties.findIndex(propIsPassiveTrue)
if (i === -1) return
const passiveProp = options.properties[i]
const l = options.properties.length
const source = context.getSourceCode()
context.report({
node: passiveProp,
message: `"${name.value}" event listener is not cancellable and so \`passive: true\` does nothing.`,
fix(fixer) {
const removals = []
if (l === 1) {
removals.push(options)
removals.push(...source.getTokensBetween(listener, options))
} else {
removals.push(passiveProp)
if (i > 0) {
removals.push(...source.getTokensBetween(options.properties[i - 1], passiveProp))
} else {
removals.push(...source.getTokensBetween(passiveProp, options.properties[i + 1]))
}
}
return removals.map(t => fixer.remove(t))
},
})
}
},
}
},
}

View File

@@ -0,0 +1,28 @@
const observerMap = {
scroll: 'IntersectionObserver',
resize: 'ResizeObserver',
}
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'disallow poorly performing event listeners',
url: require('../url')(module),
},
schema: [],
},
create(context) {
return {
['CallExpression[callee.property.name="addEventListener"]']: function (node) {
const [name] = node.arguments
if (name.type !== 'Literal') return
if (!(name.value in observerMap)) return
context.report({
node,
message: `Avoid using "${name.value}" event listener. Consider using ${observerMap[name.value]} instead`,
})
},
}
},
}

View File

@@ -0,0 +1,35 @@
const passiveEventListenerNames = new Set([
'touchstart',
'touchmove',
'touchenter',
'touchend',
'touchleave',
'wheel',
'mousewheel',
])
const propIsPassiveTrue = prop => prop.key && prop.key.name === 'passive' && prop.value && prop.value.value === true
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'enforce marking high frequency event handlers as passive',
url: require('../url')(module),
},
schema: [],
},
create(context) {
return {
['CallExpression[callee.property.name="addEventListener"]']: function (node) {
const [name, listener, options] = node.arguments
if (!listener) return
if (name.type !== 'Literal') return
if (!passiveEventListenerNames.has(name.value)) return
if (options && options.type === 'ObjectExpression' && options.properties.some(propIsPassiveTrue)) return
context.report({node, message: `High Frequency Events like "${name.value}" should be \`passive: true\``})
},
}
},
}

View File

@@ -0,0 +1,36 @@
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'disallow unescaped HTML literals',
url: require('../url')(module),
},
schema: [],
},
create(context) {
const htmlOpenTag = /^<[a-zA-Z]/
const message = 'Unescaped HTML literal. Use html`` tag template literal for secure escaping.'
return {
Literal(node) {
if (!htmlOpenTag.test(node.value)) return
context.report({
node,
message,
})
},
TemplateLiteral(node) {
if (!htmlOpenTag.test(node.quasis[0].value.raw)) return
if (!node.parent.tag || node.parent.tag.name !== 'html') {
context.report({
node,
message,
})
}
},
}
},
}

View File

@@ -0,0 +1,10 @@
const {homepage, version} = require('../package.json')
const path = require('path')
module.exports = ({id}) => {
const url = new URL(homepage)
const rule = path.basename(id, '.js')
url.hash = ''
url.pathname += `/blob/v${version}/docs/rules/${rule}.md`
return url.toString()
}

View File

@@ -0,0 +1,37 @@
const {elementType, getProp, getLiteralPropValue} = require('jsx-ast-utils')
/*
Allows custom component to be mapped to an element type.
When a default is set, all instances of the component will be mapped to the default.
If a prop determines the type, it can be specified with `props`.
For now, we only support the mapping of one prop type to an element type, rather than combinations of props.
*/
function getElementType(context, node, lazyElementCheck = false) {
const {settings} = context
if (lazyElementCheck) {
return elementType(node)
}
// check if the node contains a polymorphic prop
const polymorphicPropName = settings?.github?.polymorphicPropName ?? 'as'
const prop = getProp(node.attributes, polymorphicPropName)
const literalPropValue = getLiteralPropValue(getProp(node.attributes, polymorphicPropName))
let checkConditionalMap = true
// If the prop is not a literal and we cannot determine it, don't fall back to the conditional map value, if it exists
if (prop && !literalPropValue) {
checkConditionalMap = false
}
const rawElement = getLiteralPropValue(getProp(node.attributes, polymorphicPropName)) ?? elementType(node)
// if a component configuration does not exists, return the raw element
if (!settings?.github?.components?.[rawElement]) return rawElement
// check if the default component is also defined in the configuration
return checkConditionalMap ? settings.github.components[rawElement] : rawElement
}
module.exports = {getElementType}

View File

@@ -0,0 +1,37 @@
function getNodeName(node, options) {
const op = options || []
if (node.type === 'Identifier') {
return node.name
}
if (node.id && node.id.type === 'Identifier') {
return node.id.name
}
if (op[2] && node.type === 'CallExpression' && node.callee.type === 'Identifier') {
return node.callee.name
}
}
module.exports = function getExportedName(programNode, options) {
for (let i = 0; i < programNode.body.length; i += 1) {
const node = programNode.body[i]
if (node.type === 'ExportDefaultDeclaration') {
return getNodeName(node.declaration, options)
}
if (
node.type === 'ExpressionStatement' &&
node.expression.type === 'AssignmentExpression' &&
node.expression.left.type === 'MemberExpression' &&
node.expression.left.object.type === 'Identifier' &&
node.expression.left.object.name === 'module' &&
node.expression.left.property.type === 'Identifier' &&
node.expression.left.property.name === 'exports'
) {
return getNodeName(node.expression.right, options)
}
}
}

View File

@@ -0,0 +1,111 @@
const {getProp, getLiteralPropValue} = require('jsx-ast-utils')
const {elementRoles} = require('aria-query')
const {getElementType} = require('./get-element-type')
const ObjectMap = require('./object-map')
const elementRolesMap = cleanElementRolesMap()
/*
Returns an element roles map which uses `aria-query`'s elementRoles as the foundation.
We additionally clean the data so we're able to fetch a role using a key we construct based on the node we're looking at.
In a few scenarios, we stray from the roles returned by `aria-query` and hard code the mapping.
*/
function cleanElementRolesMap() {
const rolesMap = new ObjectMap()
for (const [key, value] of elementRoles.entries()) {
// - Remove empty `attributes` key
if (!key.attributes || key.attributes?.length === 0) {
delete key.attributes
}
rolesMap.set(key, value)
}
// Remove insufficiently-disambiguated `menuitem` entry
rolesMap.delete({name: 'menuitem'})
// Disambiguate `menuitem` and `menu` roles by `type`
rolesMap.set({name: 'menuitem', attributes: [{name: 'type', value: 'command'}]}, ['menuitem'])
rolesMap.set({name: 'menuitem', attributes: [{name: 'type', value: 'radio'}]}, ['menuitemradio'])
rolesMap.set({name: 'menuitem', attributes: [{name: 'type', value: 'toolbar'}]}, ['toolbar'])
rolesMap.set({name: 'menu', attributes: [{name: 'type', value: 'toolbar'}]}, ['toolbar'])
/* These have constraints defined in aria-query's `elementRoles` which depend on knowledge of ancestor roles which we cant accurately determine in a linter context.
However, we benefit more from assuming the role, than assuming it's generic or undefined so we opt to hard code the mapping */
rolesMap.set({name: 'aside'}, ['complementary']) // `aside` still maps to `complementary` in https://www.w3.org/TR/html-aria/#docconformance.
rolesMap.set({name: 'li'}, ['listitem']) // `li` can be generic if it's not within a list but we would never want to render `li` outside of a list.
return rolesMap
}
/*
Determine role of an element, based on its name and attributes.
We construct a key and look up the element's role in `elementRolesMap`.
If there is no match, we return undefined.
*/
function getRole(context, node) {
// Early return if role is explicitly set
const explicitRole = getLiteralPropValue(getProp(node.attributes, 'role'))
if (explicitRole) {
return explicitRole
} else if (getProp(node.attributes, 'role')) {
// If role is set to anything other than a literal prop
return undefined
}
// Assemble a key for looking-up the elements role in the `elementRolesMap`
// - Get the elements name
const key = {name: getElementType(context, node)}
for (const prop of [
'aria-label',
'aria-labelledby',
'alt',
'type',
'size',
'role',
'href',
'multiple',
'scope',
'name',
]) {
if ((prop === 'aria-labelledby' || prop === 'aria-label') && !['section', 'form'].includes(key.name)) continue
if (prop === 'name' && key.name !== 'form') continue
if (prop === 'href' && key.name !== 'a' && key.name !== 'area') continue
if (prop === 'alt' && key.name !== 'img') continue
const propOnNode = getProp(node.attributes, prop)
if (!('attributes' in key)) {
key.attributes = []
}
// Disambiguate "undefined" props
if (propOnNode === undefined && prop === 'alt' && key.name === 'img') {
key.attributes.push({name: prop, constraints: ['undefined']})
continue
}
const value = getLiteralPropValue(propOnNode)
if (propOnNode) {
if (
prop === 'href' ||
prop === 'aria-labelledby' ||
prop === 'aria-label' ||
prop === 'name' ||
(prop === 'alt' && value !== '')
) {
key.attributes.push({name: prop, constraints: ['set']})
} else if (value || (value === '' && prop === 'alt')) {
key.attributes.push({name: prop, value})
}
}
}
// - Remove empty `attributes` key
if (!key.attributes || key.attributes?.length === 0) {
delete key.attributes
}
// Get the elements implicit role
return elementRolesMap.get(key)?.[0]
}
module.exports = {getRole}

View File

@@ -0,0 +1,5 @@
const ignoredFilenames = ['<text>', '<input>']
module.exports = function isIgnoredFilename(filename) {
return ignoredFilenames.indexOf(filename) !== -1
}

View File

@@ -0,0 +1,58 @@
// @ts-check
const {isDeepStrictEqual} = require('util')
/**
* ObjectMap extends Map, but determines key equality using Node.js `util.isDeepStrictEqual` rather than using [SameValueZero](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#key_equality). This makes using objects as keys a bit simpler.
*/
module.exports = class ObjectMap extends Map {
#data
constructor(iterable = []) {
super()
this.#data = iterable
}
clear() {
this.#data = []
}
delete(key) {
if (!this.has(key)) {
return false
}
this.#data = this.#data.filter(([existingKey]) => !isDeepStrictEqual(existingKey, key))
return true
}
entries() {
return this.#data[Symbol.iterator]()
}
forEach(cb) {
for (const [key, value] of this.#data) {
cb(value, key, this.#data)
}
}
get(key) {
return this.#data.find(([existingKey]) => isDeepStrictEqual(existingKey, key))?.[1]
}
has(key) {
return this.#data.findIndex(([existingKey]) => isDeepStrictEqual(existingKey, key)) !== -1
}
keys() {
return this.#data.map(([key]) => key)[Symbol.iterator]()
}
set(key, value) {
this.delete(key)
this.#data.push([key, value])
return this
}
values() {
return this.#data.map(([, value]) => value)[Symbol.iterator]()
}
}

View File

@@ -0,0 +1,12 @@
const path = require('path')
module.exports = function parseFilename(filename) {
const ext = path.extname(filename)
return {
dir: path.dirname(filename),
base: path.basename(filename),
ext,
name: path.basename(filename, ext),
}
}

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,206 @@
# ESLint Compatibility Utilities
## Overview
This packages contains functions that allow you to wrap existing ESLint rules, plugins, and configurations that were intended for use with ESLint v8.x to allow them to work as-is in ESLint v9.x.
**Note:** All plugins are not guaranteed to work in ESLint v9.x. This package fixes the most common issues but can't fix everything.
## Installation
For Node.js and compatible runtimes:
```shell
npm install @eslint/compat -D
# or
yarn add @eslint/compat -D
# or
pnpm install @eslint/compat -D
# or
bun install @eslint/compat -D
```
For Deno:
```shell
deno add @eslint/compat
```
## Usage
This package exports the following functions in both ESM and CommonJS format:
- `fixupRule(rule)` - wraps the given rule in a compatibility layer and returns the result
- `fixupPluginRules(plugin)` - wraps each rule in the given plugin using `fixupRule()` and returns a new object that represents the plugin with the fixed-up rules
- `fixupConfigRules(configs)` - wraps all plugins found in an array of config objects using `fixupPluginRules()`
- `includeIgnoreFile(path)` - reads an ignore file (like `.gitignore`) and converts the patterns into the correct format for the config file
### Fixing Rules
If you have a rule that you'd like to make compatible with ESLint v9.x, you can do so using the `fixupRule()` function:
```js
// ESM example
import { fixupRule } from "@eslint/compat";
// Step 1: Import your rule
import myRule from "./local-rule.js";
// Step 2: Create backwards-compatible rule
const compatRule = fixupRule(myRule);
// Step 3 (optional): Export fixed rule
export default compatRule;
```
Or in CommonJS:
```js
// CommonJS example
const { fixupRule } = require("@eslint/compat");
// Step 1: Import your rule
const myRule = require("./local-rule.js");
// Step 2: Create backwards-compatible rule
const compatRule = fixupRule(myRule);
// Step 3 (optional): Export fixed rule
module.exports = compatRule;
```
### Fixing Plugins
If you are using a plugin in your `eslint.config.js` that is not yet compatible with ESLint 9.x, you can wrap it using the `fixupPluginRules()` function:
```js
// eslint.config.js - ESM example
import { fixupPluginRules } from "@eslint/compat";
import somePlugin from "eslint-plugin-some-plugin";
export default [
{
plugins: {
// insert the fixed plugin instead of the original
somePlugin: fixupPluginRules(somePlugin),
},
rules: {
"somePlugin/rule-name": "error",
},
},
];
```
Or in CommonJS:
```js
// eslint.config.js - CommonJS example
const { fixupPluginRules } = require("@eslint/compat");
const somePlugin = require("eslint-plugin-some-plugin");
module.exports = [
{
plugins: {
// insert the fixed plugin instead of the original
somePlugin: fixupPluginRules(somePlugin),
},
rules: {
"somePlugin/rule-name": "error",
},
},
];
```
### Fixing Configs
If you are importing other configs into your `eslint.config.js` that use plugins that are not yet compatible with ESLint 9.x, you can wrap the entire array or a single object using the `fixupConfigRules()` function:
```js
// eslint.config.js - ESM example
import { fixupConfigRules } from "@eslint/compat";
import someConfig from "eslint-config-some-config";
export default [
...fixupConfigRules(someConfig),
{
// your overrides
},
];
```
Or in CommonJS:
```js
// eslint.config.js - CommonJS example
const { fixupConfigRules } = require("@eslint/compat");
const someConfig = require("eslint-config-some-config");
module.exports = [
...fixupConfigRules(someConfig),
{
// your overrides
},
];
```
### Including Ignore Files
If you were using an alternate ignore file in ESLint v8.x, such as using `--ignore-path .gitignore` on the command line, you can include those patterns programmatically in your config file using the `includeIgnoreFile()` function. For example:
```js
// eslint.config.js - ESM example
import { includeIgnoreFile } from "@eslint/compat";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const gitignorePath = path.resolve(__dirname, ".gitignore");
export default [
includeIgnoreFile(gitignorePath),
{
// your overrides
},
];
```
Or in CommonJS:
```js
// eslint.config.js - CommonJS example
const { includeIgnoreFile } = require("@eslint/compat");
const path = require("node:path");
const gitignorePath = path.resolve(__dirname, ".gitignore");
module.exports = [
includeIgnoreFile(gitignorePath),
{
// your overrides
},
];
```
**Limitation:** This works without modification when the ignore file is in the same directory as your config file. If the ignore file is in a different directory, you may need to modify the patterns manually.
## License
Apache 2.0
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
## Sponsors
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
<h3>Platinum Sponsors</h3>
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="128"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://trunk.io/"><img src="https://images.opencollective.com/trunkio/fb92d60/avatar.png" alt="trunk.io" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://www.serptriumph.com/"><img src="https://images.opencollective.com/serp-triumph5/fea3074/logo.png" alt="SERP Triumph" height="64"></a> <a href="https://www.jetbrains.com/"><img src="https://images.opencollective.com/jetbrains/fe76f99/logo.png" alt="JetBrains" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a> <a href="https://americanexpress.io"><img src="https://avatars.githubusercontent.com/u/3853301?v=4" alt="American Express" height="64"></a> <a href="https://www.workleap.com"><img src="https://avatars.githubusercontent.com/u/53535748?u=d1e55d7661d724bf2281c1bfd33cb8f99fe2465f&v=4" alt="Workleap" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://syntax.fm"><img src="https://github.com/syntaxfm.png" alt="Syntax" height="32"></a> <a href="https://www.wordhint.net/"><img src="https://images.opencollective.com/wordhint/be86813/avatar.png" alt="WordHint" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340?v=4" alt="GitBook" height="32"></a> <a href="https://nx.dev"><img src="https://avatars.githubusercontent.com/u/23692104?v=4" alt="Nx" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774?v=4" alt="HeroCoders" height="32"></a></p>
<h3>Technology Sponsors</h3>
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
<!--sponsorsend-->

View File

@@ -0,0 +1,366 @@
'use strict';
var fs = require('node:fs');
var path = require('node:path');
/**
* @filedescription Functions to fix up rules to provide missing methods on the `context` object.
* @author Nicholas C. Zakas
*/
//-----------------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------------
/** @typedef {import("eslint").ESLint.Plugin} FixupPluginDefinition */
/** @typedef {import("eslint").Rule.RuleModule} FixupRuleDefinition */
/** @typedef {FixupRuleDefinition["create"]} FixupLegacyRuleDefinition */
/** @typedef {import("eslint").Linter.Config} FixupConfig */
/** @typedef {Array<FixupConfig>} FixupConfigArray */
//-----------------------------------------------------------------------------
// Data
//-----------------------------------------------------------------------------
/**
* The removed methods from the `context` object that need to be added back.
* The keys are the name of the method on the `context` object and the values
* are the name of the method on the `sourceCode` object.
* @type {Map<string, string>}
*/
const removedMethodNames = new Map([
["getSource", "getText"],
["getSourceLines", "getLines"],
["getAllComments", "getAllComments"],
["getDeclaredVariables", "getDeclaredVariables"],
["getNodeByRangeIndex", "getNodeByRangeIndex"],
["getCommentsBefore", "getCommentsBefore"],
["getCommentsAfter", "getCommentsAfter"],
["getCommentsInside", "getCommentsInside"],
["getJSDocComment", "getJSDocComment"],
["getFirstToken", "getFirstToken"],
["getFirstTokens", "getFirstTokens"],
["getLastToken", "getLastToken"],
["getLastTokens", "getLastTokens"],
["getTokenAfter", "getTokenAfter"],
["getTokenBefore", "getTokenBefore"],
["getTokenByRangeStart", "getTokenByRangeStart"],
["getTokens", "getTokens"],
["getTokensAfter", "getTokensAfter"],
["getTokensBefore", "getTokensBefore"],
["getTokensBetween", "getTokensBetween"],
]);
/**
* Tracks the original rule definition and the fixed-up rule definition.
* @type {WeakMap<FixupRuleDefinition|FixupLegacyRuleDefinition,FixupRuleDefinition>}
*/
const fixedUpRuleReplacements = new WeakMap();
/**
* Tracks all of the fixed up rule definitions so we don't duplicate effort.
* @type {WeakSet<FixupRuleDefinition>}
*/
const fixedUpRules = new WeakSet();
/**
* Tracks the original plugin definition and the fixed-up plugin definition.
* @type {WeakMap<FixupPluginDefinition,FixupPluginDefinition>}
*/
const fixedUpPluginReplacements = new WeakMap();
/**
* Tracks all of the fixed up plugin definitions so we don't duplicate effort.
* @type {WeakSet<FixupPluginDefinition>}
*/
const fixedUpPlugins = new WeakSet();
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* Takes the given rule and creates a new rule with the `create()` method wrapped
* to provide the missing methods on the `context` object.
* @param {FixupRuleDefinition|FixupLegacyRuleDefinition} ruleDefinition The rule to fix up.
* @returns {FixupRuleDefinition} The fixed-up rule.
*/
function fixupRule(ruleDefinition) {
// first check if we've already fixed up this rule
if (fixedUpRuleReplacements.has(ruleDefinition)) {
return fixedUpRuleReplacements.get(ruleDefinition);
}
const isLegacyRule = typeof ruleDefinition === "function";
// check to see if this rule definition has already been fixed up
if (!isLegacyRule && fixedUpRules.has(ruleDefinition)) {
return ruleDefinition;
}
const originalCreate = isLegacyRule
? ruleDefinition
: ruleDefinition.create.bind(ruleDefinition);
function ruleCreate(context) {
// if getScope is already there then no need to create old methods
if ("getScope" in context) {
return originalCreate(context);
}
const sourceCode = context.sourceCode;
let currentNode = sourceCode.ast;
const newContext = Object.assign(Object.create(context), {
parserServices: sourceCode.parserServices,
/*
* The following methods rely on the current node in the traversal,
* so we need to add them manually.
*/
getScope() {
return sourceCode.getScope(currentNode);
},
getAncestors() {
return sourceCode.getAncestors(currentNode);
},
markVariableAsUsed(variable) {
sourceCode.markVariableAsUsed(variable, currentNode);
},
});
// add passthrough methods
for (const [
contextMethodName,
sourceCodeMethodName,
] of removedMethodNames) {
newContext[contextMethodName] =
sourceCode[sourceCodeMethodName].bind(sourceCode);
}
// freeze just like the original context
Object.freeze(newContext);
/*
* Create the visitor object using the original create() method.
* This is necessary to ensure that the visitor object is created
* with the correct context.
*/
const visitor = originalCreate(newContext);
/*
* Wrap each method in the visitor object to update the currentNode
* before calling the original method. This is necessary because the
* methods like `getScope()` need to know the current node.
*/
for (const [methodName, method] of Object.entries(visitor)) {
/*
* Node is the second argument to most code path methods,
* and the third argument for onCodePathSegmentLoop.
*/
if (methodName.startsWith("on")) {
// eslint-disable-next-line no-loop-func -- intentionally updating shared `currentNode` variable
visitor[methodName] = (...args) => {
currentNode =
args[methodName === "onCodePathSegmentLoop" ? 2 : 1];
return method.call(visitor, ...args);
};
continue;
}
// eslint-disable-next-line no-loop-func -- intentionally updating shared `currentNode` variable
visitor[methodName] = (...args) => {
currentNode = args[0];
return method.call(visitor, ...args);
};
}
return visitor;
}
const newRuleDefinition = {
...(isLegacyRule ? undefined : ruleDefinition),
create: ruleCreate,
};
// copy `schema` property of function-style rule or top-level `schema` property of object-style rule into `meta` object
// @ts-ignore -- top-level `schema` property was not offically supported for object-style rules so it doesn't exist in types
const { schema } = ruleDefinition;
if (schema) {
if (!newRuleDefinition.meta) {
newRuleDefinition.meta = { schema };
} else {
newRuleDefinition.meta = {
...newRuleDefinition.meta,
// top-level `schema` had precedence over `meta.schema` so it's okay to overwrite `meta.schema` if it exists
schema,
};
}
}
// cache the fixed up rule
fixedUpRuleReplacements.set(ruleDefinition, newRuleDefinition);
fixedUpRules.add(newRuleDefinition);
return newRuleDefinition;
}
/**
* Takes the given plugin and creates a new plugin with all of the rules wrapped
* to provide the missing methods on the `context` object.
* @param {FixupPluginDefinition} plugin The plugin to fix up.
* @returns {FixupPluginDefinition} The fixed-up plugin.
*/
function fixupPluginRules(plugin) {
// first check if we've already fixed up this plugin
if (fixedUpPluginReplacements.has(plugin)) {
return fixedUpPluginReplacements.get(plugin);
}
/*
* If the plugin has already been fixed up, or if the plugin
* doesn't have any rules, we can just return it.
*/
if (fixedUpPlugins.has(plugin) || !plugin.rules) {
return plugin;
}
const newPlugin = {
...plugin,
rules: Object.fromEntries(
Object.entries(plugin.rules).map(([ruleId, ruleDefinition]) => [
ruleId,
fixupRule(ruleDefinition),
]),
),
};
// cache the fixed up plugin
fixedUpPluginReplacements.set(plugin, newPlugin);
fixedUpPlugins.add(newPlugin);
return newPlugin;
}
/**
* Takes the given configuration and creates a new configuration with all of the
* rules wrapped to provide the missing methods on the `context` object.
* @param {FixupConfigArray|FixupConfig} config The configuration to fix up.
* @returns {FixupConfigArray} The fixed-up configuration.
*/
function fixupConfigRules(config) {
const configs = Array.isArray(config) ? config : [config];
return configs.map(configItem => {
if (!configItem.plugins) {
return configItem;
}
const newPlugins = Object.fromEntries(
Object.entries(configItem.plugins).map(([pluginName, plugin]) => [
pluginName,
fixupPluginRules(plugin),
]),
);
return {
...configItem,
plugins: newPlugins,
};
});
}
/**
* @fileoverview Ignore file utilities for the compat package.
* @author Nicholas C. Zakas
*/
//-----------------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------------
/** @typedef {import("eslint").Linter.Config} FlatConfig */
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* Converts an ESLint ignore pattern to a minimatch pattern.
* @param {string} pattern The .eslintignore or .gitignore pattern to convert.
* @returns {string} The converted pattern.
*/
function convertIgnorePatternToMinimatch(pattern) {
const isNegated = pattern.startsWith("!");
const negatedPrefix = isNegated ? "!" : "";
const patternToTest = (isNegated ? pattern.slice(1) : pattern).trimEnd();
// special cases
if (["", "**", "/**", "**/"].includes(patternToTest)) {
return `${negatedPrefix}${patternToTest}`;
}
const firstIndexOfSlash = patternToTest.indexOf("/");
const matchEverywherePrefix =
firstIndexOfSlash < 0 || firstIndexOfSlash === patternToTest.length - 1
? "**/"
: "";
const patternWithoutLeadingSlash =
firstIndexOfSlash === 0 ? patternToTest.slice(1) : patternToTest;
/*
* Escape `{` and `(` because in gitignore patterns they are just
* literal characters without any specific syntactic meaning,
* while in minimatch patterns they can form brace expansion or extglob syntax.
*
* For example, gitignore pattern `src/{a,b}.js` ignores file `src/{a,b}.js`.
* But, the same minimatch pattern `src/{a,b}.js` ignores files `src/a.js` and `src/b.js`.
* Minimatch pattern `src/\{a,b}.js` is equivalent to gitignore pattern `src/{a,b}.js`.
*/
const escapedPatternWithoutLeadingSlash =
patternWithoutLeadingSlash.replaceAll(
/(?=((?:\\.|[^{(])*))\1([{(])/guy,
"$1\\$2",
);
const matchInsideSuffix = patternToTest.endsWith("/**") ? "/*" : "";
return `${negatedPrefix}${matchEverywherePrefix}${escapedPatternWithoutLeadingSlash}${matchInsideSuffix}`;
}
/**
* Reads an ignore file and returns an object with the ignore patterns.
* @param {string} ignoreFilePath The absolute path to the ignore file.
* @returns {FlatConfig} An object with an `ignores` property that is an array of ignore patterns.
* @throws {Error} If the ignore file path is not an absolute path.
*/
function includeIgnoreFile(ignoreFilePath) {
if (!path.isAbsolute(ignoreFilePath)) {
throw new Error("The ignore file location must be an absolute path.");
}
const ignoreFile = fs.readFileSync(ignoreFilePath, "utf8");
const lines = ignoreFile.split(/\r?\n/u);
return {
name: "Imported .gitignore patterns",
ignores: lines
.map(line => line.trim())
.filter(line => line && !line.startsWith("#"))
.map(convertIgnorePatternToMinimatch),
};
}
exports.convertIgnorePatternToMinimatch = convertIgnorePatternToMinimatch;
exports.fixupConfigRules = fixupConfigRules;
exports.fixupPluginRules = fixupPluginRules;
exports.fixupRule = fixupRule;
exports.includeIgnoreFile = includeIgnoreFile;

View File

@@ -0,0 +1,45 @@
export type FlatConfig = import("eslint").Linter.Config;
export type FixupPluginDefinition = import("eslint").ESLint.Plugin;
export type FixupRuleDefinition = import("eslint").Rule.RuleModule;
export type FixupLegacyRuleDefinition = FixupRuleDefinition["create"];
export type FixupConfig = import("eslint").Linter.Config;
export type FixupConfigArray = Array<FixupConfig>;
/**
* @fileoverview Ignore file utilities for the compat package.
* @author Nicholas C. Zakas
*/
/** @typedef {import("eslint").Linter.Config} FlatConfig */
/**
* Converts an ESLint ignore pattern to a minimatch pattern.
* @param {string} pattern The .eslintignore or .gitignore pattern to convert.
* @returns {string} The converted pattern.
*/
export function convertIgnorePatternToMinimatch(pattern: string): string;
/**
* Takes the given configuration and creates a new configuration with all of the
* rules wrapped to provide the missing methods on the `context` object.
* @param {FixupConfigArray|FixupConfig} config The configuration to fix up.
* @returns {FixupConfigArray} The fixed-up configuration.
*/
export function fixupConfigRules(config: FixupConfigArray | FixupConfig): FixupConfigArray;
/**
* Takes the given plugin and creates a new plugin with all of the rules wrapped
* to provide the missing methods on the `context` object.
* @param {FixupPluginDefinition} plugin The plugin to fix up.
* @returns {FixupPluginDefinition} The fixed-up plugin.
*/
export function fixupPluginRules(plugin: FixupPluginDefinition): FixupPluginDefinition;
/**
* Takes the given rule and creates a new rule with the `create()` method wrapped
* to provide the missing methods on the `context` object.
* @param {FixupRuleDefinition|FixupLegacyRuleDefinition} ruleDefinition The rule to fix up.
* @returns {FixupRuleDefinition} The fixed-up rule.
*/
export function fixupRule(ruleDefinition: FixupRuleDefinition | FixupLegacyRuleDefinition): FixupRuleDefinition;
/**
* Reads an ignore file and returns an object with the ignore patterns.
* @param {string} ignoreFilePath The absolute path to the ignore file.
* @returns {FlatConfig} An object with an `ignores` property that is an array of ignore patterns.
* @throws {Error} If the ignore file path is not an absolute path.
*/
export function includeIgnoreFile(ignoreFilePath: string): FlatConfig;

View File

@@ -0,0 +1,45 @@
export type FlatConfig = import("eslint").Linter.Config;
export type FixupPluginDefinition = import("eslint").ESLint.Plugin;
export type FixupRuleDefinition = import("eslint").Rule.RuleModule;
export type FixupLegacyRuleDefinition = FixupRuleDefinition["create"];
export type FixupConfig = import("eslint").Linter.Config;
export type FixupConfigArray = Array<FixupConfig>;
/**
* @fileoverview Ignore file utilities for the compat package.
* @author Nicholas C. Zakas
*/
/** @typedef {import("eslint").Linter.Config} FlatConfig */
/**
* Converts an ESLint ignore pattern to a minimatch pattern.
* @param {string} pattern The .eslintignore or .gitignore pattern to convert.
* @returns {string} The converted pattern.
*/
export function convertIgnorePatternToMinimatch(pattern: string): string;
/**
* Takes the given configuration and creates a new configuration with all of the
* rules wrapped to provide the missing methods on the `context` object.
* @param {FixupConfigArray|FixupConfig} config The configuration to fix up.
* @returns {FixupConfigArray} The fixed-up configuration.
*/
export function fixupConfigRules(config: FixupConfigArray | FixupConfig): FixupConfigArray;
/**
* Takes the given plugin and creates a new plugin with all of the rules wrapped
* to provide the missing methods on the `context` object.
* @param {FixupPluginDefinition} plugin The plugin to fix up.
* @returns {FixupPluginDefinition} The fixed-up plugin.
*/
export function fixupPluginRules(plugin: FixupPluginDefinition): FixupPluginDefinition;
/**
* Takes the given rule and creates a new rule with the `create()` method wrapped
* to provide the missing methods on the `context` object.
* @param {FixupRuleDefinition|FixupLegacyRuleDefinition} ruleDefinition The rule to fix up.
* @returns {FixupRuleDefinition} The fixed-up rule.
*/
export function fixupRule(ruleDefinition: FixupRuleDefinition | FixupLegacyRuleDefinition): FixupRuleDefinition;
/**
* Reads an ignore file and returns an object with the ignore patterns.
* @param {string} ignoreFilePath The absolute path to the ignore file.
* @returns {FlatConfig} An object with an `ignores` property that is an array of ignore patterns.
* @throws {Error} If the ignore file path is not an absolute path.
*/
export function includeIgnoreFile(ignoreFilePath: string): FlatConfig;

View File

@@ -0,0 +1,361 @@
// @ts-self-types="./index.d.ts"
import fs from 'node:fs';
import path from 'node:path';
/**
* @filedescription Functions to fix up rules to provide missing methods on the `context` object.
* @author Nicholas C. Zakas
*/
//-----------------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------------
/** @typedef {import("eslint").ESLint.Plugin} FixupPluginDefinition */
/** @typedef {import("eslint").Rule.RuleModule} FixupRuleDefinition */
/** @typedef {FixupRuleDefinition["create"]} FixupLegacyRuleDefinition */
/** @typedef {import("eslint").Linter.Config} FixupConfig */
/** @typedef {Array<FixupConfig>} FixupConfigArray */
//-----------------------------------------------------------------------------
// Data
//-----------------------------------------------------------------------------
/**
* The removed methods from the `context` object that need to be added back.
* The keys are the name of the method on the `context` object and the values
* are the name of the method on the `sourceCode` object.
* @type {Map<string, string>}
*/
const removedMethodNames = new Map([
["getSource", "getText"],
["getSourceLines", "getLines"],
["getAllComments", "getAllComments"],
["getDeclaredVariables", "getDeclaredVariables"],
["getNodeByRangeIndex", "getNodeByRangeIndex"],
["getCommentsBefore", "getCommentsBefore"],
["getCommentsAfter", "getCommentsAfter"],
["getCommentsInside", "getCommentsInside"],
["getJSDocComment", "getJSDocComment"],
["getFirstToken", "getFirstToken"],
["getFirstTokens", "getFirstTokens"],
["getLastToken", "getLastToken"],
["getLastTokens", "getLastTokens"],
["getTokenAfter", "getTokenAfter"],
["getTokenBefore", "getTokenBefore"],
["getTokenByRangeStart", "getTokenByRangeStart"],
["getTokens", "getTokens"],
["getTokensAfter", "getTokensAfter"],
["getTokensBefore", "getTokensBefore"],
["getTokensBetween", "getTokensBetween"],
]);
/**
* Tracks the original rule definition and the fixed-up rule definition.
* @type {WeakMap<FixupRuleDefinition|FixupLegacyRuleDefinition,FixupRuleDefinition>}
*/
const fixedUpRuleReplacements = new WeakMap();
/**
* Tracks all of the fixed up rule definitions so we don't duplicate effort.
* @type {WeakSet<FixupRuleDefinition>}
*/
const fixedUpRules = new WeakSet();
/**
* Tracks the original plugin definition and the fixed-up plugin definition.
* @type {WeakMap<FixupPluginDefinition,FixupPluginDefinition>}
*/
const fixedUpPluginReplacements = new WeakMap();
/**
* Tracks all of the fixed up plugin definitions so we don't duplicate effort.
* @type {WeakSet<FixupPluginDefinition>}
*/
const fixedUpPlugins = new WeakSet();
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* Takes the given rule and creates a new rule with the `create()` method wrapped
* to provide the missing methods on the `context` object.
* @param {FixupRuleDefinition|FixupLegacyRuleDefinition} ruleDefinition The rule to fix up.
* @returns {FixupRuleDefinition} The fixed-up rule.
*/
function fixupRule(ruleDefinition) {
// first check if we've already fixed up this rule
if (fixedUpRuleReplacements.has(ruleDefinition)) {
return fixedUpRuleReplacements.get(ruleDefinition);
}
const isLegacyRule = typeof ruleDefinition === "function";
// check to see if this rule definition has already been fixed up
if (!isLegacyRule && fixedUpRules.has(ruleDefinition)) {
return ruleDefinition;
}
const originalCreate = isLegacyRule
? ruleDefinition
: ruleDefinition.create.bind(ruleDefinition);
function ruleCreate(context) {
// if getScope is already there then no need to create old methods
if ("getScope" in context) {
return originalCreate(context);
}
const sourceCode = context.sourceCode;
let currentNode = sourceCode.ast;
const newContext = Object.assign(Object.create(context), {
parserServices: sourceCode.parserServices,
/*
* The following methods rely on the current node in the traversal,
* so we need to add them manually.
*/
getScope() {
return sourceCode.getScope(currentNode);
},
getAncestors() {
return sourceCode.getAncestors(currentNode);
},
markVariableAsUsed(variable) {
sourceCode.markVariableAsUsed(variable, currentNode);
},
});
// add passthrough methods
for (const [
contextMethodName,
sourceCodeMethodName,
] of removedMethodNames) {
newContext[contextMethodName] =
sourceCode[sourceCodeMethodName].bind(sourceCode);
}
// freeze just like the original context
Object.freeze(newContext);
/*
* Create the visitor object using the original create() method.
* This is necessary to ensure that the visitor object is created
* with the correct context.
*/
const visitor = originalCreate(newContext);
/*
* Wrap each method in the visitor object to update the currentNode
* before calling the original method. This is necessary because the
* methods like `getScope()` need to know the current node.
*/
for (const [methodName, method] of Object.entries(visitor)) {
/*
* Node is the second argument to most code path methods,
* and the third argument for onCodePathSegmentLoop.
*/
if (methodName.startsWith("on")) {
// eslint-disable-next-line no-loop-func -- intentionally updating shared `currentNode` variable
visitor[methodName] = (...args) => {
currentNode =
args[methodName === "onCodePathSegmentLoop" ? 2 : 1];
return method.call(visitor, ...args);
};
continue;
}
// eslint-disable-next-line no-loop-func -- intentionally updating shared `currentNode` variable
visitor[methodName] = (...args) => {
currentNode = args[0];
return method.call(visitor, ...args);
};
}
return visitor;
}
const newRuleDefinition = {
...(isLegacyRule ? undefined : ruleDefinition),
create: ruleCreate,
};
// copy `schema` property of function-style rule or top-level `schema` property of object-style rule into `meta` object
// @ts-ignore -- top-level `schema` property was not offically supported for object-style rules so it doesn't exist in types
const { schema } = ruleDefinition;
if (schema) {
if (!newRuleDefinition.meta) {
newRuleDefinition.meta = { schema };
} else {
newRuleDefinition.meta = {
...newRuleDefinition.meta,
// top-level `schema` had precedence over `meta.schema` so it's okay to overwrite `meta.schema` if it exists
schema,
};
}
}
// cache the fixed up rule
fixedUpRuleReplacements.set(ruleDefinition, newRuleDefinition);
fixedUpRules.add(newRuleDefinition);
return newRuleDefinition;
}
/**
* Takes the given plugin and creates a new plugin with all of the rules wrapped
* to provide the missing methods on the `context` object.
* @param {FixupPluginDefinition} plugin The plugin to fix up.
* @returns {FixupPluginDefinition} The fixed-up plugin.
*/
function fixupPluginRules(plugin) {
// first check if we've already fixed up this plugin
if (fixedUpPluginReplacements.has(plugin)) {
return fixedUpPluginReplacements.get(plugin);
}
/*
* If the plugin has already been fixed up, or if the plugin
* doesn't have any rules, we can just return it.
*/
if (fixedUpPlugins.has(plugin) || !plugin.rules) {
return plugin;
}
const newPlugin = {
...plugin,
rules: Object.fromEntries(
Object.entries(plugin.rules).map(([ruleId, ruleDefinition]) => [
ruleId,
fixupRule(ruleDefinition),
]),
),
};
// cache the fixed up plugin
fixedUpPluginReplacements.set(plugin, newPlugin);
fixedUpPlugins.add(newPlugin);
return newPlugin;
}
/**
* Takes the given configuration and creates a new configuration with all of the
* rules wrapped to provide the missing methods on the `context` object.
* @param {FixupConfigArray|FixupConfig} config The configuration to fix up.
* @returns {FixupConfigArray} The fixed-up configuration.
*/
function fixupConfigRules(config) {
const configs = Array.isArray(config) ? config : [config];
return configs.map(configItem => {
if (!configItem.plugins) {
return configItem;
}
const newPlugins = Object.fromEntries(
Object.entries(configItem.plugins).map(([pluginName, plugin]) => [
pluginName,
fixupPluginRules(plugin),
]),
);
return {
...configItem,
plugins: newPlugins,
};
});
}
/**
* @fileoverview Ignore file utilities for the compat package.
* @author Nicholas C. Zakas
*/
//-----------------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------------
/** @typedef {import("eslint").Linter.Config} FlatConfig */
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* Converts an ESLint ignore pattern to a minimatch pattern.
* @param {string} pattern The .eslintignore or .gitignore pattern to convert.
* @returns {string} The converted pattern.
*/
function convertIgnorePatternToMinimatch(pattern) {
const isNegated = pattern.startsWith("!");
const negatedPrefix = isNegated ? "!" : "";
const patternToTest = (isNegated ? pattern.slice(1) : pattern).trimEnd();
// special cases
if (["", "**", "/**", "**/"].includes(patternToTest)) {
return `${negatedPrefix}${patternToTest}`;
}
const firstIndexOfSlash = patternToTest.indexOf("/");
const matchEverywherePrefix =
firstIndexOfSlash < 0 || firstIndexOfSlash === patternToTest.length - 1
? "**/"
: "";
const patternWithoutLeadingSlash =
firstIndexOfSlash === 0 ? patternToTest.slice(1) : patternToTest;
/*
* Escape `{` and `(` because in gitignore patterns they are just
* literal characters without any specific syntactic meaning,
* while in minimatch patterns they can form brace expansion or extglob syntax.
*
* For example, gitignore pattern `src/{a,b}.js` ignores file `src/{a,b}.js`.
* But, the same minimatch pattern `src/{a,b}.js` ignores files `src/a.js` and `src/b.js`.
* Minimatch pattern `src/\{a,b}.js` is equivalent to gitignore pattern `src/{a,b}.js`.
*/
const escapedPatternWithoutLeadingSlash =
patternWithoutLeadingSlash.replaceAll(
/(?=((?:\\.|[^{(])*))\1([{(])/guy,
"$1\\$2",
);
const matchInsideSuffix = patternToTest.endsWith("/**") ? "/*" : "";
return `${negatedPrefix}${matchEverywherePrefix}${escapedPatternWithoutLeadingSlash}${matchInsideSuffix}`;
}
/**
* Reads an ignore file and returns an object with the ignore patterns.
* @param {string} ignoreFilePath The absolute path to the ignore file.
* @returns {FlatConfig} An object with an `ignores` property that is an array of ignore patterns.
* @throws {Error} If the ignore file path is not an absolute path.
*/
function includeIgnoreFile(ignoreFilePath) {
if (!path.isAbsolute(ignoreFilePath)) {
throw new Error("The ignore file location must be an absolute path.");
}
const ignoreFile = fs.readFileSync(ignoreFilePath, "utf8");
const lines = ignoreFile.split(/\r?\n/u);
return {
name: "Imported .gitignore patterns",
ignores: lines
.map(line => line.trim())
.filter(line => line && !line.startsWith("#"))
.map(convertIgnorePatternToMinimatch),
};
}
export { convertIgnorePatternToMinimatch, fixupConfigRules, fixupPluginRules, fixupRule, includeIgnoreFile };

View File

@@ -0,0 +1,69 @@
{
"name": "@eslint/compat",
"version": "1.2.3",
"description": "Compatibility utilities for ESLint",
"type": "module",
"main": "dist/esm/index.js",
"types": "dist/esm/index.d.ts",
"exports": {
"require": {
"types": "./dist/cjs/index.d.cts",
"default": "./dist/cjs/index.cjs"
},
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
}
},
"files": [
"dist"
],
"publishConfig": {
"access": "public"
},
"directories": {
"test": "tests"
},
"scripts": {
"build:cts": "node -e \"fs.copyFileSync('dist/esm/index.d.ts', 'dist/cjs/index.d.cts')\"",
"build": "rollup -c && tsc -p tsconfig.esm.json && npm run build:cts",
"test:jsr": "npx jsr@latest publish --dry-run",
"test": "mocha tests/*.js",
"test:coverage": "c8 npm test"
},
"repository": {
"type": "git",
"url": "git+https://github.com/eslint/rewrite.git"
},
"keywords": [
"eslint",
"compatibility",
"eslintplugin",
"eslint-plugin"
],
"author": "Nicholas C. Zakas",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/eslint/rewrite/issues"
},
"homepage": "https://github.com/eslint/rewrite#readme",
"devDependencies": {
"@eslint/core": "^0.9.0",
"c8": "^9.1.0",
"eslint": "^9.11.0",
"mocha": "^10.4.0",
"rollup": "^4.16.2",
"typescript": "^5.4.5"
},
"peerDependencies": {
"eslint": "^9.10.0"
},
"peerDependenciesMeta": {
"eslint": {
"optional": true
}
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
'use strict';
module.exports = require('./globals.json');

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,98 @@
{
"name": "globals",
"version": "15.13.0",
"description": "Global identifiers from different JavaScript environments",
"license": "MIT",
"repository": "sindresorhus/globals",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"sideEffects": false,
"engines": {
"node": ">=18"
},
"scripts": {
"test": "npm run build && xo && ava && tsd",
"prepare": "npm run build",
"update": "node scripts/update.mjs",
"update:browser": "node scripts/update.mjs --environment=browser",
"update:builtin": "node scripts/update.mjs --environment=builtin",
"update:nodeBuiltin": "node scripts/update.mjs --environment=nodeBuiltin",
"update:worker": "node scripts/update.mjs --environment=worker",
"update:shelljs": "node scripts/update.mjs --environment=shelljs",
"update:jest": "node scripts/update.mjs --environment=jest",
"build": "run-s build:data build:types",
"build:data": "node scripts/generate-data.mjs",
"build:types": "node scripts/generate-types.mjs"
},
"files": [
"index.js",
"index.d.ts",
"globals.json"
],
"keywords": [
"globals",
"global",
"identifiers",
"variables",
"vars",
"jshint",
"eslint",
"environments"
],
"devDependencies": {
"ava": "^6.1.3",
"cheerio": "^1.0.0-rc.12",
"eslint-plugin-jest": "^28.8.3",
"execa": "^9.4.0",
"get-port": "^7.1.0",
"npm-run-all2": "^6.2.3",
"outdent": "^0.8.0",
"puppeteer": "^23.4.1",
"shelljs": "^0.8.5",
"tsd": "^0.31.2",
"type-fest": "^4.26.1",
"xo": "^0.59.3"
},
"xo": {
"rules": {
"unicorn/prefer-module": "off"
},
"overrides": [
{
"files": [
"data/*.mjs"
],
"rules": {
"import/no-anonymous-default-export": "off",
"camelcase": "off",
"unicorn/filename-case": [
"error",
{
"cases": {
"camelCase": true,
"kebabCase": true
}
}
]
}
},
{
"files": [
"scripts/*.mjs"
],
"rules": {
"n/no-unsupported-features/node-builtins": "off"
}
}
]
},
"tsd": {
"compilerOptions": {
"resolveJsonModule": true
}
}
}

View File

@@ -0,0 +1,42 @@
# globals
> Global identifiers from different JavaScript environments
It's just a [JSON file](globals.json), so you can use it in any environment.
This package is used by ESLint 8 and earlier. For ESLint 9 and later, you should depend on this package directly in [your ESLint config](https://eslint.org/docs/latest/use/configure/language-options#predefined-global-variables).
## Install
```sh
npm install globals
```
## Usage
```js
import globals from 'globals';
console.log(globals.browser);
/*
{
addEventListener: false,
applicationCache: false,
ArrayBuffer: false,
atob: false,
}
*/
```
Each global is given a value of `true` or `false`. A value of `true` indicates that the variable may be overwritten. A value of `false` indicates that the variable should be considered read-only. This information is used by static analysis tools to flag incorrect behavior. We assume all variables should be `false` unless we hear otherwise.
For Node.js this package provides two sets of globals:
- `globals.nodeBuiltin`: Globals available to all code running in Node.js.
These will usually be available as properties on the `globalThis` object and include `process`, `Buffer`, but not CommonJS arguments like `require`.
See: https://nodejs.org/api/globals.html
- `globals.node`: A combination of the globals from `nodeBuiltin` plus all CommonJS arguments ("CommonJS module scope").
See: https://nodejs.org/api/modules.html#modules_the_module_scope
When analyzing code that is known to run outside of a CommonJS wrapper, for example, JavaScript modules, `nodeBuiltin` can find accidental CommonJS references.

View File

@@ -0,0 +1,75 @@
{
"name": "eslint-plugin-github",
"version": "5.1.4",
"description": "An opinionated collection of ESLint shared configs and rules used by GitHub.",
"main": "lib/index.js",
"entries": [
"lib/formatters/stylish-fixes.js"
],
"bin": {
"eslint-ignore-errors": "bin/eslint-ignore-errors.js"
},
"scripts": {
"eslint-check": "eslint-config-prettier .eslintrc.js",
"lint": "npm-run-all \"lint:*\"",
"lint:eslint-docs": "npm run update:eslint-docs -- --check",
"lint:js": "eslint .",
"pretest": "mkdir -p node_modules/ && ln -fs $(pwd) node_modules/",
"test": "npm run eslint-check && npm run lint && mocha tests/**/*.js tests/**/*.mjs",
"update:eslint-docs": "eslint-doc-generator",
"test-examples:legacy": "cd test-examples/legacy && npm install && npm run lint",
"test-examples:flat": "cd test-examples/flat && npm install && npm run lint"
},
"repository": {
"type": "git",
"url": "git+https://github.com/github/eslint-plugin-github.git"
},
"author": "GitHub, Inc.",
"license": "MIT",
"bugs": {
"url": "https://github.com/github/eslint-plugin-github/issues"
},
"homepage": "https://github.com/github/eslint-plugin-github#readme",
"dependencies": {
"@eslint/compat": "^1.2.3",
"@eslint/eslintrc": "^3.1.0",
"@eslint/js": "^9.14.0",
"@github/browserslist-config": "^1.0.0",
"@typescript-eslint/eslint-plugin": "^8.0.0",
"@typescript-eslint/parser": "^8.0.0",
"aria-query": "^5.3.0",
"eslint-config-prettier": ">=8.0.0",
"eslint-plugin-escompat": "^3.11.3",
"eslint-plugin-eslint-comments": "^3.2.0",
"eslint-plugin-filenames": "^1.3.2",
"eslint-plugin-i18n-text": "^1.0.1",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-jsx-a11y": "^6.7.1",
"eslint-plugin-no-only-tests": "^3.0.0",
"eslint-plugin-prettier": "^5.2.1",
"eslint-rule-documentation": ">=1.0.0",
"globals": "^15.12.0",
"jsx-ast-utils": "^3.3.2",
"prettier": "^3.0.0",
"svg-element-attributes": "^1.3.1",
"typescript-eslint": "^8.14.0"
},
"prettier": "@github/prettier-config",
"browserslist": "extends @github/browserslist-config",
"peerDependencies": {
"eslint": "^8 || ^9"
},
"files": [
"bin/*",
"lib/*"
],
"devDependencies": {
"@github/prettier-config": "0.0.6",
"chai": "^5.0.0",
"eslint": "^9.14.0",
"eslint-doc-generator": "^1.4.3",
"eslint-plugin-eslint-plugin": "^6.1.0",
"mocha": "^10.0.0",
"npm-run-all": "^4.1.5"
}
}