@kirill.konshin/lint 0.2.0 → 0.3.1
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/README.md +202 -51
- package/configs/base.js +98 -0
- package/configs/imports.js +162 -0
- package/configs/nx.js +48 -0
- package/configs/prettier.js +21 -0
- package/configs/promise.js +21 -0
- package/configs/react.js +262 -0
- package/configs/storybook.js +26 -0
- package/configs/tailwind.js +100 -0
- package/configs/testing.js +158 -0
- package/configs/turbo.js +29 -0
- package/configs/typescriptTypeAware.js +110 -0
- package/configs/unicorn.js +47 -0
- package/index.d.ts +271 -0
- package/index.js +119 -610
- package/lib.js +412 -15
- package/package.json +10 -4
- package/rules/tailwind.md +12 -14
- package/rules/testing.md +5 -4
- package/skills/lint-repo.md +2 -2
- package/findTailwindEntry.js +0 -46
- package/ruleTestColocation.js +0 -50
package/lib.js
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { execSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, symlinkSync, unlinkSync } from 'node:fs';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
5
|
+
import { includeIgnoreFile as includeIgnoreFileCompat } from '@eslint/compat';
|
|
6
|
+
import { globSync } from 'glob';
|
|
7
|
+
|
|
8
|
+
export const tsExtsRaw = 'js,jsx,ts,tsx,cjs,cts,mjs,mts'; // TODO mdx, needs loader
|
|
9
|
+
export const eslintExtsRaw = `${tsExtsRaw},md,mdx,htm,html,vue`;
|
|
10
|
+
export const prettierExtsRaw = 'css,scss,sass,less,yml,yaml,json,json5,jsonc,graphql,graphqls,xml';
|
|
11
|
+
|
|
12
|
+
export const tsExts = `{${tsExtsRaw}}`;
|
|
13
|
+
export const eslintExts = `*.{${eslintExtsRaw}}`;
|
|
14
|
+
export const prettierExts = `*.{${prettierExtsRaw}}`;
|
|
3
15
|
|
|
4
16
|
//TODO coverage, dist, out, build?
|
|
5
17
|
export const GLOBAL_IGNORES = [
|
|
@@ -27,26 +39,411 @@ export function isPackageResolvable(specifier) {
|
|
|
27
39
|
}
|
|
28
40
|
}
|
|
29
41
|
|
|
42
|
+
// lockfiles & workspace manifests only ever live at the workspace root
|
|
43
|
+
const ROOT_MARKERS = [
|
|
44
|
+
'yarn.lock',
|
|
45
|
+
'package-lock.json',
|
|
46
|
+
'pnpm-lock.yaml',
|
|
47
|
+
'pnpm-workspace.yaml',
|
|
48
|
+
'bun.lock',
|
|
49
|
+
'bun.lockb',
|
|
50
|
+
];
|
|
51
|
+
|
|
30
52
|
/**
|
|
31
|
-
*
|
|
32
|
-
* check this is stable across subdirectory / per-package / IDE runs - they all resolve to the same
|
|
33
|
-
* workspace root - and correctly stays negative outside such a workspace.
|
|
53
|
+
* Run a shell command, returning trimmed stdout or null on any failure.
|
|
34
54
|
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
|
|
55
|
+
* @param {string} command
|
|
56
|
+
* @param {string} cwd
|
|
57
|
+
* @returns {string | null}
|
|
58
|
+
*/
|
|
59
|
+
function tryExec(command, cwd) {
|
|
60
|
+
try {
|
|
61
|
+
return (
|
|
62
|
+
execSync(command, {
|
|
63
|
+
cwd,
|
|
64
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
65
|
+
encoding: 'utf-8',
|
|
66
|
+
timeout: 15_000,
|
|
67
|
+
}).trim() || null
|
|
68
|
+
);
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* A workspace-root candidate is only plausible when it is an absolute existing directory that
|
|
76
|
+
* contains (or is) `cwd` - guards against stale env / CLI answers leaking into unrelated
|
|
77
|
+
* directories AND against non-path CLI noise: Yarn 1 has no real `yarn node` command, its
|
|
78
|
+
* run-fallback executes it anyway and prints `yarn node v1.22.22\n...\nDone in 0.06s.` to stdout
|
|
79
|
+
* (verified) - a banner must never be mistaken for a root.
|
|
39
80
|
*
|
|
40
|
-
* @param {string
|
|
81
|
+
* @param {string | undefined} root
|
|
82
|
+
* @param {string} cwd
|
|
41
83
|
* @returns {boolean}
|
|
42
84
|
*/
|
|
43
|
-
|
|
44
|
-
|
|
85
|
+
function isRootOf(root, cwd) {
|
|
86
|
+
if (!root || root.includes('\n') || !isAbsolute(root) || !existsSync(root)) return false;
|
|
87
|
+
const rel = relative(root, cwd);
|
|
88
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Last-resort walk: nearest ancestor with a lockfile / workspace manifest, bounded by `.git`
|
|
93
|
+
* (a marker above the repo boundary belongs to another project; `.git` is a directory in a normal
|
|
94
|
+
* clone but a FILE in worktrees and submodules - existsSync covers both).
|
|
95
|
+
*
|
|
96
|
+
* @param {string} cwd
|
|
97
|
+
* @returns {string}
|
|
98
|
+
*/
|
|
99
|
+
function walkToRootMarker(cwd) {
|
|
100
|
+
let dir = cwd;
|
|
45
101
|
for (;;) {
|
|
46
|
-
if (existsSync(resolve(dir,
|
|
47
|
-
if (existsSync(resolve(dir, '.git'))) return
|
|
102
|
+
if (ROOT_MARKERS.some((marker) => existsSync(resolve(dir, marker)))) return dir;
|
|
103
|
+
if (existsSync(resolve(dir, '.git'))) return dir;
|
|
48
104
|
const parent = dirname(dir);
|
|
49
|
-
if (parent === dir) return
|
|
105
|
+
if (parent === dir) return cwd;
|
|
50
106
|
dir = parent;
|
|
51
107
|
}
|
|
52
108
|
}
|
|
109
|
+
|
|
110
|
+
const workspaceRoots = new Map();
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Workspace root of the consumer project - the anchor for every config-file scan (Tailwind entry,
|
|
114
|
+
* `next.config.*`) and root-file detection (`nx.json`): `process.cwd()` alone is unreliable
|
|
115
|
+
* because lint often runs from INSIDE a package (lint-staged, IDE, `yarn workspace x lint`) while
|
|
116
|
+
* the shared config must see the whole repo.
|
|
117
|
+
*
|
|
118
|
+
* Resolution order, cheapest first - every candidate must contain `cwd` or it is rejected:
|
|
119
|
+
* 1. env the package manager sets for its child processes: `PROJECT_CWD` (Yarn Berry),
|
|
120
|
+
* `npm_config_local_prefix` (npm >= 7, workspace-aware)
|
|
121
|
+
* 2. the package managers' own CLIs (subprocess, slow - hit when e.g. the IDE spawns eslint
|
|
122
|
+
* directly): `pnpm root -w` (dirname of the printed node_modules), Yarn Berry via `yarn node`,
|
|
123
|
+
* and `npm prefix` LAST - it walks up honoring package.json `workspaces` membership, but with
|
|
124
|
+
* no package.json around it echoes cwd back, so anything more specific must win first
|
|
125
|
+
* 3. walking up from `cwd` to the nearest lockfile / workspace manifest, bounded by `.git`
|
|
126
|
+
*
|
|
127
|
+
* TODO verify the whole package end-to-end per manager - Yarn Berry, Yarn Berry PnP, Yarn 1,
|
|
128
|
+
* pnpm, npm - see README "Issues"; so far only root detection was exercised outside this repo.
|
|
129
|
+
*
|
|
130
|
+
* Per-manager reality (all verified empirically):
|
|
131
|
+
* - Yarn Berry: env when spawned by yarn, `yarn node` probe otherwise - both give the root
|
|
132
|
+
* - npm: env when spawned by npm/npx, `npm prefix` otherwise
|
|
133
|
+
* - pnpm: sets NO usable env at all (not even in scripts) - always the `pnpm root -w` probe
|
|
134
|
+
* - Yarn 1 (classic): sets NO root env (only `INIT_CWD` = invocation dir) and has no root
|
|
135
|
+
* command; its `yarn node` banner output is rejected by {@link isRootOf}; classic workspaces
|
|
136
|
+
* resolve via `npm prefix` (same package.json `workspaces` field) or the yarn.lock walk
|
|
137
|
+
*
|
|
138
|
+
* Cached per `cwd` - the CLI probes are expensive and the config is rebuilt on every lint run.
|
|
139
|
+
*
|
|
140
|
+
* @param {string} [cwd]
|
|
141
|
+
* @returns {string} absolute path; `cwd` itself when nothing better was found
|
|
142
|
+
*/
|
|
143
|
+
export function findWorkspaceRoot(cwd = process.cwd()) {
|
|
144
|
+
if (workspaceRoots.has(cwd)) return workspaceRoots.get(cwd);
|
|
145
|
+
|
|
146
|
+
const candidates = [
|
|
147
|
+
() => process.env.PROJECT_CWD,
|
|
148
|
+
() => process.env.npm_config_local_prefix,
|
|
149
|
+
() => {
|
|
150
|
+
const nodeModules = tryExec('pnpm root -w', cwd);
|
|
151
|
+
return nodeModules && dirname(nodeModules);
|
|
152
|
+
},
|
|
153
|
+
() => tryExec(`yarn node -p "process.env.PROJECT_CWD||''"`, cwd),
|
|
154
|
+
() => tryExec('npm prefix', cwd),
|
|
155
|
+
];
|
|
156
|
+
|
|
157
|
+
let root = null;
|
|
158
|
+
for (const candidate of candidates) {
|
|
159
|
+
const value = candidate();
|
|
160
|
+
if (isRootOf(value, cwd)) {
|
|
161
|
+
root = resolve(value);
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
root ??= walkToRootMarker(cwd);
|
|
166
|
+
|
|
167
|
+
workspaceRoots.set(cwd, root);
|
|
168
|
+
return root;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/*
|
|
172
|
+
* Build outputs regularly contain COPIES of the scanned files (compiled css, a next.config.js in a
|
|
173
|
+
* published dist) and would poison the scans even in repos that don't gitignore them. Scan-only -
|
|
174
|
+
* GLOBAL_IGNORES stays the deliberate lint-wide list. `.git` matters for `dot: true` scans.
|
|
175
|
+
*/
|
|
176
|
+
const SCAN_IGNORES = [
|
|
177
|
+
'**/dist',
|
|
178
|
+
'**/build',
|
|
179
|
+
'**/out',
|
|
180
|
+
'**/coverage',
|
|
181
|
+
'**/.next',
|
|
182
|
+
'**/.expo',
|
|
183
|
+
'**/storybook-static',
|
|
184
|
+
'**/.git',
|
|
185
|
+
];
|
|
186
|
+
|
|
187
|
+
// glob's maxDepth counts path segments INCLUDING the filename (verified empirically): 6 → files up
|
|
188
|
+
// to five directory levels below the root, covering packages/<x>/src/styles and apps/<group>/<app>
|
|
189
|
+
const SCAN_DEPTH = 6;
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Glob for config-file candidates below the workspace root (up to five directory levels deep),
|
|
193
|
+
* skipping dot dirs, build outputs, the given ignore patterns and everything in the root
|
|
194
|
+
* `.gitignore`. Anchored to {@link findWorkspaceRoot}, NOT cwd.
|
|
195
|
+
*
|
|
196
|
+
* Public - useful for building consumer file lists (e.g. `typeAware.allowDefaultProject`, see README "Type-aware rules").
|
|
197
|
+
*
|
|
198
|
+
* @param {string} fileGlob e.g. `'*.css'`, `'next.config.*'`
|
|
199
|
+
* @param {string[]} [ignores] extra glob patterns to skip
|
|
200
|
+
* @param {{ dot?: boolean }} [options] `dot` also scans dot directories (e.g. `.storybook`)
|
|
201
|
+
* @returns {string[]} absolute paths
|
|
202
|
+
*/
|
|
203
|
+
export function scanWorkspace(fileGlob, ignores = [], { dot = false } = {}) {
|
|
204
|
+
const root = findWorkspaceRoot();
|
|
205
|
+
|
|
206
|
+
let gitignored = [];
|
|
207
|
+
try {
|
|
208
|
+
// Reuse ESLint's gitignore->minimatch conversion; glob's `ignore` speaks the same language.
|
|
209
|
+
// Negations dropped: glob's ignore cannot un-ignore.
|
|
210
|
+
gitignored = includeIgnoreFileCompat(resolve(root, '.gitignore')).ignores.filter(
|
|
211
|
+
(pattern) => !pattern.startsWith('!'),
|
|
212
|
+
);
|
|
213
|
+
} catch {
|
|
214
|
+
// no .gitignore - the scan is just less filtered
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// `<dir-pattern>/**` variants prune the CONTENTS of ignored directories, not just the dir itself
|
|
218
|
+
const ignore = [...ignores, ...SCAN_IGNORES, ...gitignored].flatMap((pattern) => [
|
|
219
|
+
pattern,
|
|
220
|
+
pattern.endsWith('/') ? `${pattern}**` : `${pattern}/**`,
|
|
221
|
+
]);
|
|
222
|
+
|
|
223
|
+
return globSync(`**/${fileGlob}`, {
|
|
224
|
+
cwd: root,
|
|
225
|
+
maxDepth: SCAN_DEPTH,
|
|
226
|
+
ignore,
|
|
227
|
+
absolute: true,
|
|
228
|
+
dot,
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Make sure `packageName` will be resolvable for the ESLint plugins that need it at lint time.
|
|
234
|
+
*
|
|
235
|
+
* In a monorepo a tool is often installed only in the LEAF package that uses it - invisible both
|
|
236
|
+
* to the `has*` probes and to the plugins' own resolution: eslint-plugin-tailwindcss's workers
|
|
237
|
+
* call local-pkg's `getPackageInfoSync('tailwindcss')`, whose resolver is anchored at
|
|
238
|
+
* process.cwd() (verified empirically: NOT the module location, and NODE_PATH is ignored);
|
|
239
|
+
* `eslint-config-next` `require`s files INSIDE the `next` package; `eslint-plugin-storybook`
|
|
240
|
+
* statically imports `storybook`; `eslint-plugin-jest` sniffs the installed `jest` version.
|
|
241
|
+
* Bridge: resolve the package from `fromFile`'s own package context (createRequire follows the
|
|
242
|
+
* leaf's dependencies and is PnP-aware) and symlink
|
|
243
|
+
* `<workspace root>/node_modules/<packageName>` to it - every resolution walk inside the repo
|
|
244
|
+
* passes the root node_modules, so one link fixes all cwds. The package manager prunes the link
|
|
245
|
+
* on the next install; it is simply recreated on the next lint. Nothing is touched when the
|
|
246
|
+
* package is already resolvable via the normal chain.
|
|
247
|
+
*
|
|
248
|
+
* Yarn Berry PnP (verified in a scratch PnP workspace): the leaf resolution succeeds but points
|
|
249
|
+
* INSIDE the zip cache - a virtual path a symlink cannot reach - so the bridge is skipped (the
|
|
250
|
+
* target-exists guard) and the function reports `false`; under PnP the tools must be declared at
|
|
251
|
+
* the workspace root instead (verified working - see README).
|
|
252
|
+
*
|
|
253
|
+
* @param {string} packageName e.g. `'tailwindcss'`, `'next'`, `'storybook'`
|
|
254
|
+
* @param {string} fromFile absolute path of a file owned by the leaf package (entry CSS, `next.config.*`, ...)
|
|
255
|
+
* @param {boolean} chainResolvable whether the package already resolves via the normal chain (the `has*` probe)
|
|
256
|
+
* @returns {boolean} the package is resolvable for the plugins (possibly after bridging)
|
|
257
|
+
*/
|
|
258
|
+
export function ensurePackageResolvable(packageName, fromFile, chainResolvable) {
|
|
259
|
+
let leafPackageJson = null;
|
|
260
|
+
try {
|
|
261
|
+
leafPackageJson = createRequire(fromFile).resolve(`${packageName}/package.json`);
|
|
262
|
+
} catch {
|
|
263
|
+
// not a dependency of the leaf either
|
|
264
|
+
}
|
|
265
|
+
if (!leafPackageJson) return chainResolvable;
|
|
266
|
+
if (chainResolvable) return true;
|
|
267
|
+
|
|
268
|
+
const leafPackageDir = dirname(leafPackageJson);
|
|
269
|
+
if (!existsSync(leafPackageDir)) return false; // PnP zip cache - virtual path, nothing to symlink to
|
|
270
|
+
|
|
271
|
+
const bridge = join(findWorkspaceRoot(), 'node_modules', ...packageName.split('/'));
|
|
272
|
+
|
|
273
|
+
let existing;
|
|
274
|
+
try {
|
|
275
|
+
existing = lstatSync(bridge);
|
|
276
|
+
} catch {
|
|
277
|
+
// nothing at the bridge path
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// heal a stale bridge left over from a previous layout (symlink whose target is gone)
|
|
281
|
+
if (existing?.isSymbolicLink() && !existsSync(bridge)) {
|
|
282
|
+
try {
|
|
283
|
+
unlinkSync(bridge);
|
|
284
|
+
existing = undefined;
|
|
285
|
+
} catch {
|
|
286
|
+
// fall through - the existsSync() verdict below stays authoritative
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (!existing) {
|
|
291
|
+
try {
|
|
292
|
+
mkdirSync(dirname(bridge), { recursive: true }); // scoped packages need the @scope dir
|
|
293
|
+
// 'junction' for Windows (no admin rights needed); ignored on POSIX
|
|
294
|
+
symlinkSync(leafPackageDir, bridge, 'junction');
|
|
295
|
+
} catch {
|
|
296
|
+
// best effort - verdict below
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
return existsSync(bridge);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/*
|
|
304
|
+
* Capability detection, exported for debugging. Package probes resolve from THIS package's install
|
|
305
|
+
* location, so in a monorepo where a tool lives only in leaf packages (not in the root
|
|
306
|
+
* package.json) detection can miss it - that's what the per-tool force-on flags of
|
|
307
|
+
* defineLintConfig are for. `nx.json` is checked at the workspace root, not via cwd.
|
|
308
|
+
*/
|
|
309
|
+
export const hasNext = isPackageResolvable('next/package.json');
|
|
310
|
+
export const hasStorybook = isPackageResolvable('storybook/package.json');
|
|
311
|
+
export const hasVite = isPackageResolvable('vite/package.json');
|
|
312
|
+
export const hasJest = isPackageResolvable('jest/package.json');
|
|
313
|
+
export const hasVitest = isPackageResolvable('vitest/package.json');
|
|
314
|
+
export const hasTurbo = isPackageResolvable('turbo/package.json');
|
|
315
|
+
export const hasNx = existsSync(resolve(findWorkspaceRoot(), 'nx.json'));
|
|
316
|
+
export const hasTailwind = isPackageResolvable('tailwindcss/package.json');
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Normalize a defineLintConfig flag into its options object with a canonical `enabled`:
|
|
320
|
+
* - `true` / `false` → `{ enabled: true | false }`
|
|
321
|
+
* - an options object counts as enabled unless it explicitly says otherwise - `enabled` defaults
|
|
322
|
+
* to `true`, so providing options (even `{}`) implies turning the tool on
|
|
323
|
+
* - `undefined` (flag not passed) → `{}` - `enabled` stays undefined and the caller falls back to
|
|
324
|
+
* detection: `const { enabled = hasX, ...options } = asOptions(option)`
|
|
325
|
+
*
|
|
326
|
+
* @param {boolean | { enabled?: boolean } | undefined} option user-supplied flag from `LintOptions`
|
|
327
|
+
* @returns {{ enabled?: boolean } & object}
|
|
328
|
+
*/
|
|
329
|
+
export function asOptions(option) {
|
|
330
|
+
if (typeof option === 'boolean') return { enabled: option };
|
|
331
|
+
if (typeof option === 'object' && option !== null) return { enabled: true, ...option };
|
|
332
|
+
return {};
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Shared activation gate of the tool-scoped config blocks (next, storybook, turbo, nx, jest,
|
|
337
|
+
* vitest, tailwind) - the one decision every block repeats: is the tool ON, and can its plugin
|
|
338
|
+
* actually run. The `configs/*.js` functions keep only their tool-specific parts (which blocks to
|
|
339
|
+
* emit, how the evidence feeds settings) and differ solely in the spec they pass here.
|
|
340
|
+
*
|
|
341
|
+
* Decision flow:
|
|
342
|
+
* - `enabled: false` → off, always.
|
|
343
|
+
* - strict (defineLintConfig `detection.strict`): the same-scope probe gates (`strictHas`,
|
|
344
|
+
* defaulting to `has`); `scan` never runs and nothing is bridged, but `absolutizeOptions` evidence
|
|
345
|
+
* still counts. A tool that is ON while its package is unresolvable (`requirePackage`) or its
|
|
346
|
+
* mandatory evidence is missing (`needs`) throws instead of producing a config that crashes at
|
|
347
|
+
* lint time.
|
|
348
|
+
* - non-strict: evidence-based detection - `absolutizeOptions(options)` wins over the `scan()`
|
|
349
|
+
* auto-discovery; the tool is detected when the package probe hits or evidence exists (`needs`
|
|
350
|
+
* makes evidence mandatory even when the probe hits). Leaf-only installs are bridged from the
|
|
351
|
+
* evidence files via {@link ensurePackageResolvable}; an unresolvable package turns detection
|
|
352
|
+
* off silently but fails loudly when the tool was forced on (and `requirePackage` holds).
|
|
353
|
+
*
|
|
354
|
+
* @param {boolean | { enabled?: boolean } | undefined} option the tool's defineLintConfig flag
|
|
355
|
+
* @param {boolean} strict same-scope detection only (defineLintConfig `detection.strict`)
|
|
356
|
+
* @param {object} spec
|
|
357
|
+
* @param {string} spec.tool flag name, used in error messages
|
|
358
|
+
* @param {boolean} spec.has module-load package probe (chain resolvability, see the `has*` exports)
|
|
359
|
+
* @param {boolean} [spec.strictHas] strict-mode detection gate when it differs from `has` (nx: `nx.json` at cwd)
|
|
360
|
+
* @param {string} [spec.packageName] package the tool's plugin needs resolvable at lint time - enables the leaf bridge from the evidence files
|
|
361
|
+
* @param {boolean} [spec.requirePackage] fail loudly when the tool is ON but `packageName` is unresolvable; defaults to `packageName` being set - pass `false` when the plugin works without the tool installed (jest/vitest)
|
|
362
|
+
* @param {(options: object) => string[]} [spec.absolutizeOptions] evidence files derived from the options (absolute anchor paths for the package probes - the anchor itself need not exist, resolution walks up from its directory; allowed under strict)
|
|
363
|
+
* @param {() => string[]} [spec.scan] evidence auto-discovery below the workspace root (absolute paths; never runs under strict or when `absolutizeOptions` produced files)
|
|
364
|
+
* @param {boolean} [spec.allowMultiple] whether several evidence files are usable (default true - next supports several apps); when `false` several candidates are ALWAYS a hard error, even in auto mode - the right one cannot be guessed (tailwind's single entry CSS) and a silent skip of a tool that is evidently present would be hard to detect; zero candidates keeps the usual `needs` behavior
|
|
365
|
+
* @param {{ what: string, detail: string, hint: string }} [spec.needs] makes evidence MANDATORY (the plugin crashes without it - tailwind's entry CSS): detection without evidence stays inert even when `has` hits, forcing the tool on without it throws
|
|
366
|
+
* @returns {{ enabled: boolean, options: object, files: string[] }} the verdict, the normalized options (without `enabled`) and the evidence files
|
|
367
|
+
*/
|
|
368
|
+
export function toolGate(option, strict, spec) {
|
|
369
|
+
const { enabled, ...options } = asOptions(option);
|
|
370
|
+
const off = { enabled: false, options, files: [] };
|
|
371
|
+
if (enabled === false) return off;
|
|
372
|
+
|
|
373
|
+
const {
|
|
374
|
+
tool,
|
|
375
|
+
has,
|
|
376
|
+
strictHas = has,
|
|
377
|
+
packageName,
|
|
378
|
+
requirePackage = Boolean(packageName),
|
|
379
|
+
absolutizeOptions,
|
|
380
|
+
scan,
|
|
381
|
+
allowMultiple = true,
|
|
382
|
+
needs,
|
|
383
|
+
} = spec;
|
|
384
|
+
const prefix = `[@kirill.konshin/lint] \`${tool}\``;
|
|
385
|
+
/*
|
|
386
|
+
* Several candidates with allowMultiple off are a hard error even in auto mode: the evidence
|
|
387
|
+
* proves the tool IS in use, the right candidate is unknowable, and silently skipping a tool
|
|
388
|
+
* that is evidently present would be hard to detect.
|
|
389
|
+
*/
|
|
390
|
+
const usable = (candidates) => {
|
|
391
|
+
if (!allowMultiple && candidates.length > 1) {
|
|
392
|
+
const fix = needs ? `pass ${needs.hint} to pick one, or set` : `set`;
|
|
393
|
+
throw new Error(
|
|
394
|
+
`${prefix} found several ${needs?.what ?? 'evidence'} candidates and cannot pick one - ` +
|
|
395
|
+
`${fix} \`${tool}: false\`:\n${candidates.map((file) => ` - ${file}`).join('\n')}`,
|
|
396
|
+
);
|
|
397
|
+
}
|
|
398
|
+
return candidates;
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
if (strict) {
|
|
402
|
+
if (!(enabled ?? strictHas)) return off;
|
|
403
|
+
if (requirePackage && !has) {
|
|
404
|
+
throw new Error(
|
|
405
|
+
`${prefix} is on under strict detection, but the \`${packageName}\` package is not ` +
|
|
406
|
+
`resolvable at this scope - install it here or set \`${tool}: false\`.`,
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
const files = usable(absolutizeOptions?.(options) ?? []);
|
|
410
|
+
if (needs && files.length === 0) {
|
|
411
|
+
throw new Error(
|
|
412
|
+
`${prefix} is on under strict detection, which cannot scan for the ${needs.what} - ` +
|
|
413
|
+
`pass ${needs.hint} or set \`${tool}: false\`.`,
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
return { enabled: true, options, files };
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const optionFiles = absolutizeOptions?.(options) ?? [];
|
|
420
|
+
const files = usable(optionFiles.length > 0 ? optionFiles : (scan?.() ?? []));
|
|
421
|
+
|
|
422
|
+
if (needs && files.length === 0) {
|
|
423
|
+
// `enabled` is only defined when the consumer explicitly turned the tool on - fail loudly
|
|
424
|
+
// then; detection-driven activation (enabled === undefined) stays inert instead.
|
|
425
|
+
if (enabled) {
|
|
426
|
+
throw new Error(
|
|
427
|
+
`${prefix} was enabled explicitly, but no ${needs.detail} was found - zero or several ` +
|
|
428
|
+
`candidates. Pass ${needs.hint} explicitly.`,
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
return off;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
if (!(enabled ?? (has || files.length > 0))) return off;
|
|
435
|
+
|
|
436
|
+
const resolvable = !packageName || has || files.some((file) => ensurePackageResolvable(packageName, file, has));
|
|
437
|
+
if (!resolvable) {
|
|
438
|
+
if (enabled && requirePackage) {
|
|
439
|
+
throw new Error(
|
|
440
|
+
`${prefix} is enabled, but the \`${packageName}\` package is resolvable neither from the ` +
|
|
441
|
+
`workspace root nor from the detected evidence locations - install \`${packageName}\` ` +
|
|
442
|
+
`in the package that owns them or at the workspace root.`,
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
if (!enabled) return off;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
return { enabled: true, options, files };
|
|
449
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kirill.konshin/lint",
|
|
3
3
|
"description": "ESLint + Prettier + lint-staged config and AI agent rules/skills for monorepos",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.3.1",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"skipGenerate": true,
|
|
7
7
|
"bin": {
|
|
@@ -9,20 +9,22 @@
|
|
|
9
9
|
},
|
|
10
10
|
"main": "index.js",
|
|
11
11
|
"module": "index.js",
|
|
12
|
+
"types": "index.d.ts",
|
|
12
13
|
"scripts": {
|
|
13
14
|
"----- BUILD -----": "",
|
|
14
15
|
"clean": "rm -rf dist .tscache tsconfig.tsbuildinfo",
|
|
15
16
|
"build": "echo 'No build required'",
|
|
16
17
|
"start": "echo 'No start required'",
|
|
17
18
|
"----- TEST -----": "",
|
|
18
|
-
"test": "
|
|
19
|
+
"test": "vitest run"
|
|
19
20
|
},
|
|
20
21
|
"files": [
|
|
21
22
|
"index.js",
|
|
22
|
-
"
|
|
23
|
+
"index.d.ts",
|
|
24
|
+
"configs",
|
|
25
|
+
"!configs/*.test.js",
|
|
23
26
|
"lib.js",
|
|
24
27
|
"lintPrepare.js",
|
|
25
|
-
"ruleTestColocation.js",
|
|
26
28
|
"rules",
|
|
27
29
|
"skills"
|
|
28
30
|
],
|
|
@@ -53,12 +55,16 @@
|
|
|
53
55
|
"globals": "^16.4.0",
|
|
54
56
|
"jsonc-eslint-parser": "^2.4.2"
|
|
55
57
|
},
|
|
58
|
+
"devDependencies": {
|
|
59
|
+
"vitest": "*"
|
|
60
|
+
},
|
|
56
61
|
"peerDependencies": {
|
|
57
62
|
"eslint": "^10",
|
|
58
63
|
"husky": "^9",
|
|
59
64
|
"jest": "*",
|
|
60
65
|
"lint-staged": "^16",
|
|
61
66
|
"next": "^16",
|
|
67
|
+
"prettier": "^3",
|
|
62
68
|
"storybook": "^10.5.2",
|
|
63
69
|
"tailwindcss": "*",
|
|
64
70
|
"vite": "*",
|
package/rules/tailwind.md
CHANGED
|
@@ -10,23 +10,21 @@ description: Set of rules for projects which use Tailwind
|
|
|
10
10
|
# ESLint (eslint-plugin-tailwindcss, bundled with @kirill.konshin/lint)
|
|
11
11
|
|
|
12
12
|
- The plugin MUST be able to resolve the Tailwind entry CSS or it hard-crashes lint (ENOENT)
|
|
13
|
-
- Zero-config happy path: when
|
|
14
|
-
-
|
|
13
|
+
- Zero-config happy path: when the workspace contains exactly ONE `*.css` with `@import "tailwindcss"` (scanned ≤5 dir levels, `.gitignore`-aware), rules auto-enable with that entry
|
|
14
|
+
- Several entry CSS candidates are ALWAYS a HARD ERROR (a silent skip is hard to notice)
|
|
15
|
+
- pass `cssConfigPath` to pick one (if others are not useful) OR
|
|
16
|
+
- create multiple leaf `eslint.config.ts` per app (if ALL need to be linted)
|
|
17
|
+
- When detection can't see `tailwindcss` (e.g. it lives only in leaf packages of a monorepo), force it with `tailwind: true` — then a missing entry CSS is a HARD ERROR instead of a silent skip
|
|
18
|
+
- ONLY when auto-find finds nothing (or several entries) pass the MANDATORY entry explicitly in `eslint.config.mjs`:
|
|
15
19
|
|
|
16
20
|
```js
|
|
17
|
-
import
|
|
18
|
-
|
|
19
|
-
export default
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
...tailwindPlugin.configs.recommended,
|
|
23
|
-
settings: {
|
|
24
|
-
tailwindcss: {
|
|
25
|
-
cssConfigPath: './src/styles/tailwind.css', // MANDATORY, relative to the package root
|
|
26
|
-
},
|
|
27
|
-
},
|
|
21
|
+
import { defineLintConfig } from '@kirill.konshin/lint';
|
|
22
|
+
|
|
23
|
+
export default defineLintConfig({
|
|
24
|
+
tailwind: {
|
|
25
|
+
cssConfigPath: './src/styles/tailwind.css', // MANDATORY, relative to the package root
|
|
28
26
|
},
|
|
29
|
-
|
|
27
|
+
});
|
|
30
28
|
```
|
|
31
29
|
|
|
32
30
|
# Hero UI
|
package/rules/testing.md
CHANGED
|
@@ -4,9 +4,10 @@ description: Set of rules for projects with tests
|
|
|
4
4
|
paths:
|
|
5
5
|
- '**/jest.config.{ts,js,mjs,cjs}'
|
|
6
6
|
- '**/vite.config.{ts,js,mjs,cjs}'
|
|
7
|
-
- '
|
|
8
|
-
- '**/*.
|
|
9
|
-
- '**/*.
|
|
7
|
+
- '**/vitest.config.{ts,js,mjs,cjs}'
|
|
8
|
+
- '**/*.test.*'
|
|
9
|
+
- '**/*.spec.*'
|
|
10
|
+
- '**/*.fixture.*'
|
|
10
11
|
---
|
|
11
12
|
|
|
12
13
|
- If project use `vite` use `vitest`, otherwise `jest`
|
|
@@ -16,7 +17,7 @@ paths:
|
|
|
16
17
|
- `*.spec.ts` for e2e or integration tests (require running DEV server)
|
|
17
18
|
- `*.fixture.ts` for test helpers, mocks, worker fixtures
|
|
18
19
|
- Organization
|
|
19
|
-
-
|
|
20
|
+
- Top-level `test(...)` calls are OK; use `describe(...)` to group related tests when grouping helps, nesting allowed and preferred
|
|
20
21
|
- Set timeouts on describe blocks or individual tests for slow tests to make them visible
|
|
21
22
|
- Prefer to use `vi.fn()` or `jest.fn()` to create mock functions
|
|
22
23
|
- Mock entire test-specific class implementations via `class Testable extend ClassToBeTested {}`
|
package/skills/lint-repo.md
CHANGED
|
@@ -14,10 +14,10 @@ Full config templates: @README.md
|
|
|
14
14
|
|
|
15
15
|
## A. Set up / update tooling
|
|
16
16
|
|
|
17
|
-
Follow
|
|
17
|
+
Follow @README.md, reconciling (never blindly overwriting project-specific overrides). When **upgrading** `@kirill.konshin/lint` from an older version, first apply the README's "Migration" section (e.g. 0.2.x → 0.3.x: default-exported array → `defineLintConfig()` options):
|
|
18
18
|
|
|
19
19
|
1. **Install** — add `eslint`, `prettier`, `@kirill.konshin/lint`, `husky`, `lint-staged` (+ the PNPM `.npmrc` block if pnpm).
|
|
20
|
-
2. **Config** — create/reconcile `.editorconfig`, `eslint.config.mjs` and `.prettierrc.mjs` (
|
|
20
|
+
2. **Config** — create/reconcile `.editorconfig`, `eslint.config.mjs` and `.prettierrc.mjs` (pass `defineLintConfig` options as needed — e.g. `defaultIgnore: { importMetaUrl: import.meta.url }`, `next: { rootDir }` — and keep project rule overrides).
|
|
21
21
|
3. **Lint-staged** — create/reconcile `.lintstagedrc.mjs`.
|
|
22
22
|
4. **Husky** — `prepare/postinstall` (`prepare` by default, `postinstall` if Yarn 2+ is used AND root package.json is **private**) script; `.husky/pre-commit`, plus `eslint`/`prettier`/`lint`/`lint:staged` scripts. Drop a legacy `lint:all` if it duplicates `lint`.
|
|
23
23
|
5. **IDEA** — apply the file-scope glob patterns if the repo has a JetBrains `.idea`.
|
package/findTailwindEntry.js
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { readFileSync } from 'node:fs';
|
|
2
|
-
import { resolve } from 'node:path';
|
|
3
|
-
import { includeIgnoreFile } from '@eslint/compat';
|
|
4
|
-
import { globSync } from 'glob';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Auto-find the Tailwind v4 entry CSS: scan `*.css` up to three directory levels deep (covers
|
|
8
|
-
* `packages/<x>/src`), skipping dot dirs, the given ignore patterns and everything in `.gitignore`,
|
|
9
|
-
* looking for the Tailwind v4 marker `@import "tailwindcss"`.
|
|
10
|
-
*
|
|
11
|
-
* eslint-plugin-tailwindcss v4 loads the entry (`settings.tailwindcss.cssConfigPath`) and
|
|
12
|
-
* HARD-CRASHES with ENOENT when it can't, so the caller must only enable the plugin when exactly
|
|
13
|
-
* one entry is found; with zero or several the consumer configures `cssConfigPath` manually
|
|
14
|
-
* (MANDATORY for the plugin) - see README "Tailwind CSS rules".
|
|
15
|
-
*
|
|
16
|
-
* @param {string[]} ignores glob patterns to skip, passed in (not imported) to avoid a circular dependency
|
|
17
|
-
* @returns {string | null} absolute path of the single entry, or null when zero or several were found
|
|
18
|
-
*/
|
|
19
|
-
export function findTailwindEntry(ignores) {
|
|
20
|
-
let gitignored = [];
|
|
21
|
-
try {
|
|
22
|
-
// Reuse ESLint's gitignore->minimatch conversion; glob's `ignore` speaks the same language.
|
|
23
|
-
// Negations dropped: glob's ignore cannot un-ignore.
|
|
24
|
-
gitignored = includeIgnoreFile(resolve(process.cwd(), '.gitignore')).ignores.filter(
|
|
25
|
-
(pattern) => !pattern.startsWith('!'),
|
|
26
|
-
);
|
|
27
|
-
} catch {
|
|
28
|
-
// no .gitignore - the scan is just less filtered
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
// `<dir-pattern>/**` variants prune the CONTENTS of ignored directories, not just the dir itself
|
|
32
|
-
const ignore = [...ignores, ...gitignored].flatMap((pattern) => [
|
|
33
|
-
pattern,
|
|
34
|
-
pattern.endsWith('/') ? `${pattern}**` : `${pattern}/**`,
|
|
35
|
-
]);
|
|
36
|
-
|
|
37
|
-
const entries = globSync('{*.css,*/*.css,*/*/*.css,*/*/*/*.css}', { ignore, absolute: true }).filter((file) => {
|
|
38
|
-
try {
|
|
39
|
-
return /@import\s+['"]tailwindcss['"]/.test(readFileSync(file, 'utf-8'));
|
|
40
|
-
} catch {
|
|
41
|
-
return false;
|
|
42
|
-
}
|
|
43
|
-
});
|
|
44
|
-
|
|
45
|
-
return entries.length === 1 ? entries[0] : null;
|
|
46
|
-
}
|
package/ruleTestColocation.js
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
|
|
4
|
-
const SOURCE_EXTS = ['.ts', '.tsx', '.js', '.jsx', '.mts', '.mjs', '.cts', '.cjs'];
|
|
5
|
-
const TEST_SUFFIX = new RegExp(`\\.test\\.(${SOURCE_EXTS.map((ext) => ext.slice(1)).join('|')})$`);
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Only `*.test.*` is checked, not `*.spec.*` - per testing.md, spec files cover e2e/integration
|
|
9
|
-
* flows that don't map 1:1 to a single sibling source file, so co-location isn't meaningful there.
|
|
10
|
-
*/
|
|
11
|
-
export const testColocation = {
|
|
12
|
-
meta: {
|
|
13
|
-
type: 'problem',
|
|
14
|
-
docs: {
|
|
15
|
-
description: 'require *.test.* files to sit next to the source file they test, not in a separate folder',
|
|
16
|
-
},
|
|
17
|
-
schema: [],
|
|
18
|
-
messages: {
|
|
19
|
-
missingSibling:
|
|
20
|
-
"No sibling source file found for '{{testFile}}'. Expected e.g. '{{expected}}' in the same directory, not a separate __tests__/ folder.",
|
|
21
|
-
},
|
|
22
|
-
},
|
|
23
|
-
create(context) {
|
|
24
|
-
const base = path.basename(context.filename);
|
|
25
|
-
const match = base.match(TEST_SUFFIX);
|
|
26
|
-
|
|
27
|
-
if (!match) return {};
|
|
28
|
-
|
|
29
|
-
const stem = base.slice(0, -match[0].length);
|
|
30
|
-
|
|
31
|
-
let siblings;
|
|
32
|
-
try {
|
|
33
|
-
siblings = fs.readdirSync(path.dirname(context.filename));
|
|
34
|
-
} catch {
|
|
35
|
-
return {}; // virtual filename (stdin, editor buffer) - no directory to check against
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
if (SOURCE_EXTS.some((ext) => siblings.includes(`${stem}${ext}`))) return {};
|
|
39
|
-
|
|
40
|
-
return {
|
|
41
|
-
Program(node) {
|
|
42
|
-
context.report({
|
|
43
|
-
node,
|
|
44
|
-
messageId: 'missingSibling',
|
|
45
|
-
data: { testFile: base, expected: `${stem}.ts` },
|
|
46
|
-
});
|
|
47
|
-
},
|
|
48
|
-
};
|
|
49
|
-
},
|
|
50
|
-
};
|