mirror of
https://github.com/lucide-icons/lucide.git
synced 2026-12-03 16:59:42 +00:00
build(dev): replace @html-eslint with a custom SVG ESLint plugin (#5348)
* build(lint): replace @html-eslint with a custom SVG ESLint plugin The HTML parser recovers from malformed markup and has no way to disallow text nodes, so a stray `]` could be committed to an icon. Add scripts/eslint/svgPlugin with its own strict XML parser and rules tailored to the icon code conventions: - no-text: disallow text nodes and CDATA sections - allowed-elements: `<svg>` root containing only shape elements - allowed-attrs: per-element attribute allowlist - the existing checks (required svg attributes, fill/stroke values, duplicate attributes, indentation, spacing, newlines, quotes, self-closing tags, empty lines, trailing spaces) Malformed files (unclosed or mismatched tags, unquoted attributes, several roots) are now parsing errors. Also add a `lint:svg:icons` script, include it in `lint:icons:all`, and run the plugin's tests as part of `test:scripts`. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G9u8FhtVwYGj5HsHrYP3kq * build(lint): run the SVG ESLint rules on staged icons Prettier can't remove a stray text node or a disallowed element, so lint staged icons with ESLint after formatting them. This stops such an icon at commit time instead of in CI. Also document `lint:svg:icons` in the icon code conventions. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G9u8FhtVwYGj5HsHrYP3kq * refactor(lint): parse SVG icons with saxes and leave formatting to Prettier The plugin's hand-written XML parser was large because it validated the markup itself and tracked the position of every attribute, quote and bracket for the formatting rules. Parse with saxes instead, a strict XML parser that is already installed through jsdom. The parser module now only turns its events into a tree with positions. It yields the same tree as before for every icon. Drop the eight formatting rules. A file that passes the Prettier check is identical to Prettier's output, so they could never report anything on it. ESLint now checks what an icon contains and Prettier how it is formatted. `no-duplicate-attrs` goes too, since saxes rejects a duplicate attribute as a parsing error. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G9u8FhtVwYGj5HsHrYP3kq * refactor(lint): move the ESLint plugins to tools/eslint-plugin in TypeScript Move everything in scripts/eslint (the SVG plugin, the JSON Schema plugin and the GitHub formatter) to a workspace package, @lucide/eslint-plugin, next to the other internal tools, and convert it to TypeScript. The package declares its own dependencies (saxes, ajv, jsonc-eslint-parser), so saxes and ajv leave the root manifest. Rules are typed against their own AST nodes instead of `any`. The tests run on vitest like the other tools, through `pnpm test:eslint-plugin`, and a new workflow runs them and the typecheck when the package changes. Rule names and behaviour are unchanged. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G9u8FhtVwYGj5HsHrYP3kq * Add svgo rule * Fix codeQL issue --------- Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
15253adef3
commit
bf07c9ced3
@@ -83,7 +83,6 @@ updates:
|
||||
linting-deps:
|
||||
patterns:
|
||||
- '@eslint/*'
|
||||
- '@html-eslint/*'
|
||||
- '@typescript-eslint/*'
|
||||
- 'angular-eslint'
|
||||
- 'cspell'
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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 `<use>`.
|
||||
- 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.
|
||||
|
||||
+27
-46
@@ -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 <svg> 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
|
||||
// `<path ...></path>` to become `<path ... />`.
|
||||
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 }],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -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(' ')}`,
|
||||
|
||||
+3
-4
@@ -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:",
|
||||
|
||||
Generated
+22
-116
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -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
|
||||
```
|
||||
@@ -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:"
|
||||
}
|
||||
}
|
||||
@@ -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')})`,
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as jsonSchema } from './jsonSchema.ts';
|
||||
export { default as svg } from './svg/index.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<string, import('ajv').ValidateFunction>} */
|
||||
const validators = new Map();
|
||||
/** A rule for the tree `jsonc-eslint-parser` produces, with `Options` as its `context.options`. */
|
||||
type JsonRule<Options extends unknown[]> = RuleDefinition<{
|
||||
LangOptions: Linter.LanguageOptions;
|
||||
Code: SourceCode;
|
||||
RuleOptions: Options;
|
||||
Visitor: RuleListener;
|
||||
Node: AST.JSONNode;
|
||||
MessageIds: string;
|
||||
ExtRuleDocs: Record<string, unknown>;
|
||||
}>;
|
||||
|
||||
/** @param {string} schemaPath */
|
||||
const getValidator = (schemaPath) => {
|
||||
const ajv = new Ajv2020({ allErrors: true });
|
||||
const validators = new Map<string, ValidateFunction>();
|
||||
|
||||
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<Options> = {
|
||||
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;
|
||||
@@ -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;
|
||||
@@ -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<Located & { type: string }>) =>
|
||||
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 = '<svg width="24">\n <path d = \'M1 2\' />\n</svg>\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('<svg');
|
||||
expect(program.body[1]).toEqual({
|
||||
type: 'Text',
|
||||
value: '\n',
|
||||
range: [text.length - 1, text.length],
|
||||
loc: { start: { line: 3, column: 6 }, end: { line: 4, column: 0 } },
|
||||
});
|
||||
|
||||
const [width] = svg.attributes;
|
||||
expect([width.name, width.value, width.quote]).toEqual(['width', '24', '"']);
|
||||
expect(text.slice(...width.range)).toBe('width="24"');
|
||||
expect(text.slice(...width.literal.range)).toBe('"24"');
|
||||
expect(width.loc).toEqual({ start: { line: 1, column: 5 }, end: { line: 1, column: 15 } });
|
||||
|
||||
expect(sources(text, svg.children)).toEqual([
|
||||
['Text', '\n '],
|
||||
['Element', "<path d = 'M1 2' />"],
|
||||
['Text', '\n'],
|
||||
]);
|
||||
|
||||
const path = element(svg.children[1]);
|
||||
expect(path.name).toBe('path');
|
||||
expect(path.children).toEqual([]);
|
||||
expect(text.slice(...path.openStart.range)).toBe('<path');
|
||||
expect(path.loc).toEqual({ start: { line: 2, column: 2 }, end: { line: 2, column: 21 } });
|
||||
|
||||
// Whitespace around "=" belongs to the attribute, the quotes belong to its literal.
|
||||
const [d] = path.attributes;
|
||||
expect([d.name, d.value, d.quote]).toEqual(['d', 'M1 2', "'"]);
|
||||
expect(text.slice(...d.range)).toBe("d = 'M1 2'");
|
||||
expect(text.slice(...d.literal.range)).toBe("'M1 2'");
|
||||
});
|
||||
|
||||
it('tells comments, CDATA, doctypes and processing instructions apart from text', () => {
|
||||
const text =
|
||||
'<?xml version="1.0"?>\n<!DOCTYPE svg>\n<!-- a --><svg>b & c<!-- d --><![CDATA[<e>]]><?f g?> </svg>';
|
||||
const { body } = parse(text);
|
||||
|
||||
expect(sources(text, body.slice(0, -1))).toEqual([
|
||||
['ProcessingInstruction', '<?xml version="1.0"?>'],
|
||||
['Text', '\n'],
|
||||
['Doctype', '<!DOCTYPE svg>'],
|
||||
['Text', '\n'],
|
||||
['Comment', '<!-- a -->'],
|
||||
]);
|
||||
expect(sources(text, element(body.at(-1)).children)).toEqual([
|
||||
['Text', 'b & c'],
|
||||
['Comment', '<!-- d -->'],
|
||||
['CData', '<![CDATA[<e>]]>'],
|
||||
['ProcessingInstruction', '<?f g?>'],
|
||||
['Text', ' '],
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps text in the element it is in', () => {
|
||||
const text = '<svg><g>a<path />b</g>c</svg>';
|
||||
const svg = element(parse(text).body[0]);
|
||||
|
||||
expect(sources(text, element(svg.children[0]).children)).toEqual([
|
||||
['Text', 'a'],
|
||||
['Element', '<path />'],
|
||||
['Text', 'b'],
|
||||
]);
|
||||
expect(sources(text, svg.children)).toEqual([
|
||||
['Element', '<g>a<path />b</g>'],
|
||||
['Text', 'c'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('counts CRLF as a single line break', () => {
|
||||
const svg = element(parse('<svg>\r\n <path />\r\n</svg>').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 = `<svg>${emoji}<path a="" /></svg>`;
|
||||
const svg = element(parse(text).body[0]);
|
||||
|
||||
expect(sources(text, svg.children)).toEqual([
|
||||
['Text', emoji],
|
||||
['Element', '<path a="" />'],
|
||||
]);
|
||||
expect(text.slice(...element(svg.children[1]).attributes[0].range)).toBe('a=""');
|
||||
});
|
||||
|
||||
it('rejects tags that are not closed or do not match', () => {
|
||||
expectFailure('<svg>\n <path>\n</svg>', /^Unexpected close tag/, 3);
|
||||
expectFailure('<svg>\n <path />\n', /^Unclosed tag: svg/, 3);
|
||||
expectFailure('<svg></svg>\n</svg>', /^Unmatched closing tag: svg/, 2);
|
||||
expectFailure('<svg>\n<!-- a</svg>', /^Unclosed tag: svg/, 2);
|
||||
expectFailure('<svg>\n< path /></svg>', /^Disallowed character in tag name/, 2);
|
||||
});
|
||||
|
||||
it('rejects malformed attributes', () => {
|
||||
expectFailure('<svg width></svg>', /^Attribute without value/, 1);
|
||||
expectFailure('<svg width=24></svg>', /^Unquoted attribute value/, 1);
|
||||
expectFailure('<svg a="1"b="2"></svg>', /^No whitespace between attributes/, 1);
|
||||
expectFailure('<svg a="<"></svg>', /^Disallowed character/, 1);
|
||||
expectFailure('<svg\n "a"></svg>', /^Disallowed character in attribute name/, 2);
|
||||
// Reported where the tag ends.
|
||||
expectFailure('<svg\n a="1"\n a="2"\n/>', /^Duplicate attribute: a/, 4);
|
||||
});
|
||||
|
||||
it('rejects references that do not exist', () => {
|
||||
expectFailure('<svg>&foo;</svg>', /^Undefined entity/, 1);
|
||||
expect(() => parse('<svg a="&&&" />')).not.toThrow();
|
||||
});
|
||||
|
||||
it('requires exactly one root element with no text around it', () => {
|
||||
expectFailure('', /^Document must contain a root element/, 1);
|
||||
expectFailure('<svg />\n<svg />', /^Documents may contain only one root/, 2);
|
||||
expectFailure('text\n<svg />', /^Text data outside of root node/, 2);
|
||||
expectFailure('<svg />\ntext\n', /^Text data outside of root node/, 3);
|
||||
expect(() => parse('\n<svg />\n')).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
import { SaxesParser } from 'saxes';
|
||||
|
||||
/**
|
||||
* ESLint parser for SVG files.
|
||||
*
|
||||
* The parsing itself is done by saxes. It is a strict XML parser, so unlike an HTML parser it does
|
||||
* not recover from mistakes: a tag that is never closed, a mismatched closing tag or a duplicate or
|
||||
* unquoted attribute is a parsing error. All that is left to do here is to turn its events into a
|
||||
* tree ESLint can traverse, and to work out where everything is so that rules can point at it.
|
||||
*/
|
||||
|
||||
export interface Position {
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
|
||||
export interface Located {
|
||||
range: [number, number];
|
||||
loc: { start: Position; end: Position };
|
||||
}
|
||||
|
||||
export interface Attribute extends Located {
|
||||
type: 'Attribute';
|
||||
name: string;
|
||||
/** Text between the quotes, with references such as `&` left as is. */
|
||||
value: string;
|
||||
quote: '"' | "'";
|
||||
/** The value including its quotes. */
|
||||
literal: Located;
|
||||
}
|
||||
|
||||
export interface Element extends Located {
|
||||
type: 'Element';
|
||||
name: string;
|
||||
attributes: Attribute[];
|
||||
children: ChildNode[];
|
||||
/** `<name` */
|
||||
openStart: Located;
|
||||
}
|
||||
|
||||
export interface Text extends Located {
|
||||
type: 'Text';
|
||||
value: string;
|
||||
}
|
||||
|
||||
/** Markup that is neither an element nor text. */
|
||||
export interface Other extends Located {
|
||||
type: 'CData' | 'Comment' | 'Doctype' | 'ProcessingInstruction';
|
||||
}
|
||||
|
||||
export type ChildNode = Element | Text | Other;
|
||||
|
||||
export interface Program extends Located {
|
||||
type: 'Program';
|
||||
body: ChildNode[];
|
||||
sourceType: 'module';
|
||||
tokens: never[];
|
||||
comments: never[];
|
||||
}
|
||||
|
||||
export const meta = { name: 'lucide-svg-parser', version: '2.0.0' };
|
||||
|
||||
export const visitorKeys = {
|
||||
Program: ['body'],
|
||||
Element: ['attributes', 'children'],
|
||||
Attribute: [],
|
||||
Text: [],
|
||||
CData: [],
|
||||
Comment: [],
|
||||
Doctype: [],
|
||||
ProcessingInstruction: [],
|
||||
};
|
||||
|
||||
// The same line breaks ESLint splits `sourceCode.lines` on, so positions agree.
|
||||
const LINE_BREAK = /\r\n|[\r\n\u2028\u2029]/gu;
|
||||
|
||||
export function parseForESLint(text: string): { ast: Program; visitorKeys: typeof visitorKeys } {
|
||||
const lineStarts = [0];
|
||||
for (const lineBreak of text.matchAll(LINE_BREAK)) {
|
||||
lineStarts.push(lineBreak.index + lineBreak[0].length);
|
||||
}
|
||||
|
||||
const positionAt = (index: number): Position => {
|
||||
let low = 0;
|
||||
let high = lineStarts.length - 1;
|
||||
while (low < high) {
|
||||
const middle = Math.ceil((low + high) / 2);
|
||||
if (lineStarts[middle] <= index) low = middle;
|
||||
else high = middle - 1;
|
||||
}
|
||||
return { line: low + 1, column: index - lineStarts[low] };
|
||||
};
|
||||
|
||||
const span = (start: number, end: number): Located => ({
|
||||
range: [start, end],
|
||||
loc: { start: positionAt(start), end: positionAt(end) },
|
||||
});
|
||||
|
||||
// saxes reports what it found, not where. But `parser.position` is how far it has read, which
|
||||
// during an event is the end of what the event is about, and the rest follows from that.
|
||||
const parser = new SaxesParser();
|
||||
|
||||
const body: ChildNode[] = [];
|
||||
const openElements: Element[] = [];
|
||||
let attributes: Attribute[] = [];
|
||||
// Where the last piece of markup ended.
|
||||
let end = 0;
|
||||
|
||||
const append = (node: ChildNode) => (openElements.at(-1)?.children ?? body).push(node);
|
||||
|
||||
/**
|
||||
* Locate the piece of markup that ends at `stop`. Text can't contain a `<`, so the markup starts
|
||||
* at the first one after the previous piece, and whatever lies in between is text.
|
||||
*/
|
||||
const markup = (stop = parser.position) => {
|
||||
const start = text.indexOf('<', end);
|
||||
if (start > end) append({ type: 'Text', value: text.slice(end, start), ...span(end, start) });
|
||||
end = stop;
|
||||
return span(start, stop);
|
||||
};
|
||||
|
||||
parser.on('error', (error) => {
|
||||
// saxes puts the position in front of its message, ESLint reports it separately.
|
||||
const message = error.message.replace(/^\d+:\d+: /, '');
|
||||
const { line, column } = positionAt(Math.min(parser.position, text.length));
|
||||
throw Object.assign(new SyntaxError(message[0].toUpperCase() + message.slice(1)), {
|
||||
// ESLint reads the location of a parsing error from these two, both 1-based.
|
||||
lineNumber: line,
|
||||
column: column + 1,
|
||||
});
|
||||
});
|
||||
|
||||
parser.on('attribute', ({ name }) => {
|
||||
const stop = parser.position;
|
||||
const quote = text[stop - 1] as Attribute['quote'];
|
||||
const quoteAt = text.lastIndexOf(quote, stop - 2);
|
||||
// Walk back over `name = ` to where the attribute starts.
|
||||
let start = quoteAt;
|
||||
while (/[ \t\r\n=]/.test(text[start - 1])) start--;
|
||||
start -= name.length;
|
||||
|
||||
attributes.push({
|
||||
type: 'Attribute',
|
||||
name,
|
||||
value: text.slice(quoteAt + 1, stop - 1),
|
||||
quote,
|
||||
literal: span(quoteAt, stop),
|
||||
...span(start, stop),
|
||||
});
|
||||
});
|
||||
|
||||
parser.on('opentag', ({ name }) => {
|
||||
const located = markup();
|
||||
const [start] = located.range;
|
||||
const element: Element = {
|
||||
type: 'Element',
|
||||
name,
|
||||
attributes,
|
||||
children: [],
|
||||
openStart: span(start, start + 1 + name.length),
|
||||
...located,
|
||||
};
|
||||
attributes = [];
|
||||
append(element);
|
||||
openElements.push(element);
|
||||
});
|
||||
|
||||
parser.on('closetag', ({ isSelfClosing }) => {
|
||||
const element = openElements.at(-1);
|
||||
// `<path />` was already covered by its opening tag. Otherwise the element runs up to the end
|
||||
// of the closing tag, and any text in front of that tag still belongs to it.
|
||||
if (element && !isSelfClosing) {
|
||||
markup();
|
||||
element.range[1] = end;
|
||||
element.loc.end = positionAt(end);
|
||||
}
|
||||
openElements.pop();
|
||||
});
|
||||
|
||||
// Everything else only has to be told apart from text.
|
||||
const other =
|
||||
(type: Other['type'], extra = 0) =>
|
||||
() => {
|
||||
append({ type, ...markup(parser.position + extra) });
|
||||
};
|
||||
// saxes reports a comment one character early, before its final `>`.
|
||||
parser.on('comment', other('Comment', 1));
|
||||
parser.on('cdata', other('CData'));
|
||||
parser.on('doctype', other('Doctype'));
|
||||
parser.on('processinginstruction', other('ProcessingInstruction'));
|
||||
parser.on('xmldecl', other('ProcessingInstruction'));
|
||||
|
||||
parser.write(text).close();
|
||||
if (end < text.length)
|
||||
append({ type: 'Text', value: text.slice(end), ...span(end, text.length) });
|
||||
|
||||
return {
|
||||
ast: {
|
||||
type: 'Program',
|
||||
body,
|
||||
sourceType: 'module',
|
||||
// Rules work on the nodes above, so there is no need for a token stream. Leaving comments
|
||||
// out also means a file can't switch rules off with `<!-- eslint-disable -->`.
|
||||
tokens: [],
|
||||
comments: [],
|
||||
...span(0, text.length),
|
||||
},
|
||||
visitorKeys,
|
||||
};
|
||||
}
|
||||
@@ -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 `<svg>`. */
|
||||
const icon = (...lines: string[]) =>
|
||||
[
|
||||
'<svg',
|
||||
' xmlns="http://www.w3.org/2000/svg"',
|
||||
' width="24"',
|
||||
' height="24"',
|
||||
' viewBox="0 0 24 24"',
|
||||
'>',
|
||||
...lines.map((line) => ` ${line}`),
|
||||
'</svg>',
|
||||
'',
|
||||
].join('\n');
|
||||
|
||||
const heart = icon('<path d="M12 8v8" />', '<circle cx="12" cy="12" r="10" />');
|
||||
|
||||
ruleTester.run('no-text', svg.rules['no-text'], {
|
||||
valid: [heart, '<svg>\n\t \r\n</svg>'],
|
||||
invalid: [
|
||||
{
|
||||
// https://github.com/lucide-icons/lucide/blob/c2dd25753da3f25d9ddc351ddb0ee72332189692/icons/square-letter-d.svg#L13
|
||||
code: icon('<path d="M12 8v8" />', ']', '<rect width="18" height="18" x="3" y="3" rx="2" />'),
|
||||
errors: [
|
||||
{
|
||||
message: 'Unexpected text "]"; only elements are allowed.',
|
||||
line: 8,
|
||||
column: 3,
|
||||
endLine: 8,
|
||||
endColumn: 4,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
code: icon('<title>Heart</title>'),
|
||||
errors: [{ messageId: 'text', data: { text: 'Heart' }, line: 7, column: 10 }],
|
||||
},
|
||||
{
|
||||
// Reported as one problem, without the whitespace around it.
|
||||
code: '<svg>\n stray\n text here\n</svg>\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: '<svg>\u00A0</svg>',
|
||||
errors: [{ messageId: 'text', data: { text: '\\u00A0' } }],
|
||||
},
|
||||
{
|
||||
code: `<svg>${'a'.repeat(50)}</svg>`,
|
||||
errors: [{ messageId: 'text', data: { text: `${'a'.repeat(40)}...` } }],
|
||||
},
|
||||
{
|
||||
code: '<svg><![CDATA[text]]></svg>',
|
||||
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('<title>Heart</title>', '<path d="M12 8v8" />'),
|
||||
options,
|
||||
errors: [
|
||||
{
|
||||
message: '<title> is not allowed. Allowed elements: <path>, <circle>.',
|
||||
line: 7,
|
||||
column: 3,
|
||||
endColumn: 9,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
code: '<html />',
|
||||
options,
|
||||
errors: [{ message: 'Root element must be <svg>, not <html>.' }],
|
||||
},
|
||||
{
|
||||
// Element names are case-sensitive, and the root may not be nested.
|
||||
code: icon('<Path />', '<svg />'),
|
||||
options,
|
||||
errors: [
|
||||
{ messageId: 'notAllowed', data: { name: 'Path', allowed: '<path>, <circle>' } },
|
||||
{ messageId: 'notAllowed', data: { name: 'svg', allowed: '<path>, <circle>' } },
|
||||
],
|
||||
},
|
||||
{
|
||||
code: icon('<g>', ' <path d="M12 8v8">', ' <circle />', ' </path>', '</g>'),
|
||||
options,
|
||||
errors: [
|
||||
{ messageId: 'notAllowed', data: { name: 'g', allowed: '<path>, <circle>' }, line: 7 },
|
||||
{ message: '<path> must be a direct child of <svg>, not of <g>.', line: 8 },
|
||||
{ message: '<circle> must be a direct child of <svg>, not of <path>.', line: 9 },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
const options = [{ svg: ['xmlns', 'width', 'height', 'viewBox'], path: ['d'], circle: [] }];
|
||||
|
||||
ruleTester.run('allowed-attrs', svg.rules['allowed-attrs'], {
|
||||
valid: [
|
||||
{ code: icon('<path d="M12 8v8" />', '<circle />'), options },
|
||||
// Elements that are not configured are not checked.
|
||||
{ code: icon('<rect transform="rotate(45)" />'), options },
|
||||
],
|
||||
invalid: [
|
||||
{
|
||||
code: icon('<path d="M12 8v8" style="color: red" transform="rotate(45)" />'),
|
||||
options,
|
||||
errors: [
|
||||
{
|
||||
message: 'Attribute "style" is not allowed on <path>. Allowed attributes: "d".',
|
||||
line: 7,
|
||||
column: 21,
|
||||
endColumn: 39,
|
||||
},
|
||||
{ messageId: 'notAllowed', data: { name: 'transform', element: 'path', allowed: '"d"' } },
|
||||
],
|
||||
},
|
||||
{
|
||||
code: '<svg class="lucide" />',
|
||||
options,
|
||||
errors: [
|
||||
{
|
||||
messageId: 'notAllowed',
|
||||
data: {
|
||||
name: 'class',
|
||||
element: 'svg',
|
||||
allowed: '"xmlns", "width", "height", "viewBox"',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
code: icon('<circle r="1" />'),
|
||||
options,
|
||||
errors: [
|
||||
{ message: 'Attribute "r" is not allowed on <circle>, which takes no attributes.' },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
const colors = { attrs: ['fill', 'stroke'], values: ['none', 'currentColor'] };
|
||||
|
||||
ruleTester.run('allowed-attr-values', svg.rules['allowed-attr-values'], {
|
||||
valid: [
|
||||
{ code: '<svg fill="none" stroke="currentColor"><path fill="currentColor" /></svg>' },
|
||||
{ code: '<svg fill="none"><path fill="currentColor" d="red" /></svg>', options: [colors] },
|
||||
],
|
||||
invalid: [
|
||||
{
|
||||
code: '<svg fill="none"><path fill="red" /></svg>',
|
||||
options: [colors],
|
||||
errors: [
|
||||
{
|
||||
message: 'fill="red" is not allowed. Allowed values: "none", "currentColor".',
|
||||
column: 29,
|
||||
endColumn: 34,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
code: '<svg stroke="#000" width="24" />',
|
||||
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: '<svg xmlns="http://www.w3.org/2000/svg" width="24" viewBox="0 0 16 16" />',
|
||||
options,
|
||||
},
|
||||
// Only the configured elements are checked.
|
||||
{ code: '<g />', options },
|
||||
],
|
||||
invalid: [
|
||||
{
|
||||
code: '<svg\n width="24"\n/>',
|
||||
options,
|
||||
errors: [
|
||||
{
|
||||
message: '<svg> is missing the attribute xmlns="http://www.w3.org/2000/svg".',
|
||||
line: 1,
|
||||
column: 1,
|
||||
endColumn: 5,
|
||||
},
|
||||
{ message: '<svg> is missing the attribute "viewBox".' },
|
||||
],
|
||||
},
|
||||
{
|
||||
code: `<svg xmlns="http://www.w3.org/2000/svg" width='16' viewBox="" />`,
|
||||
output: `<svg xmlns="http://www.w3.org/2000/svg" width='24' viewBox="" />`,
|
||||
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(`<path d="${from}" />`),
|
||||
output: icon(`<path d="${to}" />`),
|
||||
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('<rect x="2" y="5" width="20" height="14" rx="2" />'), options },
|
||||
{ code: icon('<circle cx="12" cy="12" r=".5" fill="currentColor" />'), options },
|
||||
// The root element is not compared.
|
||||
{ code: '<svg viewBox="0 0 24 24" stroke-width="2.0"><path d="M12 8v8"/></svg>', options },
|
||||
// A file SVGO can't make sense of is left to the other rules.
|
||||
{ code: '<html />', 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(`<circle cx='16.0' cy="13" r="0.5" fill="currentColor" />`),
|
||||
output: icon(`<circle cx='16' cy="13" r=".5" fill="currentColor" />`),
|
||||
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('<path d="M12 8v8" id="line" />'),
|
||||
output: icon('<path d="M12 8v8" />'),
|
||||
options,
|
||||
errors: [{ message: '"id" is redundant, SVGO removes it.', column: 21, endColumn: 30 }],
|
||||
},
|
||||
{
|
||||
code: icon('<ellipse cx="12" cy="12" rx="10" ry="10" />'),
|
||||
output: null,
|
||||
options,
|
||||
errors: [
|
||||
{
|
||||
message: 'SVGO turns this <ellipse> into <circle>. 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('<path d="" />', '<path d="M 22 14 L 22 10" />'),
|
||||
output: null,
|
||||
options,
|
||||
errors: [
|
||||
{
|
||||
message: 'SVGO leaves 1 element(s) of the 2 in here. Optimize the file with SVGO.',
|
||||
line: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -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<Restriction[]> = {
|
||||
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;
|
||||
@@ -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<string, string[]>];
|
||||
|
||||
const rule: SvgRule<Options> = {
|
||||
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;
|
||||
@@ -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<Options> = {
|
||||
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;
|
||||
@@ -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;
|
||||
@@ -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<Options> = {
|
||||
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;
|
||||
@@ -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<string, Record<string, string | number | true>>];
|
||||
|
||||
const rule: SvgRule<Options> = {
|
||||
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;
|
||||
@@ -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<Options extends unknown[] = []> = RuleDefinition<{
|
||||
LangOptions: Linter.LanguageOptions;
|
||||
Code: SourceCode;
|
||||
RuleOptions: Options;
|
||||
Visitor: Visitor;
|
||||
Node: Program | Element | Attribute | Text | Other;
|
||||
MessageIds: string;
|
||||
ExtRuleDocs: Record<string, unknown>;
|
||||
}>;
|
||||
@@ -0,0 +1,6 @@
|
||||
/** Format a list of names for a message: `<path>, <line>` 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}"`;
|
||||
@@ -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"]
|
||||
}
|
||||
Reference in New Issue
Block a user