@kirill.konshin/lint 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/configs/nx.js ADDED
@@ -0,0 +1,40 @@
1
+ import jsoncParser from 'jsonc-eslint-parser';
2
+
3
+ import { asOptions, hasNx } from '../lib.js';
4
+
5
+ // lazy so consumers without Nx don't pay the load cost (it drags in a large part of nx itself) -
6
+ // re-exported from index.js
7
+ export const nxPlugin = hasNx ? (await import('@nx/eslint-plugin')).default : null;
8
+
9
+ /**
10
+ * Nx blocks: plugin registration + `@nx/dependency-checks` on every `package.json`.
11
+ *
12
+ * Only `flat/base` (registers the '@nx' plugin, no rules of its own).
13
+ *
14
+ * `flat/typescript`/`flat/javascript` were deliberately NOT used - same call as with eslint-plugin-unicorn's
15
+ * recommended: they bundle the ENTIRE @stylistic plugin (hundreds of formatting rules - indent, quotes,
16
+ * semi, comma-dangle, ...) which would directly fight Prettier, plus a second full copy of
17
+ * @typescript-eslint/recommended that would relitigate rules already configured deliberately here.
18
+ *
19
+ * @param {boolean | import('../index.js').ToggleOptions} [option] the defineLintConfig `nx` flag; auto-detected (workspace `nx.json`) when omitted
20
+ * @returns {Promise<import('eslint').Linter.Config[]>}
21
+ */
22
+ export async function nxConfig(option) {
23
+ const { enabled = hasNx } = asOptions(option);
24
+ if (!enabled) return [];
25
+ const nx = (await import('@nx/eslint-plugin')).default;
26
+ return [
27
+ ...nx.configs['flat/base'],
28
+ {
29
+ name: '@nx/dependency-checks',
30
+ files: ['**/package.json'],
31
+ languageOptions: {
32
+ parser: jsoncParser,
33
+ },
34
+ rules: {
35
+ // https://nx.dev/docs/technologies/eslint/eslint-plugin/guides/dependency-checks
36
+ '@nx/dependency-checks': 'error',
37
+ },
38
+ },
39
+ ];
40
+ }
@@ -0,0 +1,21 @@
1
+ import prettierFlat from 'eslint-config-prettier/flat';
2
+
3
+ /**
4
+ * Prettier compatibility: turns off all rules that would fight the formatter.
5
+ *
6
+ * @see https://github.com/prettier/eslint-plugin-prettier?tab=readme-ov-file#arrow-body-style-and-prefer-arrow-callback-issue
7
+ * Plugin is not recommended by Prettier, they suggest to just use config, and disable all the rules, except for
8
+ * these two in plugin last since they disable some previously set rules:
9
+ * import prettierConfigRecommended from 'eslint-plugin-prettier/recommended';
10
+ * 'arrow-body-style': 'off'
11
+ * 'prefer-arrow-callback': 'off',
12
+ *
13
+ * @see https://nextjs.org/docs/app/api-reference/config/eslint#with-prettier
14
+ * Note the `/flat` suffix here, the difference from default entry is that `/flat` added `name` property to the
15
+ * exported object to improve https://eslint.org/blog/2024/04/eslint-config-inspector/ experience.
16
+ *
17
+ * @returns {import('eslint').Linter.Config[]}
18
+ */
19
+ export function prettierConfig() {
20
+ return [prettierFlat];
21
+ }
@@ -0,0 +1,21 @@
1
+ import promisePlugin from 'eslint-plugin-promise';
2
+
3
+ /**
4
+ * Promise rules: recommended + overrides.
5
+ *
6
+ * @returns {import('eslint').Linter.Config[]}
7
+ */
8
+ export function promiseConfig() {
9
+ return [
10
+ promisePlugin.configs['flat/recommended'],
11
+ {
12
+ name: 'eslint-plugin-promise overrides',
13
+ rules: {
14
+ 'promise/prefer-await-to-then': 'warn',
15
+ 'promise/param-names': 'off',
16
+ 'promise/always-return': 'off',
17
+ 'promise/catch-or-return': 'off',
18
+ },
19
+ },
20
+ ];
21
+ }
@@ -0,0 +1,15 @@
1
+ import { asOptions, hasStorybook } from '../lib.js';
2
+
3
+ /**
4
+ * Storybook recommended rules. `eslint-plugin-storybook` statically imports the `storybook` package
5
+ * itself, so it can only be loaded when Storybook is actually installed - hence the lazy import.
6
+ *
7
+ * @param {boolean | import('../index.js').ToggleOptions} [option] the defineLintConfig `storybook` flag; auto-detected when omitted
8
+ * @returns {Promise<import('eslint').Linter.Config[]>}
9
+ */
10
+ export async function storybookConfig(option) {
11
+ const { enabled = hasStorybook } = asOptions(option);
12
+ if (!enabled) return [];
13
+ const storybookPlugin = (await import('eslint-plugin-storybook')).default;
14
+ return storybookPlugin.configs['flat/recommended'];
15
+ }
@@ -0,0 +1,72 @@
1
+ import { readFileSync } from 'node:fs';
2
+
3
+ import { asOptions, GLOBAL_IGNORES, hasTailwind, scanWorkspace } from '../lib.js';
4
+
5
+ /**
6
+ * Auto-find the Tailwind v4 entry CSS: the single `*.css` below the workspace root (see
7
+ * `scanWorkspace` - up to five directory levels, `.gitignore`- and build-output-aware) containing
8
+ * the Tailwind v4 marker `@import "tailwindcss"`.
9
+ *
10
+ * eslint-plugin-tailwindcss v4 loads the entry (`settings.tailwindcss.cssConfigPath`) and
11
+ * HARD-CRASHES with ENOENT when it can't, so {@link tailwindConfig} only enables the plugin when
12
+ * exactly one entry is found; with zero or several the consumer configures `cssConfigPath`
13
+ * manually (MANDATORY for the plugin) - see README "Tailwind CSS rules".
14
+ *
15
+ * @param {string[]} ignores glob patterns to skip
16
+ * @returns {string | null} absolute path of the single entry, or null when zero or several were found
17
+ */
18
+ export function findTailwindEntry(ignores) {
19
+ const entries = scanWorkspace('*.css', ignores).filter((file) => {
20
+ try {
21
+ return /@import\s+['"]tailwindcss['"]/.test(readFileSync(file, 'utf-8'));
22
+ } catch {
23
+ return false;
24
+ }
25
+ });
26
+
27
+ return entries.length === 1 ? entries[0] : null;
28
+ }
29
+
30
+ /** @typedef {import('../index.js').TailwindOptions} TailwindOptions Defined in index.d.ts. */
31
+
32
+ /**
33
+ * Tailwind recommended rules (warnings + `no-contradicting-classname` as error) as a standalone
34
+ * block (simple to override wholesale).
35
+ *
36
+ * Detection alone isn't enough here: the plugin needs a resolvable entry CSS (see
37
+ * {@link findTailwindEntry}). Explicit `cssConfigPath` wins; otherwise auto-find. Auto-detected +
38
+ * zero-or-several entries stays inert (consumer passes the path manually), but when Tailwind was
39
+ * FORCED on (`true` / options object) the consumer explicitly asked for it, so an empty/ambiguous
40
+ * scan fails loudly instead of silently skipping.
41
+ *
42
+ * @param {boolean | TailwindOptions} [option] the defineLintConfig `tailwind` flag; auto-detected when omitted
43
+ * @returns {Promise<import('eslint').Linter.Config[]>}
44
+ */
45
+ export async function tailwindConfig(option) {
46
+ const { enabled, ...options } = asOptions(option);
47
+ if (!(enabled ?? hasTailwind)) return [];
48
+
49
+ const { cssConfigPath = findTailwindEntry(GLOBAL_IGNORES) } = options;
50
+
51
+ if (!cssConfigPath) {
52
+ // `enabled` is only defined when the consumer explicitly turned Tailwind on - fail loudly
53
+ // then; detection-driven activation (enabled === undefined) stays inert instead.
54
+ if (enabled) {
55
+ throw new Error(
56
+ '[@kirill.konshin/lint] `tailwind` was enabled explicitly, but no single Tailwind v4 entry CSS ' +
57
+ '(a *.css containing `@import "tailwindcss"`, scanned up to 5 directory levels below the ' +
58
+ 'workspace root) was found - zero or several candidates. ' +
59
+ 'Pass `tailwind: { cssConfigPath }` explicitly.',
60
+ );
61
+ }
62
+ return [];
63
+ }
64
+
65
+ const tailwindPlugin = (await import('eslint-plugin-tailwindcss')).default;
66
+ return [
67
+ {
68
+ ...tailwindPlugin.configs.recommended,
69
+ settings: { tailwindcss: { cssConfigPath } },
70
+ },
71
+ ];
72
+ }
@@ -0,0 +1,136 @@
1
+ /*
2
+ * jest/vitest plugins are statically imported even though their recommended sets are gated:
3
+ * the runner-agnostic testConfig() registers both plugins unconditionally (its rules are pure
4
+ * AST checks that work without the runner installed).
5
+ *
6
+ * Each test-runner's recommended rule set is gated on the runner actually being installed - per
7
+ * rules/testing.md ("if project use vite use vitest, otherwise jest"), a project normally has
8
+ * exactly one of these, and applying the other runner's correctness rules to it would be
9
+ * conceptually wrong (even if mechanically harmless, since the rule namespaces don't collide).
10
+ */
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import vitestPlugin from '@vitest/eslint-plugin';
14
+ import jestPlugin from 'eslint-plugin-jest';
15
+
16
+ import { asOptions, hasJest, hasVitest, tsExts, tsExtsRaw } from '../lib.js';
17
+
18
+ export { jestPlugin, vitestPlugin };
19
+
20
+ // derived from the shared extension list - one source of truth with the lint file globs
21
+ const SOURCE_EXTS = tsExtsRaw.split(',').map((ext) => `.${ext}`);
22
+ const TEST_SUFFIX = new RegExp(`\\.test\\.(${tsExtsRaw.replaceAll(',', '|')})$`);
23
+
24
+ /**
25
+ * Custom rule (registered as `local/test-colocation` by {@link testConfig}). Only `*.test.*` is
26
+ * checked, not `*.spec.*` - per testing.md, spec files cover e2e/integration flows that don't map
27
+ * 1:1 to a single sibling source file, so co-location isn't meaningful there.
28
+ */
29
+ const testColocation = {
30
+ meta: {
31
+ type: 'problem',
32
+ docs: {
33
+ description: 'require *.test.* files to sit next to the source file they test, not in a separate folder',
34
+ },
35
+ schema: [],
36
+ messages: {
37
+ missingSibling:
38
+ "No sibling source file found for '{{testFile}}'. Expected e.g. '{{expected}}' in the same directory, not a separate __tests__/ folder.",
39
+ },
40
+ },
41
+ create(context) {
42
+ const base = path.basename(context.filename);
43
+ const match = base.match(TEST_SUFFIX);
44
+
45
+ if (!match) return {};
46
+
47
+ const stem = base.slice(0, -match[0].length);
48
+
49
+ let siblings;
50
+ try {
51
+ siblings = fs.readdirSync(path.dirname(context.filename));
52
+ } catch {
53
+ return {}; // virtual filename (stdin, editor buffer) - no directory to check against
54
+ }
55
+
56
+ if (SOURCE_EXTS.some((ext) => siblings.includes(`${stem}${ext}`))) return {};
57
+
58
+ return {
59
+ Program(node) {
60
+ context.report({
61
+ node,
62
+ messageId: 'missingSibling',
63
+ data: { testFile: base, expected: `${stem}.ts` },
64
+ });
65
+ },
66
+ };
67
+ },
68
+ };
69
+
70
+ /**
71
+ * Jest recommended rules, scoped to test files.
72
+ *
73
+ * @param {boolean | import('../index.js').ToggleOptions} [option] the defineLintConfig `jest` flag; auto-detected when omitted
74
+ * @returns {import('eslint').Linter.Config[]}
75
+ */
76
+ export function jestConfig(option) {
77
+ const { enabled = hasJest } = asOptions(option);
78
+ if (!enabled) return [];
79
+ return [
80
+ {
81
+ ...jestPlugin.configs['flat/recommended'],
82
+ name: 'Jest Rules',
83
+ files: [`**/*.{test,spec}.${tsExts}`],
84
+ },
85
+ ];
86
+ }
87
+
88
+ /**
89
+ * Vitest recommended rules + globals, scoped to test files.
90
+ *
91
+ * @param {boolean | import('../index.js').ToggleOptions} [option] the defineLintConfig `vitest` flag; auto-detected when omitted
92
+ * @returns {import('eslint').Linter.Config[]}
93
+ */
94
+ export function vitestConfig(option) {
95
+ const { enabled = hasVitest } = asOptions(option);
96
+ if (!enabled) return [];
97
+ return [
98
+ {
99
+ ...vitestPlugin.configs.recommended,
100
+ name: 'Vitest Rules',
101
+ files: [`**/*.{test,spec}.${tsExts}`],
102
+ },
103
+ {
104
+ ...vitestPlugin.configs.env,
105
+ name: 'Vitest globals',
106
+ files: [`**/*.{test,spec}.${tsExts}`],
107
+ },
108
+ ];
109
+ }
110
+
111
+ /**
112
+ * Runner-agnostic test rules: pure AST/call-name checking, needs neither jest nor vitest installed
113
+ * to work correctly, so it applies regardless of which one (if either) is present.
114
+ *
115
+ * @returns {import('eslint').Linter.Config[]}
116
+ */
117
+ export function testConfig() {
118
+ return [
119
+ {
120
+ name: 'Test rules',
121
+ files: [`**/*.{test,spec}.${tsExts}`],
122
+ plugins: {
123
+ jest: jestPlugin,
124
+ vitest: vitestPlugin,
125
+ local: { rules: { 'test-colocation': testColocation } },
126
+ },
127
+ rules: {
128
+ 'jest/consistent-test-it': ['error', { fn: 'test' }],
129
+ 'vitest/consistent-test-it': ['error', { fn: 'test' }],
130
+ 'local/test-colocation': 'error',
131
+ 'jest/no-disabled-tests': 'warn',
132
+ 'vitest/no-disabled-tests': 'warn',
133
+ },
134
+ },
135
+ ];
136
+ }
@@ -0,0 +1,29 @@
1
+ import { asOptions, hasTurbo } from '../lib.js';
2
+
3
+ // lazy so consumers without Turbo don't pay the load cost - re-exported from index.js
4
+ export const turboPlugin = hasTurbo ? (await import('eslint-plugin-turbo')).default : null;
5
+
6
+ /**
7
+ * Turborepo rules.
8
+ *
9
+ * @param {boolean | import('../index.js').ToggleOptions} [option] the defineLintConfig `turbo` flag; auto-detected when omitted
10
+ * @returns {Promise<import('eslint').Linter.Config[]>}
11
+ */
12
+ export async function turboConfig(option) {
13
+ const { enabled = hasTurbo } = asOptions(option);
14
+ if (!enabled) return [];
15
+ const turbo = (await import('eslint-plugin-turbo')).default;
16
+ return [
17
+ turbo.configs['flat/recommended'],
18
+ {
19
+ name: 'eslint-plugin-turbo overrides',
20
+ rules: {
21
+ /*
22
+ * Only covers undeclared env vars, not the full dependsOn/outputs consistency - that part has no
23
+ * ESLint-shaped check. Downgraded from their default 'error' to 'warn'.
24
+ */
25
+ 'turbo/no-undeclared-env-vars': 'warn',
26
+ },
27
+ },
28
+ ];
29
+ }
@@ -0,0 +1,109 @@
1
+ import { isAbsolute, relative } from 'node:path';
2
+
3
+ import { asOptions, findWorkspaceRoot } from '../lib.js';
4
+
5
+ /** @typedef {import('../index.js').TypeAwareOptions} TypeAwareOptions Defined in index.d.ts. */
6
+
7
+ /**
8
+ * Type-aware rules. Off by default (FIXME: does not perform) - enable via
9
+ * `defineLintConfig({ typeAware: true })` or by composing this block manually; it is self-contained
10
+ * (wires typescript-eslint's projectService itself).
11
+ *
12
+ * Config files like vite.config.ts and .storybook/{main,preview}.ts sit at the package root or in
13
+ * a dotfolder, outside their tsconfig.json `include` - projectService has no tsconfig to attach
14
+ * them to. `allowDefaultProject` falls back to a synthetic single-file program for these instead
15
+ * of erroring; it has NO default (the layout is project-specific and its patterns may not contain
16
+ * `**` - see README "Type-aware rules" for how to generate the list).
17
+ * `maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING` defaults to the length of
18
+ * `allowDefaultProject` when that list is given (upstream default is 8), and `tsconfigRootDir`
19
+ * defaults to the detected workspace root.
20
+ *
21
+ * @param {boolean | TypeAwareOptions} [option] the defineLintConfig `typeAware` flag; there is
22
+ * nothing to auto-detect, so only an explicit `true` / options object enables the block
23
+ * @returns {import('eslint').Linter.Config[]}
24
+ */
25
+ export function typeAwareConfig(option) {
26
+ let {
27
+ enabled = false,
28
+ allowDefaultProject,
29
+ // matches the list when it's exact files (the scanWorkspace flow); with multi-match globs
30
+ // set the cap explicitly - typescript-eslint errors loudly when matches exceed it
31
+ maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING = allowDefaultProject?.length,
32
+ tsconfigRootDir = findWorkspaceRoot(),
33
+ } = asOptions(option);
34
+ if (!enabled) return [];
35
+
36
+ // typescript-eslint requires allowDefaultProject globs to be RELATIVE to tsconfigRootDir -
37
+ // absolute entries (e.g. produced by scanWorkspace, see README) are relativized automatically
38
+ allowDefaultProject = allowDefaultProject?.map((file) =>
39
+ isAbsolute(file) ? relative(tsconfigRootDir, file) : file,
40
+ );
41
+
42
+ return [
43
+ {
44
+ name: 'Type-aware rules (separate for performance)',
45
+ files: ['**/*.ts', '**/*.tsx', '**/*.mts', '**/*.cts', '**/*.mdx'],
46
+ languageOptions: {
47
+ parserOptions: {
48
+ projectService: {
49
+ ...(allowDefaultProject ? { allowDefaultProject } : {}),
50
+ ...(maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING
51
+ ? { maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING }
52
+ : {}),
53
+ },
54
+ tsconfigRootDir,
55
+ },
56
+ },
57
+ rules: {
58
+ '@typescript-eslint/prefer-optional-chain': 'warn',
59
+ '@typescript-eslint/prefer-nullish-coalescing': 'warn',
60
+
61
+ /**
62
+ * https://typescript-eslint.io/rules/naming-convention/
63
+ *
64
+ * Naming Conventions. Lives here (not 'Custom
65
+ * rules') because the `types: ['boolean']` filter below needs type info too, even
66
+ * though naming-convention as a whole isn't in the typed-linting rule set.
67
+ */
68
+ '@typescript-eslint/naming-convention': [
69
+ 'warn',
70
+ { selector: 'default', format: null },
71
+ /*
72
+ * PascalCase allowed too: this codebase's actual
73
+ * convention is `const Cmp: FC<Props> = memo(...)` - components are PascalCase
74
+ * variables, not just PascalCase function declarations.
75
+ */
76
+ {
77
+ selector: 'variable',
78
+ format: ['camelCase', 'UPPER_CASE', 'PascalCase'],
79
+ leadingUnderscore: 'forbid',
80
+ },
81
+ {
82
+ selector: 'variable',
83
+ types: ['boolean'],
84
+ /*
85
+ * The part AFTER the prefix is naturally capitalized (isLoading, hasError, ...),
86
+ * so it's validated as PascalCase, not camelCase - format here is for the suffix,
87
+ * not the identifier as a whole.
88
+ */
89
+ format: ['PascalCase'],
90
+ prefix: ['is', 'has', 'had', 'can', 'should', 'will', 'did'],
91
+ },
92
+ /*
93
+ * Established exceptions to the boolean-prefix rule above - conventional enough on
94
+ * their own (React's own `loading`/`done` state names, DOM/library `enabled` flags)
95
+ * that requiring is/has/can/should here would just be noise.
96
+ */
97
+ {
98
+ selector: 'variable',
99
+ types: ['boolean'],
100
+ filter: { regex: '^(done|loading|enabled)$', match: true },
101
+ format: ['camelCase'],
102
+ },
103
+ { selector: 'function', format: ['camelCase', 'PascalCase'] },
104
+ { selector: 'class', format: ['PascalCase'] },
105
+ ],
106
+ },
107
+ },
108
+ ];
109
+ }
@@ -0,0 +1,47 @@
1
+ import unicornPlugin from 'eslint-plugin-unicorn';
2
+
3
+ import { tsExts } from '../lib.js';
4
+
5
+ /**
6
+ * Filename casing + node: protocol.
7
+ *
8
+ * Deliberately NOT using unicorn.configs['flat/recommended'] - it's 337 rules (it even folds in
9
+ * a few unprefixed core-ESLint rules), extremely opinionated, and far beyond what was asked for.
10
+ * Only the two rules below are actually wanted.
11
+ *
12
+ * @returns {import('eslint').Linter.Config[]}
13
+ */
14
+ export function unicornConfig() {
15
+ return [
16
+ {
17
+ name: 'Unicorn rules',
18
+ files: [`**/*.${tsExts}`],
19
+ plugins: { unicorn: unicornPlugin },
20
+ rules: {
21
+ 'unicorn/filename-case': [
22
+ 'error',
23
+ {
24
+ case: 'camelCase',
25
+ /*
26
+ * code-style.md only mandates FILE names; this repo's own kebab-case package
27
+ * directories (e.g. electron-builder, react-native) are an established convention.
28
+ */
29
+ checkDirectories: false,
30
+ // Next.js App Router mandates these exact hyphenated filenames - not a naming choice.
31
+ ignore: [
32
+ /^not-found\.[jt]sx?$/,
33
+ /^global-error\.[jt]sx?$/,
34
+ /^opengraph-image\.[jt]sx?$/,
35
+ /^twitter-image\.[jt]sx?$/,
36
+ /^apple-icon\.[jt]sx?$/,
37
+ /^mdx-components\.[jt]sx?$/,
38
+ /\.d\.tsx?$/,
39
+ /^electron-builder\..+$/,
40
+ ],
41
+ },
42
+ ],
43
+ 'unicorn/prefer-node-protocol': 'error',
44
+ },
45
+ },
46
+ ];
47
+ }