Skip to content

fix: enforce strict syntax for @charset in no-invalid-at-rules #192

New issue

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

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

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions docs/rules/no-invalid-at-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,15 @@ CSS contains a number of at-rules, each beginning with a `@`, that perform vario
- `@supports`
- `@namespace`
- `@page`
- `@charset`

It's important to use a known at-rule because unknown at-rules cause the browser to ignore the entire block, including any rules contained within. For example:

```css
/* typo */
@charse "UTF-8";
@impor "foo.css";
```

Here, the `@charset` at-rule is incorrectly spelled as `@charse`, which means that it will be ignored.
Here, the `@import` at-rule is incorrectly spelled as `@impor`, which means that it will be ignored.

Each at-rule also has a defined prelude (which may be empty) and potentially one or more descriptors. For example:

Expand Down Expand Up @@ -73,6 +72,29 @@ Examples of **incorrect** code:
}
```

Note on `@charset`: Although it begins with an `@` symbol, it is not an at-rule. It is a specific byte sequence of the following form:

```css
@charset "<charset>";
```

where `charset` is a [`<string>`](https://developer.mozilla.org/en-US/docs/Web/CSS/string) denoting the character encoding to be used. It must be the name of a web-safe character encoding defined in the [IANA-registry](https://www.iana.org/assignments/character-sets/character-sets.xhtml), and must be double-quoted, following exactly one space character (U+0020), and immediately terminated with a semicolon.

Examples of **incorrect** code:

<!-- prettier-ignore -->
```css
@charset 'iso-8859-15'; /* Wrong quotes used */
@charset "UTF-8"; /* More than one space */
@charset UTF-8; /* The charset is a CSS <string> and requires double-quotes */
```

Examples of **correct** code:

```css
@charset "UTF-8";
```

## When Not to Use It

If you are purposely using at-rules that aren't part of the CSS specification, then you can safely disable this rule.
Expand Down
96 changes: 96 additions & 0 deletions src/rules/no-invalid-at-rules.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ import { isSyntaxMatchError } from "../util.js";
// Helpers
//-----------------------------------------------------------------------------

/**
* A valid `@charset` rule must:
* - Enclose the encoding name in double quotes
* - Include exactly one space character after `@charset`
* - End immediately with a semicolon
*/
const charsetPattern = /^@charset "[^"]+";$/u;
const charsetEncodingPattern = /^['"]?([^"';]+)['"]?/u;

/**
* Extracts metadata from an error object.
* @param {SyntaxError} error The error object to extract metadata from.
Expand Down Expand Up @@ -57,6 +66,8 @@ export default {
meta: {
type: "problem",

fixable: "code",

docs: {
description: "Disallow invalid at-rules",
recommended: true,
Expand All @@ -81,8 +92,93 @@ export default {
const { sourceCode } = context;
const lexer = sourceCode.lexer;

/**
* Validates a `@charset` rule for correct syntax:
* - Verifies the rule name is exactly "charset" (case-sensitive)
* - Ensures the rule has a prelude
* - Validates the prelude matches the expected pattern
* @param {AtrulePlain} node The node representing the rule.
*/
function validateCharsetRule(node) {
const { name, prelude, loc } = node;

const charsetNameLoc = {
start: loc.start,
end: {
line: loc.start.line,
column: loc.start.column + name.length + 1,
},
};

if (name !== "charset") {
context.report({
loc: charsetNameLoc,
messageId: "unknownAtRule",
data: {
name,
},
fix(fixer) {
return fixer.replaceTextRange(
[
loc.start.offset,
loc.start.offset + name.length + 1,
],
"@charset",
);
},
});
return;
}

if (!prelude) {
context.report({
loc: charsetNameLoc,
messageId: "missingPrelude",
data: {
name,
},
});
return;
}

const nodeText = sourceCode.getText(node);
if (!charsetPattern.test(nodeText)) {
const preludeText = nodeText.slice(
prelude.loc.start.offset,
prelude.loc.end.offset,
);

const encoding = preludeText.match(charsetEncodingPattern)?.[1];

context.report({
loc: prelude.loc,
messageId: "invalidPrelude",
data: {
name,
prelude: preludeText,
expected: "<string>",
Comment on lines +153 to +159
Copy link
Preview

Copilot AI Jul 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Currently missing semicolon errors are reported as invalidPrelude; consider introducing a distinct messageId (e.g., missingSemicolon) to clearly differentiate terminator errors from prelude syntax issues.

Suggested change
context.report({
loc: prelude.loc,
messageId: "invalidPrelude",
data: {
name,
prelude: preludeText,
expected: "<string>",
const isMissingSemicolon = !nodeText.endsWith(";");
context.report({
loc: prelude.loc,
messageId: isMissingSemicolon ? "missingSemicolon" : "invalidPrelude",
data: {
name,
prelude: preludeText,
expected: isMissingSemicolon ? "; at the end" : "<string>",

Copilot uses AI. Check for mistakes.

},
fix(fixer) {
if (!encoding) {
return null;
}

return fixer.replaceText(
node,
`@charset "${encoding}";`,
);
},
});
}
}

return {
Atrule(node) {
if (node.name.toLowerCase() === "charset") {
validateCharsetRule(node);
return;
}

// checks both name and prelude
const { error } = lexer.matchAtrulePrelude(
node.name,
Expand Down
Loading
Loading