eslint-unstick 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@ Upgrade to **ESLint 10** even though `eslint-plugin-react`, `eslint-plugin-jsx-a
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/eslint-unstick)](https://www.npmjs.com/package/eslint-unstick)
6
6
  [![CI](https://github.com/Raj-json/eslint-unstick/actions/workflows/ci.yml/badge.svg)](https://github.com/Raj-json/eslint-unstick/actions/workflows/ci.yml)
7
- [![license](https://img.shields.io/npm/l/eslint-unstick)](https://github.com/Raj-json/eslint-unstick/blob/main/LICENSE)
7
+ [![license](https://img.shields.io/github/license/Raj-json/eslint-unstick)](https://github.com/Raj-json/eslint-unstick/blob/main/LICENSE)
8
8
 
9
9
  ![eslint-unstick checks a React project, upgrades it to ESLint 10, and shows the same 11 lint problems before and after](https://raw.githubusercontent.com/Raj-json/eslint-unstick/main/docs/demo.gif)
10
10
 
@@ -102,6 +102,7 @@ It adds a thin wrapper around each rule's `context`. On the test projects there
102
102
  ## Limits
103
103
 
104
104
  - **eslintrc configs:** ESLint 10 can't load `.eslintrc*` at all. The tool stops and points you to `npx @eslint/migrate-config`.
105
+ - **Configs that use `FlatCompat`** (eslintrc-style `extends` inside a flat config): the known case, `compat.extends("eslint:recommended")`, is detected up front with a one-line fix. Other FlatCompat setups can still fail on ESLint 10. If they do, the tool rolls everything back and shows the error.
105
106
  - **Monorepos:** only the root `package.json` is checked. Run it in each workspace that has its own ESLint setup.
106
107
  - **Yarn Plug'n'Play** isn't supported yet (the tool needs `node_modules`).
107
108
  - **Switching to forks** (`eslint-plugin-import-x`, `eslint-plugin-jsx-a11y-x`, `@eslint-react/eslint-plugin`) isn't automated. The doctor lists them as alternatives.
package/dist/cli.js CHANGED
@@ -2,10 +2,11 @@
2
2
  import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { join, resolve } from "node:path";
4
4
  import { diagnose } from "./doctor.js";
5
- import { crashSummary, install, runEslint } from "./exec.js";
5
+ import semver from "semver";
6
+ import { crashSummary, install, pruneNpmLockfile, runEslint } from "./exec.js";
6
7
  import { wrapConfig } from "./fix/config.js";
7
8
  import { editPackageJson } from "./fix/package-json.js";
8
- import { COMPAT_PKG, COMPAT_RANGE, isLegacyApiCrash } from "./knowledge.js";
9
+ import { COMPAT_PKG, COMPAT_RANGE, PROBE_VERSION, isLegacyApiCrash } from "./knowledge.js";
9
10
  import { loadProject } from "./project.js";
10
11
  import { compareRuns, isCoreRule } from "./proof.js";
11
12
  import { c, lineDiff, log, printFindings, step } from "./ui.js";
@@ -85,18 +86,24 @@ function snapshot(project) {
85
86
  const abs = join(project.root, p);
86
87
  files.set(abs, existsSync(abs) ? readFileSync(abs, "utf8") : null);
87
88
  }
88
- return { files, hadNodeModules: existsSync(join(project.root, "node_modules")) };
89
+ const hadLockfile = [...files].some(([abs, text]) => text !== null && /lock|shrinkwrap/.test(abs));
90
+ return { files, hadNodeModules: existsSync(join(project.root, "node_modules")), hadLockfile };
89
91
  }
90
92
  async function rollback(project, snap, why) {
91
93
  step(c.red(`Rolling back: ${why}`));
92
- for (const [abs, text] of snap.files) {
93
- if (text === null)
94
- rmSync(abs, { force: true });
95
- else
96
- writeFileSync(abs, text);
97
- }
94
+ const restore = () => {
95
+ for (const [abs, text] of snap.files) {
96
+ if (text === null)
97
+ rmSync(abs, { force: true });
98
+ else
99
+ writeFileSync(abs, text);
100
+ }
101
+ };
102
+ restore();
98
103
  if (snap.hadNodeModules) {
99
- const r = await install(project);
104
+ // Frozen install: rebuild node_modules from the restored lockfile without rewriting it.
105
+ const r = await install(project, { frozen: snap.hadLockfile });
106
+ restore();
100
107
  log(r.code === 0 ? " Restored files and reinstalled your previous dependencies." : c.red(` Files restored, but reinstall failed: run \`${project.pm} install\`.`));
101
108
  }
102
109
  else {
@@ -167,7 +174,17 @@ async function fix(project, report, args) {
167
174
  let after;
168
175
  for (;;) {
169
176
  step(`Installing with ${project.pm}`);
170
- const inst = await install(project);
177
+ let inst = await install(project);
178
+ // npm sometimes can't move several interlocked packages at once from the existing lockfile (ERESOLVE).
179
+ // Retry once after removing just the lockfile entries that pin them.
180
+ if (inst.code !== 0 && project.pm === "npm" && /ERESOLVE/.test(inst.stderr + inst.stdout)) {
181
+ const names = new Set(["eslint", ...Object.keys(plan.ranges), ...plan.overrides]);
182
+ const pruned = pruneNpmLockfile(project.root, names, (peer) => semver.satisfies(PROBE_VERSION, peer, { includePrerelease: true }));
183
+ if (pruned) {
184
+ log(c.yellow(` npm couldn't upgrade in place; re-resolving the ${pruned} lockfile entries that pin ESLint 9 and retrying`));
185
+ inst = await install(project);
186
+ }
187
+ }
171
188
  if (inst.code !== 0) {
172
189
  log(c.red(` Install failed:\n${tail(inst)}`));
173
190
  return rollback(project, snap, "install failed");
package/dist/doctor.js CHANGED
@@ -88,6 +88,13 @@ export async function diagnose(project) {
88
88
  configText = readFileSync(join(project.root, project.configFile), "utf8");
89
89
  findings.push({ level: "ok", title: `Flat config: ${project.configFile}` });
90
90
  }
91
+ if (/\bFlatCompat\b/.test(configText) && /["']eslint:recommended["']/.test(configText)) {
92
+ block('FlatCompat loads "eslint:recommended", which fails on ESLint 10', [
93
+ 'Error you would get: ESLint configuration in » eslint:recommended is invalid: Unexpected top-level property "name".',
94
+ "@eslint/js 10's recommended config has a `name` field that the eslintrc validator (even @eslint/eslintrc 3.3.7) rejects.",
95
+ 'Fix (one line): remove "eslint:recommended" from compat.extends(...) and add js.configs.recommended (from @eslint/js) to your config array instead. Then re-run eslint-unstick.',
96
+ ]);
97
+ }
91
98
  // --- plugins / configs with a peer range that excludes ESLint 10 --------
92
99
  const candidates = Object.keys(project.direct).filter((n) => !(n in BUMP_WITH_ESLINT));
93
100
  const statuses = (await Promise.all(candidates.map((n) => peerStatus(project, n)))).filter((s) => !!s);
@@ -146,6 +153,13 @@ export async function diagnose(project) {
146
153
  detail: [fine.map((s) => s.name).join(", ")],
147
154
  });
148
155
  }
156
+ const npmrc = join(project.root, ".npmrc");
157
+ if (project.pm === "npm" && existsSync(npmrc) && /^\s*legacy-peer-deps\s*=\s*true/m.test(readFileSync(npmrc, "utf8"))) {
158
+ findings.push({
159
+ level: "info",
160
+ title: "Your .npmrc sets legacy-peer-deps=true, which turns off peer checks for every package. With the overrides below you can remove it.",
161
+ });
162
+ }
149
163
  if (plan.overrides.length && project.pm === "npm") {
150
164
  findings.push({
151
165
  level: "info",
package/dist/exec.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
- import { mkdtempSync, readFileSync, rmSync } from "node:fs";
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { createRequire } from "node:module";
4
4
  import { tmpdir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
+ import { isYarnBerry } from "./project.js";
6
7
  export function run(cmd, args, cwd, env) {
7
8
  const started = Date.now();
8
9
  return new Promise((resolve) => {
@@ -36,16 +37,27 @@ export function pmCommand(project) {
36
37
  const spec = project.pmVersion ? `${project.pm}@${project.pmVersion}` : project.pm;
37
38
  return ["npx", ["-y", spec]];
38
39
  }
39
- export async function install(project) {
40
+ export async function install(project, opts = {}) {
40
41
  const [cmd, pre] = pmCommand(project);
41
- const args = {
42
- npm: ["install", "--no-audit", "--no-fund"],
43
- pnpm: ["install", "--no-frozen-lockfile", "--config.confirmModulesPurge=false"],
44
- yarn: ["install"],
45
- bun: ["install"],
46
- };
47
- // We change package.json on purpose, so a frozen/immutable lockfile (the CI default) must be off.
48
- return run(cmd, [...pre, ...args[project.pm]], project.root, { YARN_ENABLE_IMMUTABLE_INSTALLS: "false" });
42
+ let args;
43
+ if (opts.frozen) {
44
+ args = {
45
+ npm: ["ci", "--no-audit", "--no-fund"],
46
+ pnpm: ["install", "--frozen-lockfile"],
47
+ yarn: isYarnBerry(project) ? ["install", "--immutable"] : ["install", "--frozen-lockfile"],
48
+ bun: ["install", "--frozen-lockfile"],
49
+ }[project.pm];
50
+ }
51
+ else {
52
+ args = {
53
+ npm: ["install", "--no-audit", "--no-fund"],
54
+ pnpm: ["install", "--no-frozen-lockfile", "--config.confirmModulesPurge=false"],
55
+ yarn: ["install"],
56
+ bun: ["install"],
57
+ }[project.pm];
58
+ }
59
+ // We change package.json on purpose, so a frozen/immutable lockfile (the CI default) must be off unless asked for.
60
+ return run(cmd, [...pre, ...args], project.root, opts.frozen ? {} : { YARN_ENABLE_IMMUTABLE_INSTALLS: "false" });
49
61
  }
50
62
  /**
51
63
  * Published versions matching `range` with their peer deps, oldest first.
@@ -107,3 +119,37 @@ export async function runEslint(project) {
107
119
  rmSync(outDir, { recursive: true, force: true });
108
120
  }
109
121
  }
122
+ /**
123
+ * npm resolves an upgrade starting from the existing lockfile, and can hit ERESOLVE when several
124
+ * interlocked packages (eslint, @eslint/js, typescript-eslint, ...) all have to move at once.
125
+ * Remove only the lockfile entries that pin those packages: the ones being changed, and any whose
126
+ * eslint peer range excludes the target. npm then resolves just those again; everything else stays pinned.
127
+ * Returns how many entries were removed (0 if there is no v2/v3 npm lockfile).
128
+ */
129
+ export function pruneNpmLockfile(root, names, allowsTarget) {
130
+ const lockPath = join(root, "package-lock.json");
131
+ let text;
132
+ try {
133
+ text = readFileSync(lockPath, "utf8");
134
+ }
135
+ catch {
136
+ return 0;
137
+ }
138
+ const lock = JSON.parse(text);
139
+ if (!lock.packages)
140
+ return 0;
141
+ let removed = 0;
142
+ for (const [key, entry] of Object.entries(lock.packages)) {
143
+ if (!key)
144
+ continue; // root project
145
+ const name = key.split("node_modules/").pop();
146
+ const peer = entry.peerDependencies?.eslint;
147
+ if (names.has(name) || (peer && !allowsTarget(peer))) {
148
+ delete lock.packages[key];
149
+ removed++;
150
+ }
151
+ }
152
+ const indent = /^(\s+)"/m.exec(text)?.[1] ?? " ";
153
+ writeFileSync(lockPath, JSON.stringify(lock, null, indent) + "\n");
154
+ return removed;
155
+ }
@@ -1,4 +1,4 @@
1
- import { generateCode, parseModule } from "magicast";
1
+ import { parse } from "@babel/parser";
2
2
  export const WRAPPER = "fixupConfigRules";
3
3
  export const WRAPPER_PKG = "@eslint/compat";
4
4
  /**
@@ -10,49 +10,66 @@ export const WRAPPER_PKG = "@eslint/compat";
10
10
  * name. fixupConfigRules rewrites every config's `plugins` with a cached
11
11
  * wrapper, so identity stays consistent across all of them.
12
12
  *
13
+ * The AST is only used to find positions. Every change is a plain-text
14
+ * insertion into the original source, so indentation (tabs or spaces),
15
+ * comments and formatting elsewhere are untouched: the diff is exactly the
16
+ * wrapper plus one import line.
17
+ *
13
18
  * Handles `export default <expr>` and `module.exports = <expr>`, in JS or TS.
14
- * Formatting of untouched code is preserved (recast).
15
19
  */
16
20
  export function wrapConfig(source) {
17
- const mod = parseModule(source);
18
- const program = mod.$ast;
21
+ // Positions only: we never reprint code. `typescript` also covers plain JS configs.
22
+ const program = parse(source, { sourceType: "module", plugins: ["typescript"] }).program;
19
23
  const body = program.body;
20
- let target;
24
+ const offset = offsets(source);
25
+ let exported;
21
26
  let cjs = false;
22
27
  for (const stmt of body) {
23
28
  if (stmt.type === "ExportDefaultDeclaration" && isExpression(stmt.declaration)) {
24
- target = { holder: stmt, key: "declaration" };
29
+ exported = stmt.declaration;
25
30
  }
26
31
  else if (stmt.type === "ExpressionStatement" &&
27
32
  stmt.expression.type === "AssignmentExpression" &&
28
33
  isModuleExports(stmt.expression.left)) {
29
- target = { holder: stmt.expression, key: "right" };
34
+ exported = stmt.expression.right;
30
35
  cjs = true;
31
36
  }
32
37
  }
33
- if (!target) {
38
+ if (!exported) {
34
39
  return { changed: false, code: source, reason: "Could not find `export default …` or `module.exports = …` in the config." };
35
40
  }
36
- const exported = target.holder[target.key];
37
- if (unwrapTs(exported).type === "CallExpression" && unwrapTs(exported).callee?.name === WRAPPER) {
41
+ const inner = unwrapTs(exported);
42
+ if (inner.type === "CallExpression" && inner.callee?.name === WRAPPER) {
38
43
  return { changed: false, code: source, reason: `Config export is already wrapped in ${WRAPPER}().` };
39
44
  }
40
- target.holder[target.key] = {
41
- type: "CallExpression",
42
- callee: { type: "Identifier", name: WRAPPER },
43
- arguments: [exported],
44
- };
45
- // The new import/require is inserted as text, not spliced into the AST:
46
- // recast reprints neighbouring statements on splice (e.g. `"use strict";;`).
47
- const insert = cjs ? requireInsertion(program, source) : importInsertion(body);
48
- let code = generateCode(mod).code;
49
- if (source.endsWith("\n") && !code.endsWith("\n"))
50
- code += "\n";
51
- if (!insert)
52
- return { changed: true, code };
53
- const lines = code.split("\n");
54
- lines.splice(insert.afterLine, 0, insert.text);
55
- return { changed: true, code: lines.join("\n") };
45
+ const edits = [
46
+ { at: start(exported, offset), text: `${WRAPPER}(` },
47
+ { at: end(exported, offset), text: ")" },
48
+ ];
49
+ const importEdit = cjs ? requireEdit(program, source, offset) : importEditFor(body, source, offset);
50
+ if (importEdit)
51
+ edits.push(importEdit);
52
+ // Apply from the end so earlier offsets stay valid.
53
+ let code = source;
54
+ for (const e of edits.sort((a, b) => b.at - a.at))
55
+ code = code.slice(0, e.at) + e.text + code.slice(e.at);
56
+ return { changed: true, code };
57
+ }
58
+ /** Node start/end as string offsets: babel's `start`/`end`, else computed from `loc` (recast may null either). */
59
+ const start = (n, offset) => n.start ?? offset(n.loc.start);
60
+ const end = (n, offset) => n.end ?? offset(n.loc.end);
61
+ /** Text inserted at the start of the line that follows string offset `after`. */
62
+ function afterLineOf(source, after, text) {
63
+ const nl = source.indexOf("\n", after);
64
+ return nl === -1 ? { at: source.length, text: `\n${text}` } : { at: nl + 1, text: `${text}\n` };
65
+ }
66
+ /** Map babel {line (1-based), column (0-based)} to a string offset. */
67
+ function offsets(source) {
68
+ const starts = [0];
69
+ for (let i = 0; i < source.length; i++)
70
+ if (source[i] === "\n")
71
+ starts.push(i + 1);
72
+ return (p) => starts[p.line - 1] + p.column;
56
73
  }
57
74
  function isExpression(node) {
58
75
  return node && !/Declaration$/.test(node.type);
@@ -70,35 +87,33 @@ function unwrapTs(node) {
70
87
  }
71
88
  return node;
72
89
  }
73
- /** Add `fixupConfigRules` to an existing @eslint/compat import (AST edit), or return a new import line to insert. */
74
- function importInsertion(body) {
75
- const existing = body.find((s) => s.type === "ImportDeclaration" && s.source.value === WRAPPER_PKG && s.importKind !== "type");
90
+ function importEditFor(body, source, offset) {
91
+ const existing = body.find((s) => s.type === "ImportDeclaration" &&
92
+ s.source.value === WRAPPER_PKG &&
93
+ s.importKind !== "type" &&
94
+ s.specifiers.some((sp) => sp.type === "ImportSpecifier"));
76
95
  if (existing) {
77
- const has = existing.specifiers.some((sp) => sp.type === "ImportSpecifier" && sp.local.name === WRAPPER);
78
- if (!has) {
79
- existing.specifiers.push({
80
- type: "ImportSpecifier",
81
- imported: { type: "Identifier", name: WRAPPER },
82
- local: { type: "Identifier", name: WRAPPER },
83
- });
84
- }
85
- return undefined;
96
+ if (existing.specifiers.some((sp) => sp.type === "ImportSpecifier" && sp.local.name === WRAPPER))
97
+ return undefined;
98
+ const named = existing.specifiers.filter((sp) => sp.type === "ImportSpecifier");
99
+ return { at: end(named[named.length - 1], offset), text: `, ${WRAPPER}` };
86
100
  }
87
101
  const imports = body.filter((s) => s.type === "ImportDeclaration");
88
- const afterLine = imports.length ? imports[imports.length - 1].loc.end.line : 0;
89
- return { afterLine, text: `import { ${WRAPPER} } from "${WRAPPER_PKG}";` };
102
+ const text = `import { ${WRAPPER} } from "${WRAPPER_PKG}";`;
103
+ return imports.length ? afterLineOf(source, end(imports[imports.length - 1], offset), text) : { at: 0, text: `${text}\n` };
90
104
  }
91
- function requireInsertion(program, source) {
105
+ function requireEdit(program, source, offset) {
92
106
  if (new RegExp(`\\b${WRAPPER}\\b[^\\n]*require\\(["']${WRAPPER_PKG}["']\\)`).test(source))
93
107
  return undefined;
94
108
  // After the last top-level `const x = require(...)`; else after "use strict"; else top.
95
- let afterLine = 0;
109
+ let after = -1;
96
110
  for (const s of program.body) {
97
111
  if (s.type === "VariableDeclaration" && JSON.stringify(s.declarations?.[0]?.init ?? null).includes('"name":"require"')) {
98
- afterLine = s.loc.end.line;
112
+ after = end(s, offset);
99
113
  }
100
114
  }
101
- if (!afterLine && program.directives?.length)
102
- afterLine = program.directives[program.directives.length - 1].loc.end.line;
103
- return { afterLine, text: `const { ${WRAPPER} } = require("${WRAPPER_PKG}");` };
115
+ if (after < 0 && program.directives?.length)
116
+ after = end(program.directives[program.directives.length - 1], offset);
117
+ const text = `const { ${WRAPPER} } = require("${WRAPPER_PKG}");`;
118
+ return after < 0 ? { at: 0, text: `${text}\n` } : afterLineOf(source, after, text);
104
119
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-unstick",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Upgrade to ESLint 10 when your plugins have not released support yet. Diagnoses the blockers, applies the smallest fix, and proves your lint results did not change.",
5
5
  "author": "Raj Bhardwaj",
6
6
  "license": "MIT",
@@ -44,7 +44,7 @@
44
44
  "fixupConfigRules"
45
45
  ],
46
46
  "dependencies": {
47
- "magicast": "^0.5.5",
47
+ "@babel/parser": "^7.29.17",
48
48
  "semver": "^7.8.6"
49
49
  },
50
50
  "devDependencies": {