@sssb/eslint-plugin 0.0.0 → 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/LICENSE +21 -0
- package/package.json +40 -5
- package/src/app-config.js +401 -0
- package/src/check-fences.d.ts +20 -0
- package/src/check-fences.js +269 -0
- package/src/import-ban.js +150 -0
- package/src/index.d.ts +22 -0
- package/src/index.js +31 -0
- package/src/patterns.js +318 -0
- package/src/probes.js +129 -0
- package/src/rules.js +611 -0
- package/README.md +0 -3
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// THE FENCES AS COMPOSED (ADR-0014, part 3): what `sssb check-fences` runs. An adopter's config composes the preset
|
|
2
|
+
// with blocks of its own, and nothing about that composition is visible from inside a rule. So this asks ESLint
|
|
3
|
+
// itself, through the app's real config, four questions:
|
|
4
|
+
//
|
|
5
|
+
// 1. For every source file the app has, is every sssb/* rule the preset enables there still enabled, at `error`,
|
|
6
|
+
// with the preset's options, under the preset's parser, language and no processor? It compares
|
|
7
|
+
// `calculateConfigForFile` through the app's config with the same call through the preset alone. A later block
|
|
8
|
+
// that turns a rule off or down, swaps the app's vendor list, adds a processor or a parser for one directory, a
|
|
9
|
+
// later `ignores`, a global ignore, a nested config file that takes over a directory: each shows up here.
|
|
10
|
+
// 2. Does every fence still REPORT? The probes (./probes.js) are linted as virtual files at paths in the app.
|
|
11
|
+
// 3. Does each `lint-exceptions.mjs` entry exempt exactly the file it names? The named file must pass the tenancy
|
|
12
|
+
// ban and a sibling beside it must not.
|
|
13
|
+
// 4. Does a fence's finding in the app's own files get through? The app's files are linted twice through its
|
|
14
|
+
// config, once as they are and once with inline configuration off, and ESLint itself reads every directive. For the
|
|
15
|
+
// rules the preset enables on each file, a finding at any severity (an inline comment that turns a fence down to a
|
|
16
|
+
// warning, a suppressions file the ESLint CLI applies and this API does not), one an `eslint-disable` suppressed,
|
|
17
|
+
// or one only the second run reports (an inline `/* eslint sssb/…: off */`) is reported. An app's exceptions
|
|
18
|
+
// belong in lint-exceptions.mjs, named and reasoned. A directive over code that breaks no fence hides nothing yet.
|
|
19
|
+
//
|
|
20
|
+
// What it cannot see: config code written to deceive (it behaves differently when it detects which tool loaded it,
|
|
21
|
+
// a parser borrows another's name, the preset's blocks are rebound to a look-alike plugin, a module the rules read is
|
|
22
|
+
// rewritten; see .claude/future-tasks/check-fences-real-file-probes.md); the app's lint command's own flags, except
|
|
23
|
+
// that any fence finding in the app's files is reported here whatever the command does with it.
|
|
24
|
+
// Reported instead: a symlinked directory holding a file the preset lints (ESLint does not enter it). Typed linting
|
|
25
|
+
// (parserOptions.project or projectService) cannot parse the probe files, which are not in the app's TypeScript
|
|
26
|
+
// project, and is reported as such.
|
|
27
|
+
import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs'
|
|
28
|
+
import { createRequire } from 'node:module'
|
|
29
|
+
import { basename, dirname, extname, join, relative, resolve } from 'node:path'
|
|
30
|
+
import { isDeepStrictEqual } from 'node:util'
|
|
31
|
+
import { pathToFileURL } from 'node:url'
|
|
32
|
+
import { loadAppLintExceptions } from './app-config.js'
|
|
33
|
+
import plugin from './index.js'
|
|
34
|
+
import { EXCEPTION_PROBE_CODE, PROBE, PROBES } from './probes.js'
|
|
35
|
+
|
|
36
|
+
const LINTED = new Set(['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'])
|
|
37
|
+
// Never walked, anywhere: where a package manager or git puts files.
|
|
38
|
+
const NEVER_WALKED = new Set(['node_modules', '.git'])
|
|
39
|
+
// Not walked at the APP'S ROOT, where the preset ignores them (build and test output). The same names deeper in the
|
|
40
|
+
// app (`src/coverage/`) are source like any other, and walked.
|
|
41
|
+
const ROOT_OUTPUTS = new Set(['.next', '.data', 'dist-demo', 'coverage', 'test-results', 'playwright-report'])
|
|
42
|
+
const SEVERITY = { off: 0, warn: 1, error: 2 }
|
|
43
|
+
const severityOf = (entry) => {
|
|
44
|
+
const level = Array.isArray(entry) ? entry[0] : entry
|
|
45
|
+
return typeof level === 'number' ? level : (SEVERITY[level] ?? 0)
|
|
46
|
+
}
|
|
47
|
+
const optionsOf = (entry) => (Array.isArray(entry) ? entry.slice(1) : [])
|
|
48
|
+
// A parser by what it calls itself, without its version: an app that spreads its own copy of typescript-eslint after
|
|
49
|
+
// the preset, at another version, parses the same way. (A parser that borrows another's `meta` is code written to
|
|
50
|
+
// deceive, the residual this file's header names.)
|
|
51
|
+
const parserName = (parser) =>
|
|
52
|
+
parser === undefined ? 'none' : (parser.meta?.name ?? parser.name ?? 'an unnamed parser')
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* ESLint as the app's directory finds it: the copy the app's lint script runs. WALKED up the app's `node_modules`
|
|
56
|
+
* chain rather than `require.resolve`d, because Node's resolver falls back to NODE_PATH, which `pnpm exec` sets to the
|
|
57
|
+
* workspace's hoisted `.pnpm/node_modules`.
|
|
58
|
+
*/
|
|
59
|
+
async function eslintOf(appDir) {
|
|
60
|
+
let found
|
|
61
|
+
for (let dir = appDir; !found; dir = dirname(dir)) {
|
|
62
|
+
if (existsSync(join(dir, 'node_modules', 'eslint', 'package.json'))) found = join(dir, 'node_modules', 'eslint')
|
|
63
|
+
else if (dirname(dir) === dir) throw new Error(`@sssb/eslint-plugin: ${appDir} does not install eslint`)
|
|
64
|
+
}
|
|
65
|
+
const resolved = createRequire(join(found, 'package.json')).resolve('eslint')
|
|
66
|
+
return /** @type {typeof import('eslint').ESLint} */ ((await import(pathToFileURL(resolved).href)).ESLint)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Every file ESLint would lint under `dir`, a symlinked file included (ESLint lints one); `linkedDirs` collects the
|
|
71
|
+
* symlinked directories, which ESLint does not enter, so a fence never sees their files.
|
|
72
|
+
* @param {string} dir
|
|
73
|
+
* @param {string[]} linkedDirs
|
|
74
|
+
* @param {boolean} atRoot
|
|
75
|
+
* @returns {Generator<string>}
|
|
76
|
+
*/
|
|
77
|
+
function* sourceFiles(dir, linkedDirs, atRoot = true) {
|
|
78
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
79
|
+
const full = join(dir, entry.name)
|
|
80
|
+
const skipped = NEVER_WALKED.has(entry.name) || (atRoot && ROOT_OUTPUTS.has(entry.name))
|
|
81
|
+
if (entry.isDirectory()) {
|
|
82
|
+
if (!skipped) yield* sourceFiles(full, linkedDirs, false)
|
|
83
|
+
} else if (entry.isSymbolicLink()) {
|
|
84
|
+
const target = existsSync(full) ? statSync(full) : undefined
|
|
85
|
+
if (target?.isDirectory()) {
|
|
86
|
+
if (!skipped) linkedDirs.push(full)
|
|
87
|
+
} else if (target?.isFile() && LINTED.has(extname(entry.name))) yield full
|
|
88
|
+
} else if (entry.isFile() && LINTED.has(extname(entry.name))) {
|
|
89
|
+
yield full
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Whether a symlinked directory holds a file the preset would lint, read through the link's own path (as ESLint would
|
|
96
|
+
* name it, had it entered). Each real directory is read once, so a link cycle ends.
|
|
97
|
+
* @param {string} dir
|
|
98
|
+
* @param {import('eslint').ESLint} preset
|
|
99
|
+
* @param {Set<string>} seen
|
|
100
|
+
* @returns {Promise<boolean>}
|
|
101
|
+
*/
|
|
102
|
+
async function holdsLintedFiles(dir, preset, seen = new Set()) {
|
|
103
|
+
const real = realpathSync(dir)
|
|
104
|
+
if (seen.has(real)) return false
|
|
105
|
+
seen.add(real)
|
|
106
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
107
|
+
if (NEVER_WALKED.has(entry.name)) continue
|
|
108
|
+
const full = join(dir, entry.name)
|
|
109
|
+
const target = entry.isSymbolicLink() ? (existsSync(full) ? statSync(full) : undefined) : entry
|
|
110
|
+
if (target?.isDirectory()) {
|
|
111
|
+
if (await holdsLintedFiles(full, preset, seen)) return true
|
|
112
|
+
} else if (target?.isFile() && LINTED.has(extname(entry.name)) && !(await preset.isPathIgnored(full))) {
|
|
113
|
+
return true
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return false
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Probe an app's composed lint config. Resolves ESLint from the app's directory unless one is passed.
|
|
121
|
+
* @param {{ appDir: string, ESLint?: typeof import('eslint').ESLint }} options
|
|
122
|
+
* @returns {Promise<{ problems: string[], files: number, probes: number }>}
|
|
123
|
+
*/
|
|
124
|
+
export async function checkFences({ appDir: given, ESLint: passed }) {
|
|
125
|
+
const appDir = realpathSync.native(resolve(given))
|
|
126
|
+
const ESLint = passed ?? (await eslintOf(appDir))
|
|
127
|
+
const composed = new ESLint({ cwd: appDir })
|
|
128
|
+
const noInlineConfig = new ESLint({ cwd: appDir, allowInlineConfig: false })
|
|
129
|
+
const preset = new ESLint({
|
|
130
|
+
cwd: appDir,
|
|
131
|
+
overrideConfigFile: true,
|
|
132
|
+
overrideConfig: await plugin.configs.app({ root: appDir }),
|
|
133
|
+
})
|
|
134
|
+
const problems = []
|
|
135
|
+
const at = (file) => relative(appDir, file)
|
|
136
|
+
|
|
137
|
+
// 1. the effective config, file by file
|
|
138
|
+
const linkedDirs = []
|
|
139
|
+
let unloadable = false
|
|
140
|
+
/** The sssb/* rules the preset enables at `error`, for each file the preset lints. @type {Map<string, Set<string>>} */
|
|
141
|
+
const fenced = new Map()
|
|
142
|
+
for (const file of sourceFiles(appDir, linkedDirs)) {
|
|
143
|
+
if (await preset.isPathIgnored(file)) continue
|
|
144
|
+
const wantedConfig = await preset.calculateConfigForFile(file)
|
|
145
|
+
const wanted = wantedConfig?.rules ?? {}
|
|
146
|
+
const rules = new Set(
|
|
147
|
+
Object.entries(wanted)
|
|
148
|
+
.filter(([rule, entry]) => rule.startsWith('sssb/') && severityOf(entry) === 2)
|
|
149
|
+
.map(([rule]) => rule),
|
|
150
|
+
)
|
|
151
|
+
fenced.set(file, rules)
|
|
152
|
+
let actualConfig
|
|
153
|
+
try {
|
|
154
|
+
actualConfig = await composed.calculateConfigForFile(file)
|
|
155
|
+
} catch (error) {
|
|
156
|
+
problems.push(`${at(file)}: the app's config does not load for it (${String(error).split('\n')[0]})`)
|
|
157
|
+
unloadable = true
|
|
158
|
+
continue
|
|
159
|
+
}
|
|
160
|
+
const actual = actualConfig?.rules
|
|
161
|
+
if (!actual) {
|
|
162
|
+
problems.push(`${at(file)}: the app's config ignores it, and the preset lints it`)
|
|
163
|
+
continue
|
|
164
|
+
}
|
|
165
|
+
// What reads the file before any rule does. The language is ESLint's own object, so it is the preset's or it is
|
|
166
|
+
// another; the preset sets no processor, so any processor is one the app added; the parser is compared by name.
|
|
167
|
+
if (actualConfig.language !== wantedConfig.language) {
|
|
168
|
+
problems.push(`${at(file)}: it is parsed as another language than the preset's`)
|
|
169
|
+
}
|
|
170
|
+
if (actualConfig.processor !== wantedConfig.processor) {
|
|
171
|
+
const name = actualConfig.processor?.meta?.name ?? 'an unnamed one'
|
|
172
|
+
problems.push(`${at(file)}: it runs through a processor (${name}), and the preset sets none`)
|
|
173
|
+
}
|
|
174
|
+
const [wantParser, gotParser] = [wantedConfig, actualConfig].map((c) => parserName(c.languageOptions?.parser))
|
|
175
|
+
if (wantParser !== gotParser) {
|
|
176
|
+
problems.push(`${at(file)}: its parser is ${gotParser}, and the preset's is ${wantParser}`)
|
|
177
|
+
}
|
|
178
|
+
for (const rule of rules) {
|
|
179
|
+
const got = actual[rule]
|
|
180
|
+
if (severityOf(got) !== 2) {
|
|
181
|
+
problems.push(`${at(file)}: ${rule} is ${got === undefined ? 'not enabled' : 'switched off or down'}`)
|
|
182
|
+
} else if (!isDeepStrictEqual(optionsOf(got), optionsOf(wanted[rule]))) {
|
|
183
|
+
problems.push(`${at(file)}: ${rule} runs with options the preset does not set`)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
for (const dir of linkedDirs) {
|
|
188
|
+
if (await holdsLintedFiles(dir, preset)) {
|
|
189
|
+
problems.push(`${at(dir)}: a symlinked directory, which ESLint does not enter, so no fence sees its files`)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
// When the app's config does not load for some file, step 4's lintFiles (every file at once) would throw, and the
|
|
193
|
+
// problem above already fails the check; the probes are skipped rather than run against a config known to be broken.
|
|
194
|
+
if (unloadable) return { problems, files: fenced.size, probes: 0 }
|
|
195
|
+
|
|
196
|
+
// 4. what a fence finds in the app's own files, as ESLint itself reads them. Only the rules the preset enables for
|
|
197
|
+
// each file count: an app that tightens a fence beyond the preset may relax its own tightening.
|
|
198
|
+
if (fenced.size > 0) {
|
|
199
|
+
const files = [...fenced.keys()]
|
|
200
|
+
const asWritten = await composed.lintFiles(files)
|
|
201
|
+
const withoutInline = new Map((await noInlineConfig.lintFiles(files)).map((r) => [r.filePath, r]))
|
|
202
|
+
for (const result of asWritten) {
|
|
203
|
+
const rules = fenced.get(result.filePath) ?? new Set()
|
|
204
|
+
const ours = (messages) => (messages ?? []).filter((m) => rules.has(m.ruleId))
|
|
205
|
+
const key = (m) => `${m.ruleId}@${m.line}:${m.column}`
|
|
206
|
+
const where = `${at(result.filePath)}`
|
|
207
|
+
// Reported as it stands, at any severity: a finding the app's lint lets through (an inline comment that
|
|
208
|
+
// turns the fence down to a warning, a suppressions file the ESLint CLI applies and this API does not, a
|
|
209
|
+
// lint script with flags) is a fence that is not holding.
|
|
210
|
+
for (const m of ours(result.messages)) {
|
|
211
|
+
problems.push(`${where}:${m.line}: ${m.ruleId} reports it, and the app's lint must fail on it`)
|
|
212
|
+
}
|
|
213
|
+
for (const m of ours(result.suppressedMessages)) {
|
|
214
|
+
problems.push(
|
|
215
|
+
`${where}:${m.line}: an eslint-disable comment hides ${m.ruleId}; an app's exceptions belong in lint-exceptions.mjs`,
|
|
216
|
+
)
|
|
217
|
+
}
|
|
218
|
+
const seen = new Set([...ours(result.messages), ...ours(result.suppressedMessages)].map(key))
|
|
219
|
+
for (const m of ours(withoutInline.get(result.filePath)?.messages)) {
|
|
220
|
+
if (!seen.has(key(m))) {
|
|
221
|
+
problems.push(`${where}:${m.line}: an inline /* eslint */ comment switches ${m.ruleId} off there`)
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// 2. the probes
|
|
228
|
+
const lint = async (path, code) => {
|
|
229
|
+
const [result] = await composed.lintText(code, { filePath: join(appDir, path) })
|
|
230
|
+
const unlinted = result.messages.filter((m) => !m.ruleId)
|
|
231
|
+
if (unlinted.length > 0) {
|
|
232
|
+
const why = unlinted[0].message.split('\n')[0]
|
|
233
|
+
const typed = /project service|parserOptions\.project|TSConfig/i.test(unlinted[0].message)
|
|
234
|
+
? ': typed linting cannot parse a file outside the TypeScript project, so check-fences needs the probes untyped'
|
|
235
|
+
: ''
|
|
236
|
+
problems.push(`${path}: not linted as an app file would be (${why})${typed}`)
|
|
237
|
+
return undefined
|
|
238
|
+
}
|
|
239
|
+
return new Set(result.messages.map((m) => m.ruleId))
|
|
240
|
+
}
|
|
241
|
+
for (const probe of PROBES) {
|
|
242
|
+
const fired = await lint(probe.path, probe.code)
|
|
243
|
+
if (!fired) continue
|
|
244
|
+
for (const rule of probe.fires) {
|
|
245
|
+
if (!fired.has(rule)) problems.push(`${probe.path}: ${rule} did not report what it fences`)
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// 3. the app's own exceptions: the named file exempt, a sibling not
|
|
250
|
+
const exceptions = await loadAppLintExceptions(appDir)
|
|
251
|
+
let exceptionProbes = 0
|
|
252
|
+
for (const [rule, entries] of Object.entries(exceptions)) {
|
|
253
|
+
for (const escaped of entries) {
|
|
254
|
+
const file = escaped.replace(/\\(.)/g, '$1')
|
|
255
|
+
const sibling = join(dirname(file), `${PROBE}${extname(file)}`)
|
|
256
|
+
exceptionProbes += 2
|
|
257
|
+
const named = await lint(file, EXCEPTION_PROBE_CODE)
|
|
258
|
+
if (named?.has(rule)) problems.push(`${file}: lint-exceptions.mjs names it, and ${rule} still reports`)
|
|
259
|
+
const beside = await lint(sibling, EXCEPTION_PROBE_CODE)
|
|
260
|
+
if (beside && !beside.has(rule)) {
|
|
261
|
+
problems.push(
|
|
262
|
+
`${sibling}: ${rule} does not report beside ${basename(file)}: the exception is wider than its file`,
|
|
263
|
+
)
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
return { problems, files: fenced.size, probes: PROBES.length + exceptionProbes }
|
|
269
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// HOW AN IMPORT FENCE SEES A SPECIFIER, in both of its halves.
|
|
2
|
+
//
|
|
3
|
+
// The declaration half (declarationImportBan) replaces what no-restricted-imports used to carry, and matches a
|
|
4
|
+
// pattern as that rule does (eslint's lib/rules/no-restricted-imports.js): a `group` through the `ignore` package
|
|
5
|
+
// with `allowRelativePaths: true` and `ignorecase` (no pattern here sets caseSensitive), a `regex` as a RegExp with
|
|
6
|
+
// the `iu` flags, and the specifier trimmed. It visits what that rule visits: import declarations, re-exports with a
|
|
7
|
+
// source, and TypeScript's `import m = require('…')`. One difference, a tightening: ESLint trims the specifier of
|
|
8
|
+
// import and export declarations only, and this half trims `import m = require(' x')`'s too. That includes the group syntax's quirks:
|
|
9
|
+
// a bare name matches at any depth, so core's `react` also bans `@x/react` and `./react`, and `pg` bans `./pg`.
|
|
10
|
+
//
|
|
11
|
+
// The declarationless half (declarationlessImportBan) sees what no declaration rule can: `import()`, `require()`,
|
|
12
|
+
// vitest/jest's `importActual`, `requireActual`, `importMock` and `requireMock`, and a type-position `import('…')`
|
|
13
|
+
// (TSImportType). `import type { T } from '…'` is a declaration, and the inline type form is an import too.
|
|
14
|
+
// NOT covered: `vi.mock`/`vi.doMock` and jest's. A mock names a module and, given a factory, never loads it; the
|
|
15
|
+
// module under test that imports it is what both halves catch. Out of reach of both, as of every import rule: a
|
|
16
|
+
// computed specifier (`import(name)`), and a require not called by that name (`createRequire(…)(…)`,
|
|
17
|
+
// `module.require(…)`).
|
|
18
|
+
//
|
|
19
|
+
// Both halves report EVERY pattern a specifier matches, one finding each, with that pattern's message, as
|
|
20
|
+
// no-restricted-imports did. Neither factory takes options. The two vendor rules wrap them and take `{ vendors }`
|
|
21
|
+
// (./rules.js), which a later block could replace; `sssb check-fences` compares those options exactly with the
|
|
22
|
+
// preset's, and every other import fence takes none.
|
|
23
|
+
import ignore from 'ignore'
|
|
24
|
+
|
|
25
|
+
const patternMatcher = (pattern) => {
|
|
26
|
+
if (pattern.regex) {
|
|
27
|
+
const regex = new RegExp(pattern.regex, 'iu')
|
|
28
|
+
return (specifier) => regex.test(specifier)
|
|
29
|
+
}
|
|
30
|
+
const matcher = ignore({ allowRelativePaths: true, ignorecase: true }).add(pattern.group)
|
|
31
|
+
return (specifier) => matcher.ignores(specifier)
|
|
32
|
+
}
|
|
33
|
+
/** The message of every pattern a specifier matches. */
|
|
34
|
+
export const matchesPatterns = (patterns) => {
|
|
35
|
+
const matchers = patterns.map((pattern) => ({ test: patternMatcher(pattern), message: pattern.message }))
|
|
36
|
+
return (specifier) => matchers.filter(({ test }) => test(specifier)).map(({ message }) => message)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The specifier a node holds: a string literal, or a template literal with no expressions; else undefined. */
|
|
40
|
+
export const literalSpecifier = (node) =>
|
|
41
|
+
node?.type === 'Literal'
|
|
42
|
+
? node.value
|
|
43
|
+
: node?.type === 'TemplateLiteral' && node.expressions.length === 0
|
|
44
|
+
? node.quasis[0].value.cooked
|
|
45
|
+
: undefined
|
|
46
|
+
|
|
47
|
+
/** Every place a specifier is named outside an import or export declaration, each handed to `check`. */
|
|
48
|
+
export const declarationlessVisitors = (check) => ({
|
|
49
|
+
ImportExpression: (node) => check(node.source),
|
|
50
|
+
TSImportType: (node) => check(node.source),
|
|
51
|
+
'CallExpression[callee.name="require"]': (node) => check(node.arguments[0]),
|
|
52
|
+
// A test inside the fence loads the real module with these, exactly as with import().
|
|
53
|
+
'CallExpression[callee.object.name=/^(vi|jest)$/][callee.property.name=/^(importActual|requireActual|importMock|requireMock)$/]':
|
|
54
|
+
(node) => check(node.arguments[0]),
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
/** Every declaration that names a specifier, each handed to `check` with the node to report. */
|
|
58
|
+
export const declarationVisitors = (check) => ({
|
|
59
|
+
ImportDeclaration: (node) => check(node, node.source),
|
|
60
|
+
ExportNamedDeclaration: (node) => node.source && check(node, node.source),
|
|
61
|
+
ExportAllDeclaration: (node) => check(node, node.source),
|
|
62
|
+
TSImportEqualsDeclaration: (node) =>
|
|
63
|
+
node.moduleReference.type === 'TSExternalModuleReference' && check(node, node.moduleReference.expression),
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* A declaration that is type-only as a whole (`import type …`, `export type … from`, `export type * from`,
|
|
68
|
+
* `import type x = require(…)`): TypeScript erases it under every setting, so it loads nothing. An inline
|
|
69
|
+
* `import { type X } from …` is not one: under `verbatimModuleSyntax` it is emitted as `import {} from …`, which loads
|
|
70
|
+
* the module.
|
|
71
|
+
* @param {any} node
|
|
72
|
+
*/
|
|
73
|
+
const isTypeOnly = (node) => node.importKind === 'type' || node.exportKind === 'type'
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* A fence over import and export DECLARATIONS: one finding per matching pattern, reported on the declaration with
|
|
77
|
+
* the pattern's own message. `allowTypeOnly` lets a type-only declaration through, for a fence about what a module
|
|
78
|
+
* LOADS rather than what it may name.
|
|
79
|
+
* @returns {import('eslint').Rule.RuleModule}
|
|
80
|
+
*/
|
|
81
|
+
export const declarationImportBan = ({ description, patterns, allowTypeOnly = false }) => {
|
|
82
|
+
const matches = matchesPatterns(patterns)
|
|
83
|
+
return {
|
|
84
|
+
meta: {
|
|
85
|
+
type: 'problem',
|
|
86
|
+
docs: { description },
|
|
87
|
+
schema: [],
|
|
88
|
+
messages: { banned: "'{{specifier}}' import is restricted from being used by a pattern. {{rule}}" },
|
|
89
|
+
},
|
|
90
|
+
create(context) {
|
|
91
|
+
return declarationVisitors((node, source) => {
|
|
92
|
+
if (allowTypeOnly && isTypeOnly(node)) return
|
|
93
|
+
const specifier = literalSpecifier(source)
|
|
94
|
+
if (typeof specifier !== 'string') return
|
|
95
|
+
for (const rule of matches(specifier.trim())) {
|
|
96
|
+
context.report({ node, messageId: 'banned', data: { specifier: specifier.trim(), rule } })
|
|
97
|
+
}
|
|
98
|
+
})
|
|
99
|
+
},
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A fence over everything a declaration ban cannot see. `what` names the thing the specifier is; `matches` returns
|
|
105
|
+
* the fence's own sentence for each pattern a banned specifier matches, and nothing for an allowed one.
|
|
106
|
+
* @returns {import('eslint').Rule.RuleModule}
|
|
107
|
+
*/
|
|
108
|
+
export const declarationlessImportBan = ({ description, what, matches }) => ({
|
|
109
|
+
meta: {
|
|
110
|
+
type: 'problem',
|
|
111
|
+
docs: { description },
|
|
112
|
+
schema: [],
|
|
113
|
+
messages: {
|
|
114
|
+
banned:
|
|
115
|
+
`\`{{specifier}}\` is ${what}, and reaching it with import() or require(), or naming it in a type ` +
|
|
116
|
+
"import('…'), is still importing it. {{rule}}",
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
create(context) {
|
|
120
|
+
return declarationlessVisitors((node) => {
|
|
121
|
+
const specifier = literalSpecifier(node)
|
|
122
|
+
if (typeof specifier !== 'string') return
|
|
123
|
+
for (const rule of matches(specifier.trim())) {
|
|
124
|
+
context.report({ node, messageId: 'banned', data: { specifier, rule } })
|
|
125
|
+
}
|
|
126
|
+
})
|
|
127
|
+
},
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* A fence over syntax: one esquery selector per message, each its own messageId, in a rule with its own id.
|
|
132
|
+
* @param {{ description: string, selectors: Record<string, { selector: string, message: string }> }} spec
|
|
133
|
+
* @returns {import('eslint').Rule.RuleModule}
|
|
134
|
+
*/
|
|
135
|
+
export const syntaxBan = ({ description, selectors }) => ({
|
|
136
|
+
meta: {
|
|
137
|
+
type: 'problem',
|
|
138
|
+
docs: { description },
|
|
139
|
+
schema: [],
|
|
140
|
+
messages: Object.fromEntries(Object.entries(selectors).map(([id, { message }]) => [id, message])),
|
|
141
|
+
},
|
|
142
|
+
create(context) {
|
|
143
|
+
return Object.fromEntries(
|
|
144
|
+
Object.entries(selectors).map(([messageId, { selector }]) => [
|
|
145
|
+
selector,
|
|
146
|
+
(node) => context.report({ node, messageId }),
|
|
147
|
+
]),
|
|
148
|
+
)
|
|
149
|
+
},
|
|
150
|
+
})
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ESLint, Linter, Rule } from 'eslint'
|
|
2
|
+
|
|
3
|
+
export interface AppConfigOptions {
|
|
4
|
+
/**
|
|
5
|
+
* The app's directory, as an absolute path: `import.meta.dirname` from the app's own `eslint.config.mjs`, or
|
|
6
|
+
* `join(import.meta.dirname, 'apps/<app>')` from a workspace root. A last segment of `*` means every app in
|
|
7
|
+
* that directory.
|
|
8
|
+
*/
|
|
9
|
+
root: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface SssbPlugin extends ESLint.Plugin {
|
|
13
|
+
meta: { name: string; version: string; namespace: 'sssb' }
|
|
14
|
+
rules: Record<string, Rule.RuleModule>
|
|
15
|
+
configs: {
|
|
16
|
+
/** The base config and every app-side fence, each block anchored (`basePath`) at `root`, or at its parent directory when `root`'s last segment is `*`. */
|
|
17
|
+
app(options: AppConfigOptions): Promise<Linter.Config[]>
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
declare const plugin: SssbPlugin
|
|
22
|
+
export default plugin
|
package/src/index.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// @sssb/eslint-plugin (ADR-0014, part 4 and step P6): ONE plugin object carrying every sssb/* rule, and the app
|
|
2
|
+
// preset, `configs.app({ root })`. An app binds it as `sssb`; SSSB's own repository imports this same object for its
|
|
3
|
+
// internal blocks, so the two can never be "different plugins" for a file both match.
|
|
4
|
+
import { readFileSync } from 'node:fs'
|
|
5
|
+
import { appConfig } from './app-config.js'
|
|
6
|
+
import { rules } from './rules.js'
|
|
7
|
+
|
|
8
|
+
const { name, version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
|
|
9
|
+
|
|
10
|
+
/** @type {import('./index.d.ts').SssbPlugin} */
|
|
11
|
+
const plugin = {
|
|
12
|
+
meta: { name, version, namespace: 'sssb' },
|
|
13
|
+
rules,
|
|
14
|
+
configs: {
|
|
15
|
+
app: (options) => appConfig(plugin, options),
|
|
16
|
+
},
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Frozen, with every rule and its meta: an app's config is code, and one that rewrote a rule's `create` on this shared
|
|
20
|
+
// object could unfence its files while every config comparison still matched. A frozen object makes that a TypeError
|
|
21
|
+
// in an ES-module config, and a silent no-op in a sloppy CommonJS one; either way the rule is unchanged.
|
|
22
|
+
for (const rule of Object.values(rules)) {
|
|
23
|
+
Object.freeze(rule.meta)
|
|
24
|
+
Object.freeze(rule)
|
|
25
|
+
}
|
|
26
|
+
Object.freeze(rules)
|
|
27
|
+
Object.freeze(plugin.meta)
|
|
28
|
+
Object.freeze(plugin.configs)
|
|
29
|
+
Object.freeze(plugin)
|
|
30
|
+
|
|
31
|
+
export default plugin
|