@intellectual-frontiers/lint 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/plugin.d.ts +31 -0
- package/dist/plugin.js +19 -0
- package/dist/rule.d.ts +207 -0
- package/dist/rule.js +125 -0
- package/dist/rules/import-boundary.d.ts +7 -0
- package/dist/rules/import-boundary.js +64 -0
- package/dist/rules/module-doc.d.ts +3 -0
- package/dist/rules/module-doc.js +39 -0
- package/dist/rules/no-registry-import.d.ts +5 -0
- package/dist/rules/no-registry-import.js +46 -0
- package/dist/rules/no-vendor-api.d.ts +5 -0
- package/dist/rules/no-vendor-api.js +46 -0
- package/dist/rules/switch-absurd.d.ts +5 -0
- package/dist/rules/switch-absurd.js +72 -0
- package/dist/rules/terminal-writers.d.ts +10 -0
- package/dist/rules/terminal-writers.js +53 -0
- package/dist/test-rule.d.ts +32 -0
- package/dist/test-rule.js +100 -0
- package/package.json +50 -4
- package/src/plugin.ts +49 -0
- package/src/rule.ts +281 -0
- package/src/rules/import-boundary.ts +64 -0
- package/src/rules/module-doc.ts +43 -0
- package/src/rules/no-registry-import.ts +48 -0
- package/src/rules/no-vendor-api.ts +50 -0
- package/src/rules/switch-absurd.ts +71 -0
- package/src/rules/terminal-writers.ts +57 -0
- package/src/test-rule.ts +130 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `switch-absurd` (commons lint 0001-lint FR-007): a `switch` over a union, on its discriminant (`x.kind` by default), ends in
|
|
3
|
+
* a `default` that calls `absurd` (`default: return absurd(x)`), so that an alternative added to the union and left out does not
|
|
4
|
+
* compile. A JavaScript rule has no types, so a switch over a union is a switch on a member named as one of the option `discriminants`;
|
|
5
|
+
* with `every`, every switch is held to it.
|
|
6
|
+
*
|
|
7
|
+
* Options: `discriminants` (`["kind"]` by default), `functions` (the names of the exhaustive end, `["absurd"]` by default), `every` and
|
|
8
|
+
* `allow` (`[{ files, reason }]`).
|
|
9
|
+
*
|
|
10
|
+
* Spec: 0001-lint FR-007
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
import { array, boolean, string } from "@intellectual-frontiers/core";
|
|
15
|
+
import { allowedFor, allowList, defineRule, fileOf, isIdentifier, isMember, isNode, propertyOf } from "../rule.js";
|
|
16
|
+
/** Whether a statement of a `default` calls one of the functions: `f(x);`, `return f(x);`, `throw f(x);`, or in a block. */
|
|
17
|
+
export function callsOneOf(node, functions) {
|
|
18
|
+
if (node === null || node === undefined)
|
|
19
|
+
return false;
|
|
20
|
+
const child = (key) => (key in node ? Reflect.get(node, key) : undefined);
|
|
21
|
+
switch (node.type) {
|
|
22
|
+
case "ReturnStatement":
|
|
23
|
+
case "ThrowStatement": {
|
|
24
|
+
const argument = child("argument");
|
|
25
|
+
return isNode(argument) && callsOneOf(argument, functions);
|
|
26
|
+
}
|
|
27
|
+
case "ExpressionStatement": {
|
|
28
|
+
const expression = child("expression");
|
|
29
|
+
return isNode(expression) && callsOneOf(expression, functions);
|
|
30
|
+
}
|
|
31
|
+
case "BlockStatement": {
|
|
32
|
+
const body = child("body");
|
|
33
|
+
return Array.isArray(body) && body.some((s) => isNode(s) && callsOneOf(s, functions));
|
|
34
|
+
}
|
|
35
|
+
case "CallExpression": {
|
|
36
|
+
const callee = child("callee");
|
|
37
|
+
if (!isNode(callee))
|
|
38
|
+
return false;
|
|
39
|
+
if (isIdentifier(callee))
|
|
40
|
+
return functions.includes(callee.name);
|
|
41
|
+
const name = isMember(callee) ? propertyOf(callee) : undefined;
|
|
42
|
+
return name !== undefined && functions.includes(name);
|
|
43
|
+
}
|
|
44
|
+
default:
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** The rule. */
|
|
49
|
+
export const switchAbsurd = defineRule({
|
|
50
|
+
description: "a switch over a union ends in a default that calls absurd",
|
|
51
|
+
options: { discriminants: array(string), functions: array(string), every: boolean, allow: allowList },
|
|
52
|
+
}, (context, options) => {
|
|
53
|
+
if (allowedFor(options.allow, fileOf(context)) !== undefined)
|
|
54
|
+
return {};
|
|
55
|
+
const discriminants = options.discriminants ?? ["kind"];
|
|
56
|
+
const functions = options.functions ?? ["absurd"];
|
|
57
|
+
return {
|
|
58
|
+
SwitchStatement: (node) => {
|
|
59
|
+
const d = node.discriminant;
|
|
60
|
+
const property = isMember(d) ? propertyOf(d) : undefined;
|
|
61
|
+
if (options.every !== true && (property === undefined || !discriminants.includes(property)))
|
|
62
|
+
return;
|
|
63
|
+
const last = node.cases.at(-1);
|
|
64
|
+
if (last !== undefined && last.test === null && last.consequent.some((s) => callsOneOf(s, functions)))
|
|
65
|
+
return;
|
|
66
|
+
context.report({
|
|
67
|
+
node,
|
|
68
|
+
message: `end this switch in \`default: return ${functions[0] ?? "absurd"}(value)\`, so that an alternative left out does not compile`,
|
|
69
|
+
});
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type Rule } from "../rule.js";
|
|
2
|
+
/** A writer: a global's member (`process.stdout`), or any of its members (`console.*`). */
|
|
3
|
+
export type Writer = {
|
|
4
|
+
readonly object: string;
|
|
5
|
+
readonly property: string;
|
|
6
|
+
};
|
|
7
|
+
/** The writers the rule refuses where none are given. */
|
|
8
|
+
export declare const TERMINAL_WRITERS: readonly Writer[];
|
|
9
|
+
/** The rule. */
|
|
10
|
+
export declare const terminalWriters: Rule;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `terminal-writers` (commons lint 0001-lint FR-008): nothing writes to the terminal (`process.stdout`, `process.stderr`,
|
|
3
|
+
* `console.*`, and the vendors' own streams) outside the files of the option `allow`, each with its reason; everything else emits a
|
|
4
|
+
* signal, or writes through the one module a harness lists. A named import of `stdout` or `stderr` from `node:process` is refused too.
|
|
5
|
+
*
|
|
6
|
+
* Options: `writers` (`[{ object, property }]`, `property` `*` for any member; the list above by default) and `allow` (`[{ files,
|
|
7
|
+
* reason }]`).
|
|
8
|
+
*
|
|
9
|
+
* Spec: 0001-lint FR-008
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
import { array, object, string } from "@intellectual-frontiers/core";
|
|
14
|
+
import { allowedFor, allowList, defineRule, fileOf, isIdentifier, isNode, nameOf, stringOf } from "../rule.js";
|
|
15
|
+
/** The writers the rule refuses where none are given. */
|
|
16
|
+
export const TERMINAL_WRITERS = [
|
|
17
|
+
{ object: "process", property: "stdout" },
|
|
18
|
+
{ object: "process", property: "stderr" },
|
|
19
|
+
{ object: "console", property: "*" },
|
|
20
|
+
{ object: "Bun", property: "stdout" },
|
|
21
|
+
{ object: "Bun", property: "stderr" },
|
|
22
|
+
];
|
|
23
|
+
/** The rule. */
|
|
24
|
+
export const terminalWriters = defineRule({
|
|
25
|
+
description: "no write to the terminal outside the files listed with their reasons",
|
|
26
|
+
options: { writers: array(object({ object: string, property: string })), allow: allowList },
|
|
27
|
+
}, (context, options) => {
|
|
28
|
+
if (allowedFor(options.allow, fileOf(context)) !== undefined)
|
|
29
|
+
return {};
|
|
30
|
+
const writers = options.writers ?? TERMINAL_WRITERS;
|
|
31
|
+
const writes = (o, p) => writers.some((w) => w.object === o && (w.property === "*" || w.property === p));
|
|
32
|
+
const message = (what) => `${what} writes to the terminal: emit a signal or write through the module listed for it, or list this file with its reason in allow`;
|
|
33
|
+
return {
|
|
34
|
+
MemberExpression: (node) => {
|
|
35
|
+
const name = nameOf(node);
|
|
36
|
+
if (name !== undefined && writes(name[0], name[1]))
|
|
37
|
+
context.report({ node, message: message(`${name[0]}.${name[1]}`) });
|
|
38
|
+
},
|
|
39
|
+
ImportDeclaration: (node) => {
|
|
40
|
+
const source = stringOf(node.source);
|
|
41
|
+
if (source !== "node:process" && source !== "process")
|
|
42
|
+
return;
|
|
43
|
+
for (const s of node.specifiers) {
|
|
44
|
+
if (s.type !== "ImportSpecifier" || !("imported" in s))
|
|
45
|
+
continue;
|
|
46
|
+
const imported = s.imported;
|
|
47
|
+
const text = isNode(imported) ? (isIdentifier(imported) ? imported.name : stringOf(imported)) : undefined;
|
|
48
|
+
if (text !== undefined && writes("process", text))
|
|
49
|
+
context.report({ node: s, message: message(`process.${text}`) });
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Result } from "@intellectual-frontiers/core";
|
|
2
|
+
/** The Bun whose `lint` runs ESLint plugins, until a release has it (FR-028). */
|
|
3
|
+
export declare const LINT_BUN_VERSION = "1.4.4-canary.20261115.1";
|
|
4
|
+
/** The plugin of this folder. */
|
|
5
|
+
export declare const PLUGIN_PATH: string;
|
|
6
|
+
/** A problem the linter reported: the file (as given), the rule without its prefix, the line and column from 1, and the message. */
|
|
7
|
+
export type Problem = {
|
|
8
|
+
readonly file: string;
|
|
9
|
+
readonly rule: string;
|
|
10
|
+
readonly line: number;
|
|
11
|
+
readonly column: number;
|
|
12
|
+
readonly message: string;
|
|
13
|
+
};
|
|
14
|
+
/** A rule to run: its name, its options object, the files (relative paths and their text), and the plugin (this folder's by default). */
|
|
15
|
+
export type LintRun = {
|
|
16
|
+
readonly rule: string;
|
|
17
|
+
readonly options?: unknown;
|
|
18
|
+
readonly files: Readonly<Record<string, string>>;
|
|
19
|
+
readonly plugin?: string;
|
|
20
|
+
/** The plugin's name, the prefix of its rules (`ifc` by default). */
|
|
21
|
+
readonly prefix?: string;
|
|
22
|
+
};
|
|
23
|
+
/** The command that runs `bun lint`, without `lint`: `IFC_LINT_BUN`, or the pinned canary through `bun x --no-install`. */
|
|
24
|
+
export declare function lintCommand(): readonly string[];
|
|
25
|
+
/** The linter's command where it runs and can load a plugin, or why not. */
|
|
26
|
+
export declare function linter(): Promise<Result<readonly string[], string>>;
|
|
27
|
+
/**
|
|
28
|
+
* The problems one rule of a plugin finds in the files given (0001-lint FR-009), by running `bun lint` over them in a new folder (its working
|
|
29
|
+
* folder, with a `bunfig.toml` of an empty `[lint]`), the rule set to `error` with its options. Problems of other rules (Bun's own
|
|
30
|
+
* defaults) are left out. An error where the linter fails (exit 2: a rule threw, or the plugin did not load).
|
|
31
|
+
*/
|
|
32
|
+
export declare function lintFiles(r: LintRun): Promise<Result<readonly Problem[], string>>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A rule of a lint plugin run against code, in a test (commons lint 0001-lint FR-009): the files are written to a new folder
|
|
3
|
+
* and the real linter, `bun lint` of the pinned Bun, is run over them with the plugin loaded by `--plugin` and only the rule turned on
|
|
4
|
+
* by `--rule`, so that a test proves the rule and the way `bun lint` loads it. Its problems come back from its JSON report, decoded.
|
|
5
|
+
*
|
|
6
|
+
* The linter is the Bun named by `IFC_LINT_BUN` (a path to a Bun whose `lint` runs plugins), else the pinned canary through `bun x
|
|
7
|
+
* --no-install bun@<LINT_BUN_VERSION>`, which is never fetched here: where it is not installed, `linter()` says so and the tests that
|
|
8
|
+
* need it are skipped with that reason (`bun x bun@<LINT_BUN_VERSION> --version` installs it).
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { lintFiles } from "./test-rule.ts";
|
|
13
|
+
* const problems = await lintFiles({ rule: "no-registry-import", files: { "a.ts": 'import x from "npm:x";\nexport { x };\n' } });
|
|
14
|
+
* // { kind: "ok", value: [{ file: "a.ts", rule: "no-registry-import", line: 1, column: 1, message: "..." }] }
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* Spec: 0001-lint FR-009
|
|
18
|
+
*
|
|
19
|
+
* @module
|
|
20
|
+
*/
|
|
21
|
+
import { existsSync } from "node:fs";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
import { array, integer, json, nullable, object, string, err, ok } from "@intellectual-frontiers/core";
|
|
24
|
+
import { makeTempDir, mkdir, readTextFile, realPath, remove, writeTextFile } from "@intellectual-frontiers/system/fs";
|
|
25
|
+
import { dirname, join, relative } from "@intellectual-frontiers/system/path";
|
|
26
|
+
import { env, run } from "@intellectual-frontiers/system/proc";
|
|
27
|
+
/** The Bun whose `lint` runs ESLint plugins, until a release has it (FR-028). */
|
|
28
|
+
export const LINT_BUN_VERSION = "1.4.4-canary.20261115.1";
|
|
29
|
+
/** The plugin of this folder. */
|
|
30
|
+
export const PLUGIN_PATH = fileURLToPath(new URL(existsSync(new URL("./plugin.ts", import.meta.url)) ? "./plugin.ts" : "./plugin.js", import.meta.url));
|
|
31
|
+
/** The command that runs `bun lint`, without `lint`: `IFC_LINT_BUN`, or the pinned canary through `bun x --no-install`. */
|
|
32
|
+
export function lintCommand() {
|
|
33
|
+
const given = env.get("IFC_LINT_BUN")?.trim();
|
|
34
|
+
return given !== undefined && given !== "" ? [given] : ["bun", "x", "--no-install", `bun@${LINT_BUN_VERSION}`];
|
|
35
|
+
}
|
|
36
|
+
/** The linter's command where it runs and can load a plugin, or why not. */
|
|
37
|
+
export async function linter() {
|
|
38
|
+
const command = lintCommand();
|
|
39
|
+
try {
|
|
40
|
+
const r = await run([...command, "lint", "--help", "--all"]);
|
|
41
|
+
if (r.success && r.stdout.includes("--plugin"))
|
|
42
|
+
return ok(command);
|
|
43
|
+
return err(`${command.join(" ")} lint does not load plugins here (exit ${r.code}); run bun x bun@${LINT_BUN_VERSION} --version once`);
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
return err(`${command.join(" ")} does not run here: ${e instanceof Error ? e.message : String(e)}`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const report = array(object({ filePath: string }, { messages: array(object({ message: string }, { ruleId: nullable(string), line: integer, column: integer })) }));
|
|
50
|
+
/**
|
|
51
|
+
* The problems one rule of a plugin finds in the files given (0001-lint FR-009), by running `bun lint` over them in a new folder (its working
|
|
52
|
+
* folder, with a `bunfig.toml` of an empty `[lint]`), the rule set to `error` with its options. Problems of other rules (Bun's own
|
|
53
|
+
* defaults) are left out. An error where the linter fails (exit 2: a rule threw, or the plugin did not load).
|
|
54
|
+
*/
|
|
55
|
+
export async function lintFiles(r) {
|
|
56
|
+
const prefix = r.prefix ?? "ifc";
|
|
57
|
+
const dir = await makeTempDir({ prefix: "ifc-lint-" });
|
|
58
|
+
try {
|
|
59
|
+
await writeTextFile(join(dir, "bunfig.toml"), "[lint]\n");
|
|
60
|
+
const names = Object.keys(r.files);
|
|
61
|
+
for (const [name, text] of Object.entries(r.files)) {
|
|
62
|
+
const path = join(dir, name);
|
|
63
|
+
await mkdir(dirname(path), { recursive: true });
|
|
64
|
+
await writeTextFile(path, text);
|
|
65
|
+
}
|
|
66
|
+
const out = join(dir, "report.json");
|
|
67
|
+
const setting = r.options === undefined ? ["error"] : ["error", r.options];
|
|
68
|
+
const result = await run([
|
|
69
|
+
...lintCommand(),
|
|
70
|
+
"lint",
|
|
71
|
+
"--format",
|
|
72
|
+
"json",
|
|
73
|
+
"--output-file",
|
|
74
|
+
out,
|
|
75
|
+
`--plugin=${r.plugin ?? PLUGIN_PATH}`,
|
|
76
|
+
"--rule",
|
|
77
|
+
JSON.stringify({ [`${prefix}/${r.rule}`]: setting }),
|
|
78
|
+
...names,
|
|
79
|
+
], { cwd: dir });
|
|
80
|
+
if (result.code !== 0 && result.code !== 1)
|
|
81
|
+
return err(`bun lint exited with ${result.code}: ${result.stderr}${result.stdout}`);
|
|
82
|
+
const decoded = json(await readTextFile(out), report);
|
|
83
|
+
if (decoded.kind === "err")
|
|
84
|
+
return err(`bun lint's report is not what it should be: ${decoded.error.expected} at ${decoded.error.path}`);
|
|
85
|
+
const problems = [];
|
|
86
|
+
const real = await realPath(dir);
|
|
87
|
+
for (const f of decoded.value) {
|
|
88
|
+
const file = relative(real, await realPath(f.filePath)).replaceAll("\\", "/");
|
|
89
|
+
for (const m of f.messages ?? []) {
|
|
90
|
+
if (m.ruleId === undefined || m.ruleId === null || !m.ruleId.startsWith(`${prefix}/`))
|
|
91
|
+
continue;
|
|
92
|
+
problems.push({ file, rule: m.ruleId.slice(prefix.length + 1), line: m.line ?? 0, column: m.column ?? 0, message: m.message });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return ok(problems.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line || a.column - b.column)));
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
await remove(dir, { recursive: true });
|
|
99
|
+
}
|
|
100
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intellectual-frontiers/lint",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "The lint plugin of Intellectual Frontiers in the ESLint plugin format that bun lint --plugin loads, with the rules every harness wants (no vendor API, no registry import, import boundaries, a module block in every file, absurd in every switch, no write to the terminal outside a list) and the typed way to define a rule of its own and to test it against the real linter.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=26"
|
|
9
|
+
},
|
|
10
|
+
"sideEffects": false,
|
|
11
|
+
"types": "./dist/plugin.d.ts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/plugin.d.ts",
|
|
15
|
+
"bun": "./src/plugin.ts",
|
|
16
|
+
"default": "./dist/plugin.js"
|
|
17
|
+
},
|
|
18
|
+
"./rule": {
|
|
19
|
+
"types": "./dist/rule.d.ts",
|
|
20
|
+
"bun": "./src/rule.ts",
|
|
21
|
+
"default": "./dist/rule.js"
|
|
22
|
+
},
|
|
23
|
+
"./test-rule": {
|
|
24
|
+
"types": "./dist/test-rule.d.ts",
|
|
25
|
+
"bun": "./src/test-rule.ts",
|
|
26
|
+
"default": "./dist/test-rule.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@intellectual-frontiers/core": "0.1.3",
|
|
31
|
+
"@intellectual-frontiers/formats": "0.1.3",
|
|
32
|
+
"@intellectual-frontiers/system": "0.1.3"
|
|
33
|
+
},
|
|
34
|
+
"files": [
|
|
35
|
+
"dist",
|
|
36
|
+
"src",
|
|
37
|
+
"README.md",
|
|
38
|
+
"LICENSE"
|
|
39
|
+
],
|
|
40
|
+
"repository": {
|
|
41
|
+
"type": "git",
|
|
42
|
+
"url": "git+https://github.com/intellectual-frontiers/.github.git",
|
|
43
|
+
"directory": "commons/lint"
|
|
44
|
+
},
|
|
45
|
+
"homepage": "https://github.com/intellectual-frontiers/.github/tree/main/commons/lint",
|
|
46
|
+
"bugs": {
|
|
47
|
+
"url": "https://github.com/intellectual-frontiers/.github/issues"
|
|
48
|
+
},
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public"
|
|
51
|
+
}
|
|
52
|
+
}
|
package/src/plugin.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IFC TypeScript's lint plugin in the ESLint plugin format (commons lint 0001-lint FR-001), named `ifc`, which `bun lint`
|
|
3
|
+
* loads from this file as it is (TypeScript, no build): `bun lint --plugin=<path to lint/plugin.ts> --rule '{"ifc/no-vendor-api":
|
|
4
|
+
* ["error", {...}]}'` for one run, or in `bunfig.toml`:
|
|
5
|
+
*
|
|
6
|
+
* ```toml
|
|
7
|
+
* [lint]
|
|
8
|
+
* plugins = ["./lint/plugin.ts"] # relative to bunfig.toml
|
|
9
|
+
*
|
|
10
|
+
* [lint.rules]
|
|
11
|
+
* "ifc/no-vendor-api" = ["error", { allow = [{ files = "src/host/**", reason = "the one module that wraps the vendor's API" }] }]
|
|
12
|
+
* "ifc/terminal-writers" = ["error", { allow = [{ files = "src/console.ts", reason = "the renderer, the one writer for a person" }] }]
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* The rules every harness wants, each taking its lists from its options so that a harness keeps its own lists and adds its own rules
|
|
16
|
+
* (as its own plugin, with `defineRule` of `./rule.ts`):
|
|
17
|
+
* - `no-vendor-api`: no member of a vendor's global (`Bun.*` and the like) outside the files listed with their reasons;
|
|
18
|
+
* - `no-registry-import`: no `npm:`, `jsr:` or URL specifier;
|
|
19
|
+
* - `import-boundary`: a relative import that leaves its package (the option `roots`) is refused;
|
|
20
|
+
* - `module-doc`: every file begins with a JSDoc block that says `@module`;
|
|
21
|
+
* - `switch-absurd`: a `switch` on a union's `kind` ends in `default` calling `absurd`;
|
|
22
|
+
* - `terminal-writers`: no write to the terminal outside the files listed with their reasons.
|
|
23
|
+
*
|
|
24
|
+
* Spec: 0001-lint FR-001
|
|
25
|
+
*
|
|
26
|
+
* @module
|
|
27
|
+
*/
|
|
28
|
+
import type { Plugin } from "./rule.ts";
|
|
29
|
+
import { importBoundary } from "./rules/import-boundary.ts";
|
|
30
|
+
import { moduleDoc } from "./rules/module-doc.ts";
|
|
31
|
+
import { noRegistryImport } from "./rules/no-registry-import.ts";
|
|
32
|
+
import { noVendorApi } from "./rules/no-vendor-api.ts";
|
|
33
|
+
import { switchAbsurd } from "./rules/switch-absurd.ts";
|
|
34
|
+
import { terminalWriters } from "./rules/terminal-writers.ts";
|
|
35
|
+
|
|
36
|
+
/** The plugin: `ifc`, the prefix of its rules' ids, and its rules. */
|
|
37
|
+
const plugin: Plugin = {
|
|
38
|
+
meta: { name: "ifc", version: "0.5.0" },
|
|
39
|
+
rules: {
|
|
40
|
+
"no-vendor-api": noVendorApi,
|
|
41
|
+
"no-registry-import": noRegistryImport,
|
|
42
|
+
"import-boundary": importBoundary,
|
|
43
|
+
"module-doc": moduleDoc,
|
|
44
|
+
"switch-absurd": switchAbsurd,
|
|
45
|
+
"terminal-writers": terminalWriters,
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export default plugin;
|
package/src/rule.ts
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The typed way to define a lint rule in the ESLint plugin format that `bun lint --plugin` loads (commons lint 0001-lint
|
|
3
|
+
* FR-002): the few ESTree nodes the rules of `./rules/` read (as typescript-estree gives them to a plugin, written here, without
|
|
4
|
+
* `@types/eslint`), a rule's context, its visitor, `defineRule`, which decodes a rule's options once with the kernel's decoders and
|
|
5
|
+
* reports options that do not decode instead of running, and what the rules share: a list of files, each with its reason, by glob
|
|
6
|
+
* (`allowList`), the file being linted relative to the working folder (`fileOf`), and the names a node gives (`nameOf`, `stringOf`).
|
|
7
|
+
*
|
|
8
|
+
* A rule takes one options object, the second element of its setting: `"ifc/no-vendor-api" = ["error", { allow = [...] }]` in
|
|
9
|
+
* `bunfig.toml`'s `[lint.rules]`, or `--rule '{"ifc/no-vendor-api": ["error", {...}]}'`. Rules never get types: a JavaScript rule of
|
|
10
|
+
* `bun lint` has no `parserServices.program`.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { boolean } from "@intellectual-frontiers/core";
|
|
15
|
+
* import { defineRule } from "./rule.ts";
|
|
16
|
+
* export const noDebugger = defineRule({ description: "no debugger statement", options: { strict: boolean } }, (context, options) => ({
|
|
17
|
+
* DebuggerStatement: (node) => context.report({ node, message: options.strict === true ? "remove it" : "remove it, please" }),
|
|
18
|
+
* }));
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* Spec: 0001-lint FR-002
|
|
22
|
+
*
|
|
23
|
+
* @module
|
|
24
|
+
*/
|
|
25
|
+
import { relative } from "node:path";
|
|
26
|
+
import {
|
|
27
|
+
array,
|
|
28
|
+
type Decoded,
|
|
29
|
+
type Decoder,
|
|
30
|
+
type DecodeError,
|
|
31
|
+
type Fields,
|
|
32
|
+
formatDecodeError,
|
|
33
|
+
object,
|
|
34
|
+
string,
|
|
35
|
+
err,
|
|
36
|
+
ok,
|
|
37
|
+
} from "@intellectual-frontiers/core";
|
|
38
|
+
import { formatGlobError, globToRegExp } from "@intellectual-frontiers/formats/glob";
|
|
39
|
+
|
|
40
|
+
// ---------------------------------------------------------------------------------------------------------------------------- ESTree
|
|
41
|
+
|
|
42
|
+
/** Any node: its type, its offsets in the source (`range`), and its parent where the linter links them. */
|
|
43
|
+
export type Node = { readonly type: string; readonly range?: readonly [number, number]; readonly parent?: Node };
|
|
44
|
+
|
|
45
|
+
/** A name: `Bun`, `kind`. */
|
|
46
|
+
export type Identifier = Node & { readonly type: "Identifier"; readonly name: string };
|
|
47
|
+
|
|
48
|
+
/** A literal: a string, a number, a boolean, `null` or a regular expression. */
|
|
49
|
+
export type Literal = Node & { readonly type: "Literal"; readonly value: unknown };
|
|
50
|
+
|
|
51
|
+
/** `a.b` or `a[b]`. */
|
|
52
|
+
export type MemberExpression = Node & {
|
|
53
|
+
readonly type: "MemberExpression";
|
|
54
|
+
readonly object: Node;
|
|
55
|
+
readonly property: Node;
|
|
56
|
+
readonly computed: boolean;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** `f(x)`. */
|
|
60
|
+
export type CallExpression = Node & { readonly type: "CallExpression"; readonly callee: Node; readonly arguments: readonly Node[] };
|
|
61
|
+
|
|
62
|
+
/** `import ... from "x"`. */
|
|
63
|
+
export type ImportDeclaration = Node & {
|
|
64
|
+
readonly type: "ImportDeclaration";
|
|
65
|
+
readonly source: Literal;
|
|
66
|
+
readonly specifiers: readonly Node[];
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** `export * from "x"`. */
|
|
70
|
+
export type ExportAllDeclaration = Node & { readonly type: "ExportAllDeclaration"; readonly source: Literal };
|
|
71
|
+
|
|
72
|
+
/** `export { a } from "x"`, or `export { a }` (no source). */
|
|
73
|
+
export type ExportNamedDeclaration = Node & { readonly type: "ExportNamedDeclaration"; readonly source: Literal | null };
|
|
74
|
+
|
|
75
|
+
/** `import("x")`. */
|
|
76
|
+
export type ImportExpression = Node & { readonly type: "ImportExpression"; readonly source: Node };
|
|
77
|
+
|
|
78
|
+
/** `typeof import("x")` in a type. */
|
|
79
|
+
export type TSImportType = Node & { readonly type: "TSImportType"; readonly source?: Node; readonly argument?: Node };
|
|
80
|
+
|
|
81
|
+
/** `import x = require("x")`'s reference. */
|
|
82
|
+
export type TSExternalModuleReference = Node & { readonly type: "TSExternalModuleReference"; readonly expression: Node };
|
|
83
|
+
|
|
84
|
+
/** `A.B` in a type. */
|
|
85
|
+
export type TSQualifiedName = Node & { readonly type: "TSQualifiedName"; readonly left: Node; readonly right: Node };
|
|
86
|
+
|
|
87
|
+
/** One `case` (or `default`, whose `test` is null) of a switch. */
|
|
88
|
+
export type SwitchCase = Node & { readonly type: "SwitchCase"; readonly test: Node | null; readonly consequent: readonly Node[] };
|
|
89
|
+
|
|
90
|
+
/** `switch (d) { ... }`. */
|
|
91
|
+
export type SwitchStatement = Node & {
|
|
92
|
+
readonly type: "SwitchStatement";
|
|
93
|
+
readonly discriminant: Node;
|
|
94
|
+
readonly cases: readonly SwitchCase[];
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/** The whole file. */
|
|
98
|
+
export type Program = Node & { readonly type: "Program"; readonly body: readonly Node[] };
|
|
99
|
+
|
|
100
|
+
/** `debugger;`. */
|
|
101
|
+
export type DebuggerStatement = Node & { readonly type: "DebuggerStatement" };
|
|
102
|
+
|
|
103
|
+
/** The nodes a visitor may name, by type. */
|
|
104
|
+
export type Nodes = {
|
|
105
|
+
readonly Program: Program;
|
|
106
|
+
readonly Identifier: Identifier;
|
|
107
|
+
readonly MemberExpression: MemberExpression;
|
|
108
|
+
readonly CallExpression: CallExpression;
|
|
109
|
+
readonly ImportDeclaration: ImportDeclaration;
|
|
110
|
+
readonly ExportAllDeclaration: ExportAllDeclaration;
|
|
111
|
+
readonly ExportNamedDeclaration: ExportNamedDeclaration;
|
|
112
|
+
readonly ImportExpression: ImportExpression;
|
|
113
|
+
readonly TSImportType: TSImportType;
|
|
114
|
+
readonly TSExternalModuleReference: TSExternalModuleReference;
|
|
115
|
+
readonly TSQualifiedName: TSQualifiedName;
|
|
116
|
+
readonly SwitchStatement: SwitchStatement;
|
|
117
|
+
readonly DebuggerStatement: DebuggerStatement;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
/** What a rule does on each node of a type, as the linter walks the file. */
|
|
121
|
+
export type Visitor = { readonly [K in keyof Nodes]?: (node: Nodes[K]) => void };
|
|
122
|
+
|
|
123
|
+
/** A comment: `Line` (`//`), `Block` (between `/*` and its end; its `value` starts with `*` for a JSDoc block) or the file's `Shebang`. */
|
|
124
|
+
export type Comment = { readonly type: "Line" | "Block" | "Shebang"; readonly value: string; readonly range: readonly [number, number] };
|
|
125
|
+
|
|
126
|
+
/** A place in the source: the line from 1 and the column from 0. */
|
|
127
|
+
export type Position = { readonly line: number; readonly column: number };
|
|
128
|
+
|
|
129
|
+
/** A problem a rule reports: at a node, or at a place. */
|
|
130
|
+
export type Report = { readonly node: Node; readonly message: string } | { readonly loc: Position; readonly message: string };
|
|
131
|
+
|
|
132
|
+
/** What a rule is given for each file, as ESLint gives it. */
|
|
133
|
+
export type RuleContext = {
|
|
134
|
+
/** The rule's id with its plugin's prefix: `ifc/no-vendor-api`. */
|
|
135
|
+
readonly id: string;
|
|
136
|
+
/** The file's absolute path. */
|
|
137
|
+
readonly filename: string;
|
|
138
|
+
/** The linter's working folder. */
|
|
139
|
+
readonly cwd: string;
|
|
140
|
+
/** The rule's options: what follows the severity in its setting. */
|
|
141
|
+
readonly options: readonly unknown[];
|
|
142
|
+
readonly sourceCode: { readonly text: string; readonly getAllComments: () => readonly Comment[] };
|
|
143
|
+
readonly report: (report: Report) => void;
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
/** A rule in ESLint's format. */
|
|
147
|
+
export type Rule = {
|
|
148
|
+
readonly meta: {
|
|
149
|
+
readonly type: "problem" | "suggestion";
|
|
150
|
+
readonly docs: { readonly description: string };
|
|
151
|
+
/** `false`: the options are decoded by the rule itself (`defineRule`), not by a JSON schema. */
|
|
152
|
+
readonly schema: false;
|
|
153
|
+
};
|
|
154
|
+
readonly create: (context: RuleContext) => Visitor;
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
/** A plugin in ESLint's format: its name, which is the prefix of its rules' ids, and its rules. */
|
|
158
|
+
export type Plugin = {
|
|
159
|
+
readonly meta: { readonly name: string; readonly version?: string };
|
|
160
|
+
readonly rules: Readonly<Record<string, Rule>>;
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
// ---------------------------------------------------------------------------------------------------------------------------- defining a rule
|
|
164
|
+
|
|
165
|
+
/** A rule's options as decoded: each of the decoders' fields, absent where it was not given. */
|
|
166
|
+
export type OptionsOf<O extends Fields> = { readonly [K in keyof O]?: Decoded<O[K]> };
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* A rule in ESLint's format from its description and the decoders of its optional options, and what it does with the options decoded
|
|
170
|
+
* (0001-lint FR-002). The options are the first after the severity, an object (absent is `{}`); options that do not decode are reported once, at
|
|
171
|
+
* the top of each file, and the rule does nothing else.
|
|
172
|
+
*/
|
|
173
|
+
export function defineRule<const O extends Fields>(
|
|
174
|
+
spec: { readonly description: string; readonly type?: "problem" | "suggestion"; readonly options: O },
|
|
175
|
+
create: (context: RuleContext, options: OptionsOf<O>) => Visitor,
|
|
176
|
+
): Rule {
|
|
177
|
+
const decode = object({}, spec.options);
|
|
178
|
+
return {
|
|
179
|
+
meta: { type: spec.type ?? "problem", docs: { description: spec.description }, schema: false },
|
|
180
|
+
create: (context: RuleContext): Visitor => {
|
|
181
|
+
const given: unknown = context.options[0] ?? {};
|
|
182
|
+
const options = decode(given);
|
|
183
|
+
if (options.kind === "err") {
|
|
184
|
+
const message = `${context.id}: its options are not right: ${formatDecodeError(options.error)}`;
|
|
185
|
+
return { Program: () => context.report({ loc: { line: 1, column: 0 }, message }) };
|
|
186
|
+
}
|
|
187
|
+
return create(context, options.value);
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ---------------------------------------------------------------------------------------------------------------------------- what rules share
|
|
193
|
+
|
|
194
|
+
/** A file, or files by glob, allowed what a rule refuses elsewhere, with the reason. */
|
|
195
|
+
export type Allowed = { readonly files: string; readonly reason: string; readonly pattern: RegExp };
|
|
196
|
+
|
|
197
|
+
const allowedEntry = object({ files: string, reason: string });
|
|
198
|
+
|
|
199
|
+
/** One allowed entry: `{ files, reason }`, the glob read as `kernel/glob.ts` reads one, the reason not empty. */
|
|
200
|
+
export const allowed: Decoder<Allowed> = (input, path = "$") => {
|
|
201
|
+
const e = allowedEntry(input, path);
|
|
202
|
+
if (e.kind === "err") return e;
|
|
203
|
+
const fail = (expected: string): ReturnType<Decoder<Allowed>> =>
|
|
204
|
+
err<DecodeError>({ kind: "decode", path, expected, found: JSON.stringify(input) });
|
|
205
|
+
if (e.value.reason.trim() === "") return fail("an entry with its reason (`reason` is empty)");
|
|
206
|
+
const pattern = globToRegExp(e.value.files);
|
|
207
|
+
if (pattern.kind === "err") return fail(`an entry whose files are a glob: ${formatGlobError(pattern.error)}`);
|
|
208
|
+
return ok({ files: e.value.files, reason: e.value.reason, pattern: pattern.value });
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
/** A list of files, each with its reason, as a rule's option `allow` (0001-lint FR-002). */
|
|
212
|
+
export const allowList: Decoder<readonly Allowed[]> = array(allowed);
|
|
213
|
+
|
|
214
|
+
/** The file being linted, relative to the linter's working folder, with `/`. */
|
|
215
|
+
export function fileOf(context: RuleContext): string {
|
|
216
|
+
return relative(context.cwd, context.filename).replaceAll("\\", "/");
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** The entry of the list that allows the file, if any. */
|
|
220
|
+
export function allowedFor(list: readonly Allowed[] | undefined, file: string): Allowed | undefined {
|
|
221
|
+
return list?.find((a) => a.pattern.test(file));
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Whether the node is the identifier, or any identifier where no name is given. */
|
|
225
|
+
export function isIdentifier(node: Node | null | undefined, name?: string): node is Identifier {
|
|
226
|
+
return (
|
|
227
|
+
node !== null &&
|
|
228
|
+
node !== undefined &&
|
|
229
|
+
node.type === "Identifier" &&
|
|
230
|
+
"name" in node &&
|
|
231
|
+
typeof node.name === "string" &&
|
|
232
|
+
(name === undefined || node.name === name)
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** The string a node holds: a string literal, a template with no expression, or a type's string literal (`TSLiteralType`). */
|
|
237
|
+
export function stringOf(node: Node | null | undefined): string | undefined {
|
|
238
|
+
if (node === null || node === undefined) return undefined;
|
|
239
|
+
if (node.type === "Literal" && "value" in node) return typeof node.value === "string" ? node.value : undefined;
|
|
240
|
+
if (node.type === "TSLiteralType" && "literal" in node && isNode(node.literal)) return stringOf(node.literal);
|
|
241
|
+
if (node.type === "TemplateLiteral" && "quasis" in node && "expressions" in node && Array.isArray(node.expressions)) {
|
|
242
|
+
const quasis: unknown = node.quasis;
|
|
243
|
+
if (node.expressions.length !== 0 || !Array.isArray(quasis)) return undefined;
|
|
244
|
+
const first: unknown = quasis[0];
|
|
245
|
+
if (typeof first !== "object" || first === null || !("value" in first)) return undefined;
|
|
246
|
+
const value: unknown = first.value;
|
|
247
|
+
return typeof value === "object" && value !== null && "cooked" in value && typeof value.cooked === "string" ? value.cooked : undefined;
|
|
248
|
+
}
|
|
249
|
+
return undefined;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Whether a value is a node. */
|
|
253
|
+
export function isNode(value: unknown): value is Node {
|
|
254
|
+
return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* The name a member expression's object and property give, `globalThis.` taken off the object: `Bun.file` is `["Bun",
|
|
259
|
+
* "file"]`, `globalThis.console.log` is `["console", "log"]`, `a["b"]` is `["a", "b"]`; undefined where either is not a name.
|
|
260
|
+
*/
|
|
261
|
+
export function nameOf(node: MemberExpression): readonly [string, string] | undefined {
|
|
262
|
+
const object = isIdentifier(node.object)
|
|
263
|
+
? node.object.name
|
|
264
|
+
: isMember(node.object) && isIdentifier(node.object.object, "globalThis")
|
|
265
|
+
? propertyOf(node.object)
|
|
266
|
+
: undefined;
|
|
267
|
+
const property = propertyOf(node);
|
|
268
|
+
return object === undefined || property === undefined ? undefined : [object, property];
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** The property a member expression names: `b` of `a.b` and of `a["b"]`. */
|
|
272
|
+
export function propertyOf(node: MemberExpression): string | undefined {
|
|
273
|
+
return node.computed ? stringOf(node.property) : isIdentifier(node.property) ? node.property.name : undefined;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Whether a node is a member expression. */
|
|
277
|
+
export function isMember(node: Node | null | undefined): node is MemberExpression {
|
|
278
|
+
return (
|
|
279
|
+
node !== null && node !== undefined && node.type === "MemberExpression" && "object" in node && isNode(node.object) && "property" in node
|
|
280
|
+
);
|
|
281
|
+
}
|