diff --git a/.github/dependabot.yml b/.github/dependabot.yml index f9f248678..af21e2e60 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -83,7 +83,6 @@ updates: linting-deps: patterns: - '@eslint/*' - - '@html-eslint/*' - '@typescript-eslint/*' - 'angular-eslint' - 'cspell' diff --git a/.github/workflows/eslint-plugin.yml b/.github/workflows/eslint-plugin.yml new file mode 100644 index 000000000..9b93d54c8 --- /dev/null +++ b/.github/workflows/eslint-plugin.yml @@ -0,0 +1,46 @@ +name: ESLint plugin checks + +on: + push: + branches: + - next + pull_request: + paths: + - tools/eslint-plugin/** + - pnpm-lock.yaml + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + cache: 'pnpm' + node-version-file: 'package.json' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Execute unit tests for eslint-plugin + run: pnpm test:eslint-plugin + + typecheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + cache: 'pnpm' + node-version-file: 'package.json' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Typecheck + run: pnpm --filter @lucide/eslint-plugin typecheck diff --git a/.github/workflows/lint-code.yml b/.github/workflows/lint-code.yml index 1d0239944..baf894c7d 100644 --- a/.github/workflows/lint-code.yml +++ b/.github/workflows/lint-code.yml @@ -23,7 +23,7 @@ jobs: # The formatter prints workflow commands, which GitHub shows as inline annotations. - name: Run ESLint - run: pnpm lint:es --format ./scripts/eslint/githubFormatter.mjs + run: pnpm lint:es --format ./tools/eslint-plugin/src/githubFormatter.ts prettier: name: Prettier @@ -57,7 +57,7 @@ jobs: run: pnpm install --frozen-lockfile - name: Validate icon and category JSON - run: pnpm lint:json --format ./scripts/eslint/githubFormatter.mjs + run: pnpm lint:json --format ./tools/eslint-plugin/src/githubFormatter.ts spelling: name: Spelling diff --git a/docs/contribute/icons/code-conventions.md b/docs/contribute/icons/code-conventions.md index 66f95afa7..26a2da656 100644 --- a/docs/contribute/icons/code-conventions.md +++ b/docs/contribute/icons/code-conventions.md @@ -70,6 +70,19 @@ You can automatically format SVG files with Prettier: pnpm run lint:icons-fix ``` +To check that the SVG files only contain allowed elements and attributes, and that their paths and numbers are optimized, run: + +```sh +pnpm run lint:svg:icons +``` + +Values that are not optimized can be fixed automatically, either for one icon or for all of them: + +```sh +pnpm exec eslint --fix icons/my-icon.svg +pnpm run optimize +``` + To check icon names, categories, metadata, and SVG structure together, run: ```sh @@ -88,4 +101,5 @@ Before opening a pull request, confirm that: - The SVG does not use transforms, filters, fills, explicit strokes, or ``. - The icon has a matching JSON metadata file. - `pnpm run lint:icons` passes. +- `pnpm run lint:svg:icons` passes. - `pnpm run lint:json:icons` passes. diff --git a/eslint.config.js b/eslint.config.js index f33c8ce5a..a2181cf16 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -4,15 +4,26 @@ import { includeIgnoreFile } from '@eslint/compat'; import { defineConfig } from 'eslint/config'; import prettier from 'eslint-config-prettier'; import importX, { createNodeResolver } from 'eslint-plugin-import-x'; -import htmlEslint from '@html-eslint/eslint-plugin'; -import htmlParser from '@html-eslint/parser'; import defaultAttrs from './tools/build-icons/render/default-attrs.json' with { type: 'json' }; import tseslint from 'typescript-eslint'; -import jsonSchema from './scripts/eslint/jsonSchemaPlugin.mjs'; +import { jsonSchema, svg } from './tools/eslint-plugin/src/index.ts'; import * as jsoncParser from 'jsonc-eslint-parser'; +import svgoPlugins from './scripts/render/svgoConfig.mts'; const gitignorePath = path.join(import.meta.dirname, '.gitignore'); +// The elements an icon may be drawn with, and the attributes each of them may have. Keep this in +// sync with the `removeAttrs` list in prettier-plugin-lucide-svg.mjs, which strips everything else. +const shapeAttrs = { + path: ['d'], + line: ['x1', 'y1', 'x2', 'y2'], + polygon: ['points'], + polyline: ['points'], + circle: ['cx', 'cy', 'r', 'fill'], + ellipse: ['cx', 'cy', 'rx', 'ry'], + rect: ['x', 'y', 'width', 'height', 'rx', 'ry'], +}; + export default defineConfig([ tseslint.configs.recommended, { @@ -99,59 +110,29 @@ export default defineConfig([ { files: ['./icons/*.svg'], languageOptions: { - parser: htmlParser, + parser: svg.parser, }, plugins: { - '@html-eslint': htmlEslint, + svg, }, rules: { - '@html-eslint/require-doctype': 'off', - '@html-eslint/no-duplicate-attrs': 'error', - '@html-eslint/no-inline-styles': 'error', - '@html-eslint/require-attrs': [ - 'error', - ...Object.entries(defaultAttrs).map(([attr, value]) => ({ - tag: 'svg', - attr, - value: String(value), - })), - ], - '@html-eslint/indent': ['error', 2], - '@html-eslint/no-multiple-empty-lines': ['error', { max: 0 }], - '@html-eslint/no-extra-spacing-attrs': [ + // What an icon may contain, see docs/contribute/icons/code-conventions.md. How it is + // formatted is checked by Prettier, see prettier-plugin-lucide-svg.mjs. + 'svg/no-text': 'error', + 'svg/allowed-elements': ['error', { root: 'svg', children: Object.keys(shapeAttrs) }], + 'svg/allowed-attrs': ['error', { svg: Object.keys(defaultAttrs), ...shapeAttrs }], + 'svg/require-attrs': ['error', { svg: defaultAttrs }], + 'svg/allowed-attr-values': [ 'error', { - enforceBeforeSelfClose: true, - }, - ], - '@html-eslint/attrs-newline': [ - 'error', - { - inline: ['path', 'line', 'polyline', 'polygon', 'rect', 'circle', 'ellipse'], - }, - ], - '@html-eslint/require-closing-tags': [ - 'error', - { - selfClosing: 'always', - // Inside every tag counts as "foreign", where the rule only checks that a tag - // already written `/>` stays that way. Listing the shapes here is what actually forces - // `` to become ``. - selfClosingCustomPatterns: ['^(path|line|polyline|polygon|rect|circle|ellipse)$'], - }, - ], - '@html-eslint/no-restricted-attr-values': [ - 'error', - { - attrPatterns: ['^(fill|stroke)$'], - attrValuePatterns: ['^(?!(none|currentColor)$).*$'], + attrs: ['fill', 'stroke'], + values: ['none', 'currentColor'], message: 'Icons must inherit their colors: `fill` and `stroke` may only be `none` or `currentColor`.', }, ], - '@html-eslint/element-newline': 'error', - '@html-eslint/no-trailing-spaces': 'error', - '@html-eslint/quotes': 'error', + // Icons must stay the way `pnpm optimize` leaves them. Fixable with `eslint --fix`. + 'svg/optimized': ['error', { plugins: svgoPlugins }], }, }, { diff --git a/lint-staged.config.mjs b/lint-staged.config.mjs index 37c788c0a..929743628 100644 --- a/lint-staged.config.mjs +++ b/lint-staged.config.mjs @@ -4,6 +4,8 @@ const config = { 'node ./scripts/optimizeStagedSvgs.mts', 'node ./scripts/generateNextJSAliases.mts', `prettier --write ${filenames.join(' ')}`, + // After formatting, so only what Prettier can't fix is left to report. + `eslint ${filenames.join(' ')}`, ], 'icons/*.json': (filenames) => [ `eslint ${filenames.join(' ')}`, diff --git a/package.json b/package.json index 07a58f1d3..9a40ba9d1 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "test:integrations:vue": "pnpm --filter @lucide/vue build && pnpm -r --workspace-concurrency=1 --filter './integrations/lucide-vue/**' check", "test:integrations:svelte": "pnpm --filter @lucide/svelte build && pnpm -r --workspace-concurrency=1 --filter './integrations/lucide-svelte/**' check", "test:font": "pnpm --filter build-font test", + "test:eslint-plugin": "pnpm --filter @lucide/eslint-plugin test", "test:scripts": "node --test scripts/*.test.mts", "lucide": "pnpm --filter lucide", "lucide-angular": "pnpm --filter lucide-angular", @@ -42,13 +43,14 @@ "lint:icons": "prettier \"icons/*.svg\" --check", "lint:icons-fix": "prettier \"icons/*.svg\" --write", "lint:format:ci": "node ./scripts/lintFormat.mts", + "lint:svg:icons": "eslint 'icons/*.svg'", "lint:json:icons": "eslint 'icons/*.json'", "lint:json:categories": "eslint 'categories/*.json'", "lint:json:groups": "eslint 'groups/*.json'", "lint:json": "eslint 'icons/*.json' 'categories/*.json' 'groups/*.json'", "lint:spelling": "cspell --no-progress 'icons/*.json' 'categories/*.json' 'groups/*.json'", "lint:spelling:ci": "node ./scripts/lintSpelling.mts", - "lint:icons:all": "pnpm run lint:icons && pnpm run lint:json:icons", + "lint:icons:all": "pnpm run lint:icons && pnpm run lint:svg:icons && pnpm run lint:json:icons", "lint": "pnpm lint:es && pnpm lint:format && pnpm lint:json && pnpm lint:spelling && pnpm lint:icons", "format": "prettier \"**/*.{js,mjs,ts,jsx,tsx,html,css,scss,json,yml,yaml}\" --write", "prepare": "husky", @@ -61,15 +63,12 @@ "@actions/github": "catalog:", "@eslint/compat": "catalog:", "@eslint/js": "catalog:", - "@html-eslint/eslint-plugin": "catalog:", - "@html-eslint/parser": "catalog:", "@octokit/rest": "catalog:", "@types/yargs": "catalog:", "@typescript-eslint/eslint-plugin": "catalog:", "@typescript-eslint/parser": "catalog:", "@vitest/coverage-v8": "catalog:", "@vitest/ui": "catalog:", - "ajv": "catalog:", "cpy-cli": "catalog:", "cspell": "catalog:", "eslint": "catalog:", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6c1f4b067..821781a35 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -252,12 +252,6 @@ catalogs: '@headlessui/vue': specifier: ^1.7.23 version: 1.7.23 - '@html-eslint/eslint-plugin': - specifier: ^0.65.0 - version: 0.65.0 - '@html-eslint/parser': - specifier: ^0.65.0 - version: 0.65.0 '@octokit/rest': specifier: ^22.0.1 version: 22.0.1 @@ -745,12 +739,6 @@ importers: '@eslint/js': specifier: 'catalog:' version: 10.0.1(eslint@10.16.0(jiti@2.7.0)(supports-color@10.2.2)) - '@html-eslint/eslint-plugin': - specifier: 'catalog:' - version: 0.65.0(eslint@10.16.0(jiti@2.7.0)(supports-color@10.2.2)) - '@html-eslint/parser': - specifier: 'catalog:' - version: 0.65.0 '@octokit/rest': specifier: 'catalog:' version: 22.0.1 @@ -769,9 +757,6 @@ importers: '@vitest/ui': specifier: 'catalog:' version: 5.0.5(vitest@5.0.5) - ajv: - specifier: 'catalog:' - version: 8.20.0 cpy-cli: specifier: 'catalog:' version: 7.0.0 @@ -2196,6 +2181,28 @@ importers: specifier: 'catalog:' version: 26.6.11 + tools/eslint-plugin: + dependencies: + ajv: + specifier: 'catalog:' + version: 8.20.0 + jsonc-eslint-parser: + specifier: 'catalog:' + version: 3.3.2 + saxes: + specifier: ^6.0.0 + version: 6.0.0 + svgo: + specifier: 'catalog:' + version: 4.1.0 + devDependencies: + '@eslint/core': + specifier: ^1.2.1 + version: 1.2.1 + '@types/node': + specifier: 'catalog:' + version: 26.6.11 + tools/rollup-plugins: dependencies: '@rollup/plugin-node-resolve': @@ -3889,10 +3896,6 @@ packages: resolution: {integrity: sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} - '@eslint/core@0.17.0': - resolution: {integrity: sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@eslint/core@1.2.1': resolution: {integrity: sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} @@ -3918,10 +3921,6 @@ packages: resolution: {integrity: sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} - '@eslint/plugin-kit@0.4.1': - resolution: {integrity: sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@eslint/plugin-kit@0.7.3': resolution: {integrity: sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} @@ -3958,28 +3957,6 @@ packages: peerDependencies: vue: ^3.2.0 - '@html-eslint/core@0.65.0': - resolution: {integrity: sha512-UJUf0dDI6xq6iitksPXrfLwu2Gc143LGFHMlVnRPZxkoLz1xIzKbkQVxrqxqNmandsSmhWfkGw//U2BsBH/QRw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@html-eslint/eslint-plugin@0.65.0': - resolution: {integrity: sha512-zYa4ARNbkp/GPlIY+1NFV5v6H3EDs+jby4/rFnZDaS/S3mFEvBail4+dPqugHljrBmAZ0UkxMATR696ypRvPCQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: '>=8.0.0 || ^10.0.0-0' - - '@html-eslint/parser@0.65.0': - resolution: {integrity: sha512-sMZ8D60uQ/yLKViiqkzX3vnpBwcBNE8x/Ax8roAdrLiErkJ4wLMdXq+kmRm0rqfTuC0mqPJ+7uRTAgUB6wXg2w==} - - '@html-eslint/template-parser@0.65.0': - resolution: {integrity: sha512-gUc9D4PaV5uvQjR21Q1wumbe2Qyf6decJjCZCpM77kZ7mMprIDvnF4LgCJBkTldidc4j1GzJvqkJ5e+r+skFyw==} - - '@html-eslint/template-syntax-parser@0.65.0': - resolution: {integrity: sha512-Kh7TFOM4cYcutzGZdWKxnZJpWpuZwu4hcSxbn/PHVBgDOytKOwpuPvCKn1+B11fSFxLhrrR3RHvsBVknntpcbA==} - - '@html-eslint/types@0.65.0': - resolution: {integrity: sha512-bWMTSRwFXwvturEYvA5ng43+jpFh9FTpAgC2HE3O0ijsde40VcoO6DtcjFl7QY8AW5O/PeisDDl1Hbe5q89wsg==} - '@humanfs/core@0.19.2': resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} engines: {node: '>=18.18.0'} @@ -6615,9 +6592,6 @@ packages: '@rrweb/utils@2.3.1': resolution: {integrity: sha512-04LX4JftJAtwF3wYU1M9OGKvDO0Rky/rKCRBS1UZCkszFadzzXY8gZImj7bmKxWyUWP9pz8Z0hc0yT8VPYA0fQ==} - '@rviscomi/capo.js@2.3.1': - resolution: {integrity: sha512-RW3MxHN/HujvKHgDFEq9+vg+6EeOJSgYSwCQ4c3HwGvHMSQNeW89IsEvAYFkKZDeqjGbblRBwNSJdkbl5RnL3Q==} - '@schematics/angular@22.3.0': resolution: {integrity: sha512-SqnAJfBfDHuoUMDrhMIpkIYQiDI8mgJuQC8YcEzynbWG+eIsmuS17CgYKj69J7o/9ndEQU9lIi9nAEOYDlLVKQ==} engines: {node: ^22.22.3 || ^24.15.0 || >=26.0.0, npm: ^6.11.0 || ^7.5.6 || >=8.0.0, yarn: '>= 1.13.0'} @@ -7202,9 +7176,6 @@ packages: '@types/css-font-loading-module@0.0.7': resolution: {integrity: sha512-nl09VhutdjINdWyXxHWN/w9zlNCfr60JUqJbd24YXUuCwgeL0TpFSdElCwb6cxfB6ybE19Gjj4g0jsgkXxKv1Q==} - '@types/css-tree@2.3.11': - resolution: {integrity: sha512-aEokibJOI77uIlqoBOkVbaQGC9zII0A+JH1kcTNKW2CwyYWD8KM6qdo+4c77wD3wZOQfJuNWAr9M4hdk+YhDIg==} - '@types/debug@4.1.13': resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==} @@ -9401,9 +9372,6 @@ packages: es-get-iterator@1.1.3: resolution: {integrity: sha512-sPZmqHBe6JIiTfN5q2pEi//TwxmAFHwj/XEuYjTuse78i8KxaqMTTzxPoFKuzRpDpTJ+0NAbpfenkmH2rePtuw==} - es-html-parser@0.3.1: - resolution: {integrity: sha512-YTEasG4xt7FEN4b6qJIPbFo/fzQ5kjRMEQ33QMqSXTvfXqAbC2rHxo32x2/1Rhq7Mlu6wI3MIpM5Kf2VHPXrUQ==} - es-module-lexer@1.7.0: resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} @@ -10059,9 +10027,6 @@ packages: html-escaper@3.0.3: resolution: {integrity: sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==} - html-standard@0.0.13: - resolution: {integrity: sha512-6oNfW3c1t44O7jVXu0tp4E5MbHifWlXrHlZBPt6y7vFdgLOUUh8hyzoRhfUgozlBUK6oLLYhqP1uIqbZ8ggcBA==} - html-to-image@1.11.13: resolution: {integrity: sha512-cuOPoI7WApyhBElTTb9oqsawRvZ0rHhaHwghRLlTuffoD1B2aDemlCruLeZrUIIdvG7gs9xeELEPm6PhuASqrg==} @@ -16300,10 +16265,6 @@ snapshots: dependencies: '@eslint/core': 1.2.1 - '@eslint/core@0.17.0': - dependencies: - '@types/json-schema': 7.0.15 - '@eslint/core@1.2.1': dependencies: '@types/json-schema': 7.0.15 @@ -16330,11 +16291,6 @@ snapshots: '@eslint/object-schema@3.0.5': {} - '@eslint/plugin-kit@0.4.1': - dependencies: - '@eslint/core': 0.17.0 - levn: 0.4.1 - '@eslint/plugin-kit@0.7.3': dependencies: '@eslint/core': 1.2.1 @@ -16367,45 +16323,6 @@ snapshots: '@tanstack/vue-virtual': 3.13.57(vue@3.5.46(typescript@6.0.3)) vue: 3.5.46(typescript@6.0.3) - '@html-eslint/core@0.65.0': - dependencies: - '@html-eslint/types': 0.65.0 - html-standard: 0.0.13 - - '@html-eslint/eslint-plugin@0.65.0(eslint@10.16.0(jiti@2.7.0)(supports-color@10.2.2))': - dependencies: - '@eslint/plugin-kit': 0.4.1 - '@html-eslint/core': 0.65.0 - '@html-eslint/parser': 0.65.0 - '@html-eslint/template-parser': 0.65.0 - '@html-eslint/template-syntax-parser': 0.65.0 - '@html-eslint/types': 0.65.0 - '@rviscomi/capo.js': 2.3.1 - eslint: 10.16.0(jiti@2.7.0)(supports-color@10.2.2) - html-standard: 0.0.13 - - '@html-eslint/parser@0.65.0': - dependencies: - '@html-eslint/template-syntax-parser': 0.65.0 - '@html-eslint/types': 0.65.0 - css-tree: 3.2.1 - es-html-parser: 0.3.1 - - '@html-eslint/template-parser@0.65.0': - dependencies: - '@html-eslint/types': 0.65.0 - es-html-parser: 0.3.1 - - '@html-eslint/template-syntax-parser@0.65.0': - dependencies: - '@html-eslint/types': 0.65.0 - - '@html-eslint/types@0.65.0': - dependencies: - '@types/css-tree': 2.3.11 - '@types/estree': 1.0.11 - es-html-parser: 0.3.1 - '@humanfs/core@0.19.2': dependencies: '@humanfs/types': 0.15.0 @@ -19083,8 +19000,6 @@ snapshots: '@rrweb/utils@2.3.1': {} - '@rviscomi/capo.js@2.3.1': {} - '@schematics/angular@22.3.0(chokidar@6.0.0)': dependencies: '@angular-devkit/core': 22.3.0(chokidar@6.0.0) @@ -19808,8 +19723,6 @@ snapshots: '@types/css-font-loading-module@0.0.7': {} - '@types/css-tree@2.3.11': {} - '@types/debug@4.1.13': dependencies: '@types/ms': 2.1.0 @@ -22106,8 +22019,6 @@ snapshots: isarray: 2.0.5 stop-iteration-iterator: 1.1.0 - es-html-parser@0.3.1: {} - es-module-lexer@1.7.0: {} es-module-lexer@2.3.2: {} @@ -22826,11 +22737,6 @@ snapshots: html-escaper@3.0.3: {} - html-standard@0.0.13: - dependencies: - vscode-css-languageservice: 6.3.10 - vscode-languageserver-textdocument: 1.0.16 - html-to-image@1.11.13: {} html-to-text@9.0.5: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index b91cab052..9fe671a0b 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -63,8 +63,6 @@ catalog: '@eslint/js': ^10.0.1 '@floating-ui/vue': ^2.0.1 '@headlessui/vue': ^1.7.23 - '@html-eslint/eslint-plugin': ^0.65.0 - '@html-eslint/parser': ^0.65.0 '@lucide/helpers': '*' '@octokit/rest': ^22.0.1 '@openpanel/web': ^1.4.2 diff --git a/scripts/render/processSvg.mts b/scripts/render/processSvg.mts index cb5c3020d..b183d5f00 100644 --- a/scripts/render/processSvg.mts +++ b/scripts/render/processSvg.mts @@ -2,6 +2,7 @@ import { optimize } from 'svgo'; import * as prettier from 'prettier'; import { parseSync, stringify } from 'svgson'; import DEFAULT_ATTRS from '../../tools/build-icons/render/default-attrs.json' with { type: 'json' }; +import svgoPlugins from './svgoConfig.mts'; /** * Optimize SVG with `svgo`. @@ -12,15 +13,7 @@ async function optimizeSvg(svg: string, path: string) { const result = optimize(svg, { path, plugins: [ - { - name: 'preset-default', - params: { - overrides: { - convertShapeToPath: false, - mergePaths: false, - }, - }, - }, + ...svgoPlugins, { name: 'removeAttrs', params: { @@ -45,7 +38,7 @@ function setAttrs(svg: string) { ...DEFAULT_ATTRS, width: String(DEFAULT_ATTRS.width), height: String(DEFAULT_ATTRS.height), - "stroke-width": String(DEFAULT_ATTRS['stroke-width']), + 'stroke-width': String(DEFAULT_ATTRS['stroke-width']), ...contents.attributes, }; diff --git a/scripts/render/svgoConfig.mts b/scripts/render/svgoConfig.mts new file mode 100644 index 000000000..7a004ce4e --- /dev/null +++ b/scripts/render/svgoConfig.mts @@ -0,0 +1,21 @@ +import type { PluginConfig } from 'svgo'; + +/** + * The SVGO plugins that decide what an optimized icon looks like. + * + * Shared by `pnpm optimize` (see `processSvg.mts`) and the `svg/optimized` ESLint rule (see + * `eslint.config.js`), so that what is linted is exactly what optimizing produces. + */ +const svgoPlugins: PluginConfig[] = [ + { + name: 'preset-default', + params: { + overrides: { + convertShapeToPath: false, + mergePaths: false, + }, + }, + }, +]; + +export default svgoPlugins; diff --git a/tools/eslint-plugin/README.md b/tools/eslint-plugin/README.md new file mode 100644 index 000000000..87cfb216f --- /dev/null +++ b/tools/eslint-plugin/README.md @@ -0,0 +1,14 @@ +# @lucide/eslint-plugin + +A internal used package with the ESLint plugins and formatter used to lint the Lucide repository. They are wired up in the root `eslint.config.js`. + +- `svg`: a strict SVG parser and rules for what an icon in `icons/*.svg` may contain (`svg/no-text`, `svg/allowed-elements`, `svg/allowed-attrs`, `svg/allowed-attr-values`, `svg/require-attrs`), and `svg/optimized`, which reports and fixes every attribute SVGO would write differently. How an icon is formatted is left to Prettier. +- `jsonSchema`: `json-schema/no-invalid`, which validates the icon, category and group JSON files against their JSON Schema. +- `src/githubFormatter.ts`: an ESLint formatter that prints problems as GitHub Actions annotations. + +## Scripts + +```sh +pnpm --filter @lucide/eslint-plugin test +pnpm --filter @lucide/eslint-plugin typecheck +``` diff --git a/tools/eslint-plugin/package.json b/tools/eslint-plugin/package.json new file mode 100644 index 000000000..fe96215d4 --- /dev/null +++ b/tools/eslint-plugin/package.json @@ -0,0 +1,25 @@ +{ + "name": "@lucide/eslint-plugin", + "description": "A internal used package with the ESLint plugins and formatter used to lint the Lucide repository.", + "private": true, + "version": "1.0.0", + "main": "src/index.ts", + "types": "src/index.ts", + "type": "module", + "scripts": { + "test": "vitest run", + "typecheck": "tsc" + }, + "author": "", + "license": "ISC", + "dependencies": { + "ajv": "catalog:", + "jsonc-eslint-parser": "catalog:", + "saxes": "^6.0.0", + "svgo": "catalog:" + }, + "devDependencies": { + "@eslint/core": "^1.2.1", + "@types/node": "catalog:" + } +} diff --git a/scripts/eslint/githubFormatter.mjs b/tools/eslint-plugin/src/githubFormatter.ts similarity index 81% rename from scripts/eslint/githubFormatter.mjs rename to tools/eslint-plugin/src/githubFormatter.ts index e4eb1cc82..919d6613e 100644 --- a/scripts/eslint/githubFormatter.mjs +++ b/tools/eslint-plugin/src/githubFormatter.ts @@ -1,4 +1,5 @@ import path from 'node:path'; +import type { ESLint } from 'eslint'; /** * ESLint formatter for GitHub Actions. Prints each problem as a readable line plus a workflow @@ -7,18 +8,17 @@ import path from 'node:path'; * Unlike setup-node's `eslint-stylish` problem matcher, this also annotates parsing errors, which * have no rule id. * - * Usage: eslint --format ./scripts/eslint/githubFormatter.mjs + * Usage: eslint --format ./tools/eslint-plugin/src/githubFormatter.ts */ /** Escape data for a workflow command, see https://github.com/actions/toolkit/blob/main/packages/core/src/command.ts */ -const escapeData = (/** @type {string} */ value) => +const escapeData = (value: string) => value.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A'); -const escapeProperty = (/** @type {string} */ value) => +const escapeProperty = (value: string) => escapeData(value).replaceAll(':', '%3A').replaceAll(',', '%2C'); -/** @type {import('eslint').ESLint.FormatterFunction} */ -const formatter = (results) => { - const lines = []; +const formatter: ESLint.FormatterFunction = (results) => { + const lines: string[] = []; let errors = 0; let warnings = 0; @@ -48,8 +48,7 @@ const formatter = (results) => { } if (errors + warnings > 0) { - const plural = (/** @type {number} */ count, /** @type {string} */ word) => - `${count} ${word}${count === 1 ? '' : 's'}`; + const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}`; lines.push( '', `✖ ${plural(errors + warnings, 'problem')} (${plural(errors, 'error')}, ${plural(warnings, 'warning')})`, diff --git a/tools/eslint-plugin/src/index.ts b/tools/eslint-plugin/src/index.ts new file mode 100644 index 000000000..96a099f7c --- /dev/null +++ b/tools/eslint-plugin/src/index.ts @@ -0,0 +1,2 @@ +export { default as jsonSchema } from './jsonSchema.ts'; +export { default as svg } from './svg/index.ts'; diff --git a/scripts/eslint/jsonSchemaPlugin.mjs b/tools/eslint-plugin/src/jsonSchema.ts similarity index 70% rename from scripts/eslint/jsonSchemaPlugin.mjs rename to tools/eslint-plugin/src/jsonSchema.ts index 7a317fea9..9e8f9b4dd 100644 --- a/scripts/eslint/jsonSchemaPlugin.mjs +++ b/tools/eslint-plugin/src/jsonSchema.ts @@ -1,7 +1,10 @@ import fs from 'node:fs'; import path from 'node:path'; +import type { RuleDefinition } from '@eslint/core'; +import type { ValidateFunction } from 'ajv'; import { Ajv2020 } from 'ajv/dist/2020.js'; -import { getStaticJSONValue } from 'jsonc-eslint-parser'; +import type { ESLint, Linter, SourceCode } from 'eslint'; +import { type AST, type RuleListener, getStaticJSONValue } from 'jsonc-eslint-parser'; /** * ESLint plugin that validates JSON files against a configured JSON Schema (draft 2020-12), @@ -12,12 +15,21 @@ import { getStaticJSONValue } from 'jsonc-eslint-parser'; * which silently skips 2020-12 keywords such as `dependentRequired`. */ -const ajv = new Ajv2020({ allErrors: true }); -/** @type {Map} */ -const validators = new Map(); +/** A rule for the tree `jsonc-eslint-parser` produces, with `Options` as its `context.options`. */ +type JsonRule = RuleDefinition<{ + LangOptions: Linter.LanguageOptions; + Code: SourceCode; + RuleOptions: Options; + Visitor: RuleListener; + Node: AST.JSONNode; + MessageIds: string; + ExtRuleDocs: Record; +}>; -/** @param {string} schemaPath */ -const getValidator = (schemaPath) => { +const ajv = new Ajv2020({ allErrors: true }); +const validators = new Map(); + +const getValidator = (schemaPath: string) => { let validate = validators.get(schemaPath); if (!validate) { validate = ajv.compile(JSON.parse(fs.readFileSync(schemaPath, 'utf-8'))); @@ -29,26 +41,23 @@ const getValidator = (schemaPath) => { /** * Find the AST node for a JSON pointer (e.g. `/aliases/0/name`). Returns the property node for * object members so the report points at the key, falling back to the closest existing parent. - * - * @param {any} node - * @param {string} pointer */ -const findNode = (node, pointer) => { +const findNode = (node: AST.JSONExpression, pointer: string) => { const segments = pointer .split('/') .slice(1) .map((segment) => segment.replaceAll('~1', '/').replaceAll('~0', '~')); let current = node; - let reportNode = node; + let reportNode: AST.JSONExpression | AST.JSONProperty = node; for (const segment of segments) { - if (current?.type === 'JSONObjectExpression') { + if (current.type === 'JSONObjectExpression') { const property = current.properties.find( - (/** @type {any} */ prop) => (prop.key.value ?? prop.key.name) === segment, + ({ key }) => ('name' in key ? key.name : key.value) === segment, ); if (!property) break; reportNode = property; current = property.value; - } else if (current?.type === 'JSONArrayExpression') { + } else if (current.type === 'JSONArrayExpression') { const element = current.elements[Number(segment)]; if (!element) break; reportNode = element; @@ -60,8 +69,14 @@ const findNode = (node, pointer) => { return { node: current, reportNode }; }; -/** @type {import('eslint').Rule.RuleModule} */ -const noInvalid = { +type Options = [ + { + /** Path to the schema, relative to the ESLint working directory (the repo root). */ + schema: string; + }, +]; + +const noInvalid: JsonRule = { meta: { type: 'problem', docs: { @@ -71,7 +86,6 @@ const noInvalid = { { type: 'object', properties: { - // Path to the schema, relative to the ESLint working directory (the repo root). schema: { type: 'string' }, }, required: ['schema'], @@ -81,7 +95,6 @@ const noInvalid = { }, create(context) { return { - /** @param {any} program */ Program(program) { const root = program.body[0]?.expression; if (root?.type !== 'JSONObjectExpression') { @@ -90,7 +103,7 @@ const noInvalid = { } const data = getStaticJSONValue(root); - if (typeof data?.$schema !== 'string') { + if (typeof data.$schema !== 'string') { context.report({ node: root, message: 'Missing `$schema` field.' }); return; } @@ -116,14 +129,15 @@ const noInvalid = { const { node, reportNode } = findNode(root, error.instancePath); const location = error.instancePath || '(root)'; - if (error.keyword === 'additionalProperties' && node?.type === 'JSONObjectExpression') { + if (error.keyword === 'additionalProperties' && node.type === 'JSONObjectExpression') { + const additionalProperty: string = error.params.additionalProperty; const property = findNode( node, - `/${error.params.additionalProperty.replaceAll('~', '~0').replaceAll('/', '~1')}`, + `/${additionalProperty.replaceAll('~', '~0').replaceAll('/', '~1')}`, ).reportNode; context.report({ node: property, - message: `${location} has unexpected property "${error.params.additionalProperty}".`, + message: `${location} has unexpected property "${additionalProperty}".`, }); continue; } @@ -141,7 +155,9 @@ const noInvalid = { }, }; -export default { +const plugin = { meta: { name: 'json-schema' }, rules: { 'no-invalid': noInvalid }, -}; +} satisfies ESLint.Plugin; + +export default plugin; diff --git a/tools/eslint-plugin/src/svg/index.ts b/tools/eslint-plugin/src/svg/index.ts new file mode 100644 index 000000000..f4037f62d --- /dev/null +++ b/tools/eslint-plugin/src/svg/index.ts @@ -0,0 +1,36 @@ +import type { ESLint, Linter } from 'eslint'; +import * as parser from './parser.ts'; +import allowedAttrValues from './rules/allowed-attr-values.ts'; +import allowedAttrs from './rules/allowed-attrs.ts'; +import allowedElements from './rules/allowed-elements.ts'; +import noText from './rules/no-text.ts'; +import optimized from './rules/optimized.ts'; +import requireAttrs from './rules/require-attrs.ts'; + +/** + * ESLint plugin that checks what an SVG file contains. + * + * Its parser (see `parser.ts`) is strict, so malformed markup is a parsing error instead of being + * silently repaired, and its rules can restrict a file to exactly the elements and attributes an + * icon may have. Use it by setting `languageOptions.parser` to `svg.parser`. + * + * Whether its values are optimized is checked by `optimized`, which compares a file with what SVGO + * makes of it. + * + * How a file is formatted is not checked here. That is up to Prettier, see + * `prettier-plugin-lucide-svg.mjs`. + */ +const plugin = { + meta: { name: 'svg' }, + parser, + rules: { + 'allowed-attr-values': allowedAttrValues, + 'allowed-attrs': allowedAttrs, + 'allowed-elements': allowedElements, + 'no-text': noText, + optimized, + 'require-attrs': requireAttrs, + }, +} satisfies ESLint.Plugin & { parser: Linter.Parser }; + +export default plugin; diff --git a/tools/eslint-plugin/src/svg/parser.spec.ts b/tools/eslint-plugin/src/svg/parser.spec.ts new file mode 100644 index 000000000..888afd8a4 --- /dev/null +++ b/tools/eslint-plugin/src/svg/parser.spec.ts @@ -0,0 +1,159 @@ +import { describe, expect, it } from 'vitest'; +import { type ChildNode, type Element, type Located, parseForESLint } from './parser.ts'; + +const parse = (text: string) => parseForESLint(text).ast; + +/** The root element of a file, or any other node that has to be an element. */ +const element = (node: ChildNode | undefined): Element => { + if (node?.type !== 'Element') throw new Error(`Expected an element, found ${node?.type}`); + return node; +}; + +/** The node types in a list of nodes, each with the source text its range covers. */ +const sources = (text: string, nodes: Array) => + nodes.map((node) => [node.type, text.slice(...node.range)]); + +/** Expect parsing to fail with `message` on the given 1-based line. */ +const expectFailure = (text: string, message: RegExp, line: number) => { + let failure: unknown; + try { + parse(text); + } catch (error) { + failure = error; + } + expect(failure).toBeInstanceOf(SyntaxError); + expect(failure).toMatchObject({ + message: expect.stringMatching(message), + lineNumber: line, + column: expect.any(Number), + }); +}; + +describe('svg parser', () => { + it('parses elements, attributes and their locations', () => { + const text = '\n \n\n'; + const program = parse(text); + const svg = element(program.body[0]); + + expect(program.range).toEqual([0, text.length]); + expect(svg.name).toBe('svg'); + expect(svg.range).toEqual([0, text.length - 1]); + expect(svg.loc).toEqual({ start: { line: 1, column: 0 }, end: { line: 3, column: 6 } }); + expect(text.slice(...svg.openStart.range)).toBe('"], + ['Text', '\n'], + ]); + + const path = element(svg.children[1]); + expect(path.name).toBe('path'); + expect(path.children).toEqual([]); + expect(text.slice(...path.openStart.range)).toBe(' { + const text = + '\n\nb & c<e> '; + const { body } = parse(text); + + expect(sources(text, body.slice(0, -1))).toEqual([ + ['ProcessingInstruction', ''], + ['Text', '\n'], + ['Doctype', ''], + ['Text', '\n'], + ['Comment', ''], + ]); + expect(sources(text, element(body.at(-1)).children)).toEqual([ + ['Text', 'b & c'], + ['Comment', ''], + ['CData', '<e>'], + ['ProcessingInstruction', ''], + ['Text', ' '], + ]); + }); + + it('keeps text in the element it is in', () => { + const text = 'abc'; + const svg = element(parse(text).body[0]); + + expect(sources(text, element(svg.children[0]).children)).toEqual([ + ['Text', 'a'], + ['Element', ''], + ['Text', 'b'], + ]); + expect(sources(text, svg.children)).toEqual([ + ['Element', 'ab'], + ['Text', 'c'], + ]); + }); + + it('counts CRLF as a single line break', () => { + const svg = element(parse('\r\n \r\n').body[0]); + expect(svg.children[1].loc.start).toEqual({ line: 2, column: 2 }); + expect(svg.loc.end).toEqual({ line: 3, column: 6 }); + }); + + it('counts characters outside the BMP the way string indices do', () => { + const emoji = String.fromCodePoint(0x1f600); + const text = `${emoji}`; + const svg = element(parse(text).body[0]); + + expect(sources(text, svg.children)).toEqual([ + ['Text', emoji], + ['Element', ''], + ]); + expect(text.slice(...element(svg.children[1]).attributes[0].range)).toBe('a=""'); + }); + + it('rejects tags that are not closed or do not match', () => { + expectFailure('\n \n', /^Unexpected close tag/, 3); + expectFailure('\n \n', /^Unclosed tag: svg/, 3); + expectFailure('\n', /^Unmatched closing tag: svg/, 2); + expectFailure('\n`. + tokens: [], + comments: [], + ...span(0, text.length), + }, + visitorKeys, + }; +} diff --git a/tools/eslint-plugin/src/svg/rules.spec.ts b/tools/eslint-plugin/src/svg/rules.spec.ts new file mode 100644 index 000000000..b65c354cc --- /dev/null +++ b/tools/eslint-plugin/src/svg/rules.spec.ts @@ -0,0 +1,348 @@ +import { RuleTester } from 'eslint'; +import { describe, it } from 'vitest'; +import svg from './index.ts'; + +RuleTester.describe = describe; +RuleTester.it = it; +RuleTester.itOnly = it.only; + +const ruleTester = new RuleTester({ languageOptions: { parser: svg.parser } }); + +/** An icon in the canonical format, with the given lines inside its ``. */ +const icon = (...lines: string[]) => + [ + '', + ...lines.map((line) => ` ${line}`), + '', + '', + ].join('\n'); + +const heart = icon('', ''); + +ruleTester.run('no-text', svg.rules['no-text'], { + valid: [heart, '\n\t \r\n'], + invalid: [ + { + // https://github.com/lucide-icons/lucide/blob/c2dd25753da3f25d9ddc351ddb0ee72332189692/icons/square-letter-d.svg#L13 + code: icon('', ']', ''), + errors: [ + { + message: 'Unexpected text "]"; only elements are allowed.', + line: 8, + column: 3, + endLine: 8, + endColumn: 4, + }, + ], + }, + { + code: icon('Heart'), + errors: [{ messageId: 'text', data: { text: 'Heart' }, line: 7, column: 10 }], + }, + { + // Reported as one problem, without the whitespace around it. + code: '\n stray\n text here\n\n', + errors: [ + { + messageId: 'text', + data: { text: 'stray text here' }, + line: 2, + column: 3, + endLine: 3, + endColumn: 14, + }, + ], + }, + { + // A no-break space is invisible, but it is not whitespace in XML. + code: '\u00A0', + errors: [{ messageId: 'text', data: { text: '\\u00A0' } }], + }, + { + code: `${'a'.repeat(50)}`, + errors: [{ messageId: 'text', data: { text: `${'a'.repeat(40)}...` } }], + }, + { + code: 'text', + errors: [{ messageId: 'cdata', column: 6, endColumn: 22 }], + }, + ], +}); + +{ + const options = [{ root: 'svg', children: ['path', 'circle'] }]; + + ruleTester.run('allowed-elements', svg.rules['allowed-elements'], { + valid: [{ code: heart, options }], + invalid: [ + { + code: icon('Heart', ''), + options, + errors: [ + { + message: ' is not allowed. Allowed elements: , .', + line: 7, + column: 3, + endColumn: 9, + }, + ], + }, + { + code: '', + options, + errors: [{ message: 'Root element must be , not .' }], + }, + { + // Element names are case-sensitive, and the root may not be nested. + code: icon('', ''), + options, + errors: [ + { messageId: 'notAllowed', data: { name: 'Path', allowed: ', ' } }, + { messageId: 'notAllowed', data: { name: 'svg', allowed: ', ' } }, + ], + }, + { + code: icon('', ' ', ' ', ' ', ''), + options, + errors: [ + { messageId: 'notAllowed', data: { name: 'g', allowed: ', ' }, line: 7 }, + { message: ' must be a direct child of , not of .', line: 8 }, + { message: ' must be a direct child of , not of .', line: 9 }, + ], + }, + ], + }); +} + +{ + const options = [{ svg: ['xmlns', 'width', 'height', 'viewBox'], path: ['d'], circle: [] }]; + + ruleTester.run('allowed-attrs', svg.rules['allowed-attrs'], { + valid: [ + { code: icon('', ''), options }, + // Elements that are not configured are not checked. + { code: icon(''), options }, + ], + invalid: [ + { + code: icon(''), + options, + errors: [ + { + message: 'Attribute "style" is not allowed on . Allowed attributes: "d".', + line: 7, + column: 21, + endColumn: 39, + }, + { messageId: 'notAllowed', data: { name: 'transform', element: 'path', allowed: '"d"' } }, + ], + }, + { + code: '', + options, + errors: [ + { + messageId: 'notAllowed', + data: { + name: 'class', + element: 'svg', + allowed: '"xmlns", "width", "height", "viewBox"', + }, + }, + ], + }, + { + code: icon(''), + options, + errors: [ + { message: 'Attribute "r" is not allowed on , which takes no attributes.' }, + ], + }, + ], + }); +} + +{ + const colors = { attrs: ['fill', 'stroke'], values: ['none', 'currentColor'] }; + + ruleTester.run('allowed-attr-values', svg.rules['allowed-attr-values'], { + valid: [ + { code: '' }, + { code: '', options: [colors] }, + ], + invalid: [ + { + code: '', + options: [colors], + errors: [ + { + message: 'fill="red" is not allowed. Allowed values: "none", "currentColor".', + column: 29, + endColumn: 34, + }, + ], + }, + { + code: '', + options: [ + { ...colors, message: 'Icons must inherit their colors.' }, + { attrs: ['width'], values: [] }, + ], + errors: [ + { message: 'Icons must inherit their colors.', column: 13 }, + { message: 'width="24" is not allowed. Allowed values: .', column: 26 }, + ], + }, + ], + }); +} + +{ + const options = [{ svg: { xmlns: 'http://www.w3.org/2000/svg', width: 24, viewBox: true } }]; + + ruleTester.run('require-attrs', svg.rules['require-attrs'], { + valid: [ + { code: heart, options }, + { + code: '', + options, + }, + // Only the configured elements are checked. + { code: '', options }, + ], + invalid: [ + { + code: '', + options, + errors: [ + { + message: ' is missing the attribute xmlns="http://www.w3.org/2000/svg".', + line: 1, + column: 1, + endColumn: 5, + }, + { message: ' is missing the attribute "viewBox".' }, + ], + }, + { + code: ``, + output: ``, + options, + errors: [ + { + message: 'Expected width="24", but found width="16".', + column: 47, + endColumn: 51, + }, + ], + }, + ], + }); +} + +{ + // The settings of `pnpm optimize`, see scripts/render/svgoConfig.mts. + const options = [ + { + plugins: [ + { + name: 'preset-default', + params: { overrides: { convertShapeToPath: false, mergePaths: false } }, + }, + ], + }, + ]; + + /** A path that is not optimized, with what the fix makes of it. */ + const path = (from: string, to: string) => ({ + code: icon(``), + output: icon(``), + options, + errors: [{ message: `"d" is not optimized. Expected d="${to}".` }], + }); + + ruleTester.run('optimized', svg.rules.optimized, { + valid: [ + { code: heart, options }, + // The order of the attributes is up to the formatter. + { code: icon(''), options }, + { code: icon(''), options }, + // The root element is not compared. + { code: '', options }, + // A file SVGO can't make sense of is left to the other rules. + { code: '', options }, + ], + invalid: [ + // A closing `Z` on a path that already ends where it started. + path( + 'M20.2 20.2c2.04-2.03.02-7.36-4.5-11.9-4.54-4.52-9.87-6.54-11.9-4.5-2.04 2.03-.02 7.36 4.5 11.9 4.54 4.52 9.87 6.54 11.9 4.5Z', + 'M20.2 20.2c2.04-2.03.02-7.36-4.5-11.9-4.54-4.52-9.87-6.54-11.9-4.5-2.04 2.03-.02 7.36 4.5 11.9 4.54 4.52 9.87 6.54 11.9 4.5', + ), + // A last line back to the start, which closing the path draws as well. + path( + 'M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z', + 'M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5z', + ), + // A command that does not move. + path('M12 6.528V3a1 1 0 0 1 1-1h0', 'M12 6.528V3a1 1 0 0 1 1-1'), + // Absolute commands and spaces that take more characters than needed. + path('M 22 14 L 22 10', 'M22 14v-4'), + path('M7 15h4M15 15h2M7 11h2M13 11h4', 'M7 15h4m4 0h2M7 11h2m4 0h4'), + // Arc flags without spaces between them. + path('M18 20v-8a6 6 0 00-12 0v8', 'M18 20v-8a6 6 0 0 0-12 0v8'), + // More decimals than the precision of 3. + path('M16.8607 4.4824A6 6 0 0 0 6 8', 'M16.86 4.482A6 6 0 0 0 6 8'), + { + // Every attribute is reported and fixed on its own, in the quotes it has. + code: icon(``), + output: icon(``), + options, + errors: [ + { + message: '"cx" is not optimized. Expected cx="16".', + line: 7, + column: 14, + endColumn: 20, + }, + { messageId: 'value', data: { name: 'r', expected: '.5' } }, + ], + }, + { + code: icon(''), + output: icon(''), + options, + errors: [{ message: '"id" is redundant, SVGO removes it.', column: 21, endColumn: 30 }], + }, + { + code: icon(''), + output: null, + options, + errors: [ + { + message: 'SVGO turns this into . Optimize the file with SVGO.', + line: 7, + column: 3, + endColumn: 11, + }, + ], + }, + { + // Without knowing which element is gone, nothing can be compared or fixed. + code: icon('', ''), + output: null, + options, + errors: [ + { + message: 'SVGO leaves 1 element(s) of the 2 in here. Optimize the file with SVGO.', + line: 1, + }, + ], + }, + ], + }); +} diff --git a/tools/eslint-plugin/src/svg/rules/allowed-attr-values.ts b/tools/eslint-plugin/src/svg/rules/allowed-attr-values.ts new file mode 100644 index 000000000..a4ed69942 --- /dev/null +++ b/tools/eslint-plugin/src/svg/rules/allowed-attr-values.ts @@ -0,0 +1,55 @@ +import type { SvgRule } from '../types.ts'; +import { list, quoted } from '../utils.ts'; + +export interface Restriction { + attrs: string[]; + values: string[]; + /** Replaces the default message, to explain why. */ + message?: string; +} + +const rule: SvgRule = { + meta: { + type: 'problem', + docs: { description: 'Only allow the listed values for an attribute, on any element' }, + schema: { + type: 'array', + items: { + type: 'object', + properties: { + attrs: { type: 'array', items: { type: 'string' }, minItems: 1, uniqueItems: true }, + values: { type: 'array', items: { type: 'string' }, uniqueItems: true }, + message: { type: 'string' }, + }, + required: ['attrs', 'values'], + additionalProperties: false, + }, + }, + messages: { + notAllowed: '{{name}}="{{value}}" is not allowed. Allowed values: {{allowed}}.', + custom: '{{message}}', + }, + }, + create(context) { + const restrictions = context.options; + + return { + Attribute(node) { + for (const { attrs, values, message } of restrictions) { + if (!attrs.includes(node.name) || values.includes(node.value)) continue; + context.report({ + loc: node.literal.loc, + ...(message + ? { messageId: 'custom', data: { message } } + : { + messageId: 'notAllowed', + data: { name: node.name, value: node.value, allowed: list(values, quoted) }, + }), + }); + } + }, + }; + }, +}; + +export default rule; diff --git a/tools/eslint-plugin/src/svg/rules/allowed-attrs.ts b/tools/eslint-plugin/src/svg/rules/allowed-attrs.ts new file mode 100644 index 000000000..ebead60cb --- /dev/null +++ b/tools/eslint-plugin/src/svg/rules/allowed-attrs.ts @@ -0,0 +1,44 @@ +import type { SvgRule } from '../types.ts'; +import { list, quoted } from '../utils.ts'; + +/** Element name → the attributes it may have. Elements that are not listed are not checked. */ +type Options = [Record]; + +const rule: SvgRule = { + meta: { + type: 'problem', + docs: { description: 'Only allow the listed attributes on an element' }, + schema: [ + { + type: 'object', + additionalProperties: { type: 'array', items: { type: 'string' }, uniqueItems: true }, + }, + ], + messages: { + notAllowed: + 'Attribute "{{name}}" is not allowed on <{{element}}>. Allowed attributes: {{allowed}}.', + none: 'Attribute "{{name}}" is not allowed on <{{element}}>, which takes no attributes.', + }, + }, + create(context) { + const [allowedByElement] = context.options; + + return { + Element(node) { + if (!Object.hasOwn(allowedByElement, node.name)) return; + const allowed = allowedByElement[node.name]; + + for (const attribute of node.attributes) { + if (allowed.includes(attribute.name)) continue; + context.report({ + loc: attribute.loc, + messageId: allowed.length > 0 ? 'notAllowed' : 'none', + data: { name: attribute.name, element: node.name, allowed: list(allowed, quoted) }, + }); + } + }, + }; + }, +}; + +export default rule; diff --git a/tools/eslint-plugin/src/svg/rules/allowed-elements.ts b/tools/eslint-plugin/src/svg/rules/allowed-elements.ts new file mode 100644 index 000000000..fb59dabc2 --- /dev/null +++ b/tools/eslint-plugin/src/svg/rules/allowed-elements.ts @@ -0,0 +1,60 @@ +import type { SvgRule } from '../types.ts'; +import { asTag, list } from '../utils.ts'; + +type Options = [{ root: string; children: string[] }]; + +const rule: SvgRule = { + meta: { + type: 'problem', + docs: { + description: 'Require a given root element that only contains the listed, childless elements', + }, + schema: [ + { + type: 'object', + properties: { + // Name of the root element. + root: { type: 'string' }, + // Elements allowed directly inside the root. They can't have child elements themselves. + children: { type: 'array', items: { type: 'string' }, uniqueItems: true }, + }, + required: ['root', 'children'], + additionalProperties: false, + }, + ], + messages: { + root: 'Root element must be <{{root}}>, not <{{name}}>.', + notAllowed: '<{{name}}> is not allowed. Allowed elements: {{allowed}}.', + nested: '<{{name}}> must be a direct child of <{{root}}>, not of <{{parent}}>.', + }, + }, + create(context) { + const { root, children } = context.options[0]; + + return { + Element(node) { + const { name, parent } = node; + + if (parent.type === 'Program') { + if (name !== root) { + context.report({ loc: node.openStart.loc, messageId: 'root', data: { root, name } }); + } + } else if (!children.includes(name)) { + context.report({ + loc: node.openStart.loc, + messageId: 'notAllowed', + data: { name, allowed: list(children, asTag) }, + }); + } else if (parent.parent.type !== 'Program') { + context.report({ + loc: node.openStart.loc, + messageId: 'nested', + data: { name, root, parent: parent.name }, + }); + } + }, + }; + }, +}; + +export default rule; diff --git a/tools/eslint-plugin/src/svg/rules/no-text.ts b/tools/eslint-plugin/src/svg/rules/no-text.ts new file mode 100644 index 000000000..547e377d9 --- /dev/null +++ b/tools/eslint-plugin/src/svg/rules/no-text.ts @@ -0,0 +1,57 @@ +import type { SvgRule } from '../types.ts'; + +/** Make invisible and non-ASCII characters readable in a message. */ +const visible = (text: string) => + text.replace( + /[^\x20-\x7E]/g, + (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0').toUpperCase()}`, + ); + +const isXmlWhitespace = (char: string) => + char === ' ' || char === '\t' || char === '\r' || char === '\n'; + +const rule: SvgRule = { + meta: { + type: 'problem', + docs: { description: 'Disallow text and CDATA sections' }, + schema: [], + messages: { + text: 'Unexpected text "{{text}}"; only elements are allowed.', + cdata: 'Unexpected CDATA section; only elements are allowed.', + }, + }, + create(context) { + const { sourceCode } = context; + + return { + Text(node) { + // XML whitespace only: a no-break or zero-width space is text, even if it can't be seen. + // Scanned by hand: a trailing `[ \t\r\n]+$` regex backtracks quadratically on long whitespace runs. + const { value } = node; + let from = 0; + let to = value.length; + while (from < to && isXmlWhitespace(value[from])) from += 1; + while (to > from && isXmlWhitespace(value[to - 1])) to -= 1; + if (from === to) return; + + // Report just the text, not the line breaks and indentation around it. + const content = value.slice(from, to); + const start = node.range[0] + from; + const preview = content.replace(/[ \t\r\n]+/g, ' '); + context.report({ + loc: { + start: sourceCode.getLocFromIndex(start), + end: sourceCode.getLocFromIndex(start + content.length), + }, + messageId: 'text', + data: { text: `${visible(preview.slice(0, 40))}${preview.length > 40 ? '...' : ''}` }, + }); + }, + CData(node) { + context.report({ node, messageId: 'cdata' }); + }, + }; + }, +}; + +export default rule; diff --git a/tools/eslint-plugin/src/svg/rules/optimized.ts b/tools/eslint-plugin/src/svg/rules/optimized.ts new file mode 100644 index 000000000..cbf7286bf --- /dev/null +++ b/tools/eslint-plugin/src/svg/rules/optimized.ts @@ -0,0 +1,113 @@ +import { optimize, type Config } from 'svgo'; +import { parseForESLint, type ChildNode, type Element } from '../parser.ts'; +import type { SvgRule } from '../types.ts'; + +/** The SVGO config to optimize with. Without one, SVGO uses its default preset. */ +type Options = [Config?]; + +const elementsIn = (nodes: ChildNode[]) => + nodes.filter((node): node is Element => node.type === 'Element'); + +const rule: SvgRule = { + meta: { + type: 'suggestion', + fixable: 'code', + docs: { + description: 'Require the elements inside the root to be as SVGO would optimize them', + }, + schema: [ + { + type: 'object', + properties: { + plugins: { type: 'array' }, + multipass: { type: 'boolean' }, + floatPrecision: { type: 'number' }, + }, + additionalProperties: false, + }, + ], + messages: { + value: '"{{name}}" is not optimized. Expected {{name}}="{{expected}}".', + redundant: '"{{name}}" is redundant, SVGO removes it.', + element: 'SVGO turns this <{{name}}> into <{{expected}}>. Optimize the file with SVGO.', + count: + 'SVGO leaves {{expected}} element(s) of the {{found}} in here. Optimize the file with SVGO.', + }, + }, + create(context) { + const [config] = context.options; + const { text } = context.sourceCode; + + return { + Program(node) { + let optimized; + try { + optimized = parseForESLint(optimize(text, config).data).ast; + } catch { + // Markup SVGO can't read is not this rule's problem, the parser reports it. + return; + } + + const [root] = elementsIn(node.body); + const [optimizedRoot] = elementsIn(optimized.body); + if (!root || !optimizedRoot) return; + + const children = elementsIn(root.children); + const expected = elementsIn(optimizedRoot.children); + + // Elements are compared by position. If SVGO removed or merged some, that no longer says + // which belongs to which, and a fix would move values to the wrong element. + if (children.length !== expected.length) { + context.report({ + loc: root.openStart.loc, + messageId: 'count', + data: { expected: String(expected.length), found: String(children.length) }, + }); + return; + } + + children.forEach((child, index) => { + const target = expected[index]; + + if (child.name !== target.name) { + context.report({ + loc: child.openStart.loc, + messageId: 'element', + data: { name: child.name, expected: target.name }, + }); + return; + } + + // By name, so the order of the attributes is free. That is formatting. + for (const attribute of child.attributes) { + const { name, quote, literal } = attribute; + const optimizedValue = target.attributes.find((attr) => attr.name === name)?.value; + + if (optimizedValue === undefined) { + // Take the whitespace in front along, so no gap is left behind. + let start = attribute.range[0]; + while (/\s/.test(text[start - 1])) start--; + + context.report({ + loc: attribute.loc, + messageId: 'redundant', + data: { name }, + fix: (fixer) => fixer.removeRange([start, attribute.range[1]]), + }); + } else if (optimizedValue !== attribute.value) { + context.report({ + loc: literal.loc, + messageId: 'value', + data: { name, expected: optimizedValue }, + fix: (fixer) => + fixer.replaceTextRange(literal.range, `${quote}${optimizedValue}${quote}`), + }); + } + } + }); + }, + }; + }, +}; + +export default rule; diff --git a/tools/eslint-plugin/src/svg/rules/require-attrs.ts b/tools/eslint-plugin/src/svg/rules/require-attrs.ts new file mode 100644 index 000000000..30cce6668 --- /dev/null +++ b/tools/eslint-plugin/src/svg/rules/require-attrs.ts @@ -0,0 +1,61 @@ +import type { SvgRule } from '../types.ts'; + +/** Element name → attribute name → the required value, or `true` when any value will do. */ +type Options = [Record>]; + +const rule: SvgRule = { + meta: { + type: 'problem', + fixable: 'code', + docs: { description: 'Require attributes on an element, optionally with an exact value' }, + schema: [ + { + type: 'object', + additionalProperties: { + type: 'object', + additionalProperties: { anyOf: [{ type: ['string', 'number'] }, { const: true }] }, + }, + }, + ], + messages: { + missing: '<{{element}}> is missing the attribute {{expected}}.', + wrongValue: 'Expected {{expected}}, but found {{name}}="{{value}}".', + }, + }, + create(context) { + const [requiredByElement] = context.options; + + return { + Element(node) { + if (!Object.hasOwn(requiredByElement, node.name)) return; + + for (const [name, required] of Object.entries(requiredByElement[node.name])) { + const value = required === true ? null : String(required); + const expected = value === null ? `"${name}"` : `${name}="${value}"`; + const attribute = node.attributes.find((attr) => attr.name === name); + + if (!attribute) { + context.report({ + loc: node.openStart.loc, + messageId: 'missing', + data: { element: node.name, expected }, + }); + } else if (value !== null && attribute.value !== value) { + context.report({ + loc: attribute.literal.loc, + messageId: 'wrongValue', + data: { expected, name, value: attribute.value }, + fix: (fixer) => + fixer.replaceTextRange( + attribute.literal.range, + `${attribute.quote}${value}${attribute.quote}`, + ), + }); + } + } + }, + }; + }, +}; + +export default rule; diff --git a/tools/eslint-plugin/src/svg/types.ts b/tools/eslint-plugin/src/svg/types.ts new file mode 100644 index 000000000..6915d2717 --- /dev/null +++ b/tools/eslint-plugin/src/svg/types.ts @@ -0,0 +1,25 @@ +import type { RuleDefinition } from '@eslint/core'; +import type { Linter, SourceCode } from 'eslint'; +import type { Attribute, Element, Other, Program, Text } from './parser.ts'; + +/** ESLint gives every node a `parent` while it walks the tree. */ +export type ElementNode = Element & { parent: ElementNode | Program }; + +type Visitor = { + Program?: (node: Program) => void; + Element?: (node: ElementNode) => void; + Attribute?: (node: Attribute) => void; + Text?: (node: Text) => void; + CData?: (node: Other) => void; +}; + +/** A rule for the tree `parser.ts` produces, with `Options` as its `context.options`. */ +export type SvgRule = RuleDefinition<{ + LangOptions: Linter.LanguageOptions; + Code: SourceCode; + RuleOptions: Options; + Visitor: Visitor; + Node: Program | Element | Attribute | Text | Other; + MessageIds: string; + ExtRuleDocs: Record; +}>; diff --git a/tools/eslint-plugin/src/svg/utils.ts b/tools/eslint-plugin/src/svg/utils.ts new file mode 100644 index 000000000..017204540 --- /dev/null +++ b/tools/eslint-plugin/src/svg/utils.ts @@ -0,0 +1,6 @@ +/** Format a list of names for a message: `, ` or `"fill", "stroke"`. */ +export const list = (names: string[], format: (name: string) => string) => + names.map(format).join(', '); + +export const asTag = (name: string) => `<${name}>`; +export const quoted = (name: string) => `"${name}"`; diff --git a/tools/eslint-plugin/tsconfig.json b/tools/eslint-plugin/tsconfig.json new file mode 100644 index 000000000..ae7e15132 --- /dev/null +++ b/tools/eslint-plugin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "strict": true, + "declaration": true, + "noEmitOnError": true, + "noFallthroughCasesInSwitch": true, + "moduleResolution": "nodenext", + "module": "nodenext", + "target": "ESNext", + "esModuleInterop": true, + "lib": ["esnext"], + "types": ["node"], + "resolveJsonModule": true, + "skipLibCheck": true, + "allowImportingTsExtensions": true, + "erasableSyntaxOnly": true, + "verbatimModuleSyntax": true, + "noEmit": true, + "sourceMap": true, + "outDir": "./dist" + }, + "include": ["src"] +}