twenty/packages/twenty-oxlint-rules/rules/sort-css-properties-alphabetically.ts
Charles Bochet 9d57bc39e5
Migrate from ESLint to OxLint (#18443)
## Summary

Fully replaces ESLint with OxLint across the entire monorepo:

- **Replaced all ESLint configs** (`eslint.config.mjs`) with OxLint
configs (`.oxlintrc.json`) for every package: `twenty-front`,
`twenty-server`, `twenty-emails`, `twenty-ui`, `twenty-shared`,
`twenty-sdk`, `twenty-zapier`, `twenty-docs`, `twenty-website`,
`twenty-apps/*`, `create-twenty-app`
- **Migrated custom lint rules** from ESLint plugin format to OxLint JS
plugin system (`@oxlint/plugins`), including
`styled-components-prefixed-with-styled`, `no-hardcoded-colors`,
`sort-css-properties-alphabetically`,
`graphql-resolvers-should-be-guarded`,
`rest-api-methods-should-be-guarded`, `max-consts-per-file`, and
Jotai-related rules
- **Migrated custom rule tests** from ESLint `RuleTester` + Jest to
`oxlint/plugins-dev` `RuleTester` + Vitest
- **Removed all ESLint dependencies** from `package.json` files and
regenerated lockfiles
- **Updated Nx targets** (`lint`, `lint:diff-with-main`, `fmt`) in
`nx.json` and per-project `project.json` to use `oxlint` commands with
proper `dependsOn` for plugin builds
- **Updated CI workflows** (`.github/workflows/ci-*.yaml`) — no more
ESLint executor
- **Updated IDE setup**: replaced `dbaeumer.vscode-eslint` with
`oxc.oxc-vscode` extension, configured `source.fixAll.oxc` and
format-on-save with Prettier
- **Replaced all `eslint-disable` comments** with `oxlint-disable`
equivalents across the codebase
- **Updated docs** (`twenty-docs`) to reference OxLint instead of ESLint
- **Renamed** `twenty-eslint-rules` package to `twenty-oxlint-rules`

### Temporarily disabled rules (tracked in `OXLINT_MIGRATION_TODO.md`)

| Rule | Package | Violations | Auto-fixable |
|------|---------|-----------|-------------|
| `twenty/sort-css-properties-alphabetically` | twenty-front | 578 | Yes
|
| `typescript/consistent-type-imports` | twenty-server | 3814 | Yes |
| `twenty/max-consts-per-file` | twenty-server | 94 | No |

### Dropped plugins (no OxLint equivalent)

`eslint-plugin-project-structure`, `lingui/*`, `@stylistic/*`,
`import/order`, `prefer-arrow/prefer-arrow-functions`,
`eslint-plugin-mdx`, `@next/eslint-plugin-next`,
`eslint-plugin-storybook`, `eslint-plugin-react-refresh`. Partial
coverage for `jsx-a11y` and `unused-imports`.

### Additional fixes (pre-existing issues exposed by merge)

- Fixed `EmailThreadPreview.tsx` broken import from main rename
(`useOpenEmailThreadInSidePanel`)
- Restored truthiness guard in `getActivityTargetObjectRecords.ts`
- Fixed `AgentTurnResolver` return types to match entity (virtual
`fileMediaType`/`fileUrl` are resolved via `@ResolveField()`)

## Test plan

- [x] `npx nx lint twenty-front` passes
- [x] `npx nx lint twenty-server` passes
- [x] `npx nx lint twenty-docs` passes
- [x] Custom oxlint rules validated with Vitest: `npx nx test
twenty-oxlint-rules`
- [x] `npx nx typecheck twenty-front` passes
- [x] `npx nx typecheck twenty-server` passes
- [x] CI workflows trigger correctly with `dependsOn:
["twenty-oxlint-rules:build"]`
- [x] IDE linting works with `oxc.oxc-vscode` extension
2026-03-06 01:03:50 +01:00

270 lines
6.4 KiB
TypeScript

import postcss from 'postcss';
import { defineRule } from '@oxlint/plugins';
export const RULE_NAME = 'sort-css-properties-alphabetically';
interface Loc {
start: {
line: number;
column: number;
};
end: {
line: number;
column: number;
};
}
const isMemberExpression = (node: any): boolean =>
node.type === 'MemberExpression';
const isCallExpression = (node: any): boolean =>
node.type === 'CallExpression';
const isStyledTagname = (node: any): boolean => {
if (node.tag?.type === 'Identifier') {
return node.tag.name === 'css';
}
if (
isMemberExpression(node.tag) &&
node.tag.object?.type === 'Identifier'
) {
return node.tag.object.name === 'styled';
}
if (
isCallExpression(node.tag) &&
node.tag.callee?.type === 'Identifier'
) {
return node.tag.callee.name === 'styled';
}
if (
isCallExpression(node.tag) &&
isMemberExpression(node.tag.callee) &&
node.tag.callee.object?.type === 'Identifier'
) {
return node.tag.callee.object.name === 'styled';
}
if (
isCallExpression(node.tag) &&
isMemberExpression(node.tag.callee) &&
isMemberExpression(node.tag.callee.object) &&
node.tag.callee.object.object?.type === 'Identifier'
) {
return node.tag.callee.object.object.name === 'styled';
}
return false;
};
const isValidAtomicRule = (
rule: postcss.Rule,
): { isValid: boolean; loc?: Loc } => {
const decls = rule.nodes.filter(
(node) => node.type === 'decl',
) as unknown as postcss.Declaration[];
const invalidDeclIndex = decls.findIndex((decl, index) => {
if (index === 0) return false;
const current = decl.prop;
const prev = decls[index - 1].prop;
return current < prev;
});
return invalidDeclIndex > 0
? {
isValid: false,
loc: {
start: {
line: decls[invalidDeclIndex - 1].source!.start!.line,
column:
decls[invalidDeclIndex - 1].source!.start!.column - 1,
},
end: {
line: decls[invalidDeclIndex].source!.end!.line,
column: decls[invalidDeclIndex].source!.end!.column - 1,
},
},
}
: { isValid: true };
};
const isValidRule = (
rule: postcss.Rule,
): { isValid: boolean; loc?: Loc } => {
const { isValid, loc } = rule.nodes.reduce<{
isValid: boolean;
loc?: Loc;
}>(
(map, node) => {
return node.type === 'rule' ? isValidRule(node) : map;
},
{ isValid: true },
);
if (!isValid) {
return { isValid, loc };
}
return isValidAtomicRule(rule);
};
const getNodeStyles = (node: any): string => {
const [firstQuasi, ...quasis] = node.quasi.quasis;
const lineBreakCount = node.quasi.loc.start.line - 1;
let styles = `${'\n'.repeat(lineBreakCount)}${' '.repeat(
node.quasi.loc.start.column + 1,
)}${firstQuasi.value.raw}`;
quasis.forEach(({ value, loc }: any, idx: number) => {
const prevLoc = idx === 0 ? firstQuasi.loc : quasis[idx - 1].loc;
const lineBreaksCount = loc.start.line - prevLoc.end.line;
const spacesCount =
loc.start.line === prevLoc.end.line
? loc.start.column - prevLoc.end.column + 2
: loc.start.column + 1;
styles = `${styles}${' '}${'\n'.repeat(lineBreaksCount)}${' '.repeat(
spacesCount,
)}${value.raw}`;
});
return styles;
};
const fix = ({
rule,
fixer,
src,
}: {
rule: postcss.Rule;
fixer: any;
src: any;
}): any[] => {
const fixings = rule.nodes
.filter((node): node is postcss.Rule => node.type === 'rule')
.flatMap((node) => fix({ rule: node, fixer, src }));
const declarations = rule.nodes.filter(
(node): node is postcss.Declaration => node.type === 'decl',
);
const sortedDeclarations = sortDeclarations(declarations);
return [
...fixings,
...declarations.flatMap((decl, index) => {
if (!areSameDeclarations(decl, sortedDeclarations[index])) {
try {
const range = getDeclRange({ decl, src });
const sortedDeclText = getDeclText({
decl: sortedDeclarations[index],
src,
});
return [
fixer.removeRange([range.startIdx, range.endIdx + 1]),
fixer.insertTextAfterRange(
[range.startIdx, range.startIdx],
sortedDeclText,
),
];
} catch (e) {
console.log(e);
}
}
}),
];
};
const areSameDeclarations = (
a: postcss.ChildNode,
b: postcss.ChildNode,
): boolean =>
a.source!.start!.line === b.source!.start!.line &&
a.source!.start!.column === b.source!.start!.column;
const getDeclRange = ({
decl,
src,
}: {
decl: postcss.ChildNode;
src: any;
}): { startIdx: number; endIdx: number } => {
const loc = {
start: {
line: decl.source!.start!.line,
column: decl.source!.start!.column - 1,
},
end: {
line: decl.source!.end!.line,
column: decl.source!.end!.column - 1,
},
};
const startIdx = src.getIndexFromLoc(loc.start);
const endIdx = src.getIndexFromLoc(loc.end);
return { startIdx, endIdx };
};
const getDeclText = ({
decl,
src,
}: {
decl: postcss.ChildNode;
src: any;
}) => {
const { startIdx, endIdx } = getDeclRange({ decl, src });
return src.getText().substring(startIdx, endIdx + 1);
};
const sortDeclarations = (declarations: postcss.Declaration[]) =>
declarations
.slice()
.sort((declA, declB) => (declA.prop > declB.prop ? 1 : -1));
export const rule = defineRule({
meta: {
docs: {
description: 'Styles are sorted alphabetically.',
},
messages: {
sortCssPropertiesAlphabetically:
'Declarations should be sorted alphabetically.',
},
type: 'suggestion',
schema: [],
fixable: 'code',
},
create: (context) => {
return {
TaggedTemplateExpression: (node: any) => {
if (!isStyledTagname(node)) return;
try {
const root = postcss.parse(
getNodeStyles(node),
) as unknown as postcss.Rule;
const { isValid } = isValidRule(root);
if (!isValid) {
return context.report({
node,
messageId: 'sortCssPropertiesAlphabetically',
fix: (fixer) =>
fix({
rule: root,
fixer,
src: context.sourceCode,
}),
});
}
} catch (e) {
return true;
}
},
};
},
});