@robosophy/lint 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +177 -2
- package/bin/cli.mjs +7 -0
- package/bin/lib.mjs +701 -0
- package/eslint/base.mjs +90 -0
- package/eslint/browser.mjs +13 -0
- package/eslint/node.mjs +24 -0
- package/eslint/react.mjs +30 -0
- package/eslint/vue.mjs +30 -0
- package/lint-staged.config.mjs +4 -0
- package/lint-staged.strict.config.mjs +7 -0
- package/package.json +64 -4
- package/prettier.config.mjs +14 -0
package/README.md
CHANGED
|
@@ -1,3 +1,178 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @robosophy/lint
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Configuraciones compartidas de ESLint, Prettier y lint-staged, con presets para Vue, React y Node.js. Incluye un instalador opcional para configurar un proyecto con Husky.
|
|
4
|
+
|
|
5
|
+
## Requisitos
|
|
6
|
+
|
|
7
|
+
- Node.js `>=20.19.0`.
|
|
8
|
+
- npm, porque el instalador y `doctor` ejecutan comandos `npm`.
|
|
9
|
+
- Un `package.json` en la raíz del proyecto para ejecutar `init`.
|
|
10
|
+
|
|
11
|
+
El instalador usa `npm install`. Si el proyecto usa pnpm, Yarn u otro gestor, configura las dependencias con ese gestor e importa los presets manualmente (ver [Configuración manual](#configuración-manual)).
|
|
12
|
+
|
|
13
|
+
## Inicio rápido
|
|
14
|
+
|
|
15
|
+
Ejecuta desde la raíz del proyecto:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npx @robosophy/lint@latest init
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Sin un preset explícito, el CLI detecta Vue o React en `dependencies`, `devDependencies` o `peerDependencies`. Si encuentra ambos, o no encuentra ninguno, la detección falla. Para Node.js selecciona `--node` explícitamente:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npx @robosophy/lint@latest init --node
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
También puedes elegir el preset explícitamente para Vue o React:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npx @robosophy/lint@latest init --vue
|
|
31
|
+
npx @robosophy/lint@latest init --react
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
El modo predeterminado es **legacy**: los errores de ESLint bloquean el hook de commit, pero los warnings no. Para que los warnings restantes también lo bloqueen:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
npx @robosophy/lint@latest init --strict
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`--strict` solo cambia el comando de ESLint en lint-staged; no cambia la severidad de las reglas ni agrega `--max-warnings=0` a `npm run lint`.
|
|
41
|
+
|
|
42
|
+
## Comandos y opciones
|
|
43
|
+
|
|
44
|
+
| Comando u opción | Comportamiento |
|
|
45
|
+
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
46
|
+
| `init` | Instala dependencias y genera configuraciones en el directorio actual. Requiere `package.json`. |
|
|
47
|
+
| `--vue`, `--react`, `--node` | Elige un preset. Usa como máximo uno; `--node` siempre debe indicarse explícitamente. |
|
|
48
|
+
| `--strict` | Hace que warnings de ESLint no corregidos automáticamente bloqueen lint-staged. |
|
|
49
|
+
| `--dry-run` | Muestra archivos, backups y cambios previstos en `package.json`; no escribe ni instala. |
|
|
50
|
+
| `--clean` | Además de respaldar las configuraciones que reemplaza, archiva los archivos raíz `.eslintignore` y `.prettierignore`. No los elimina. |
|
|
51
|
+
| `--no-husky` | No agrega Husky ni escribe el hook del paquete; conserva el `prepare` y el hook existentes. |
|
|
52
|
+
| `--yes`, `-y` | Confirma la instalación sin mostrar el prompt. |
|
|
53
|
+
| `--force` | También omite el prompt. **No** elimina ni evita los backups. |
|
|
54
|
+
| `--skip-install` | Omite `npm install`, pero aun así actualiza `package.json` y escribe las configuraciones. Úsalo solo si instalarás las dependencias por separado. |
|
|
55
|
+
| `doctor` o `--doctor` | Revisa el setup sin modificar archivos. Puede consultar el registry de npm. |
|
|
56
|
+
| `--help`, `-h` | Muestra el uso del CLI. |
|
|
57
|
+
|
|
58
|
+
En entornos no interactivos debes pasar `--yes` o `--force`. `--yes` y `--force` solo confirman la operación; los archivos que se reemplazan siguen respaldándose.
|
|
59
|
+
|
|
60
|
+
Ejemplo para previsualizar una migración sin Husky:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
npx @robosophy/lint@latest init --node --clean --no-husky --dry-run
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Backups y opciones de limpieza
|
|
67
|
+
|
|
68
|
+
Antes de reemplazar una configuración reconocida en la raíz del proyecto, el instalador la mueve a `.backup`. Si ese nombre ya existe, usa `.backup.2`, `.backup.3`, etc.; no sobrescribe backups existentes. Si vuelves a ejecutar `init` con el mismo preset, las configuraciones sin cambios se conservan. Cambiar entre legacy y strict actualiza el wrapper generado de lint-staged sin backup; cambiar de framework sí respalda el `eslint.config.mjs` anterior antes de reemplazarlo.
|
|
69
|
+
|
|
70
|
+
Este backup de configuraciones que van a reemplazarse ocurre aunque no pases `--clean`. `--clean` agrega el archivado de `.eslintignore` y `.prettierignore`:
|
|
71
|
+
|
|
72
|
+
- ESLint Flat Config no consume `.eslintignore`; migra los patrones que necesites a `eslint.config.mjs`.
|
|
73
|
+
- `.prettierignore` sigue siendo válido para Prettier. Al archivarlo, sus exclusiones dejan de aplicarse hasta que lo restaures o migres sus patrones.
|
|
74
|
+
|
|
75
|
+
El instalador no hace un formateo masivo del proyecto. El hook ejecuta lint-staged sobre los archivos preparados para el commit.
|
|
76
|
+
|
|
77
|
+
### Dependencias y `package.json`
|
|
78
|
+
|
|
79
|
+
`init` ejecuta npm e instala/actualiza `@robosophy/lint`, ESLint 10, Prettier 3 y lint-staged 16; con el preset Vue también actualiza `eslint-plugin-vue` a la versión compatible con el preset. Instala o actualiza Husky 9 salvo que uses `--no-husky`. Las versiones antiguas de estas dependencias se migran aunque la configuración previa se respalde; npm también actualiza el lockfile. Otras dependencias legacy de ESLint que no gestione el instalador pueden seguir causando conflictos de peers.
|
|
80
|
+
|
|
81
|
+
El instalador conserva los scripts existentes, agrega `lint: eslint .` solo si no hay un script `lint`, y configura `prepare: husky` cuando Husky está habilitado. Si ya existe un `prepare`, agrega `&& husky` salvo que detecte ya el comando `husky`. Con `--no-husky`, no modifica `prepare` ni agrega Husky.
|
|
82
|
+
|
|
83
|
+
Salvo que uses `--skip-install` o `--dry-run`, `init` ejecuta `npm install`; npm puede ejecutar el `prepare` que ya existía en el proyecto. Por eso `--no-husky` evita que este paquete agregue o escriba su hook, pero no puede impedir que un `prepare` personalizado configure hooks por su cuenta. Para no ejecutar scripts de ciclo de vida de npm, combina `--no-husky --skip-install` y gestiona las dependencias manualmente.
|
|
84
|
+
|
|
85
|
+
## Archivos que configura
|
|
86
|
+
|
|
87
|
+
- `eslint.config.mjs`: wrapper para el preset Vue, React o Node.js.
|
|
88
|
+
- `prettier.config.mjs`: importa la configuración compartida de Prettier.
|
|
89
|
+
- `lint-staged.config.mjs`: ESLint con `--fix` y Prettier para archivos preparados.
|
|
90
|
+
- `.husky/pre-commit`: ejecuta `npx lint-staged` cuando Husky está habilitado.
|
|
91
|
+
- `package.json`: incorpora las dependencias y scripts descritos arriba.
|
|
92
|
+
|
|
93
|
+
El preset de lint-staged procesa `js`, `mjs`, `cjs`, `jsx`, `ts`, `tsx` y `vue` con ESLint y Prettier. `json`, `md`, `css`, `scss`, `html`, `yml` y `yaml` pasan solo por Prettier. Otros tipos de archivo no tienen una tarea asignada por estas configuraciones.
|
|
94
|
+
|
|
95
|
+
## Presets y reglas
|
|
96
|
+
|
|
97
|
+
Los tres presets comparten reglas de JavaScript/TypeScript, orden de imports/exports, igualdad estricta, `prefer-const`, prohibición de `var` y detección de variables sin usar. Los presets Vue y React agregan globals de navegador y reglas específicas del framework; el preset Node agrega globals de Node.js.
|
|
98
|
+
|
|
99
|
+
- **Errores:** variables sin usar, imports/exports desordenados, `no-mutating-props` en Vue y Rules of Hooks en React, entre otros errores de las reglas recomendadas.
|
|
100
|
+
- **Warnings:** `any`, comentarios TS restringidos, `console` (se permiten `console.warn` y `console.error`), `v-html`, refs sin usar y orden de bloques/macros en Vue; `exhaustive-deps` y React Refresh en React.
|
|
101
|
+
- **Autofix:** ESLint ordena imports/exports y aplica los fixes disponibles. Prettier define el formato y ordena clases Tailwind, incluso dentro de `clsx`, `cn` y `cva`.
|
|
102
|
+
- **Strict:** lint-staged agrega `--max-warnings=0` al comando de ESLint. Los warnings que ESLint haya corregido con `--fix` no bloquean; los que queden sí.
|
|
103
|
+
|
|
104
|
+
El preset Node no activa reglas de Vue ni React. El preset Vue o React añade sus reglas sobre la base compartida.
|
|
105
|
+
|
|
106
|
+
La configuración de Prettier usa comillas simples, punto y coma, ancho de línea 100, indentación de 2 espacios y comas finales. El plugin Tailwind ordena las clases; también reconoce las funciones `clsx`, `cn` y `cva`.
|
|
107
|
+
|
|
108
|
+
## Configuración manual
|
|
109
|
+
|
|
110
|
+
Si no quieres que el CLI instale dependencias o escriba archivos, instala las dependencias compatibles con tu gestor y crea wrappers que importen los exports del paquete. Los peers son ESLint `^9 || ^10`, Prettier `^3` y lint-staged `^16`; Husky `^9` solo es necesario si quieres configurar el hook. Por ejemplo, para React:
|
|
111
|
+
|
|
112
|
+
```js
|
|
113
|
+
// eslint.config.mjs
|
|
114
|
+
import config from '@robosophy/lint/eslint/react';
|
|
115
|
+
|
|
116
|
+
export default config;
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Usa `@robosophy/lint/eslint/vue` o `@robosophy/lint/eslint/node` para los otros presets. Para Prettier y lint-staged:
|
|
120
|
+
|
|
121
|
+
```js
|
|
122
|
+
// prettier.config.mjs
|
|
123
|
+
export { default } from '@robosophy/lint/prettier';
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
```js
|
|
127
|
+
// lint-staged.config.mjs (modo legacy)
|
|
128
|
+
export { default } from '@robosophy/lint/lint-staged';
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Para strict, cambia el último export por `@robosophy/lint/lint-staged/strict`. Si configuras Husky manualmente, invoca lint-staged con el gestor del proyecto; por ejemplo, `npx lint-staged` con npm o `pnpm exec lint-staged` con pnpm.
|
|
132
|
+
|
|
133
|
+
## Validar y diagnosticar
|
|
134
|
+
|
|
135
|
+
Después de instalar:
|
|
136
|
+
|
|
137
|
+
```bash
|
|
138
|
+
npm run lint
|
|
139
|
+
npx prettier --check .
|
|
140
|
+
npx robosophy-lint doctor
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
`npm run lint` solo aparece si el proyecto no tenía ya un script `lint`. `doctor` informa checks como `[OK]`, `[WARN]`, `[INFO]` o `[ERROR]`; devuelve código de salida distinto de cero si encuentra errores, no por warnings. Consulta `npm view` para comparar la versión instalada con la publicada, así que necesita acceso al registry para completar ese check. El comando no escribe archivos del proyecto.
|
|
144
|
+
|
|
145
|
+
En Husky v9, `doctor` revisa el runner ubicado en `core.hooksPath` (o la ruta predeterminada de Git). El archivo `.husky/pre-commit` no necesita permiso ejecutable: Husky lo invoca con `sh`.
|
|
146
|
+
|
|
147
|
+
### Problemas frecuentes
|
|
148
|
+
|
|
149
|
+
- **No encuentra `package.json`:** ejecuta `init` desde la raíz del proyecto, no desde `packages/` u otro subdirectorio.
|
|
150
|
+
- **No puede detectar un preset:** pasa `--vue`, `--react` o `--node`. Si el proyecto contiene Vue y React, elige explícitamente uno.
|
|
151
|
+
- **Hay configuraciones antiguas:** consulta los archivos `.backup` antes de migrar reglas o patrones. `doctor` señala `.eslintrc*`, `.prettierrc*` y `.eslintignore` activos.
|
|
152
|
+
- **`doctor` avisa que no conoce la última versión:** revisa conexión y permisos del registry npm. Ese aviso no produce un código de salida fallido; una comprobación con `[ERROR]` sí.
|
|
153
|
+
|
|
154
|
+
## Actualizar las reglas
|
|
155
|
+
|
|
156
|
+
Los proyectos importan los presets del paquete; no necesitan copiar las reglas. Para actualizar dentro del rango declarado:
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
npm update @robosophy/lint
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
El lockfile fija la versión instalada: los cambios publicados no llegan al proyecto hasta actualizar la dependencia y su lockfile.
|
|
163
|
+
|
|
164
|
+
## Notas para asistentes de IA
|
|
165
|
+
|
|
166
|
+
- Trata este README y los exports de `package.json` como la referencia del comportamiento del paquete. Importa los presets compartidos; no copies sus reglas a configuraciones locales.
|
|
167
|
+
- Antes de recomendar cambios que escriban archivos o actualicen dependencias, revisa `package.json` y las configuraciones existentes. Recomienda `--dry-run` primero.
|
|
168
|
+
- No recomiendes `--clean` sin explicar que archiva `.prettierignore` y puede cambiar qué archivos formatea Prettier. Conserva y consulta los backups; no los sobrescribas.
|
|
169
|
+
- Elige un solo preset: `--vue`, `--react` o `--node`. Vue/React se detectan desde las dependencias; Node requiere selección explícita. Si hay Vue y React, pide que se elija.
|
|
170
|
+
- No confundas `--strict` con el script `npm run lint`: solo cambia la política de warnings del hook lint-staged.
|
|
171
|
+
- Si el proyecto no usa npm, evita ejecutar `init`; configura sus dependencias con el gestor del proyecto y usa los exports de [Configuración manual](#configuración-manual).
|
|
172
|
+
|
|
173
|
+
## Desarrollo en este monorepo
|
|
174
|
+
|
|
175
|
+
```bash
|
|
176
|
+
npm run test -w @robosophy/lint
|
|
177
|
+
npm run build -w @robosophy/lint
|
|
178
|
+
```
|
package/bin/cli.mjs
ADDED
package/bin/lib.mjs
ADDED
|
@@ -0,0 +1,701 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { mkdir, readFile, readdir, rename, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { createInterface } from 'node:readline/promises';
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { dirname, join, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
9
|
+
const PACKAGE_JSON = JSON.parse(await readFile(join(PACKAGE_ROOT, 'package.json'), 'utf8'));
|
|
10
|
+
|
|
11
|
+
const FILES = {
|
|
12
|
+
eslintVue: `// Generated by @robosophy/lint. Local changes will be backed up by the installer.\nimport config from "@robosophy/lint/eslint/vue";\n\nexport default config;\n`,
|
|
13
|
+
eslintReact: `// Generated by @robosophy/lint. Local changes will be backed up by the installer.\nimport config from "@robosophy/lint/eslint/react";\n\nexport default config;\n`,
|
|
14
|
+
eslintNode: `// Generated by @robosophy/lint. Local changes will be backed up by the installer.\nimport config from "@robosophy/lint/eslint/node";\n\nexport default config;\n`,
|
|
15
|
+
prettier: `// Generated by @robosophy/lint. Local changes will be backed up by the installer.\nexport { default } from "@robosophy/lint/prettier";\n`,
|
|
16
|
+
lintStaged: `// Generated by @robosophy/lint. Local changes will be backed up by the installer.\nexport { default } from "@robosophy/lint/lint-staged";\n`,
|
|
17
|
+
lintStagedStrict: `// Generated by @robosophy/lint. Local changes will be backed up by the installer.\nexport { default } from "@robosophy/lint/lint-staged/strict";\n`,
|
|
18
|
+
preCommit: `npx lint-staged\n`,
|
|
19
|
+
};
|
|
20
|
+
const GENERATED_LINT_STAGED_CONFIGS = [FILES.lintStaged, FILES.lintStagedStrict];
|
|
21
|
+
const CLEAN_FIXED_TARGETS = ['.eslintignore', '.prettierignore'];
|
|
22
|
+
const USAGE =
|
|
23
|
+
'Uso: robosophy-lint init [--vue|--react|--node] [--strict] [--force] [--clean] [--dry-run] [--no-husky] [--yes] [--skip-install]';
|
|
24
|
+
|
|
25
|
+
const CONFIG_TARGETS = [
|
|
26
|
+
'eslint.config.js',
|
|
27
|
+
'eslint.config.mjs',
|
|
28
|
+
'eslint.config.cjs',
|
|
29
|
+
'eslint.config.ts',
|
|
30
|
+
'eslint.config.mts',
|
|
31
|
+
'eslint.config.cts',
|
|
32
|
+
'eslint.config.json',
|
|
33
|
+
'.eslintrc',
|
|
34
|
+
'.eslintrc.js',
|
|
35
|
+
'.eslintrc.cjs',
|
|
36
|
+
'.eslintrc.json',
|
|
37
|
+
'.eslintrc.yaml',
|
|
38
|
+
'.eslintrc.yml',
|
|
39
|
+
'.eslintrc.json5',
|
|
40
|
+
'.prettierrc',
|
|
41
|
+
'.prettierrc.json',
|
|
42
|
+
'.prettierrc.json5',
|
|
43
|
+
'.prettierrc.yaml',
|
|
44
|
+
'.prettierrc.yml',
|
|
45
|
+
'.prettierrc.toml',
|
|
46
|
+
'.prettierrc.js',
|
|
47
|
+
'.prettierrc.cjs',
|
|
48
|
+
'.prettierrc.mjs',
|
|
49
|
+
'.prettierrc.mts',
|
|
50
|
+
'.prettierrc.cts',
|
|
51
|
+
'prettier.config.js',
|
|
52
|
+
'prettier.config.cjs',
|
|
53
|
+
'prettier.config.mjs',
|
|
54
|
+
'prettier.config.ts',
|
|
55
|
+
'lint-staged.config.js',
|
|
56
|
+
'lint-staged.config.cjs',
|
|
57
|
+
'lint-staged.config.mjs',
|
|
58
|
+
'lint-staged.config.ts',
|
|
59
|
+
'.lintstagedrc',
|
|
60
|
+
'.lintstagedrc.json',
|
|
61
|
+
'.lintstagedrc.json5',
|
|
62
|
+
'.lintstagedrc.yaml',
|
|
63
|
+
'.lintstagedrc.yml',
|
|
64
|
+
'.lintstagedrc.js',
|
|
65
|
+
'.lintstagedrc.cjs',
|
|
66
|
+
'.lintstagedrc.mjs',
|
|
67
|
+
];
|
|
68
|
+
|
|
69
|
+
export function parseArgs(args) {
|
|
70
|
+
const options = {
|
|
71
|
+
framework: undefined,
|
|
72
|
+
strict: false,
|
|
73
|
+
force: false,
|
|
74
|
+
clean: false,
|
|
75
|
+
dryRun: false,
|
|
76
|
+
noHusky: false,
|
|
77
|
+
doctor: false,
|
|
78
|
+
yes: false,
|
|
79
|
+
skipInstall: false,
|
|
80
|
+
help: false,
|
|
81
|
+
};
|
|
82
|
+
const positional = [];
|
|
83
|
+
|
|
84
|
+
const frameworks = new Set();
|
|
85
|
+
for (const arg of args) {
|
|
86
|
+
if (arg === '--vue') frameworks.add('vue');
|
|
87
|
+
else if (arg === '--react') frameworks.add('react');
|
|
88
|
+
else if (arg === '--node') frameworks.add('node');
|
|
89
|
+
else if (arg === '--strict') options.strict = true;
|
|
90
|
+
else if (arg === '--force') options.force = true;
|
|
91
|
+
else if (arg === '--clean') options.clean = true;
|
|
92
|
+
else if (arg === '--dry-run') options.dryRun = true;
|
|
93
|
+
else if (arg === '--no-husky') options.noHusky = true;
|
|
94
|
+
else if (arg === '--doctor') options.doctor = true;
|
|
95
|
+
else if (arg === '--yes' || arg === '-y') options.yes = true;
|
|
96
|
+
else if (arg === '--help' || arg === '-h') options.help = true;
|
|
97
|
+
else if (arg === '--skip-install') options.skipInstall = true;
|
|
98
|
+
else if (arg.startsWith('--')) throw new Error(`Opción desconocida: ${arg}`);
|
|
99
|
+
else positional.push(arg);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (options.help) return options;
|
|
103
|
+
if (frameworks.size > 1) throw new Error('Elegí un solo preset: --vue, --react o --node.');
|
|
104
|
+
options.framework = frameworks.values().next().value;
|
|
105
|
+
|
|
106
|
+
if (positional.length > 1) throw new Error(USAGE);
|
|
107
|
+
if (positional.length === 1 && !['init', 'doctor'].includes(positional[0])) {
|
|
108
|
+
throw new Error(`Comando desconocido: ${positional[0]}. ${USAGE}`);
|
|
109
|
+
}
|
|
110
|
+
if (positional[0] === 'doctor') options.doctor = true;
|
|
111
|
+
if (positional[0] === 'init' && options.doctor) {
|
|
112
|
+
throw new Error('Usá `doctor` o `init`, no ambos.');
|
|
113
|
+
}
|
|
114
|
+
if (
|
|
115
|
+
options.doctor &&
|
|
116
|
+
(options.framework ||
|
|
117
|
+
options.strict ||
|
|
118
|
+
options.force ||
|
|
119
|
+
options.clean ||
|
|
120
|
+
options.dryRun ||
|
|
121
|
+
options.noHusky)
|
|
122
|
+
) {
|
|
123
|
+
throw new Error('Las opciones de instalación no se pueden combinar con --doctor.');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return options;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function detectFramework(packageJson, explicitFramework) {
|
|
130
|
+
if (explicitFramework) return explicitFramework;
|
|
131
|
+
const dependencies = {
|
|
132
|
+
...packageJson.dependencies,
|
|
133
|
+
...packageJson.devDependencies,
|
|
134
|
+
...packageJson.peerDependencies,
|
|
135
|
+
};
|
|
136
|
+
const hasVue = Boolean(dependencies.vue);
|
|
137
|
+
const hasReact = Boolean(dependencies.react);
|
|
138
|
+
|
|
139
|
+
if (hasVue && hasReact) {
|
|
140
|
+
throw new Error('Se detectaron Vue y React. Indicá el framework con --vue o --react.');
|
|
141
|
+
}
|
|
142
|
+
if (hasVue) return 'vue';
|
|
143
|
+
if (hasReact) return 'react';
|
|
144
|
+
throw new Error('No pude detectar Vue o React en package.json. Indicá --vue o --react.');
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function getEslintTemplate(framework) {
|
|
148
|
+
if (framework === 'vue') return FILES.eslintVue;
|
|
149
|
+
if (framework === 'react') return FILES.eslintReact;
|
|
150
|
+
if (framework === 'node') return FILES.eslintNode;
|
|
151
|
+
throw new Error(`Preset no soportado: ${framework}`);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function backupPath(target) {
|
|
155
|
+
const first = `${target}.backup`;
|
|
156
|
+
if (!existsSync(first)) return first;
|
|
157
|
+
for (let index = 2; ; index += 1) {
|
|
158
|
+
const candidate = `${first}.${index}`;
|
|
159
|
+
if (!existsSync(candidate)) return candidate;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export async function backupFile(target) {
|
|
164
|
+
if (!existsSync(target)) return null;
|
|
165
|
+
const destination = backupPath(target);
|
|
166
|
+
await rename(target, destination);
|
|
167
|
+
return destination;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function writeConfig(target, content, backups, replaceWithoutBackup = []) {
|
|
171
|
+
if (existsSync(target)) {
|
|
172
|
+
const existing = await readFile(target, 'utf8');
|
|
173
|
+
if (existing === content) return;
|
|
174
|
+
if (!replaceWithoutBackup.includes(existing)) {
|
|
175
|
+
const backup = await backupFile(target);
|
|
176
|
+
backups.push(backup);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
await mkdir(dirname(target), { recursive: true });
|
|
180
|
+
await writeFile(target, content, 'utf8');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function getCleanCandidates(root) {
|
|
184
|
+
const entries = await readdir(root, { withFileTypes: true });
|
|
185
|
+
return entries
|
|
186
|
+
.filter((entry) => entry.isFile())
|
|
187
|
+
.map((entry) => entry.name)
|
|
188
|
+
.filter((name) => {
|
|
189
|
+
if (/\.backup(?:\.\d+)?$/.test(name)) return false;
|
|
190
|
+
return (
|
|
191
|
+
/^\.eslintrc(?:$|[.-])/.test(name) ||
|
|
192
|
+
/^\.prettierrc(?:$|[.-])/.test(name) ||
|
|
193
|
+
CLEAN_FIXED_TARGETS.includes(name)
|
|
194
|
+
);
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async function getBackupCandidates(
|
|
199
|
+
root,
|
|
200
|
+
framework,
|
|
201
|
+
strict = false,
|
|
202
|
+
{ clean = false, noHusky = false } = {},
|
|
203
|
+
) {
|
|
204
|
+
const expected = new Map([
|
|
205
|
+
['eslint.config.mjs', getEslintTemplate(framework)],
|
|
206
|
+
['prettier.config.mjs', FILES.prettier],
|
|
207
|
+
['lint-staged.config.mjs', strict ? FILES.lintStagedStrict : FILES.lintStaged],
|
|
208
|
+
[join('.husky', 'pre-commit'), FILES.preCommit],
|
|
209
|
+
]);
|
|
210
|
+
const candidates = [];
|
|
211
|
+
|
|
212
|
+
for (const name of CONFIG_TARGETS) {
|
|
213
|
+
const target = join(root, name);
|
|
214
|
+
if (!existsSync(target)) continue;
|
|
215
|
+
const content = await readFile(target, 'utf8');
|
|
216
|
+
if (name === 'lint-staged.config.mjs' && GENERATED_LINT_STAGED_CONFIGS.includes(content))
|
|
217
|
+
continue;
|
|
218
|
+
if (expected.get(name) === content) continue;
|
|
219
|
+
candidates.push(name);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const hook = join(root, '.husky', 'pre-commit');
|
|
223
|
+
if (!noHusky && existsSync(hook)) {
|
|
224
|
+
const content = await readFile(hook, 'utf8');
|
|
225
|
+
if (expected.get(join('.husky', 'pre-commit')) !== content)
|
|
226
|
+
candidates.push(join('.husky', 'pre-commit'));
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (clean) {
|
|
230
|
+
for (const name of await getCleanCandidates(root)) {
|
|
231
|
+
if (!candidates.includes(name)) candidates.push(name);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return candidates;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function backupExistingConfigs(root, backups, framework, strict, options) {
|
|
239
|
+
for (const name of await getBackupCandidates(root, framework, strict, options)) {
|
|
240
|
+
backups.push(await backupFile(join(root, name)));
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export function updatePackageJson(packageJson, { framework, noHusky = false } = {}) {
|
|
245
|
+
const updated = structuredClone(packageJson);
|
|
246
|
+
updated.devDependencies ??= {};
|
|
247
|
+
const setDependency = (name, version) => {
|
|
248
|
+
let found = false;
|
|
249
|
+
for (const section of ['dependencies', 'devDependencies', 'peerDependencies']) {
|
|
250
|
+
if (updated[section]?.[name] !== undefined) {
|
|
251
|
+
updated[section][name] = version;
|
|
252
|
+
found = true;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (!found) updated.devDependencies[name] = version;
|
|
256
|
+
};
|
|
257
|
+
setDependency('@robosophy/lint', `^${PACKAGE_JSON.version}`);
|
|
258
|
+
setDependency('eslint', '^10.0.0');
|
|
259
|
+
setDependency('prettier', '^3.0.0');
|
|
260
|
+
setDependency('lint-staged', '^16.0.0');
|
|
261
|
+
if (framework === 'vue')
|
|
262
|
+
setDependency('eslint-plugin-vue', PACKAGE_JSON.dependencies['eslint-plugin-vue']);
|
|
263
|
+
if (!noHusky) setDependency('husky', '^9.0.0');
|
|
264
|
+
updated.scripts ??= {};
|
|
265
|
+
|
|
266
|
+
if (!noHusky) {
|
|
267
|
+
const prepare = updated.scripts.prepare;
|
|
268
|
+
if (!prepare) updated.scripts.prepare = 'husky';
|
|
269
|
+
else if (!/(^|&&\s*)husky(?:\s|$)/.test(prepare))
|
|
270
|
+
updated.scripts.prepare = `${prepare} && husky`;
|
|
271
|
+
}
|
|
272
|
+
updated.scripts.lint ??= 'eslint .';
|
|
273
|
+
|
|
274
|
+
return updated;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function run(command, args, cwd) {
|
|
278
|
+
return new Promise((resolvePromise, reject) => {
|
|
279
|
+
const child = spawn(command, args, {
|
|
280
|
+
cwd,
|
|
281
|
+
stdio: 'inherit',
|
|
282
|
+
shell: process.platform === 'win32',
|
|
283
|
+
});
|
|
284
|
+
child.once('error', reject);
|
|
285
|
+
child.once('exit', (code) => {
|
|
286
|
+
if (code === 0) resolvePromise();
|
|
287
|
+
else reject(new Error(`${command} terminó con código ${code ?? 'desconocido'}.`));
|
|
288
|
+
});
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export async function createInstallPlan(root, options = {}) {
|
|
293
|
+
const packageFile = join(root, 'package.json');
|
|
294
|
+
if (!existsSync(packageFile)) throw new Error(`No encontré package.json en ${root}.`);
|
|
295
|
+
|
|
296
|
+
const packageJson = JSON.parse(await readFile(packageFile, 'utf8'));
|
|
297
|
+
const framework = detectFramework(packageJson, options.framework);
|
|
298
|
+
const strict = Boolean(options.strict);
|
|
299
|
+
const noHusky = Boolean(options.noHusky);
|
|
300
|
+
const backupTargets = await getBackupCandidates(root, framework, strict, {
|
|
301
|
+
clean: Boolean(options.clean),
|
|
302
|
+
noHusky,
|
|
303
|
+
});
|
|
304
|
+
const files = [
|
|
305
|
+
{ path: 'eslint.config.mjs', content: getEslintTemplate(framework) },
|
|
306
|
+
{ path: 'prettier.config.mjs', content: FILES.prettier },
|
|
307
|
+
{
|
|
308
|
+
path: 'lint-staged.config.mjs',
|
|
309
|
+
content: strict ? FILES.lintStagedStrict : FILES.lintStaged,
|
|
310
|
+
replaceWithoutBackup: GENERATED_LINT_STAGED_CONFIGS,
|
|
311
|
+
},
|
|
312
|
+
];
|
|
313
|
+
if (!noHusky) files.push({ path: join('.husky', 'pre-commit'), content: FILES.preCommit });
|
|
314
|
+
|
|
315
|
+
const installArgs = [
|
|
316
|
+
'install',
|
|
317
|
+
'--save-dev',
|
|
318
|
+
'@robosophy/lint@latest',
|
|
319
|
+
'eslint@^10.0.0',
|
|
320
|
+
'prettier@^3.0.0',
|
|
321
|
+
'lint-staged@^16.0.0',
|
|
322
|
+
];
|
|
323
|
+
if (framework === 'vue') {
|
|
324
|
+
installArgs.push(`eslint-plugin-vue@${PACKAGE_JSON.dependencies['eslint-plugin-vue']}`);
|
|
325
|
+
}
|
|
326
|
+
if (!noHusky) installArgs.push('husky@^9.0.0');
|
|
327
|
+
|
|
328
|
+
return {
|
|
329
|
+
root,
|
|
330
|
+
framework,
|
|
331
|
+
strict,
|
|
332
|
+
noHusky,
|
|
333
|
+
clean: Boolean(options.clean),
|
|
334
|
+
packageJson,
|
|
335
|
+
packageUpdated: updatePackageJson(packageJson, { framework, noHusky }),
|
|
336
|
+
backupTargets,
|
|
337
|
+
files,
|
|
338
|
+
installArgs,
|
|
339
|
+
skipInstall: Boolean(options.skipInstall),
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function packageJsonChanged(before, after) {
|
|
344
|
+
return JSON.stringify(before) !== JSON.stringify(after);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export async function printDryRun(plan) {
|
|
348
|
+
const frameworkName = { vue: 'Vue', react: 'React', node: 'Node.js' }[plan.framework];
|
|
349
|
+
console.log(
|
|
350
|
+
`Dry run — preset ${frameworkName}${plan.strict ? ', modo strict' : ', modo legacy'}`,
|
|
351
|
+
);
|
|
352
|
+
if (plan.noHusky)
|
|
353
|
+
console.log(
|
|
354
|
+
'No se instalará ni inicializará Husky; se dejará cualquier hook existente intacto.',
|
|
355
|
+
);
|
|
356
|
+
if (!plan.skipInstall) console.log(`Dependencias: npm ${plan.installArgs.join(' ')}`);
|
|
357
|
+
|
|
358
|
+
const backupSet = new Set(plan.backupTargets);
|
|
359
|
+
for (const target of plan.backupTargets) {
|
|
360
|
+
console.log(`RESPALDAR ${target} -> ${backupPath(join(plan.root, target))}`);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
for (const file of plan.files) {
|
|
364
|
+
const target = join(plan.root, file.path);
|
|
365
|
+
if (!existsSync(target)) {
|
|
366
|
+
console.log(`CREAR ${file.path}`);
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
const existing = await readFile(target, 'utf8');
|
|
370
|
+
if (existing === file.content) {
|
|
371
|
+
console.log(`SIN CAMBIOS ${file.path}`);
|
|
372
|
+
} else if (backupSet.has(file.path)) {
|
|
373
|
+
console.log(`REEMPLAZAR ${file.path} (con backup)`);
|
|
374
|
+
} else if (file.replaceWithoutBackup?.includes(existing)) {
|
|
375
|
+
console.log(`ACTUALIZAR wrapper generado ${file.path}`);
|
|
376
|
+
} else {
|
|
377
|
+
console.log(`REEMPLAZAR ${file.path}`);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
if (plan.clean) {
|
|
382
|
+
console.log(
|
|
383
|
+
'Los archivos legacy indicados por --clean se archivarán como .backup; no se borrarán definitivamente.',
|
|
384
|
+
);
|
|
385
|
+
if (plan.backupTargets.includes('.prettierignore')) {
|
|
386
|
+
console.log(
|
|
387
|
+
'AVISO: .prettierignore sigue siendo válido; al archivarlo dejará de excluir esos archivos de Prettier.',
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
if (plan.backupTargets.includes('.eslintignore')) {
|
|
391
|
+
console.log(
|
|
392
|
+
'AVISO: revisa .eslintignore.backup y migra sus patrones personalizados al flat config si los necesitas.',
|
|
393
|
+
);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (packageJsonChanged(plan.packageJson, plan.packageUpdated)) {
|
|
398
|
+
console.log('package.json quedaría así:');
|
|
399
|
+
console.log(JSON.stringify(plan.packageUpdated, null, 2));
|
|
400
|
+
} else {
|
|
401
|
+
console.log('package.json: sin cambios.');
|
|
402
|
+
}
|
|
403
|
+
console.log('Dry run terminado: no se modificaron archivos ni se instalaron dependencias.');
|
|
404
|
+
return plan;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
async function confirmInstall(plan, options) {
|
|
408
|
+
const frameworkName = { vue: 'Vue', react: 'React', node: 'Node.js' }[plan.framework];
|
|
409
|
+
console.log(`Preset detectado/seleccionado: ${frameworkName}`);
|
|
410
|
+
console.log(
|
|
411
|
+
plan.strict
|
|
412
|
+
? 'Modo strict: los warnings de ESLint también bloquearán el commit.'
|
|
413
|
+
: 'Modo legacy: los warnings de ESLint no bloquearán el commit.',
|
|
414
|
+
);
|
|
415
|
+
if (plan.noHusky) console.log('Husky omitido (--no-husky).');
|
|
416
|
+
else console.log('Se configurará Husky y el hook .husky/pre-commit.');
|
|
417
|
+
console.log('Se instalarán/actualizarán @robosophy/lint, ESLint, Prettier y lint-staged.');
|
|
418
|
+
if (plan.framework === 'vue') {
|
|
419
|
+
console.log('El preset Vue también actualizará eslint-plugin-vue a una versión compatible.');
|
|
420
|
+
}
|
|
421
|
+
if (plan.backupTargets.length) {
|
|
422
|
+
console.log('Se respaldarán los archivos existentes antes de reemplazarlos:');
|
|
423
|
+
for (const target of plan.backupTargets) console.log(` - ${target}`);
|
|
424
|
+
}
|
|
425
|
+
if (options.yes || options.force) return;
|
|
426
|
+
if (!process.stdin.isTTY)
|
|
427
|
+
throw new Error(
|
|
428
|
+
'Usá --yes o --force para confirmar la instalación en un entorno no interactivo.',
|
|
429
|
+
);
|
|
430
|
+
|
|
431
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
432
|
+
try {
|
|
433
|
+
const answer = await prompt.question('¿Continuar? [s/N] ');
|
|
434
|
+
if (!/^s(i)?$/i.test(answer.trim())) throw new Error('Instalación cancelada.');
|
|
435
|
+
} finally {
|
|
436
|
+
prompt.close();
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
export async function initProject(root, options = {}) {
|
|
441
|
+
const plan = await createInstallPlan(resolve(root), options);
|
|
442
|
+
if (options.dryRun) return printDryRun(plan);
|
|
443
|
+
|
|
444
|
+
await confirmInstall(plan, options);
|
|
445
|
+
if (!plan.skipInstall) await run('npm', plan.installArgs, plan.root);
|
|
446
|
+
|
|
447
|
+
const backups = [];
|
|
448
|
+
await backupExistingConfigs(plan.root, backups, plan.framework, plan.strict, {
|
|
449
|
+
clean: plan.clean,
|
|
450
|
+
noHusky: plan.noHusky,
|
|
451
|
+
});
|
|
452
|
+
for (const file of plan.files) {
|
|
453
|
+
await writeConfig(join(plan.root, file.path), file.content, backups, file.replaceWithoutBackup);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const packageFile = join(plan.root, 'package.json');
|
|
457
|
+
const currentPackage = JSON.parse(await readFile(packageFile, 'utf8'));
|
|
458
|
+
const packageUpdated = updatePackageJson(currentPackage, {
|
|
459
|
+
framework: plan.framework,
|
|
460
|
+
noHusky: plan.noHusky,
|
|
461
|
+
});
|
|
462
|
+
await writeFile(packageFile, `${JSON.stringify(packageUpdated, null, 2)}\n`, 'utf8');
|
|
463
|
+
|
|
464
|
+
if (!plan.noHusky && !plan.skipInstall && existsSync(join(plan.root, '.git'))) {
|
|
465
|
+
await run('npm', ['exec', '--', 'husky'], plan.root);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
console.log('Configuración instalada correctamente.');
|
|
469
|
+
if (backups.length) {
|
|
470
|
+
console.log('Archivos respaldados:');
|
|
471
|
+
for (const backup of backups) console.log(` - ${backup}`);
|
|
472
|
+
}
|
|
473
|
+
if (plan.clean && backups.some((backup) => backup.endsWith('.eslintignore.backup'))) {
|
|
474
|
+
console.warn(
|
|
475
|
+
'Revisa los patrones de .eslintignore.backup y migra los que necesites a eslint.config.mjs.',
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
if (plan.clean && backups.some((backup) => backup.endsWith('.prettierignore.backup'))) {
|
|
479
|
+
console.warn(
|
|
480
|
+
'.prettierignore sigue siendo válido; sus exclusiones ya no se aplicarán tras --clean.',
|
|
481
|
+
);
|
|
482
|
+
}
|
|
483
|
+
console.log('Podés ejecutar `npm run lint` para validar el proyecto.');
|
|
484
|
+
return { framework: plan.framework, strict: plan.strict, noHusky: plan.noHusky, backups };
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function capture(command, args, cwd, timeoutMs = 10000) {
|
|
488
|
+
return new Promise((resolvePromise) => {
|
|
489
|
+
const child = spawn(command, args, {
|
|
490
|
+
cwd,
|
|
491
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
492
|
+
shell: process.platform === 'win32',
|
|
493
|
+
});
|
|
494
|
+
let stdout = '';
|
|
495
|
+
let stderr = '';
|
|
496
|
+
const timeout = setTimeout(() => child.kill(), timeoutMs);
|
|
497
|
+
child.stdout?.on('data', (chunk) => (stdout += chunk));
|
|
498
|
+
child.stderr?.on('data', (chunk) => (stderr += chunk));
|
|
499
|
+
child.once('error', (error) => {
|
|
500
|
+
clearTimeout(timeout);
|
|
501
|
+
resolvePromise({ code: null, stdout, stderr: `${stderr}${error.message}` });
|
|
502
|
+
});
|
|
503
|
+
child.once('exit', (code) => {
|
|
504
|
+
clearTimeout(timeout);
|
|
505
|
+
resolvePromise({ code, stdout, stderr });
|
|
506
|
+
});
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function compareVersions(left, right) {
|
|
511
|
+
const parse = (version) => {
|
|
512
|
+
const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(version ?? '');
|
|
513
|
+
return match ? match.slice(1).map(Number) : null;
|
|
514
|
+
};
|
|
515
|
+
const a = parse(left);
|
|
516
|
+
const b = parse(right);
|
|
517
|
+
if (!a || !b) return null;
|
|
518
|
+
for (let index = 0; index < 3; index += 1) {
|
|
519
|
+
if (a[index] !== b[index]) return a[index] < b[index] ? -1 : 1;
|
|
520
|
+
}
|
|
521
|
+
return 0;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function findLocalBinary(root, name) {
|
|
525
|
+
let current = root;
|
|
526
|
+
while (true) {
|
|
527
|
+
const suffix = process.platform === 'win32' ? '.cmd' : '';
|
|
528
|
+
const candidate = join(current, 'node_modules', '.bin', `${name}${suffix}`);
|
|
529
|
+
if (existsSync(candidate)) return candidate;
|
|
530
|
+
const parent = dirname(current);
|
|
531
|
+
if (parent === current) return null;
|
|
532
|
+
current = parent;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function isExecutable(mode) {
|
|
537
|
+
return (mode & 0o111) !== 0;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
export async function doctorProject(root, { checkRegistry = true, checkCommands = true } = {}) {
|
|
541
|
+
const checks = [];
|
|
542
|
+
const add = (status, title, detail = '') => checks.push({ status, title, detail });
|
|
543
|
+
const packageFile = join(root, 'package.json');
|
|
544
|
+
if (!existsSync(packageFile)) {
|
|
545
|
+
add('error', 'package.json', 'No se encontró package.json en este directorio.');
|
|
546
|
+
console.log('[ERROR] package.json — No se encontró en este directorio.');
|
|
547
|
+
return { checks, exitCode: 1 };
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
const packageJson = JSON.parse(await readFile(packageFile, 'utf8'));
|
|
551
|
+
const declared = {
|
|
552
|
+
...packageJson.dependencies,
|
|
553
|
+
...packageJson.devDependencies,
|
|
554
|
+
...packageJson.peerDependencies,
|
|
555
|
+
}['@robosophy/lint'];
|
|
556
|
+
if (declared) add('ok', '@robosophy/lint declarado', declared);
|
|
557
|
+
else add('warn', '@robosophy/lint declarado', 'No aparece en dependencies/devDependencies.');
|
|
558
|
+
|
|
559
|
+
const installedResult = await capture(
|
|
560
|
+
'npm',
|
|
561
|
+
['ls', '@robosophy/lint', '--depth=0', '--json'],
|
|
562
|
+
root,
|
|
563
|
+
);
|
|
564
|
+
let installedVersion;
|
|
565
|
+
try {
|
|
566
|
+
installedVersion = JSON.parse(installedResult.stdout).dependencies?.['@robosophy/lint']
|
|
567
|
+
?.version;
|
|
568
|
+
} catch {
|
|
569
|
+
installedVersion = undefined;
|
|
570
|
+
}
|
|
571
|
+
if (installedVersion) add('ok', '@robosophy/lint instalado', installedVersion);
|
|
572
|
+
else add('warn', '@robosophy/lint instalado', 'npm ls no pudo resolver la dependencia.');
|
|
573
|
+
|
|
574
|
+
if (checkRegistry) {
|
|
575
|
+
const latestResult = await capture(
|
|
576
|
+
'npm',
|
|
577
|
+
['view', '@robosophy/lint', 'version', '--json'],
|
|
578
|
+
root,
|
|
579
|
+
);
|
|
580
|
+
if (latestResult.code === 0 && installedVersion) {
|
|
581
|
+
const latestVersion = latestResult.stdout.trim().replace(/^"|"$/g, '');
|
|
582
|
+
const comparison = compareVersions(installedVersion, latestVersion);
|
|
583
|
+
if (comparison === 0) add('ok', 'Versión actualizada', `v${installedVersion}`);
|
|
584
|
+
else if (comparison < 0)
|
|
585
|
+
add(
|
|
586
|
+
'warn',
|
|
587
|
+
'Paquete desactualizado',
|
|
588
|
+
`instalada v${installedVersion}; latest v${latestVersion}`,
|
|
589
|
+
);
|
|
590
|
+
else
|
|
591
|
+
add(
|
|
592
|
+
'ok',
|
|
593
|
+
'Versión instalada',
|
|
594
|
+
`v${installedVersion} (posterior a latest v${latestVersion})`,
|
|
595
|
+
);
|
|
596
|
+
} else {
|
|
597
|
+
add(
|
|
598
|
+
'warn',
|
|
599
|
+
'Versión latest',
|
|
600
|
+
'No se pudo consultar el registry; verifica conexión/permisos.',
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
const entries = await readdir(root, { withFileTypes: true });
|
|
606
|
+
const legacyFiles = entries
|
|
607
|
+
.filter((entry) => entry.isFile())
|
|
608
|
+
.map((entry) => entry.name)
|
|
609
|
+
.filter((name) => !/\.backup(?:\.\d+)?$/.test(name));
|
|
610
|
+
const conflicts = legacyFiles.filter(
|
|
611
|
+
(name) => /^\.eslintrc(?:$|[.-])/.test(name) || /^\.prettierrc(?:$|[.-])/.test(name),
|
|
612
|
+
);
|
|
613
|
+
if (conflicts.length) add('warn', 'Configuraciones legacy', conflicts.join(', '));
|
|
614
|
+
else add('ok', 'Configuraciones legacy', 'No se encontraron .eslintrc ni .prettierrc activos.');
|
|
615
|
+
if (legacyFiles.includes('.eslintignore'))
|
|
616
|
+
add(
|
|
617
|
+
'warn',
|
|
618
|
+
'.eslintignore',
|
|
619
|
+
'ESLint Flat Config no lo consume; migra los patrones a eslint.config.mjs.',
|
|
620
|
+
);
|
|
621
|
+
if (legacyFiles.includes('.prettierignore'))
|
|
622
|
+
add(
|
|
623
|
+
'info',
|
|
624
|
+
'.prettierignore',
|
|
625
|
+
'Sigue siendo válido para Prettier; no es un conflicto por sí mismo.',
|
|
626
|
+
);
|
|
627
|
+
|
|
628
|
+
for (const file of ['eslint.config.mjs', 'prettier.config.mjs', 'lint-staged.config.mjs']) {
|
|
629
|
+
if (existsSync(join(root, file))) add('ok', file, 'presente');
|
|
630
|
+
else add('warn', file, 'no encontrado');
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
if (checkCommands) {
|
|
634
|
+
const lintStagedBinary = findLocalBinary(root, 'lint-staged');
|
|
635
|
+
if (!lintStagedBinary) add('error', 'lint-staged', 'No se encontró el ejecutable local.');
|
|
636
|
+
else {
|
|
637
|
+
const result = await capture(lintStagedBinary, ['--version'], root);
|
|
638
|
+
if (result.code === 0) add('ok', 'lint-staged responde', result.stdout.trim());
|
|
639
|
+
else add('error', 'lint-staged responde', result.stderr.trim() || `código ${result.code}`);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
const hook = join(root, '.husky', 'pre-commit');
|
|
644
|
+
if (existsSync(hook)) {
|
|
645
|
+
const contents = await readFile(hook, 'utf8');
|
|
646
|
+
if (/lint-staged/.test(contents)) add('ok', 'Hook pre-commit', 'invoca lint-staged');
|
|
647
|
+
else add('warn', 'Hook pre-commit', 'existe, pero no parece invocar lint-staged.');
|
|
648
|
+
} else add('info', 'Hook pre-commit', 'no existe; puede ser intencional con --no-husky.');
|
|
649
|
+
|
|
650
|
+
if (checkCommands) {
|
|
651
|
+
const gitResult = await capture('git', ['-C', root, 'rev-parse', '--git-dir'], root);
|
|
652
|
+
if (gitResult.code !== 0)
|
|
653
|
+
add('info', 'Git hooks', 'el directorio no parece ser un repositorio Git.');
|
|
654
|
+
else {
|
|
655
|
+
const hooksResult = await capture(
|
|
656
|
+
'git',
|
|
657
|
+
['-C', root, 'config', '--get', 'core.hooksPath'],
|
|
658
|
+
root,
|
|
659
|
+
);
|
|
660
|
+
const hooksPath = hooksResult.code === 0 ? hooksResult.stdout.trim() : '.git/hooks';
|
|
661
|
+
const runnerPath = resolve(root, hooksPath, 'pre-commit');
|
|
662
|
+
if (existsSync(runnerPath)) {
|
|
663
|
+
if (process.platform === 'win32')
|
|
664
|
+
add('ok', 'Runner de Husky', 'presente (permisos no aplican en Windows).');
|
|
665
|
+
else {
|
|
666
|
+
const runnerStat = await stat(runnerPath);
|
|
667
|
+
if (isExecutable(runnerStat.mode))
|
|
668
|
+
add('ok', 'Runner de Husky', `${hooksPath}/pre-commit es ejecutable.`);
|
|
669
|
+
else
|
|
670
|
+
add(
|
|
671
|
+
'warn',
|
|
672
|
+
'Runner de Husky',
|
|
673
|
+
`${hooksPath}/pre-commit no tiene permiso de ejecución; usa chmod +x.`,
|
|
674
|
+
);
|
|
675
|
+
}
|
|
676
|
+
} else add('warn', 'Runner de Husky', `no se encontró ${hooksPath}/pre-commit.`);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
for (const check of checks) {
|
|
681
|
+
const label = check.status.toUpperCase();
|
|
682
|
+
console.log(`[${label}] ${check.title}${check.detail ? ` — ${check.detail}` : ''}`);
|
|
683
|
+
}
|
|
684
|
+
return { checks, exitCode: checks.some((check) => check.status === 'error') ? 1 : 0 };
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
export async function main(args = process.argv.slice(2), cwd = process.cwd()) {
|
|
688
|
+
const options = parseArgs(args);
|
|
689
|
+
if (options.help) {
|
|
690
|
+
console.log(USAGE);
|
|
691
|
+
console.log(' robosophy-lint doctor | robosophy-lint --doctor');
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
const root = resolve(cwd);
|
|
695
|
+
if (options.doctor) {
|
|
696
|
+
const result = await doctorProject(root);
|
|
697
|
+
process.exitCode = result.exitCode;
|
|
698
|
+
return result;
|
|
699
|
+
}
|
|
700
|
+
return initProject(root, options);
|
|
701
|
+
}
|
package/eslint/base.mjs
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import js from '@eslint/js';
|
|
2
|
+
import globals from 'globals';
|
|
3
|
+
import simpleImportSort from 'eslint-plugin-simple-import-sort';
|
|
4
|
+
import tseslint from 'typescript-eslint';
|
|
5
|
+
|
|
6
|
+
export default [
|
|
7
|
+
{
|
|
8
|
+
ignores: [
|
|
9
|
+
'**/node_modules/**',
|
|
10
|
+
'**/dist/**',
|
|
11
|
+
'**/build/**',
|
|
12
|
+
'**/coverage/**',
|
|
13
|
+
'**/.vite/**',
|
|
14
|
+
'**/.husky/**',
|
|
15
|
+
'**/*.min.js',
|
|
16
|
+
],
|
|
17
|
+
},
|
|
18
|
+
js.configs.recommended,
|
|
19
|
+
...tseslint.configs.recommended,
|
|
20
|
+
{
|
|
21
|
+
files: [
|
|
22
|
+
'**/vite.config.{js,mjs,cjs,ts,mts,cts}',
|
|
23
|
+
'**/*.config.{js,mjs,cjs,ts,mts,cts}',
|
|
24
|
+
'**/*.cjs',
|
|
25
|
+
],
|
|
26
|
+
languageOptions: {
|
|
27
|
+
globals: globals.node,
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
plugins: {
|
|
32
|
+
'simple-import-sort': simpleImportSort,
|
|
33
|
+
},
|
|
34
|
+
rules: {
|
|
35
|
+
'simple-import-sort/imports': [
|
|
36
|
+
'error',
|
|
37
|
+
{
|
|
38
|
+
groups: [
|
|
39
|
+
['^vue', '^react', '^@?\\w'],
|
|
40
|
+
['^(@|~)/'],
|
|
41
|
+
['^\\.\\.(?!/?$)', '^\\.\\./?$', '^\\./(?=.*/)(?!/?$)', '^\\.(?!/?$)', '^\\./?$'],
|
|
42
|
+
['^.+\\.s?css$'],
|
|
43
|
+
],
|
|
44
|
+
},
|
|
45
|
+
],
|
|
46
|
+
'simple-import-sort/exports': 'error',
|
|
47
|
+
eqeqeq: ['error', 'always', { null: 'ignore' }],
|
|
48
|
+
'prefer-const': 'error',
|
|
49
|
+
'no-var': 'error',
|
|
50
|
+
'no-debugger': 'error',
|
|
51
|
+
'no-console': ['warn', { allow: ['warn', 'error'] }],
|
|
52
|
+
'no-unused-vars': [
|
|
53
|
+
'error',
|
|
54
|
+
{
|
|
55
|
+
argsIgnorePattern: '^_',
|
|
56
|
+
varsIgnorePattern: '^_',
|
|
57
|
+
caughtErrorsIgnorePattern: '^_',
|
|
58
|
+
},
|
|
59
|
+
],
|
|
60
|
+
'@typescript-eslint/consistent-type-imports': [
|
|
61
|
+
'error',
|
|
62
|
+
{ prefer: 'type-imports', fixStyle: 'inline-type-imports' },
|
|
63
|
+
],
|
|
64
|
+
'@typescript-eslint/no-unused-vars': [
|
|
65
|
+
'error',
|
|
66
|
+
{
|
|
67
|
+
argsIgnorePattern: '^_',
|
|
68
|
+
varsIgnorePattern: '^_',
|
|
69
|
+
caughtErrorsIgnorePattern: '^_',
|
|
70
|
+
},
|
|
71
|
+
],
|
|
72
|
+
'@typescript-eslint/no-explicit-any': 'warn',
|
|
73
|
+
'@typescript-eslint/ban-ts-comment': 'warn',
|
|
74
|
+
'@typescript-eslint/no-empty-object-type': 'warn',
|
|
75
|
+
'@typescript-eslint/no-unused-expressions': 'warn',
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
files: ['**/*.{ts,tsx,mts,cts,vue}'],
|
|
80
|
+
rules: {
|
|
81
|
+
'no-unused-vars': 'off',
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
files: ['**/*.{js,jsx,cjs,mjs}'],
|
|
86
|
+
rules: {
|
|
87
|
+
'@typescript-eslint/no-require-imports': 'off',
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
];
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import globals from 'globals';
|
|
2
|
+
|
|
3
|
+
export default [
|
|
4
|
+
{
|
|
5
|
+
files: ['**/*.{js,mjs,jsx,ts,tsx,vue}'],
|
|
6
|
+
ignores: ['**/*.config.{js,mjs,ts,mts,cts}', '**/vite.config.{js,mjs,ts,mts,cts}'],
|
|
7
|
+
languageOptions: {
|
|
8
|
+
ecmaVersion: 'latest',
|
|
9
|
+
sourceType: 'module',
|
|
10
|
+
globals: globals.browser,
|
|
11
|
+
},
|
|
12
|
+
},
|
|
13
|
+
];
|
package/eslint/node.mjs
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import prettier from 'eslint-config-prettier';
|
|
2
|
+
import globals from 'globals';
|
|
3
|
+
|
|
4
|
+
import base from './base.mjs';
|
|
5
|
+
|
|
6
|
+
export default [
|
|
7
|
+
...base,
|
|
8
|
+
{
|
|
9
|
+
files: ['**/*.{js,mjs,jsx,ts,tsx}'],
|
|
10
|
+
ignores: ['**/*.config.{js,mjs,ts,mts,cts}', '**/vite.config.{js,mjs,ts,mts,cts}'],
|
|
11
|
+
languageOptions: {
|
|
12
|
+
ecmaVersion: 'latest',
|
|
13
|
+
sourceType: 'module',
|
|
14
|
+
globals: globals.node,
|
|
15
|
+
},
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
files: ['**/*.cjs'],
|
|
19
|
+
languageOptions: {
|
|
20
|
+
globals: globals.node,
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
prettier,
|
|
24
|
+
];
|
package/eslint/react.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import prettier from 'eslint-config-prettier';
|
|
2
|
+
import reactHooks from 'eslint-plugin-react-hooks';
|
|
3
|
+
import reactRefresh from 'eslint-plugin-react-refresh';
|
|
4
|
+
|
|
5
|
+
import base from './base.mjs';
|
|
6
|
+
import browser from './browser.mjs';
|
|
7
|
+
|
|
8
|
+
export default [
|
|
9
|
+
...base,
|
|
10
|
+
...browser,
|
|
11
|
+
{
|
|
12
|
+
files: ['**/*.{jsx,tsx}'],
|
|
13
|
+
plugins: {
|
|
14
|
+
'react-hooks': reactHooks,
|
|
15
|
+
'react-refresh': reactRefresh,
|
|
16
|
+
},
|
|
17
|
+
settings: {
|
|
18
|
+
react: {
|
|
19
|
+
version: 'detect',
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
rules: {
|
|
23
|
+
...reactHooks.configs.recommended.rules,
|
|
24
|
+
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
|
|
25
|
+
'react-hooks/rules-of-hooks': 'error',
|
|
26
|
+
'react-hooks/exhaustive-deps': 'warn',
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
prettier,
|
|
30
|
+
];
|
package/eslint/vue.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import prettier from 'eslint-config-prettier';
|
|
2
|
+
import pluginVue from 'eslint-plugin-vue';
|
|
3
|
+
import tseslint from 'typescript-eslint';
|
|
4
|
+
|
|
5
|
+
import base from './base.mjs';
|
|
6
|
+
import browser from './browser.mjs';
|
|
7
|
+
|
|
8
|
+
export default [
|
|
9
|
+
...base,
|
|
10
|
+
...browser,
|
|
11
|
+
...pluginVue.configs['flat/recommended'],
|
|
12
|
+
{
|
|
13
|
+
files: ['**/*.vue'],
|
|
14
|
+
languageOptions: {
|
|
15
|
+
parserOptions: {
|
|
16
|
+
parser: tseslint.parser,
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
rules: {
|
|
20
|
+
'vue/multi-word-component-names': 'off',
|
|
21
|
+
'vue/require-default-prop': 'off',
|
|
22
|
+
'vue/no-mutating-props': 'error',
|
|
23
|
+
'vue/block-order': ['warn', { order: ['script', 'template', 'style'] }],
|
|
24
|
+
'vue/define-macros-order': ['warn', { order: ['defineProps', 'defineEmits'] }],
|
|
25
|
+
'vue/no-unused-refs': 'warn',
|
|
26
|
+
'vue/no-v-html': 'warn',
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
prettier,
|
|
30
|
+
];
|
package/package.json
CHANGED
|
@@ -1,6 +1,66 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@robosophy/lint",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"private": false,
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"description": "Configuraciones compartidas de ESLint, Prettier y lint-staged con presets Vue, React y Node.js, más un instalador opcional para Husky.",
|
|
8
|
+
"homepage": "https://robosophy.gitlab.io/robosophy-basf/robosophy-library/",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+ssh://git@gitlab.com/robosophy/robosophy-basf/robosophy-library.git"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://gitlab.com/robosophy/robosophy-basf/robosophy-library/-/issues"
|
|
15
|
+
},
|
|
16
|
+
"bin": {
|
|
17
|
+
"robosophy-lint": "bin/cli.mjs"
|
|
18
|
+
},
|
|
19
|
+
"exports": {
|
|
20
|
+
"./eslint/base": "./eslint/base.mjs",
|
|
21
|
+
"./eslint/vue": "./eslint/vue.mjs",
|
|
22
|
+
"./eslint/react": "./eslint/react.mjs",
|
|
23
|
+
"./eslint/node": "./eslint/node.mjs",
|
|
24
|
+
"./prettier": "./prettier.config.mjs",
|
|
25
|
+
"./lint-staged": "./lint-staged.config.mjs",
|
|
26
|
+
"./lint-staged/strict": "./lint-staged.strict.config.mjs"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"bin",
|
|
30
|
+
"eslint",
|
|
31
|
+
"prettier.config.mjs",
|
|
32
|
+
"lint-staged.config.mjs",
|
|
33
|
+
"lint-staged.strict.config.mjs",
|
|
34
|
+
"README.md",
|
|
35
|
+
"package.json"
|
|
36
|
+
],
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=20.19.0"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "node -e \"console.log('@robosophy/lint: nada que compilar')\"",
|
|
42
|
+
"test": "node --test test/*.test.mjs"
|
|
43
|
+
},
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"@eslint/js": "^10.0.1",
|
|
46
|
+
"eslint-config-prettier": "^10.1.8",
|
|
47
|
+
"eslint-plugin-react-hooks": "^7.1.1",
|
|
48
|
+
"eslint-plugin-react-refresh": "^0.5.8",
|
|
49
|
+
"eslint-plugin-simple-import-sort": "^14.0.0",
|
|
50
|
+
"eslint-plugin-vue": "^10.12.1",
|
|
51
|
+
"globals": "^17.14.0",
|
|
52
|
+
"prettier-plugin-tailwindcss": "^0.8.1",
|
|
53
|
+
"typescript-eslint": "^8.61.0"
|
|
54
|
+
},
|
|
55
|
+
"peerDependencies": {
|
|
56
|
+
"eslint": "^9.0.0 || ^10.0.0",
|
|
57
|
+
"husky": "^9.0.0",
|
|
58
|
+
"lint-staged": "^16.0.0",
|
|
59
|
+
"prettier": "^3.0.0"
|
|
60
|
+
},
|
|
61
|
+
"peerDependenciesMeta": {
|
|
62
|
+
"husky": {
|
|
63
|
+
"optional": true
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import * as tailwindPlugin from 'prettier-plugin-tailwindcss';
|
|
2
|
+
|
|
3
|
+
export default {
|
|
4
|
+
arrowParens: 'always',
|
|
5
|
+
endOfLine: 'lf',
|
|
6
|
+
printWidth: 100,
|
|
7
|
+
semi: true,
|
|
8
|
+
singleQuote: true,
|
|
9
|
+
tabWidth: 2,
|
|
10
|
+
trailingComma: 'all',
|
|
11
|
+
useTabs: false,
|
|
12
|
+
plugins: [tailwindPlugin],
|
|
13
|
+
tailwindFunctions: ['clsx', 'cn', 'cva'],
|
|
14
|
+
};
|