@mks2508/no-throw-lint 0.0.0-stage → 4.0.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/README.md +88 -2
- package/eslint.d.mts +7 -0
- package/eslint.mjs +89 -0
- package/nt-lint.d.mts +38 -0
- package/nt-lint.mjs +783 -0
- package/package.json +55 -4
- package/rules.mjs +115 -0
package/README.md
CHANGED
|
@@ -1,3 +1,89 @@
|
|
|
1
|
-
#
|
|
1
|
+
# lint — lo que los tipos no paran, y cómo se mide
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Este directorio es el paquete publicado `@mks2508/no-throw-lint`: bin
|
|
4
|
+
`nt-lint`, la API en `@mks2508/no-throw-lint` y el plugin de ESLint en
|
|
5
|
+
`@mks2508/no-throw-lint/eslint`. `typescript` 5–6 es dependencia suya, así
|
|
6
|
+
que `@mks2508/no-throw` no arrastra el compilador (con él como peer, el
|
|
7
|
+
linker isolated de bun instala una copia de la librería por cada versión de
|
|
8
|
+
TS, y los Result nominales no encajan entre copias). Los fixtures y las dos
|
|
9
|
+
medidas no se publican.
|
|
10
|
+
|
|
11
|
+
## nt-lint
|
|
12
|
+
|
|
13
|
+
Un script sobre la API del compilador de TypeScript. Reconoce un `Result`
|
|
14
|
+
**por su tipo**, no por su nombre: la misma vara para no-throw v4 y v3,
|
|
15
|
+
neverthrow, better-result, unthrown, byethrow, Effect y errore.
|
|
16
|
+
|
|
17
|
+
| regla | clase | qué para | ejemplo |
|
|
18
|
+
|---|---|---|---|
|
|
19
|
+
| `NT-A` | Result no comprobado | el Result se tira: una sentencia, un `void`, un callback que vuelve a un `void` | `await save()` suelto, `ids.forEach((id) => kill(id))` |
|
|
20
|
+
| `NT-B` | Result no comprobado | un Result usado como booleano | `if (await save())`, `!r`, `r && x`, `xs.filter((x) => check(x))` |
|
|
21
|
+
| `NT-C` | Result no comprobado | el Result guardado y nunca leído | `const r = save()` |
|
|
22
|
+
| `NT-D` | código equivocado | el código decidido por el texto de un fallo | `e.message.includes('timeout')`, `msg === 'x'`, `switch (e.message)` |
|
|
23
|
+
| `NT-E` | código equivocado | una cadena ancha forzada a un código `dominio.clave` | `wire.code as Code`, `x as unknown as Code` |
|
|
24
|
+
| `NT-F` | muerte que no llega | una promesa sin envolver en el cuerpo de un `gen` | `await mkdir()` |
|
|
25
|
+
| `NT-G` | fallo leído como valor | el brazo «para todo» que no mira el error, sobre un error con códigos | `err: () => []`, `orElse({ _: () => ok(x) })` |
|
|
26
|
+
| `NT-H` | causa aplastada | un fallo nuevo con el texto de otro y sin `cause`; un fallo sin `toString` dentro de un texto | `X.make.failed(\`${e.code}: ${e.message}\`)`, `` `${r.error}` `` |
|
|
27
|
+
| `NT-I` | plazos y señales | el cuerpo de una respuesta HTTP leído sin mirar `ok`/`status` | `res.json()` sin `if (!res.ok)` |
|
|
28
|
+
| `NT-J` | código equivocado | una tabla por código con clave `string` | `const T: Record<string, X> = { 'ops.busy': … }` |
|
|
29
|
+
| `NT-K` | plazos y señales | una función acepta una `AbortSignal`, hay una a mano y no se pasa | `tryCatch(() => fetch(url), f, { within })` |
|
|
30
|
+
| `NT-L` | cierre que falta | un `AbortController` que nunca se aborta | `const c = new AbortController()` sólo para `c.signal` |
|
|
31
|
+
| `NT-M` | cierre que falta | un `lock`/`open`/`acquire`/`connect`/`subscribe` en un `gen` sin su cierre | `lock(file)` sin `defer(() => unlock(file))` |
|
|
32
|
+
| `NT-N` | muerte que no llega | una promesa suelta en un brazo de Result o en un `gen` | `'api.busy': () => { dead(job) }` |
|
|
33
|
+
| `NT-O` | Result no comprobado | algo que lanza (`JSON.parse`, `new URL`, …) sin envolver dentro de `ok(...)`, un `gen` o un `map` | `ok(JSON.parse(text))` |
|
|
34
|
+
|
|
35
|
+
El porqué y el arreglo de cada una están en `rules.mjs` y los imprime la CLI.
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
nt-lint [tsconfig.json] [--rule=NT-A,NT-D] [--only=subcadena] [--format=pretty|compact|json|github]
|
|
39
|
+
nt-lint --rules # la lista
|
|
40
|
+
nt-lint --explain=NT-G # por qué y cómo
|
|
41
|
+
# rc=1 si encuentra algo, rc=0 si no, rc=2 si no puede correr
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Un aviso se calla en su línea, diciendo cuál: `// nt-lint-disable-next-line NT-K -- motivo`
|
|
45
|
+
(o `// nt-lint-disable-line NT-A` al final de la línea).
|
|
46
|
+
|
|
47
|
+
`typescript` 5–6 viene como dependencia del paquete: el compilador con su API
|
|
48
|
+
de JS. `typescript@7` es el nativo y no la trae; con él,
|
|
49
|
+
`NT_LINT_TYPESCRIPT=/ruta/a/typescript@6`.
|
|
50
|
+
|
|
51
|
+
### Dentro de ESLint
|
|
52
|
+
|
|
53
|
+
`eslint.mjs` es un plugin de flat config: cada regla es `no-throw/nt-x` y
|
|
54
|
+
`configs.recommended` las enciende todas. Corre sobre el programa de
|
|
55
|
+
typescript-eslint (`parserOptions.projectService`), así que no construye otro;
|
|
56
|
+
sin tipos, lo dice en vez de callar.
|
|
57
|
+
|
|
58
|
+
### Por qué no oxlint
|
|
59
|
+
|
|
60
|
+
Todas las reglas leen tipos (un Result se reconoce por su tipo), y los
|
|
61
|
+
plugins de JS de oxlint no tienen comprobador de tipos: su lint con tipos es
|
|
62
|
+
`tsgolint`, en Go, sólo con reglas propias. Un plugin de oxlint tendría que
|
|
63
|
+
construir su propio programa de TypeScript en cada pasada, que es lo que ya
|
|
64
|
+
hace la CLI, pero escondido. Con oxlint en el proyecto, `nt-lint` va al lado
|
|
65
|
+
(en CI, `--format=github`).
|
|
66
|
+
|
|
67
|
+
## Los fixtures
|
|
68
|
+
|
|
69
|
+
`fixtures/` es la pareja de control. `bad-rules.ts` y `bad-variants.ts`
|
|
70
|
+
anotan en cada línea que tiene que dar aviso un comentario «espera» con la
|
|
71
|
+
regla, y el test compara el conjunto exacto; los `good*.ts` no pueden dar
|
|
72
|
+
nada. `bad-variants.ts` son las variantes que el censo de agentics tenía y el
|
|
73
|
+
banco de 40 no (por `||`, por `===`, por `switch`, por desestructuración, el
|
|
74
|
+
doble `as`, el `forEach`, el `filter`, el `${r.error}` de v3). El test también
|
|
75
|
+
pasa el lint por `core/src` (tiene que salir limpio) y por la CLI.
|
|
76
|
+
|
|
77
|
+
## Las dos medidas
|
|
78
|
+
|
|
79
|
+
Las dos siembran un error en un programa que está bien y cuentan quién lo
|
|
80
|
+
para: `tsc`, el lint, el banco de pruebas, o nadie. Las dos comprueban antes
|
|
81
|
+
que el programa sin sembrar sale limpio.
|
|
82
|
+
|
|
83
|
+
| | qué siembra | cómo corre | hoy |
|
|
84
|
+
|---|---|---|---|
|
|
85
|
+
| [`battery-v4/`](./battery-v4) | 31 fallos humanos en 6 programas | `node lint/battery-v4/measure.mjs` | tsc 23 · banco 7 · nadie 1 (con el lint: 29 de 31) |
|
|
86
|
+
| [`bugs40/`](./bugs40) | 40 bugs reales de agentics, migrados a la v4 | `node lint/bugs40/measure.mjs` | tsc 6 · lint 24 · banco 8 · desactivados 2 · nadie 0 |
|
|
87
|
+
|
|
88
|
+
Son la puerta de un cambio en la librería: ninguna de las dos puede empeorar.
|
|
89
|
+
Necesitan `bun` en el `PATH` (o `BUN=`).
|
package/eslint.d.mts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** El plugin de ESLint (flat config): `no-throw/nt-a` … y `configs.recommended`. */
|
|
2
|
+
declare const plugin: {
|
|
3
|
+
readonly meta: { readonly name: string }
|
|
4
|
+
readonly rules: Record<string, unknown>
|
|
5
|
+
readonly configs: { readonly recommended: { readonly plugins: Record<string, unknown>; readonly rules: Record<string, 'error'> } }
|
|
6
|
+
}
|
|
7
|
+
export default plugin
|
package/eslint.mjs
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// nt-lint como plugin de ESLint (flat config), sobre los tipos de typescript-eslint.
|
|
2
|
+
//
|
|
3
|
+
// import noThrow from '@mks2508/no-throw/eslint'
|
|
4
|
+
// export default [
|
|
5
|
+
// { languageOptions: { parser: tsParser, parserOptions: { projectService: true } } },
|
|
6
|
+
// noThrow.configs.recommended,
|
|
7
|
+
// ]
|
|
8
|
+
//
|
|
9
|
+
// Cada regla NT-X es `no-throw/nt-x`. Las reglas necesitan el programa con
|
|
10
|
+
// tipos (`projectService` o `project`): sin él no hay forma de reconocer un
|
|
11
|
+
// Result, y el plugin lo dice en vez de callar.
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
import { createRequire } from 'node:module'
|
|
14
|
+
import { lintFile, collectDomains, RULES, RULE } from './nt-lint.mjs'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* El `typescript` que construyó el programa: el que resuelve
|
|
18
|
+
* `@typescript-eslint/typescript-estree`. Con otro módulo los `SyntaxKind`
|
|
19
|
+
* no tienen por qué coincidir.
|
|
20
|
+
*/
|
|
21
|
+
const tsOfParser = () => {
|
|
22
|
+
const tries = [path.join(process.cwd(), 'noop.js'), import.meta.url]
|
|
23
|
+
for (const from of tries) {
|
|
24
|
+
try {
|
|
25
|
+
const req = createRequire(from)
|
|
26
|
+
const parser = req.resolve('@typescript-eslint/parser')
|
|
27
|
+
const estree = createRequire(parser).resolve('@typescript-eslint/typescript-estree')
|
|
28
|
+
return createRequire(estree)('typescript')
|
|
29
|
+
} catch {
|
|
30
|
+
// se prueba el siguiente sitio
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return undefined
|
|
34
|
+
}
|
|
35
|
+
let ts
|
|
36
|
+
/** Los avisos de cada fichero, una vez por programa. */
|
|
37
|
+
const cache = new WeakMap()
|
|
38
|
+
|
|
39
|
+
const findingsFor = (context) => {
|
|
40
|
+
const services = context.sourceCode?.parserServices ?? context.parserServices
|
|
41
|
+
const program = services?.program
|
|
42
|
+
if (!program) {
|
|
43
|
+
throw new Error(
|
|
44
|
+
'no-throw/eslint necesita los tipos: usa @typescript-eslint/parser con parserOptions.projectService (o project)'
|
|
45
|
+
)
|
|
46
|
+
}
|
|
47
|
+
ts ??= tsOfParser()
|
|
48
|
+
let per = cache.get(program)
|
|
49
|
+
if (!per) {
|
|
50
|
+
per = { domains: collectDomains(program, ts), files: new Map() }
|
|
51
|
+
cache.set(program, per)
|
|
52
|
+
}
|
|
53
|
+
const file = context.filename ?? context.getFilename()
|
|
54
|
+
if (!per.files.has(file)) {
|
|
55
|
+
const sf = program.getSourceFile(file)
|
|
56
|
+
per.files.set(file, sf ? lintFile(program, sf, { domains: per.domains, ts }) : [])
|
|
57
|
+
}
|
|
58
|
+
return per.files.get(file)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const ruleFor = (id) => ({
|
|
62
|
+
meta: {
|
|
63
|
+
type: 'problem',
|
|
64
|
+
docs: { description: RULE[id].title },
|
|
65
|
+
schema: [],
|
|
66
|
+
},
|
|
67
|
+
create(context) {
|
|
68
|
+
return {
|
|
69
|
+
Program() {
|
|
70
|
+
for (const f of findingsFor(context)) {
|
|
71
|
+
if (f.rule !== id) continue
|
|
72
|
+
context.report({ loc: { line: f.line, column: f.col - 1 }, message: `${f.msg}. ${RULE[id].fix}` })
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
const plugin = {
|
|
80
|
+
meta: { name: '@mks2508/no-throw/eslint' },
|
|
81
|
+
rules: Object.fromEntries(RULES.map((r) => [r.id.toLowerCase(), ruleFor(r.id)])),
|
|
82
|
+
configs: {},
|
|
83
|
+
}
|
|
84
|
+
plugin.configs.recommended = {
|
|
85
|
+
plugins: { 'no-throw': plugin },
|
|
86
|
+
rules: Object.fromEntries(RULES.map((r) => [`no-throw/${r.id.toLowerCase()}`, 'error'])),
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export default plugin
|
package/nt-lint.d.mts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { Program, SourceFile } from 'typescript'
|
|
2
|
+
|
|
3
|
+
/** Una regla: qué para, por qué duele y cómo se arregla. */
|
|
4
|
+
export interface Rule {
|
|
5
|
+
readonly id: string
|
|
6
|
+
readonly clase: string
|
|
7
|
+
readonly title: string
|
|
8
|
+
readonly why: string
|
|
9
|
+
readonly fix: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Un aviso: dónde, qué regla y el trozo de código. */
|
|
13
|
+
export interface Finding {
|
|
14
|
+
readonly file: string
|
|
15
|
+
readonly line: number
|
|
16
|
+
readonly col: number
|
|
17
|
+
readonly rule: string
|
|
18
|
+
readonly msg: string
|
|
19
|
+
readonly text: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export declare const RULES: readonly Rule[]
|
|
23
|
+
export declare const RULE: Readonly<Record<string, Rule>>
|
|
24
|
+
|
|
25
|
+
/** Las reglas sobre un fichero; `ts` es el módulo que construyó el programa. */
|
|
26
|
+
export declare const lintFile: (
|
|
27
|
+
program: Program,
|
|
28
|
+
sf: SourceFile,
|
|
29
|
+
ctx?: { readonly domains?: Set<string>; readonly ts?: typeof import('typescript') }
|
|
30
|
+
) => Finding[]
|
|
31
|
+
/** Las reglas sobre todo el programa, con un filtro por ruta. */
|
|
32
|
+
export declare const lint: (program: Program, only?: (file: string) => boolean) => Finding[]
|
|
33
|
+
/** Los dominios de `defineErrors('dominio', ...)` del programa. */
|
|
34
|
+
export declare const collectDomains: (program: Program, ts?: typeof import('typescript')) => Set<string>
|
|
35
|
+
/** El programa de un tsconfig. */
|
|
36
|
+
export declare const load: (tsconfig: string) => Program
|
|
37
|
+
/** Los avisos como texto: `pretty` (por qué y arreglo), `compact`, `json` o `github`. */
|
|
38
|
+
export declare const format: (found: readonly Finding[], how?: 'pretty' | 'compact' | 'json' | 'github', cwd?: string) => string
|
package/nt-lint.mjs
ADDED
|
@@ -0,0 +1,783 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// nt-lint — reglas con tipos para los Result de la familia no-throw.
|
|
3
|
+
//
|
|
4
|
+
// nt-lint [tsconfig.json] [--rule=NT-A,NT-D] [--only=subcadena]
|
|
5
|
+
// [--format=pretty|compact|json|github] [--explain=NT-X] [--rules]
|
|
6
|
+
//
|
|
7
|
+
// rc=1 si encuentra algo, rc=0 si no, rc=2 si no puede correr.
|
|
8
|
+
//
|
|
9
|
+
// La detección del Result es POR TIPO, no por nombre: la misma vara para
|
|
10
|
+
// no-throw v4, v3, neverthrow, better-result, unthrown, byethrow, Effect y
|
|
11
|
+
// errore. Las reglas, su porqué y su arreglo viven en `rules.mjs`.
|
|
12
|
+
//
|
|
13
|
+
// Un aviso se calla en su línea con un comentario que dice cuál y por qué:
|
|
14
|
+
// // nt-lint-disable-next-line NT-K -- el cierre tiene que acabar aunque cancelen
|
|
15
|
+
// x() // nt-lint-disable-line NT-A -- motivo
|
|
16
|
+
import path from 'node:path'
|
|
17
|
+
import fs from 'node:fs'
|
|
18
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
19
|
+
import { RULE, RULES } from './rules.mjs'
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* El compilador con su API de JS (typescript 5 o 6). `typescript@7` es el
|
|
23
|
+
* nativo y no la trae: con él, `NT_LINT_TYPESCRIPT=/ruta/a/typescript` apunta a uno que sí.
|
|
24
|
+
*/
|
|
25
|
+
const loadTs = async () => {
|
|
26
|
+
const tried = []
|
|
27
|
+
for (const spec of [process.env.NT_LINT_TYPESCRIPT, 'typescript'].filter(Boolean)) {
|
|
28
|
+
try {
|
|
29
|
+
const m = await import(spec.startsWith('/') ? pathToFileURL(path.join(spec, fs.statSync(spec).isDirectory() ? 'lib/typescript.js' : '')).href : spec)
|
|
30
|
+
const ts = m.default ?? m
|
|
31
|
+
if (typeof ts.createProgram === 'function') return { ts }
|
|
32
|
+
tried.push(`${spec} (${ts.version ?? '?'}: sin la API de JS)`)
|
|
33
|
+
} catch (e) {
|
|
34
|
+
tried.push(`${spec} (${e instanceof Error ? e.message.split('\n')[0] : String(e)})`)
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return { why: `nt-lint necesita typescript 5 o 6 con su API de JS; probé: ${tried.join('; ')}. Instálalo, o apunta NT_LINT_TYPESCRIPT a uno.` }
|
|
38
|
+
}
|
|
39
|
+
const loaded = await loadTs()
|
|
40
|
+
const tsDefault = loaded.ts
|
|
41
|
+
|
|
42
|
+
/** Cómo se reconoce un Result de cada librería por su TIPO. */
|
|
43
|
+
const BRANDS = [
|
|
44
|
+
// no-throw v4 (y v3 0.3): { ok, value } | { ok, error }
|
|
45
|
+
(t) => Boolean(t.getProperty('ok')) && Boolean(t.getProperty('value') || t.getProperty('error')),
|
|
46
|
+
// neverthrow, better-result, unthrown: { isOk, isErr }
|
|
47
|
+
(t) => Boolean(t.getProperty('isErr')) && Boolean(t.getProperty('isOk')),
|
|
48
|
+
// final4 / unthrown: la marca ~nt
|
|
49
|
+
(t) => Boolean(t.getProperty('~nt') || t.getProperty('~nt.defer')),
|
|
50
|
+
// byethrow: { type, value } | { type, error }
|
|
51
|
+
(t) =>
|
|
52
|
+
Boolean(t.getProperty('type')) &&
|
|
53
|
+
Boolean(t.getProperty('value') || t.getProperty('error')) &&
|
|
54
|
+
/Success|Failure|ResultAsync/.test(t.aliasSymbol?.name ?? t.symbol?.name ?? ''),
|
|
55
|
+
// Effect: Effect / Exit / Pool
|
|
56
|
+
(t) =>
|
|
57
|
+
/^(Effect|Exit|Pool|YieldableError)$/.test(t.symbol?.name ?? '') &&
|
|
58
|
+
/effect/.test(t.declarations?.[0]?.getSourceFile().fileName ?? ''),
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
/** Lo que se hace con un texto para sacar de él un código. */
|
|
62
|
+
const CASE_OPS = new Set(['toLowerCase', 'toUpperCase', 'toLocaleLowerCase', 'toLocaleUpperCase', 'trim', 'trimStart', 'trimEnd', 'toString'])
|
|
63
|
+
const TEXT_OPS = new Set(['includes', 'startsWith', 'endsWith', 'indexOf', 'lastIndexOf', 'match', 'matchAll', 'split', 'search'])
|
|
64
|
+
/** Los métodos de un Result que reciben callbacks o brazos. */
|
|
65
|
+
const RESULT_METHODS = new Set(['match', 'orElse', 'map', 'mapErr', 'andThen', 'andThenAsync', 'inspect', 'inspectErr', 'unwrapOrElse'])
|
|
66
|
+
/** Los predicados de un array: un Result ahí es siempre verdadero. */
|
|
67
|
+
const PREDICATES = new Set(['filter', 'some', 'every', 'find', 'findIndex', 'findLast', 'findLastIndex'])
|
|
68
|
+
/** Lo que se lee del cuerpo de una respuesta. */
|
|
69
|
+
const BODY_READS = new Set(['json', 'text', 'arrayBuffer', 'blob', 'formData', 'bytes', 'body'])
|
|
70
|
+
/** Abrir → lo que lo cierra. */
|
|
71
|
+
const PAIRS = {
|
|
72
|
+
lock: ['unlock', 'release'],
|
|
73
|
+
acquire: ['release'],
|
|
74
|
+
open: ['close'],
|
|
75
|
+
connect: ['disconnect', 'close', 'end'],
|
|
76
|
+
subscribe: ['unsubscribe'],
|
|
77
|
+
}
|
|
78
|
+
/** Lo que lanza con una entrada mala. */
|
|
79
|
+
const THROWING_GLOBALS = new Set(['decodeURIComponent', 'decodeURI', 'atob', 'BigInt'])
|
|
80
|
+
const CODE_RE = /^[\w-]+\.[\w*-]+$/
|
|
81
|
+
/** Cómo se suele llamar lo lanzado. */
|
|
82
|
+
const FAIL_NAMES = /^(e|er|err|error|errors?|cause|reason|ex|exc|exception|failure|fault)$/i
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Corre las reglas sobre un fichero de un programa.
|
|
86
|
+
* @param {import('typescript').Program} program
|
|
87
|
+
* @param {import('typescript').SourceFile} sf
|
|
88
|
+
* @param {{ domains?: Set<string>, ts?: typeof import('typescript') }} [ctx] `ts`: el
|
|
89
|
+
* módulo que construyó el programa (el de typescript-eslint, si viene de ESLint)
|
|
90
|
+
*/
|
|
91
|
+
export const lintFile = (program, sf, ctx = {}) => {
|
|
92
|
+
const ts = ctx.ts ?? tsDefault
|
|
93
|
+
if (!ts) throw new Error(loaded.why)
|
|
94
|
+
const EQ_OPS = new Set([ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken, ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken])
|
|
95
|
+
const ck = program.getTypeChecker()
|
|
96
|
+
const domains = ctx.domains ?? collectDomains(program, ts)
|
|
97
|
+
const out = []
|
|
98
|
+
// en una prueba el estado lo mira la propia prueba, y la aserción sobre el cuerpo falla sola
|
|
99
|
+
const isTestFile = /\.(test|spec)\.[cm]?[jt]sx?$|\/__tests__\//.test(sf.fileName)
|
|
100
|
+
const parts = (t) => (t.isUnion() ? t.types : [t])
|
|
101
|
+
const aw = (t) => ck.getAwaitedType(t) ?? t
|
|
102
|
+
const symName = (t) => t?.symbol?.name ?? t?.aliasSymbol?.name ?? ''
|
|
103
|
+
const isLit = (q) => q.isStringLiteral() || Boolean(q.flags & ts.TypeFlags.TemplateLiteral)
|
|
104
|
+
const isErrObj = (t) =>
|
|
105
|
+
parts(t).some(
|
|
106
|
+
(x) =>
|
|
107
|
+
x.getProperty('stack') &&
|
|
108
|
+
x.getProperty('message') &&
|
|
109
|
+
(x.getProperty('_tag') || x.getProperty('code')) &&
|
|
110
|
+
[x.getProperty('_tag'), x.getProperty('code')].some((p) => p && parts(ck.getTypeOfSymbol(p)).some((q) => q.isStringLiteral()))
|
|
111
|
+
)
|
|
112
|
+
const one = (x) =>
|
|
113
|
+
!(x.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) &&
|
|
114
|
+
BRANDS.some((b) => {
|
|
115
|
+
try {
|
|
116
|
+
return b(x)
|
|
117
|
+
} catch {
|
|
118
|
+
return false
|
|
119
|
+
}
|
|
120
|
+
})
|
|
121
|
+
/** El tipo (o el de la promesa) es un Result de alguna de las librerías. */
|
|
122
|
+
const isRes = (t) => {
|
|
123
|
+
if (!t) return false
|
|
124
|
+
const p = parts(aw(t)).filter((x) => !(x.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Void | ts.TypeFlags.Null)))
|
|
125
|
+
if (p.length > 0 && p.every(one)) return true
|
|
126
|
+
// errore: el resultado es `valor | Error`
|
|
127
|
+
const q = parts(aw(t))
|
|
128
|
+
return q.some((x) => isErrObj(x)) && q.some((x) => !isErrObj(x))
|
|
129
|
+
}
|
|
130
|
+
/** Un Result que no puede ser `null`/`undefined`: ahí la condición sí es un chequeo de nulo. */
|
|
131
|
+
const isResStrict = (t) => Boolean(t) && !parts(t).some((x) => x.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Void)) && isRes(t)
|
|
132
|
+
const isThenable = (t) => parts(t).some((x) => Boolean(x.getProperty('then')))
|
|
133
|
+
const isSignal = (t) => parts(ck.getNonNullableType(t)).some((x) => symName(x) === 'AbortSignal')
|
|
134
|
+
const isAnyish = (t) => Boolean(t.flags & (ts.TypeFlags.Unknown | ts.TypeFlags.Any))
|
|
135
|
+
/** Algo con forma de fallo: un Error, un `{ code, message }`, un `{ name, message }`. */
|
|
136
|
+
const isFailureLike = (t) =>
|
|
137
|
+
isAnyish(t) ||
|
|
138
|
+
parts(t).some((x) => Boolean(x.getProperty('stack') || (x.getProperty('message') && (x.getProperty('code') || x.getProperty('name') || x.getProperty('_tag')))))
|
|
139
|
+
/**
|
|
140
|
+
* Lo que se lanzó o se rechazó: la variable de un `catch`, el parámetro de
|
|
141
|
+
* un traductor (`tryCatch(f, (cause) => ...)`, `.catch((e) => ...)`), o algo
|
|
142
|
+
* que se llama como un fallo. Un `unknown` cualquiera (un `input` de fetch)
|
|
143
|
+
* no lo es.
|
|
144
|
+
*/
|
|
145
|
+
const isThrown = (e) => {
|
|
146
|
+
e = strip(e)
|
|
147
|
+
if (ts.isPropertyAccessExpression(e)) return /^(error|cause|reason|message)$/.test(e.name.text)
|
|
148
|
+
if (!ts.isIdentifier(e)) return false
|
|
149
|
+
if (FAIL_NAMES.test(e.text)) return true
|
|
150
|
+
const d = ck.getSymbolAtLocation(e)?.valueDeclaration
|
|
151
|
+
if (!d) return false
|
|
152
|
+
if (ts.isVariableDeclaration(d) && d.parent && ts.isCatchClause(d.parent)) return true
|
|
153
|
+
if (ts.isParameter(d) && d.parent && ts.isFunctionLike(d.parent)) {
|
|
154
|
+
const call = d.parent.parent
|
|
155
|
+
if (call && ts.isCallExpression(call)) {
|
|
156
|
+
const i = call.arguments.indexOf(d.parent)
|
|
157
|
+
const name = calleeName(call)
|
|
158
|
+
return (i === 1 && /^(tryCatch|attempt\w*|then|from\w*)$/.test(name)) || (i === 0 && name === 'catch')
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return false
|
|
162
|
+
}
|
|
163
|
+
/** Una expresión con forma de fallo; si su tipo es `unknown`, sólo si es lo lanzado. */
|
|
164
|
+
const failureExpr = (e) => {
|
|
165
|
+
const t = ck.getTypeAtLocation(strip(e))
|
|
166
|
+
return isAnyish(t) ? isThrown(e) : isFailureLike(t)
|
|
167
|
+
}
|
|
168
|
+
/** Los códigos del error de un Result (vacío si no tiene). */
|
|
169
|
+
const errTypesOf = (t) =>
|
|
170
|
+
parts(aw(t)).flatMap((p) => {
|
|
171
|
+
const e = p.getProperty('error')
|
|
172
|
+
return e ? parts(ck.getTypeOfSymbol(e)) : []
|
|
173
|
+
})
|
|
174
|
+
const hasCodes = (errs) =>
|
|
175
|
+
errs.some((x) => {
|
|
176
|
+
const c = x.getProperty('code') ?? x.getProperty('_tag')
|
|
177
|
+
return c && parts(ck.getTypeOfSymbol(c)).some(isLit)
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
const add = (n, rule, msg) => {
|
|
181
|
+
const p = sf.getLineAndCharacterOfPosition(n.getStart(sf))
|
|
182
|
+
out.push({
|
|
183
|
+
file: sf.fileName,
|
|
184
|
+
line: p.line + 1,
|
|
185
|
+
col: p.character + 1,
|
|
186
|
+
rule,
|
|
187
|
+
msg,
|
|
188
|
+
text: n.getText(sf).replace(/\s+/g, ' ').slice(0, 90),
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
const strip = (e) => {
|
|
192
|
+
while (ts.isParenthesizedExpression(e) || ts.isNonNullExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression?.(e) || ts.isTypeAssertionExpression(e)) e = e.expression
|
|
193
|
+
return e
|
|
194
|
+
}
|
|
195
|
+
const unwrapParens = (e) => {
|
|
196
|
+
while (ts.isParenthesizedExpression(e) || ts.isVoidExpression(e) || ts.isNonNullExpression(e)) e = e.expression
|
|
197
|
+
return e
|
|
198
|
+
}
|
|
199
|
+
const fnOf = (n) => ts.findAncestor(n.parent, ts.isFunctionLike)
|
|
200
|
+
/** El símbolo se lee en algún sitio de `scope` (fuera de `skip`). */
|
|
201
|
+
const usedIn = (scope, sym, name, skip) => {
|
|
202
|
+
let used = false
|
|
203
|
+
const w = (x) => {
|
|
204
|
+
if (used || x === skip) return
|
|
205
|
+
if (ts.isIdentifier(x) && x.text === name && ck.getSymbolAtLocation(x) === sym) used = true
|
|
206
|
+
else if (ts.isShorthandPropertyAssignment(x) && x.name.text === name && ck.getShorthandAssignmentValueSymbol(x) === sym) used = true
|
|
207
|
+
x.forEachChild(w)
|
|
208
|
+
}
|
|
209
|
+
w(scope)
|
|
210
|
+
return used
|
|
211
|
+
}
|
|
212
|
+
/** Las referencias a un símbolo en `scope`. */
|
|
213
|
+
const refsIn = (scope, sym, name) => {
|
|
214
|
+
const r = []
|
|
215
|
+
const w = (x) => {
|
|
216
|
+
if (ts.isIdentifier(x) && x.text === name && ck.getSymbolAtLocation(x) === sym && !(x.parent && ts.isVariableDeclaration(x.parent) && x.parent.name === x)) r.push(x)
|
|
217
|
+
x.forEachChild(w)
|
|
218
|
+
}
|
|
219
|
+
w(scope)
|
|
220
|
+
return r
|
|
221
|
+
}
|
|
222
|
+
/** `X.make.y(...)` o `m.make.dom.y(...)`. */
|
|
223
|
+
const isMakeCall = (call) => {
|
|
224
|
+
let c = call.expression
|
|
225
|
+
while (ts.isPropertyAccessExpression(c)) {
|
|
226
|
+
if (ts.isPropertyAccessExpression(c.expression) && c.expression.name.text === 'make') return true
|
|
227
|
+
c = c.expression
|
|
228
|
+
}
|
|
229
|
+
return false
|
|
230
|
+
}
|
|
231
|
+
const calleeName = (call) => {
|
|
232
|
+
const c = strip(call.expression)
|
|
233
|
+
return ts.isIdentifier(c) ? c.text : ts.isPropertyAccessExpression(c) ? c.name.text : ''
|
|
234
|
+
}
|
|
235
|
+
/** Dentro de un callback de un método de Result (map, andThen, los brazos de match/orElse). */
|
|
236
|
+
const resultCallbackOf = (fn) => {
|
|
237
|
+
let x = fn
|
|
238
|
+
while (x.parent && (ts.isPropertyAssignment(x.parent) || ts.isObjectLiteralExpression(x.parent))) x = x.parent
|
|
239
|
+
const call = x.parent
|
|
240
|
+
if (!call || !ts.isCallExpression(call) || !call.arguments.includes(x)) return undefined
|
|
241
|
+
const c = call.expression
|
|
242
|
+
if (!ts.isPropertyAccessExpression(c) || !RESULT_METHODS.has(c.name.text)) return undefined
|
|
243
|
+
return isRes(ck.getTypeAtLocation(c.expression)) ? call : undefined
|
|
244
|
+
}
|
|
245
|
+
/** El generador que se le pasa a `gen(...)`/`task(...)`. */
|
|
246
|
+
const isGenFn = (fn) => {
|
|
247
|
+
if (!fn || !ts.isFunctionExpression(fn) || !fn.asteriskToken) return false
|
|
248
|
+
const call = fn.parent
|
|
249
|
+
if (!ts.isCallExpression(call)) return false
|
|
250
|
+
return ['gen', 'task'].includes(calleeName(call))
|
|
251
|
+
}
|
|
252
|
+
const inGenBody = (n) => isGenFn(fnOf(n))
|
|
253
|
+
/** El primer argumento de un tryCatch/attempt: lo que lanza ahí se traduce. */
|
|
254
|
+
const isWrapperArg = (fn) =>
|
|
255
|
+
fn.parent && ts.isCallExpression(fn.parent) && fn.parent.arguments[0] === fn && /^(tryCatch|attempt\w*|from\w*|try)$/.test(calleeName(fn.parent))
|
|
256
|
+
const optionsOf = (call, i) => {
|
|
257
|
+
const a = call.arguments[i]
|
|
258
|
+
return a && ts.isObjectLiteralExpression(strip(a)) ? strip(a) : undefined
|
|
259
|
+
}
|
|
260
|
+
const hasProp = (obj, name) =>
|
|
261
|
+
obj.properties.some((p) => ts.isSpreadAssignment(p) || (p.name && ts.isIdentifier(p.name) && p.name.text === name) || (p.name && ts.isStringLiteral(p.name) && p.name.text === name))
|
|
262
|
+
|
|
263
|
+
/** El texto de un fallo: `x.message`, `String(causa)`, `e.toString()`, por una variable, `?? ''`. */
|
|
264
|
+
const isFailureText = (e, depth = 0, withCode = false) => {
|
|
265
|
+
e = strip(e)
|
|
266
|
+
if (depth > 4) return false
|
|
267
|
+
if (ts.isIdentifier(e)) {
|
|
268
|
+
const sym = ck.getSymbolAtLocation(e)
|
|
269
|
+
const d = sym?.valueDeclaration
|
|
270
|
+
if (!d) return false
|
|
271
|
+
if (ts.isVariableDeclaration(d) && d.initializer && ts.isIdentifier(d.name)) return isFailureText(d.initializer, depth + 1, withCode)
|
|
272
|
+
// `const { message } = err`
|
|
273
|
+
if (ts.isBindingElement(d) && ts.isIdentifier(d.name)) {
|
|
274
|
+
const key = d.propertyName && ts.isIdentifier(d.propertyName) ? d.propertyName.text : d.name.text
|
|
275
|
+
const decl = d.parent?.parent
|
|
276
|
+
if ((key === 'message' || (withCode && key === 'code')) && decl && ts.isVariableDeclaration(decl) && decl.initializer) {
|
|
277
|
+
return failureExpr(decl.initializer)
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return false
|
|
281
|
+
}
|
|
282
|
+
if (ts.isConditionalExpression(e)) return isFailureText(e.whenTrue, depth + 1, withCode) || isFailureText(e.whenFalse, depth + 1, withCode)
|
|
283
|
+
if (ts.isBinaryExpression(e) && [ts.SyntaxKind.BarBarToken, ts.SyntaxKind.QuestionQuestionToken].includes(e.operatorToken.kind)) {
|
|
284
|
+
return isFailureText(e.left, depth + 1, withCode)
|
|
285
|
+
}
|
|
286
|
+
if (ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && CASE_OPS.has(e.expression.name.text)) {
|
|
287
|
+
if (e.expression.name.text === 'toString') return failureExpr(e.expression.expression) || isFailureText(e.expression.expression, depth + 1, withCode)
|
|
288
|
+
return isFailureText(e.expression.expression, depth + 1, withCode)
|
|
289
|
+
}
|
|
290
|
+
if (ts.isPropertyAccessExpression(e) && (e.name.text === 'message' || (withCode && e.name.text === 'code'))) {
|
|
291
|
+
// el `message` de un fallo, no el de un commit o un chat
|
|
292
|
+
return failureExpr(e.expression)
|
|
293
|
+
}
|
|
294
|
+
if (ts.isCallExpression(e) && ts.isIdentifier(e.expression) && e.expression.text === 'String' && e.arguments[0]) {
|
|
295
|
+
const a = ck.getTypeAtLocation(e.arguments[0])
|
|
296
|
+
return isAnyish(a) ? isThrown(e.arguments[0]) : parts(a).some((x) => Boolean(x.flags & ts.TypeFlags.Object) && Boolean(x.getProperty('message')))
|
|
297
|
+
}
|
|
298
|
+
return false
|
|
299
|
+
}
|
|
300
|
+
/** El mensaje lleva texto de otro fallo (en una plantilla, una suma o tal cual). */
|
|
301
|
+
const carriesFailureText = (e) => {
|
|
302
|
+
e = strip(e)
|
|
303
|
+
if (ts.isTemplateExpression(e)) return e.templateSpans.some((s) => carriesFailureText(s.expression) || failureObject(s.expression))
|
|
304
|
+
if (ts.isBinaryExpression(e) && e.operatorToken.kind === ts.SyntaxKind.PlusToken) return carriesFailureText(e.left) || carriesFailureText(e.right)
|
|
305
|
+
return isFailureText(e, 0, true)
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** v4 da a sus fallos un `toString` que escribe `code: message`. */
|
|
309
|
+
const isV4Fault = (t) => {
|
|
310
|
+
const d = t.getProperty('code')?.declarations?.[0]
|
|
311
|
+
if (!d) return false
|
|
312
|
+
const f = d.getSourceFile()
|
|
313
|
+
return /\bdefineErrors\b/.test(f.text) && /\b(type|interface) Fault\b/.test(f.text)
|
|
314
|
+
}
|
|
315
|
+
/** Un objeto de fallo sin `toString` propio: en un texto escribe `[object Object]`. */
|
|
316
|
+
const failureObject = (e) => {
|
|
317
|
+
const t = ck.getTypeAtLocation(strip(e))
|
|
318
|
+
if (isAnyish(t) || t.flags & ts.TypeFlags.StringLike) return false
|
|
319
|
+
const ps = parts(t).filter((x) => !(x.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null)))
|
|
320
|
+
return (
|
|
321
|
+
ps.length > 0 &&
|
|
322
|
+
ps.every((x) => {
|
|
323
|
+
if (!(x.flags & ts.TypeFlags.Object) || x.getProperty('stack') || x.getCallSignatures().length) return false
|
|
324
|
+
if (!x.getProperty('message') || !(x.getProperty('code') || x.getProperty('_tag'))) return false
|
|
325
|
+
const toStr = x.getProperty('toString')
|
|
326
|
+
const own = toStr?.declarations?.some((d) => !d.getSourceFile().hasNoDefaultLib && !/lib\.[\w.]+\.d\.ts$/.test(d.getSourceFile().fileName))
|
|
327
|
+
return !own && !isV4Fault(x)
|
|
328
|
+
})
|
|
329
|
+
)
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** Hay una AbortSignal a mano en la llamada (un parámetro o una variable de las funciones que la envuelven). */
|
|
333
|
+
const signalInScope = (call) => {
|
|
334
|
+
for (let f = fnOf(call); f; f = fnOf(f)) {
|
|
335
|
+
for (const p of f.parameters ?? []) {
|
|
336
|
+
if (ts.isIdentifier(p.name) && isSignal(ck.getTypeAtLocation(p))) return p.name.text
|
|
337
|
+
}
|
|
338
|
+
// `tryCatch(() => ..., traduce, { within })`: el callback recibe la señal
|
|
339
|
+
if (isWrapperArg(f) && f.parameters.length === 0) {
|
|
340
|
+
const o = optionsOf(f.parent, 2)
|
|
341
|
+
if (o && (hasProp(o, 'within') || hasProp(o, 'signal'))) return '(el primer parámetro del callback)'
|
|
342
|
+
}
|
|
343
|
+
let found
|
|
344
|
+
const w = (x) => {
|
|
345
|
+
if (found || x.pos > call.pos) return
|
|
346
|
+
if (ts.isFunctionLike(x) && x !== f) return
|
|
347
|
+
if (ts.isVariableDeclaration(x) && ts.isIdentifier(x.name) && x.end < call.pos && isSignal(ck.getTypeAtLocation(x.name))) found = x.name.text
|
|
348
|
+
x.forEachChild(w)
|
|
349
|
+
}
|
|
350
|
+
if (f.body) w(f.body)
|
|
351
|
+
if (found) return found
|
|
352
|
+
}
|
|
353
|
+
return undefined
|
|
354
|
+
}
|
|
355
|
+
const mentionsSignal = (call) => {
|
|
356
|
+
let seen = false
|
|
357
|
+
const w = (x) => {
|
|
358
|
+
if (seen) return
|
|
359
|
+
if (ts.isIdentifier(x) && !(ts.isPropertyAccessExpression(x.parent) && x.parent.name === x) && isSignal(ck.getTypeAtLocation(x))) seen = true
|
|
360
|
+
x.forEachChild(w)
|
|
361
|
+
}
|
|
362
|
+
call.arguments.forEach(w)
|
|
363
|
+
return seen
|
|
364
|
+
}
|
|
365
|
+
/** La llamada acepta una señal y no se le pasa. */
|
|
366
|
+
const missingSignal = (call) => {
|
|
367
|
+
const c = strip(call.expression)
|
|
368
|
+
// la señal no se pasa a sí misma, y un listener es otra conversación
|
|
369
|
+
if (ts.isPropertyAccessExpression(c) && (/EventListener$/.test(c.name.text) || isSignal(ck.getTypeAtLocation(c.expression)))) return false
|
|
370
|
+
// un stream muere con lo que lo produce (el fetch que ya lleva la señal)
|
|
371
|
+
if (ts.isPropertyAccessExpression(c) && /^(Readable|Writable|Transform)Stream$/.test(symName(ck.getNonNullableType(ck.getTypeAtLocation(c.expression))))) return false
|
|
372
|
+
// la señal ya va dentro, al trabajo: `attempt(() => fetch(url, { signal: s }))`
|
|
373
|
+
if (mentionsSignal(call)) return false
|
|
374
|
+
const sig = ck.getResolvedSignature(call)
|
|
375
|
+
if (!sig) return false
|
|
376
|
+
const carries = (t) =>
|
|
377
|
+
parts(ck.getNonNullableType(t)).some((x) => {
|
|
378
|
+
const s = x.flags & ts.TypeFlags.Object ? x.getProperty('signal') : undefined
|
|
379
|
+
return Boolean(s) && isSignal(ck.getTypeOfSymbol(s))
|
|
380
|
+
})
|
|
381
|
+
// un argumento que ya lleva su señal (un `Request`) la pasa
|
|
382
|
+
if (call.arguments.some((a) => carries(ck.getTypeAtLocation(a)) && !ts.isObjectLiteralExpression(strip(a)))) return false
|
|
383
|
+
const ps = sig.getParameters()
|
|
384
|
+
for (let i = 0; i < ps.length; i++) {
|
|
385
|
+
const pt = ck.getTypeOfSymbolAtLocation(ps[i], call)
|
|
386
|
+
const a = call.arguments[i]
|
|
387
|
+
if (isSignal(pt)) {
|
|
388
|
+
if (!a) return true
|
|
389
|
+
continue
|
|
390
|
+
}
|
|
391
|
+
if (!carries(pt)) continue
|
|
392
|
+
if (!a) return true
|
|
393
|
+
const o = strip(a)
|
|
394
|
+
if (ts.isObjectLiteralExpression(o) && !hasProp(o, 'signal')) return true
|
|
395
|
+
}
|
|
396
|
+
return false
|
|
397
|
+
}
|
|
398
|
+
const inCleanup = (n) =>
|
|
399
|
+
Boolean(
|
|
400
|
+
ts.findAncestor(n, (x) => {
|
|
401
|
+
if (x.parent && ts.isTryStatement(x.parent) && x.parent.finallyBlock === x) return true
|
|
402
|
+
if (ts.isFunctionLike(x) && x.parent && ts.isCallExpression(x.parent) && /^(defer|errdefer)$/.test(calleeName(x.parent))) return true
|
|
403
|
+
return false
|
|
404
|
+
})
|
|
405
|
+
)
|
|
406
|
+
|
|
407
|
+
const visit = (n) => {
|
|
408
|
+
// NT-A: la sentencia se tira
|
|
409
|
+
if (ts.isExpressionStatement(n)) {
|
|
410
|
+
const e = unwrapParens(n.expression)
|
|
411
|
+
const isThen = ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && ['then', 'catch', 'finally'].includes(e.expression.name.text)
|
|
412
|
+
if (!ts.isBinaryExpression(e) && !isThen) {
|
|
413
|
+
const t = ck.getTypeAtLocation(e)
|
|
414
|
+
if (isRes(t)) {
|
|
415
|
+
add(n, 'NT-A', ts.isAwaitExpression(e) ? 'el Result awaited se ignora: no se mira ok ni error' : 'el Result se ignora: no se mira ok ni error')
|
|
416
|
+
} else if (!ts.isVoidExpression(strip(n.expression)) && !ts.isAwaitExpression(e) && isThenable(t) && !isAnyish(t)) {
|
|
417
|
+
// NT-N: la promesa suelta en un brazo de Result o en el cuerpo de un gen
|
|
418
|
+
const f = fnOf(n)
|
|
419
|
+
if (f && (resultCallbackOf(f) || isGenFn(f))) {
|
|
420
|
+
add(n, 'NT-N', isGenFn(f) ? 'una promesa suelta en el cuerpo de gen: el gen acaba antes que ella' : 'una promesa suelta en un brazo: el Result se resuelve antes que ella')
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
// NT-A: un callback que devuelve un Result a un sitio que lo tira (forEach, un listener)
|
|
426
|
+
if (ts.isArrowFunction(n) && !ts.isBlock(n.body) && isRes(ck.getTypeAtLocation(n.body))) {
|
|
427
|
+
const ct = ck.getContextualType(n)
|
|
428
|
+
const sig = ct && parts(ct).flatMap((x) => x.getCallSignatures())[0]
|
|
429
|
+
const rt = sig && ck.getReturnTypeOfSignature(sig)
|
|
430
|
+
if (rt && rt.flags & ts.TypeFlags.Void) add(n.body, 'NT-A', 'el callback devuelve un Result a un sitio que lo tira (su tipo es `void`)')
|
|
431
|
+
}
|
|
432
|
+
// NT-B: la condición sobre un Result
|
|
433
|
+
if (ts.isIfStatement(n) || ts.isWhileStatement(n) || ts.isDoStatement(n)) {
|
|
434
|
+
if (isResStrict(ck.getTypeAtLocation(unwrapParens(n.expression)))) add(n, 'NT-B', 'la condición es un Result: un objeto es siempre verdadero')
|
|
435
|
+
}
|
|
436
|
+
if (ts.isConditionalExpression(n) && isResStrict(ck.getTypeAtLocation(unwrapParens(n.condition)))) {
|
|
437
|
+
add(n, 'NT-B', 'la condición es un Result: un objeto es siempre verdadero')
|
|
438
|
+
}
|
|
439
|
+
if (ts.isPrefixUnaryExpression(n) && n.operator === ts.SyntaxKind.ExclamationToken && isResStrict(ck.getTypeAtLocation(unwrapParens(n.operand)))) {
|
|
440
|
+
add(n, 'NT-B', '`!` sobre un Result: un objeto negado es siempre falso; mira `.ok`')
|
|
441
|
+
}
|
|
442
|
+
if (ts.isBinaryExpression(n) && [ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken].includes(n.operatorToken.kind) && isResStrict(ck.getTypeAtLocation(unwrapParens(n.left)))) {
|
|
443
|
+
add(n, 'NT-B', 'un Result a la izquierda de `&&`/`||`: es siempre verdadero')
|
|
444
|
+
}
|
|
445
|
+
if ((ts.isArrowFunction(n) || ts.isFunctionExpression(n)) && n.parent && ts.isCallExpression(n.parent) && n.parent.arguments[0] === n) {
|
|
446
|
+
const c = n.parent.expression
|
|
447
|
+
if (ts.isPropertyAccessExpression(c) && PREDICATES.has(c.name.text)) {
|
|
448
|
+
const sig = ck.getSignatureFromDeclaration(n)
|
|
449
|
+
if (sig && isRes(ck.getReturnTypeOfSignature(sig))) add(n, 'NT-B', `el predicado de \`${c.name.text}\` devuelve un Result: es siempre verdadero`)
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
// NT-C: guardado y nunca leído
|
|
453
|
+
if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.initializer) {
|
|
454
|
+
if (isRes(ck.getTypeAtLocation(n.name))) {
|
|
455
|
+
const sym = ck.getSymbolAtLocation(n.name)
|
|
456
|
+
const scope = ts.findAncestor(n.parent, (x) => ts.isFunctionLike(x) && !!x.body) ?? sf
|
|
457
|
+
if (!usedIn(scope, sym, n.name.text, n)) add(n, 'NT-C', 'el Result se guarda y nunca se lee')
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
if (ts.isCallExpression(n)) visitCall(n)
|
|
461
|
+
// NT-D: `e.message === 'x'`, `switch (e.message)`
|
|
462
|
+
if (ts.isBinaryExpression(n) && EQ_OPS.has(n.operatorToken.kind)) {
|
|
463
|
+
const [a, b] = [strip(n.left), strip(n.right)]
|
|
464
|
+
const lit = (x) => (ts.isStringLiteral(x) || ts.isNoSubstitutionTemplateLiteral(x)) && x.text !== ''
|
|
465
|
+
if (!isTestFile && ((lit(b) && isFailureText(a)) || (lit(a) && isFailureText(b)))) add(n, 'NT-D', 'el código se decide comparando el texto del fallo: usa su `code`')
|
|
466
|
+
}
|
|
467
|
+
if (ts.isSwitchStatement(n) && isFailureText(n.expression) && n.caseBlock.clauses.some((c) => ts.isCaseClause(c) && ts.isStringLiteralLike(strip(c.expression)))) {
|
|
468
|
+
add(n, 'NT-D', 'un `switch` sobre el texto del fallo: usa su `code`')
|
|
469
|
+
}
|
|
470
|
+
// NT-E: una cadena forzada a un código
|
|
471
|
+
if ((ts.isAsExpression(n) || ts.isTypeAssertionExpression(n)) && !ts.isConstTypeReference(n.type)) {
|
|
472
|
+
const lits = parts(ck.getTypeFromTypeNode(n.type))
|
|
473
|
+
let inner = n.expression
|
|
474
|
+
// `x as unknown as Code`: la cadena de verdad es la de dentro
|
|
475
|
+
while ((ts.isAsExpression(inner) || ts.isParenthesizedExpression(inner)) && !(ts.isAsExpression(inner) && ts.isConstTypeReference(inner.type))) inner = inner.expression
|
|
476
|
+
const src = ck.getTypeAtLocation(inner)
|
|
477
|
+
const wide = parts(src).some((x) => x.flags & (ts.TypeFlags.String | ts.TypeFlags.TemplateLiteral | ts.TypeFlags.Any | ts.TypeFlags.Unknown))
|
|
478
|
+
if (wide && lits.length > 0 && lits.every((x) => x.isStringLiteral() && CODE_RE.test(x.value))) {
|
|
479
|
+
add(n, 'NT-E', 'una cadena forzada a un código: usa `decode` (da `unrecognized` si no lo es)')
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
// NT-F: una promesa sin envolver dentro del cuerpo de un gen
|
|
483
|
+
if (ts.isAwaitExpression(n) && inGenBody(n)) {
|
|
484
|
+
const t = ck.getTypeAtLocation(n.expression)
|
|
485
|
+
if (isThenable(t) && !isRes(t)) add(n, 'NT-F', 'una promesa sin envolver dentro de gen: si rechaza, el Task rechaza; envuélvela con tryCatch')
|
|
486
|
+
}
|
|
487
|
+
// NT-H: un objeto de fallo interpolado en un texto
|
|
488
|
+
if (ts.isTemplateSpan(n) && failureObject(n.expression)) {
|
|
489
|
+
add(n.expression, 'NT-H', 'un fallo interpolado en un texto: escribe `[object Object]`; usa `${e.code}: ${e.message}`')
|
|
490
|
+
}
|
|
491
|
+
// NT-J: una tabla por código con clave `string`
|
|
492
|
+
if (ts.isVariableDeclaration(n) && n.type && n.initializer && ts.isObjectLiteralExpression(strip(n.initializer))) {
|
|
493
|
+
const t = ck.getTypeFromTypeNode(n.type)
|
|
494
|
+
const obj = strip(n.initializer)
|
|
495
|
+
const keys = obj.properties.map((p) => (p.name && (ts.isStringLiteral(p.name) || ts.isIdentifier(p.name)) ? p.name.text : null))
|
|
496
|
+
if (
|
|
497
|
+
ck.getIndexInfoOfType(t, ts.IndexKind.String) &&
|
|
498
|
+
t.getProperties().length === 0 &&
|
|
499
|
+
keys.length > 0 &&
|
|
500
|
+
keys.every((k) => k && CODE_RE.test(k)) &&
|
|
501
|
+
keys.some((k) => domains.has(k.split('.')[0]))
|
|
502
|
+
) {
|
|
503
|
+
add(n, 'NT-J', 'una tabla por código con clave `string`: un código nuevo no da error aquí')
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
// NT-I: el cuerpo de una respuesta sin mirar `ok`
|
|
507
|
+
if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && !isTestFile && isResponse(ck.getTypeAtLocation(n.name))) {
|
|
508
|
+
const sym = ck.getSymbolAtLocation(n.name)
|
|
509
|
+
const scope = ts.findAncestor(n.parent, (x) => ts.isFunctionLike(x) && !!x.body) ?? sf
|
|
510
|
+
const refs = refsIn(scope, sym, n.name.text)
|
|
511
|
+
const reads = refs.map((r) => (ts.isPropertyAccessExpression(r.parent) && r.parent.expression === r ? r.parent.name.text : null))
|
|
512
|
+
const escapes = reads.some((x) => x === null)
|
|
513
|
+
if (!escapes && reads.some((x) => BODY_READS.has(x)) && !reads.some((x) => x === 'ok' || x === 'status')) {
|
|
514
|
+
add(n, 'NT-I', 'el cuerpo de la respuesta se lee sin mirar `ok` ni `status`: un 500 se lee como el bueno')
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
if (ts.isPropertyAccessExpression(n) && BODY_READS.has(n.name.text)) {
|
|
518
|
+
const o = strip(n.expression)
|
|
519
|
+
const inner = ts.isAwaitExpression(o) ? strip(o.expression) : o
|
|
520
|
+
if (ts.isCallExpression(inner) && calleeName(inner) === 'fetch' && isResponse(ck.getTypeAtLocation(o))) {
|
|
521
|
+
add(n, 'NT-I', 'el cuerpo de la respuesta se lee sin mirar `ok` ni `status`: un 500 se lee como el bueno')
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
// NT-L: un AbortController que nunca se aborta
|
|
525
|
+
if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.initializer && ts.isNewExpression(n.initializer) && symName(ck.getTypeAtLocation(n.name)) === 'AbortController') {
|
|
526
|
+
const sym = ck.getSymbolAtLocation(n.name)
|
|
527
|
+
const scope = ts.findAncestor(n.parent, (x) => ts.isFunctionLike(x) && !!x.body) ?? sf
|
|
528
|
+
const refs = refsIn(scope, sym, n.name.text)
|
|
529
|
+
if (refs.length > 0 && refs.every((r) => ts.isPropertyAccessExpression(r.parent) && r.parent.expression === r && r.parent.name.text === 'signal')) {
|
|
530
|
+
add(n, 'NT-L', 'el AbortController no se aborta nunca: su señal no se dispara')
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
n.forEachChild(visit)
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
const isResponse = (t) => parts(t).some((x) => symName(x) === 'Response' && x.getProperty('ok') && x.getProperty('json'))
|
|
537
|
+
|
|
538
|
+
const visitCall = (n) => {
|
|
539
|
+
// NT-D: el código decidido por texto
|
|
540
|
+
if (ts.isPropertyAccessExpression(n.expression)) {
|
|
541
|
+
const op = n.expression.name.text
|
|
542
|
+
const recv = n.expression.expression
|
|
543
|
+
if (isTestFile) {
|
|
544
|
+
// una prueba que lee el texto lo está comprobando, no decidiendo con él
|
|
545
|
+
} else if (TEXT_OPS.has(op) && isFailureText(recv)) {
|
|
546
|
+
add(n, 'NT-D', 'el código se decide por el texto del fallo: usa su `code` (o el tipo de la causa)')
|
|
547
|
+
} else if ((op === 'test' || op === 'exec') && n.arguments[0] && isFailureText(n.arguments[0])) {
|
|
548
|
+
if (symName(ck.getTypeAtLocation(recv)) === 'RegExp') add(n, 'NT-D', 'el código se saca del texto del fallo con una regex: usa su `code`')
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
// NT-G: el brazo «para todo» que no mira el error
|
|
552
|
+
if (ts.isPropertyAccessExpression(n.expression) && ['match', 'orElse'].includes(n.expression.name.text) && n.arguments[0]) {
|
|
553
|
+
const recvT = ck.getTypeAtLocation(n.expression.expression)
|
|
554
|
+
const on = strip(n.arguments[0])
|
|
555
|
+
if (isRes(recvT) && ts.isObjectLiteralExpression(on) && hasCodes(errTypesOf(recvT))) {
|
|
556
|
+
const arms = []
|
|
557
|
+
const armsOf = (o) => {
|
|
558
|
+
for (const p of o.properties) {
|
|
559
|
+
const name = p.name && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) ? p.name.text : ''
|
|
560
|
+
const v = ts.isPropertyAssignment(p) ? strip(p.initializer) : ts.isMethodDeclaration(p) ? p : undefined
|
|
561
|
+
if (!v) continue
|
|
562
|
+
if (name === '_' && ts.isFunctionLike(v)) arms.push(v)
|
|
563
|
+
if (name === 'err' && n.expression.name.text === 'match') {
|
|
564
|
+
if (ts.isFunctionLike(v)) arms.push(v)
|
|
565
|
+
else if (ts.isObjectLiteralExpression(v)) armsOf(v)
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
armsOf(on)
|
|
570
|
+
for (const f of arms) {
|
|
571
|
+
const p = f.parameters[0]
|
|
572
|
+
const ignores = !p || (ts.isIdentifier(p.name) && !usedIn(f.body, ck.getSymbolAtLocation(p.name), p.name.text))
|
|
573
|
+
if (ignores) add(f, 'NT-G', 'el brazo «para todo» no mira el error: cualquier código (también los que se añadan) pasa por valor normal')
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
// NT-H: un fallo nuevo hecho con el texto de otro, sin `cause`
|
|
578
|
+
const msgArg = n.arguments[0]
|
|
579
|
+
if (msgArg) {
|
|
580
|
+
const name = calleeName(n)
|
|
581
|
+
const isMake = isMakeCall(n)
|
|
582
|
+
// v3: fail(code, message, cause?)
|
|
583
|
+
const isFail = !isMake && ['fail', 'resultError'].includes(name) && n.arguments[1]
|
|
584
|
+
const message = isFail ? n.arguments[1] : msgArg
|
|
585
|
+
if ((isMake || isFail) && carriesFailureText(message)) {
|
|
586
|
+
const causeArg = isFail ? n.arguments[2] : n.arguments[1]
|
|
587
|
+
const o = causeArg && strip(causeArg)
|
|
588
|
+
const noCause = !causeArg || (ts.isObjectLiteralExpression(o) && !hasProp(o, 'cause'))
|
|
589
|
+
if (noCause) add(n, 'NT-H', 'un fallo nuevo con el texto de otro y sin `cause`: el código y la pila del original se pierden')
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
// NT-K: hay una señal y no se pasa
|
|
593
|
+
if (!inCleanup(n) && missingSignal(n)) {
|
|
594
|
+
const s = signalInScope(n)
|
|
595
|
+
if (s) add(n, 'NT-K', `la llamada acepta una señal y no se le pasa (hay una a mano: ${s})`)
|
|
596
|
+
}
|
|
597
|
+
// NT-M: se abre dentro de gen y no se cierra
|
|
598
|
+
const opener = calleeName(n)
|
|
599
|
+
if (PAIRS[opener]) {
|
|
600
|
+
let g = fnOf(n)
|
|
601
|
+
while (g && !isGenFn(g)) g = fnOf(g)
|
|
602
|
+
if (g && !ts.findAncestor(n, ts.isReturnStatement)) {
|
|
603
|
+
const closers = PAIRS[opener]
|
|
604
|
+
const c = strip(n.expression)
|
|
605
|
+
const exists = closers.some((cl) =>
|
|
606
|
+
ts.isPropertyAccessExpression(c) ? Boolean(ck.getTypeAtLocation(c.expression).getProperty(cl)) : Boolean(ck.resolveName(cl, n, ts.SymbolFlags.Value, false))
|
|
607
|
+
)
|
|
608
|
+
let closed = false
|
|
609
|
+
const w = (x) => {
|
|
610
|
+
if (closed) return
|
|
611
|
+
if (ts.isIdentifier(x) && closers.includes(x.text)) closed = true
|
|
612
|
+
x.forEachChild(w)
|
|
613
|
+
}
|
|
614
|
+
w(g)
|
|
615
|
+
if (exists && !closed) add(n, 'NT-M', `\`${opener}\` dentro de gen sin su cierre (${closers.join(' / ')}): apila \`yield* defer(...)\` justo después`)
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
// NT-O: una llamada que lanza, sin envolver, en código de Result
|
|
619
|
+
const throws =
|
|
620
|
+
(ts.isPropertyAccessExpression(n.expression) && ts.isIdentifier(n.expression.expression) && n.expression.expression.text === 'JSON' && n.expression.name.text === 'parse') ||
|
|
621
|
+
(ts.isIdentifier(n.expression) && THROWING_GLOBALS.has(n.expression.text))
|
|
622
|
+
if (throws) checkThrowing(n)
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
const checkThrowing = (n) => {
|
|
626
|
+
// dentro de un try, o del callback de un tryCatch: está envuelto
|
|
627
|
+
let resultCode = false
|
|
628
|
+
for (let x = n.parent; x; x = x.parent) {
|
|
629
|
+
if (x.parent && ts.isTryStatement(x.parent) && x.parent.tryBlock === x) return
|
|
630
|
+
if (ts.isCallExpression(x) && ['ok', 'err'].includes(calleeName(x)) && isRes(ck.getTypeAtLocation(x))) resultCode = true
|
|
631
|
+
if (ts.isFunctionLike(x)) {
|
|
632
|
+
if (isWrapperArg(x)) return
|
|
633
|
+
if (isGenFn(x) || resultCallbackOf(x)) resultCode = true
|
|
634
|
+
break
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
if (resultCode) add(n, 'NT-O', `\`${n.getText(sf).split('(')[0]}\` lanza con la entrada mala y aquí no hay nada que lo traduzca: envuélvelo con tryCatch`)
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
ts.forEachChild(sf, visit)
|
|
641
|
+
const visitNew = (n) => {
|
|
642
|
+
if (ts.isNewExpression(n) && ts.isIdentifier(n.expression)) {
|
|
643
|
+
// `new URL(x)` también lanza
|
|
644
|
+
if (n.expression.text === 'URL') checkThrowing(n)
|
|
645
|
+
// NT-H: `new Error(\`... ${e.message}\`)` sin `{ cause }`
|
|
646
|
+
const a = n.arguments ?? []
|
|
647
|
+
// `new Error(String(e))` a secas normaliza lo lanzado a un Error: no hay otro texto que se pierda
|
|
648
|
+
const bare = a[0] && ts.isCallExpression(strip(a[0])) && calleeName(strip(a[0])) === 'String'
|
|
649
|
+
if (a[0] && !bare && ck.getTypeAtLocation(n).getProperty('stack') && carriesFailureText(a[0])) {
|
|
650
|
+
const o = a[1] && strip(a[1])
|
|
651
|
+
if (!a[1] || (ts.isObjectLiteralExpression(o) && !hasProp(o, 'cause'))) add(n, 'NT-H', 'un Error nuevo con el texto de otro fallo y sin `cause`: el original se pierde')
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
n.forEachChild(visitNew)
|
|
655
|
+
}
|
|
656
|
+
visitNew(sf)
|
|
657
|
+
return suppress(sf, out)
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** Los avisos que su línea calla con `nt-lint-disable-line` / `-next-line`. */
|
|
661
|
+
const suppress = (sf, found) => {
|
|
662
|
+
const lines = sf.text.split('\n')
|
|
663
|
+
const says = (ln, kind, rule) => {
|
|
664
|
+
const m = new RegExp(`nt-lint-disable-${kind}\\b([^\\n]*)`).exec(lines[ln] ?? '')
|
|
665
|
+
if (!m) return false
|
|
666
|
+
const ids = m[1].split('--')[0].match(/NT-[A-Z]/g)
|
|
667
|
+
return !ids || ids.includes(rule)
|
|
668
|
+
}
|
|
669
|
+
return found.filter((f) => !says(f.line - 1, 'line', f.rule) && !says(f.line - 2, 'next-line', f.rule))
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/** Los dominios declarados con `defineErrors('dominio', ...)` en el programa. */
|
|
673
|
+
const domainCache = new WeakMap()
|
|
674
|
+
export const collectDomains = (program, ts = tsDefault) => {
|
|
675
|
+
if (domainCache.has(program)) return domainCache.get(program)
|
|
676
|
+
const set = new Set()
|
|
677
|
+
for (const sf of program.getSourceFiles()) {
|
|
678
|
+
if (sf.isDeclarationFile || !sf.text.includes('defineErrors')) continue
|
|
679
|
+
const w = (x) => {
|
|
680
|
+
if (ts.isCallExpression(x) && x.arguments[0] && ts.isStringLiteralLike(x.arguments[0])) {
|
|
681
|
+
const c = x.expression
|
|
682
|
+
const name = ts.isIdentifier(c) ? c.text : ts.isPropertyAccessExpression(c) ? c.name.text : ''
|
|
683
|
+
if (name === 'defineErrors') set.add(x.arguments[0].text)
|
|
684
|
+
}
|
|
685
|
+
x.forEachChild(w)
|
|
686
|
+
}
|
|
687
|
+
w(sf)
|
|
688
|
+
}
|
|
689
|
+
domainCache.set(program, set)
|
|
690
|
+
return set
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* Corre las reglas sobre todo el programa.
|
|
695
|
+
* @param {import('typescript').Program} program
|
|
696
|
+
* @param {(f: string) => boolean} [only] filtro por ruta de fichero
|
|
697
|
+
*/
|
|
698
|
+
export const lint = (program, only = () => true) => {
|
|
699
|
+
const domains = collectDomains(program)
|
|
700
|
+
const out = []
|
|
701
|
+
for (const sf of program.getSourceFiles()) {
|
|
702
|
+
if (sf.isDeclarationFile) continue
|
|
703
|
+
if (sf.fileName.includes('/node_modules/')) continue
|
|
704
|
+
if (!only(sf.fileName)) continue
|
|
705
|
+
out.push(...lintFile(program, sf, { domains }))
|
|
706
|
+
}
|
|
707
|
+
return out
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/**
|
|
711
|
+
* @param {string} cfg ruta del tsconfig
|
|
712
|
+
* @returns {import('typescript').Program}
|
|
713
|
+
*/
|
|
714
|
+
export const load = (cfg) => {
|
|
715
|
+
const ts = tsDefault
|
|
716
|
+
if (!ts) throw new Error(loaded.why)
|
|
717
|
+
const r = ts.readConfigFile(cfg, ts.sys.readFile)
|
|
718
|
+
if (r.error) throw new Error(ts.flattenDiagnosticMessageText(r.error.messageText, '\n'))
|
|
719
|
+
const p = ts.parseJsonConfigFileContent(r.config, ts.sys, path.dirname(path.resolve(cfg)))
|
|
720
|
+
return ts.createProgram(p.fileNames, { ...p.options, noEmit: true })
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
export { RULES, RULE }
|
|
724
|
+
|
|
725
|
+
/** El aviso, para leerlo en una terminal. */
|
|
726
|
+
export const format = (found, how = 'pretty', cwd = process.cwd()) => {
|
|
727
|
+
const rel = (f) => path.relative(cwd, f) || f
|
|
728
|
+
if (how === 'json') return JSON.stringify(found.map((x) => ({ ...x, file: rel(x.file), title: RULE[x.rule]?.title })), null, 2)
|
|
729
|
+
if (how === 'github') {
|
|
730
|
+
return found.map((x) => `::warning file=${rel(x.file)},line=${x.line},col=${x.col},title=${x.rule} ${RULE[x.rule]?.title ?? ''}::${x.msg}. ${RULE[x.rule]?.fix ?? ''}`).join('\n')
|
|
731
|
+
}
|
|
732
|
+
if (how === 'compact') return found.map((x) => `${rel(x.file)}:${x.line}:${x.col} ${x.rule} ${x.msg} — ${x.text}`).join('\n')
|
|
733
|
+
return found
|
|
734
|
+
.map((x) => {
|
|
735
|
+
const r = RULE[x.rule]
|
|
736
|
+
return [`${rel(x.file)}:${x.line}:${x.col} ${x.rule} ${x.msg}`, ` ${x.text}`, ` por qué: ${r.why}`, ` arreglo: ${r.fix}`].join('\n')
|
|
737
|
+
})
|
|
738
|
+
.join('\n\n')
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
const isMain = process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url))
|
|
742
|
+
if (isMain) {
|
|
743
|
+
const args = process.argv.slice(2)
|
|
744
|
+
const opt = (k) => args.find((a) => a.startsWith(`--${k}=`))?.slice(k.length + 3)
|
|
745
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
746
|
+
console.log('uso: nt-lint [tsconfig.json] [--rule=NT-A,NT-D] [--only=subcadena] [--format=pretty|compact|json|github] [--explain=NT-X] [--rules]')
|
|
747
|
+
process.exit(0)
|
|
748
|
+
}
|
|
749
|
+
if (args.includes('--rules')) {
|
|
750
|
+
for (const r of RULES) console.log(`${r.id} ${r.title} (${r.clase})`)
|
|
751
|
+
process.exit(0)
|
|
752
|
+
}
|
|
753
|
+
const explain = opt('explain')
|
|
754
|
+
if (explain) {
|
|
755
|
+
const r = RULE[explain.toUpperCase()]
|
|
756
|
+
if (!r) {
|
|
757
|
+
console.error(`no existe la regla ${explain}; las hay de NT-A a ${RULES.at(-1).id}`)
|
|
758
|
+
process.exit(2)
|
|
759
|
+
}
|
|
760
|
+
console.log(`${r.id} — ${r.title}\nclase: ${r.clase}\n\npor qué: ${r.why}\n\narreglo: ${r.fix}`)
|
|
761
|
+
process.exit(0)
|
|
762
|
+
}
|
|
763
|
+
const cfg = args.find((a) => !a.startsWith('--')) ?? 'tsconfig.json'
|
|
764
|
+
if (!fs.existsSync(cfg)) {
|
|
765
|
+
console.error(`nt-lint: no encuentro ${cfg} (pásale la ruta de un tsconfig.json)`)
|
|
766
|
+
process.exit(2)
|
|
767
|
+
}
|
|
768
|
+
const only = opt('only')
|
|
769
|
+
const rules = opt('rule')?.toUpperCase().split(',')
|
|
770
|
+
const legacy = args.includes('--json')
|
|
771
|
+
const how = legacy ? 'json' : opt('format') ?? 'pretty'
|
|
772
|
+
let program
|
|
773
|
+
try {
|
|
774
|
+
program = load(cfg)
|
|
775
|
+
} catch (e) {
|
|
776
|
+
console.error(`nt-lint: ${e instanceof Error ? e.message : String(e)}`)
|
|
777
|
+
process.exit(2)
|
|
778
|
+
}
|
|
779
|
+
const found = lint(program, (f) => !only || f.includes(only)).filter((x) => !rules || rules.includes(x.rule))
|
|
780
|
+
if (found.length) console.log(format(found, how))
|
|
781
|
+
if (how !== 'json') console.log(`${found.length ? '\n' : ''}${found.length} avisos`)
|
|
782
|
+
process.exit(found.length ? 1 : 0)
|
|
783
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mks2508/no-throw-lint",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "4.0.0",
|
|
4
|
+
"description": "nt-lint — type-aware lint for what the type system cannot stop (un Result sin mirar, un código decidido por texto); CLI + ESLint plugin",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"nt-lint": "nt-lint.mjs"
|
|
8
|
+
},
|
|
9
|
+
"main": "./nt-lint.mjs",
|
|
10
|
+
"types": "./nt-lint.d.mts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./nt-lint.d.mts",
|
|
14
|
+
"default": "./nt-lint.mjs"
|
|
15
|
+
},
|
|
16
|
+
"./eslint": {
|
|
17
|
+
"types": "./eslint.d.mts",
|
|
18
|
+
"default": "./eslint.mjs"
|
|
19
|
+
},
|
|
20
|
+
"./package.json": "./package.json"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"nt-lint.mjs",
|
|
24
|
+
"nt-lint.d.mts",
|
|
25
|
+
"rules.mjs",
|
|
26
|
+
"eslint.mjs",
|
|
27
|
+
"eslint.d.mts",
|
|
28
|
+
"README.md"
|
|
29
|
+
],
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "node --check nt-lint.mjs && node --check rules.mjs && node --check eslint.mjs",
|
|
32
|
+
"typecheck": "tsc --noEmit",
|
|
33
|
+
"test": "bun test"
|
|
34
|
+
},
|
|
35
|
+
"keywords": [
|
|
36
|
+
"lint",
|
|
37
|
+
"typescript",
|
|
38
|
+
"result",
|
|
39
|
+
"eslint",
|
|
40
|
+
"error-handling",
|
|
41
|
+
"no-throw"
|
|
42
|
+
],
|
|
43
|
+
"author": "MKS2508",
|
|
44
|
+
"license": "MIT",
|
|
45
|
+
"repository": {
|
|
46
|
+
"type": "git",
|
|
47
|
+
"url": "git+https://github.com/MKS2508/no-throw.git",
|
|
48
|
+
"directory": "lint"
|
|
49
|
+
},
|
|
50
|
+
"bugs": {
|
|
51
|
+
"url": "https://github.com/MKS2508/no-throw/issues"
|
|
52
|
+
},
|
|
53
|
+
"homepage": "https://github.com/MKS2508/no-throw#readme",
|
|
54
|
+
"dependencies": {
|
|
55
|
+
"typescript": ">=5.0.0 <7"
|
|
56
|
+
}
|
|
57
|
+
}
|
package/rules.mjs
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Las reglas de nt-lint: qué paran, por qué duele y cómo se arregla.
|
|
2
|
+
// Es lo que la CLI imprime debajo de cada aviso y lo que `--explain` enseña.
|
|
3
|
+
|
|
4
|
+
/** @typedef {{ id: string, clase: string, title: string, why: string, fix: string }} Rule */
|
|
5
|
+
|
|
6
|
+
/** @type {Rule[]} */
|
|
7
|
+
export const RULES = [
|
|
8
|
+
{
|
|
9
|
+
id: 'NT-A',
|
|
10
|
+
clase: 'Result no comprobado',
|
|
11
|
+
title: 'el Result se tira sin mirar',
|
|
12
|
+
why: 'una sentencia, un `void` o un callback que devuelve a un sitio que no lo lee (forEach, un listener, setTimeout) deja el fallo sin que nadie lo vea.',
|
|
13
|
+
fix: 'cédelo con `yield*` dentro de `gen`, guárdalo y mira `.ok`, o decide con `.match({...})`.',
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
id: 'NT-B',
|
|
17
|
+
clase: 'Result no comprobado',
|
|
18
|
+
title: 'un Result usado como booleano',
|
|
19
|
+
why: 'un Result es un objeto: `if (r)`, `!r`, `r && x` o un `filter` que lo devuelve son siempre verdaderos (o siempre falsos), haya fallado o no.',
|
|
20
|
+
fix: 'mira el discriminante: `r.ok`.',
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
id: 'NT-C',
|
|
24
|
+
clase: 'Result no comprobado',
|
|
25
|
+
title: 'el Result se guarda y nunca se lee',
|
|
26
|
+
why: 'la variable existe, pero nadie mira si la operación falló.',
|
|
27
|
+
fix: 'lee `r.ok` (o cede con `yield*`); si de verdad da igual, no lo guardes y dilo con un comentario.',
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
id: 'NT-D',
|
|
31
|
+
clase: 'código equivocado',
|
|
32
|
+
title: 'el código se decide por el texto del fallo',
|
|
33
|
+
why: 'el mensaje es para personas: cambia con otra versión, otro idioma u otro proveedor, y el `includes`/`===`/regex deja de cuadrar sin avisar.',
|
|
34
|
+
fix: 'decide por `e.code`, por el tipo de la causa (`instanceof`, `errno`, `status`) o con `decode` en el cable.',
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
id: 'NT-E',
|
|
38
|
+
clase: 'código equivocado',
|
|
39
|
+
title: 'una cadena forzada a un código',
|
|
40
|
+
why: 'el `as` le dice al compilador que confíe: un código que no existe pasa como si existiera y el `match` exhaustivo deja de serlo.',
|
|
41
|
+
fix: 'pásalo por `decode` del registro: da `unrecognized` si no es uno de los tuyos.',
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
id: 'NT-F',
|
|
45
|
+
clase: 'muerte que no llega al que espera',
|
|
46
|
+
title: 'una promesa sin envolver dentro de gen',
|
|
47
|
+
why: 'si rechaza, el Task rechaza: el fallo sale como excepción y no por el tipo, y los `defer` no ven un fallo sino un rechazo.',
|
|
48
|
+
fix: '`yield* tryCatch((s) => p(s), traduce, { within })`.',
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
id: 'NT-G',
|
|
52
|
+
clase: 'fallo leído como valor normal',
|
|
53
|
+
title: 'el brazo «para todo» se traga el fallo',
|
|
54
|
+
why: 'un `err: () => x` o un `_: () => ...` que no mira el error convierte cualquier fallo con código (los de hoy y los que se añadan) en un valor normal: es el `unwrapOr` que la librería no deja compilar, escrito a mano.',
|
|
55
|
+
fix: 'nombra los códigos que recuperas (`orElse({ "dom.clave": ... })`, `err: { "dom.clave": ... }`) y deja pasar el resto; si de verdad es «para todo», usa el error.',
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
id: 'NT-H',
|
|
59
|
+
clase: 'causa aplastada a texto',
|
|
60
|
+
title: 'el fallo se convierte en texto y se pierde',
|
|
61
|
+
why: 'construir un fallo nuevo con `${e.message}`/`${e.code}` sin `cause` deja el original (su código, su pila, su `data`) fuera; e interpolar un objeto sin `toString` escribe `[object Object]`.',
|
|
62
|
+
fix: 'pasa el original como `{ cause: e }` (o devuélvelo con su código); en un texto, escribe `${e.code}: ${e.message}`.',
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
id: 'NT-I',
|
|
66
|
+
clase: 'plazos y señales',
|
|
67
|
+
title: 'la respuesta HTTP se lee sin mirar `ok`',
|
|
68
|
+
why: '`fetch` no falla con un 4xx/5xx: el cuerpo de un error se lee como si fuera el bueno.',
|
|
69
|
+
fix: 'antes de `.json()`/`.text()`, `if (!res.ok) return yield* Http.make.status(...)`.',
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
id: 'NT-J',
|
|
73
|
+
clase: 'código equivocado',
|
|
74
|
+
title: 'una tabla por código con clave `string`',
|
|
75
|
+
why: 'con `Record<string, X>` un código nuevo del registro no da error en la tabla: cae al `undefined` en tiempo de ejecución.',
|
|
76
|
+
fix: 'tipa la clave con los códigos: `Record<Code<ErrorsOf<typeof Dom>>, X>`.',
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
id: 'NT-K',
|
|
80
|
+
clase: 'plazos y señales',
|
|
81
|
+
title: 'hay una señal y no se pasa',
|
|
82
|
+
why: 'la función acepta una `AbortSignal` y tienes una a mano: sin pasarla, cancelar o vencer el plazo no para el trabajo, que sigue corriendo (y escribiendo) después.',
|
|
83
|
+
fix: 'pásala (`fetch(url, { signal })`, `f(x, signal)`); en `tryCatch`, el primer parámetro del callback es la señal.',
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
id: 'NT-L',
|
|
87
|
+
clase: 'cierre que falta',
|
|
88
|
+
title: 'un AbortController que nunca se aborta',
|
|
89
|
+
why: 'su señal se reparte pero nadie llama a `abort()`: lo que escucha no se para nunca.',
|
|
90
|
+
fix: '`c.abort()` en un `finally`, o `yield* defer(() => c.abort())` dentro de `gen`.',
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
id: 'NT-M',
|
|
94
|
+
clase: 'cierre que falta',
|
|
95
|
+
title: 'se abre dentro de gen y no se cierra',
|
|
96
|
+
why: 'un `lock`/`open`/`acquire`/`connect`/`subscribe` sin su pareja en el cuerpo del `gen` deja el recurso tomado si algo falla después (y si nada falla, también).',
|
|
97
|
+
fix: 'apila el cierre justo después: `yield* defer(() => unlock(x))`.',
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
id: 'NT-N',
|
|
101
|
+
clase: 'muerte que no llega al que espera',
|
|
102
|
+
title: 'una promesa suelta en un brazo o en un gen',
|
|
103
|
+
why: 'la promesa no se devuelve ni se espera: el Result (o el gen) termina antes que ella y, si rechaza, nadie se entera.',
|
|
104
|
+
fix: 'devuélvela (`() => dead(job)`), espérala con `yield* tryCatch(...)`, o márcala con `void` si de verdad no importa.',
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
id: 'NT-O',
|
|
108
|
+
clase: 'Result no comprobado',
|
|
109
|
+
title: 'una llamada que lanza, sin envolver, en código de Result',
|
|
110
|
+
why: '`JSON.parse`, `new URL`, `decodeURIComponent`, `atob`, `BigInt` lanzan con la entrada mala: dentro de `ok(...)`, de un `gen` o de un `map`, la excepción se salta el tipo.',
|
|
111
|
+
fix: '`tryCatch(() => JSON.parse(s), (cause) => Dom.make.syntax("...", { cause }).error)`.',
|
|
112
|
+
},
|
|
113
|
+
]
|
|
114
|
+
|
|
115
|
+
export const RULE = Object.fromEntries(RULES.map((r) => [r.id, r]))
|